我试图根据移动方法给出的数字向上,向下,向左和向右移动角色P,不幸的是,Junit测试人员没有给我这个:org.junit.ComparisonFailure:预期测试失败:&lt ;的 * [P] * * * * >但是:< ** [P] * * * * *>
印刷品应如下所示:
P * * *
游戏类:
public class Game {
public static final int UP = 1;
public static final int DOWN = 2;
public static final int LEFT = 3;
public static final int RIGHT = 4;
String[][] board; //Creates a matrix a rows and j columns
int playerRow, playerCol;
public Game(int a, int j) {
board = new String[a][j]; //Creates a matrix a rows and j columns
playerCol = 0;
playerRow = 1;
for(int row =0; row < a; row++){
for(int col = 0; col < j; col++){
board [row] [col] =" ";
}
}
//Fills the first row with *s
for (int i=0; i < j ; i++){
board [0][i] ="*";
}
//Place *s across the bottom row
for (int i=1; i<j; i++){
board [a-1][i] = "*";
}
//Place *s down the right side
for (int i=0; i < a ; i++){
board [i][0] ="*";
board [i][j-1] ="*";
}
//Place the player on the first column of the second row
board [1] [0] = "P";
board [a-1][j-2] =" ";
}
public String toString(){
String output = "";
for(int row =0; row < board.length; row++){
for(int col = 0; col < board[0].length; col++){
output += board[row][col];
}
output += "\n";
}
output = (String) output.subSequence(0, output.length()-1);
return output;
}
public void move(int a){
if(a == Game.UP){
playerRow -= 1;
}
if(a == Game.DOWN){
playerRow += 1;
}
if(a == Game.LEFT){
playerCol -= 1;
}
if(a == Game.RIGHT){
playerCol += 1;
}
}
}
游戏测试员:
import static org.junit.Assert.*;
import org.junit.Test;
public class GameTester {
@Test
public void test() {
Game g = new Game(3,4);
String result = g.toString();
String shouldBe="****\nP *\n** *";
//****
//P *
//** *
assertEquals("failed test", shouldBe, result);
Game g2 = new Game(4,7);
result = g2.toString();
shouldBe="*******\nP *\n* *\n***** *";
//*******
//P *
//* *
//***** *
assertEquals("failed test", shouldBe, result);
g2.move(Game.RIGHT);
shouldBe ="*******\n P *\n* *\n***** *";
//*******
// P *
//* *
//***** *
assertEquals("failed test", shouldBe, result);
//Make a 2D Matrix to hold all the positions and make it move
}
}
答案 0 :(得分:0)
我相信你在代码中遇到了一些问题:
- as part of the move to the right code, you correctly set the playerCol value up by 1 but board is not updated to move the 'P' to the next column.
- as a result of the above code, the toString() still shows the player in col 0
- you don't call result = g2.toString(); after moving to the right, so the result is still left over from the previous move
- the assert is using the stale version of result
- I believe no matter how you move, the player will always be shown in the same position, as a result of the 1st item.
- the shouldBe value for the row with the player only has 6 slots, whereas the board has 7 columns - so that expected result needs to be udpated.
希望这有帮助!