icfp-model/src/main/java/ru/bosony/model/mine/Mine.java
author indvdum (gotoindvdum[at]gmail[dot]com)
Sat, 14 Jul 2012 00:36:43 +0400
branchindvdum
changeset 6 0dbbc8983926
child 7 251961e44b5f
permissions -rw-r--r--
Parsing Mine from string
     1 package ru.bosony.model.mine;
     2 
     3 import ru.bosony.model.cellscontents.CellContent;
     4 import ru.bosony.model.io.TextRepresentable;
     5 
     6 public class Mine implements TextRepresentable {
     7 
     8 	public Cell[][]	cells;
     9 	protected int	sizeX;
    10 	protected int	sizeY;
    11 
    12 	public Mine(String text) {
    13 		fromText(text);
    14 	}
    15 
    16 	@Override
    17 	public String toText() {
    18 		String text = "";
    19 		for (int y = 0; y < sizeY; y++) {
    20 			for (int x = 0; x < sizeX; x++) {
    21 				text += cells[x][y].getContent().toText();
    22 			}
    23 			text += "\n";
    24 		}
    25 		return text.replaceAll("\n*$", "");
    26 	}
    27 
    28 	private void fromText(String text) {
    29 		String[] rows = text.split("\n+");
    30 		int y = rows.length;
    31 		int x = 0;
    32 		for (String row : rows) {
    33 			if (x < row.length())
    34 				x = row.length();
    35 		}
    36 		sizeX = x;
    37 		sizeY = y;
    38 		cells = new Cell[x][y];
    39 		for (int curY = 0; curY < rows.length; curY++) {
    40 			String row = rows[curY];
    41 			for (int curX = 0; curX < row.length() || curX < x; curX++) {
    42 				CellContent content = null;
    43 				if (curX < row.length())
    44 					content = CellContent.fromText("" + row.charAt(curX));
    45 				else
    46 					content = CellContent.Empty;
    47 				Cell cell = new Cell(curX + 1, rows.length - curY, content);
    48 				cells[curX][curY] = cell;
    49 			}
    50 		}
    51 	}
    52 
    53 	@Override
    54 	public String toString() {
    55 		return toText();
    56 	}
    57 
    58 }