Convert a coordinate system into a board for a game
I currently have code that prints out a coordinate system as shown below. The code asks the user to input dimensions and then prints out a coordinate system appropriately. The board below is a 5 x 5.
(0, 0) (1, 0) (2, 0) (3, 0) (4, 0)
(0, 1) (1, 1) (2, 1) (3, 1) (4, 1)
(0, 2) (1, 2) (2, 2) (3, 2) (4, 2)
(0, 3) (1, 3) (2, 3) (3, 3) (4, 3)
(0, 4) (1, 4) (2, 4) (3, 4) (4, 4)
I was wondering if anyone could give me a hand as to how to convert this into a board that looks like this:
X O X O X
O X O X O
X O X O X
O X O X 开发者_运维知识库O
X O X O X
So far I've tried making a list of strings and appending it the the coordinate system but haven't quite got the desired outcome. if anyone has any hints they would be much appreciated.
You could try checking if x+y is even, then printing the appropriate string. So, (1,1) would be X, and (1,4) would be O
You could make a count. if count = 0 print X if count = 1 print O and set count back to 0
I would make a BoardElement class, and a BoardElement[][]
class BoardElement {
String value;
BoardElement(String v) { value = v; }
public String toString() { return value; }
}
class Board {
BoardElement[][] board;
Board(int x, int y) { board = new BoardElement[x][y]; }
public String toString() {
StringBuilder sb = new StringBuilder();
for(int x = 0; x < board.length; x++) {
for(int y = 0; y < board[0].length; y++) {
sb.append(board[x][y]).append(" ");
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
public void set(int x, int y, String v) { board[x][y].value = v; }
}
then to make your system you would go like this
public static void main(String[] args) {
Board b = new Board(5,5);
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
b.set(x,y,(x+y)%2==0?"X":"O");
}
}
System.out.println(b);
}
Your first system was more like
public static void main(String[] args) {
Board b = new Board(5,5);
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
b.set(x,y,"(" + x + "," + y + ")");
}
}
System.out.println(b);
}
精彩评论