2013-10-23 31 views
2

我正試圖將遊戲片從初始位置移動到新的位置。注意:此舉被認爲是「合法」的。這個棋盤運動爲什麼不能正確運作?

public void move (int fromRow, int fromCol, int toRow, int toCol) { 
    GamePiece tmp; //Gamepiece is superclass 
    tmp=board[fromRow][fromCol]; 
    board[toRow][toCol]=tmp; 
    board[fromRow][fromCol]=new Gamepiece(); //default constructor 
    System.out.print(toString()); //this method has the board array printed in correct format 
} 

當我測試這個,它不移動正確的作品,並沒有給一個空白。爲什麼?

+1

需要更多的代碼,比如你的'GamePiece'類和'toString()'方法,我們可能還需要'board'類。 –

+0

我不知道是否是這種情況,但根據我的經驗,在處理2D數組時,交換行和列通常解決了我的問題。所以它會像'tmp = board [fromCol] [fromRow]'等。 – npinti

+0

每當有東西移動時,是否應該製作新作品?可能不會。這就是爲什麼'null'存在的原因。或者如果你喜歡或需要,有一個'GamePiece'的特殊實例,這意味着沒有一件。 – clwhisk

回答

3

你在代碼中做什麼是交換。在一個普通的國際象棋遊戲中,你永遠不需要交換。只需更換

 tmp=board[fromRow][fromCol]; // don't need this 
     board[toRow][toCol]=tmp; // don't need this 
     board[fromRow][fromCol]=new Gamepiece(); // don't need this 

只要做到:

 board[toRow][toCol] = board[fromRow][fromCol]; 
     board[fromRow][fromCol] = null 

這是所有考慮你的主板是2D array of ChessPiece s,例如:ChessPiece[][] board = new ChessPiece[8][8];

我不知道這是否會解決您的問題,不看到更多的代碼,但我只是指出了這一點。

相關問題