2012-03-09 103 views
1

我在java中创建简单的国际象棋棋盘游戏,它们运行平稳,但是我在测试时遇到了2个故障,而且我不明白它们背后的逻辑。Java简单游戏测试错误

失败#1:玩家1已经克隆了国王,他统治预期< 8>,但它是< 1>

失败#2:符号应该被视为空细胞。预计< 1>,但它是< 0>

这是我的代码:

import java.io.ObjectInputStream.GetField; 

public class ChessBoard { 
    public static boolean belongsToPlayer(final char piece, final int player) { // method to check a piece is related to player 1 or 2 
     if (player == 0 && Character.isUpperCase(piece)) { 
      return true; 
     } 
     if (player == 1 && Character.isLowerCase(piece)) { 
      return true; 
     } 
     return false; 
    } 

    public static int getCount(final String[] board, final int player) { // method to return the number of pieces belonging to each player 
     int count = 0; 

     if (board.length == 0) { 
      return count = 0; 
     } 
     else if (board.length == 1) { 
      return count = 1; 
     } 
     else { 
     int size = board.length; 
     for (int i = 1; i < size; i++) {   
      for (int j = 0; j < board[i].length(); j++) { 

       if (belongsToPlayer(board[i].charAt(j), player)) { 
        count++; 
       } 
      } 
     } 
     } 
     return count; 
    } 

} 

and these are the test methods: 
test #1 
@Test(timeout = 1000) 
    public void test8KingsPlayer1() { 
     String[] board = { 
       "kkkkkkkk" 
      }; 
     assertEquals("Player 1 has cloned his king and has dominated", 
       8, instance.getCount(board, PLAYER1)); 
    } 

test #2 
@Test(timeout = 1000) 
    public void testAPieceOfCode() { 
     String[] board = { 
       "int factorIal(int n) {", 
       " int n = 8, r = 1; ", 
       " while (n-- > 1) ", 
       "  r *= n;  ", 
       " return r;   ", 
       "}      " 
      }; 
     assertEquals("Symbols should be treated as empty cells.", 
       1, instance.getCount(board, PLAYER0)); 
    } 

有谁知道如何解决这个问题?

+2

什么是失败?当没有问题时没有解决方案... – Jon 2012-03-09 20:27:47

+2

for(int i = 1; i PeskyGnat 2012-03-09 20:32:45

+0

好吧,我编辑它,并添加了失败的解释。 @Jon – 2012-03-09 20:34:40

回答

2

故障1:

else if (board.length == 1) { 
    return count = 1; 
} 

,因为你用1元传递一个字符串[]它返回1的时候了。

故障2:

for (int i = 1; i < size; i++) { 
    ... 
     if (belongsToPlayer(board[i] ... 

数组索引从0开始您开始使用1,其跳过数组中的第一字符串。由于首都我在第一排,所以没有计算在内。