Agile Java 习题3,4--类方法和类变量

 

看完第三课之后做习题,怎么做都觉得不合适,于是留到看完第四课再做的。

1、将Pawn类修改成Piece。

先修改测试:

 

@Test
public void testCreate() {
	Piece piece = Piece.createPiece("white","Pawn");
	assertEquals("white", piece.getColor());
	assertEquals("Pawn", piece.getName());
}

 在修改Pawn类为Piece,并使其通过测试。

 

public class Piece {
	
	private String color ;
	private String name;
	
	private Piece(String color, String name) {
		this.color = color;
		this.name = name;
	}

	public static Piece createPiece(String color, String name) {
		return new Piece(color, name);
	}

	public String getColor() {
		return color;
	}
	
	public String getName() {
		return name;
	}
}

 2、按照题目修改BoardTest,并修改Board使其通过测试,得到最简单的Board代码如下:

 

public class Board {

	public void initialize() {
		
	}

	public int pieceCount() {
		return 32;
	}

	public String print() {
		return "RNBQKBNR\n" +
				"PPPPPPPP\n" +
				"........\n" +
				"........\n" +
				"........\n" +
				"........\n" +
				"pppppppp\n" +
				"rnbqkbnr\n";
	}

}

 这个明显是不对的,但是的确又能够通过测试(很大的可能是我跳过了第三课的习题)。只要能够通过测试,就可以先不管,进而进行下一步。

3、测试Board包含了16个黑棋,16个白棋。

先在Board中testCreate添加测试代码:

 

assertEquals(16, board.blackPieceCount());
assertEquals(16, board.whitePieceCount());

 相应的修改Board代码:

 

public int blackPieceCount() {
	return 16;
}

public int whitePieceCount() {
	return 16;
}

现在在反过来看第三课的习题,会发现我错过了一个约定:用小写字母表示白棋,大写字母表示黑棋。同时在Board中存储Piece(开始是Pawn),在initialize中完成为棋盘添加棋子的操作。

4、重构:向棋盘添加棋子。

首先将测试PieceTest中的“Pawn”修改为“p”;

然后修改Board类用一个数组来表示棋盘。

 

private Piece pieces[][] = new Piece[8][8];

再在initialize方法中初始化这个数组:

 

pieces[0][0] = Piece.createPiece("black", "R");
pieces[0][1] = Piece.createPiece("black", "N");
pieces[0][2] = Piece.createPiece("black", "B");
pieces[0][3] = Piece.createPiece("black", "Q");
pieces[0][4] = Piece.createPiece("black", "K");
pieces[0][5] = Piece.createPiece("black", "B");
pieces[0][6] = Piece.createPiece("black", "N");
pieces[0][7] = Piece.createPiece("black", "R");
for(int i = 0; i<8; i++) {
	pieces[1][i] = Piece.createPiece("black", "P");
	pieces[6][i] = Piece.createPiece("white", "p");
}
pieces[7][0] = Piece.createPiece("white", "r");
pieces[7][1] = Piece.createPiece("white", "n");
pieces[7][2] = Piece.createPiece("white", "b");
pieces[7][3] = Piece.createPiece("white", "q");
pieces[7][4] = Piece.createPiece("white", "k");
pieces[7][5] = Piece.createPiece("white", "b");
pieces[7][6] = Piece.createPiece("white", "n");
pieces[7][7] = Piece.createPiece("white", "r");

 再用类属性来表示piece数量:

 

private int pieceCount = 0;
private int blackPieceCount = 0;
private int whitePieceCount = 0;

 在initialize中初始化:

 

pieceCount = 32;
whitePieceCount = 16;
blackPieceCount = 16;

5、重构修改print(),使其按照存储的piece来打印:

StringBuilder builder = new StringBuilder();
for(Piece tempPieces[] : pieces) {
    for(Piece piece : tempPieces) {
	if(piece == null) {
            builder.append(".");
	} else {
	    builder.append(piece.getName());
	}
    }
    builder.append("\n");
}		
return builder.toString();

你可能感兴趣的:(java)