2012-03-09 92 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,其跳過數組中的第一字符串。由於首都我在第一排,所以沒有計算在內。