我收到了一個項目來解決使用枚舉,我有點卡住了。這是一個tic tac腳趾遊戲,它具有將單元格的位置存儲在3x3網格表中的枚舉值,以及存儲單元格狀態的枚舉值(空,X或O)。另外,我有一個返回CellState
的GameBoard
接口:getCellState (CellLocation cellLocation);
從接口返回數據檢索數據
我的任務是隻寫Consultant
界面,我無法改變這是給我提供的代碼什麼。 我很努力地在每一步之前檢查Board
的狀態。
我的想法是,X開始遊戲,我使用for
循環的步驟和每一步,我檢查if nrOfSteps%2==0
。如果是,我將cellState
設置爲玩家O.檢查我們是否處於獲勝位置,如果我們贏了或者是否有平局。如果不是,我會建議一個舉措。 例如
if (nrOfSteps%2!=0){
cState =CellState.OCCUPIED_BY_X;
if (isWon(cState, board)){
throw new IllegalStateException("Player X won!");
} else if (draw(board, locations)){
throw new IllegalStateException("No more empty fields!");
} else
for (int remainingCells = 0; remainingCells <9; remainingCells++) {
if (board.equals(locations[remainingCells]) &&
cState==CellState.EMPTY){
availableCells[index] = locations[remainingCells];
index++;
}
CellLocation cellToTake = availableCells[(int)(Math.random()*
(availableCells.length-1))];
return cellToTake;
}
現在,我的問題是,我試圖爲isWon
方法(部分的代碼只驗證的第一行)以下:
private boolean isWon(CellState player, GameBoard board){
if (board.equals(CellLocation.TOP_LEFT) && cState==player &&
board.equals(CellLocation.TOP_CENTRE) && cState==player &&
board.equals(CellLocation.TOP_RIGHT) && cState==player){
return true;
}
return false;
}
但我已經意識到,當前狀態因爲我正在檢查上面的代碼,所以電路板不能僅僅等於一個單元。它顯然不能等於3個不同的「只有一個細胞」--s。我甚至不知道我是否會被檢查,如果董事會有這個由玩家X只佔用一個單元:
board.equals (CellLocation.TOP_LEFT) && cState==player
可能有人請給我如何可以將前端兩個CellState
和CellLocation
成一個查詢?我應該使用數組嗎?例如CellState[][]
?
感謝您的幫助。 我已經嘗試過你的代碼,並修改了一下,因爲我必須寫的接口將有一個「public CellLocation(GameBoard gameBoard)」方法返回null。 所以它沒有一個主要的方法,並且爲我預先編寫的JUnit測試着眼於這個建議的方法。我將不得不從這裏委託任務。 但是,這種方式我不能將for循環中的枚舉轉換爲cellLocation,只返回一個位置。 它顯示getCellOwner方法的錯誤,表示它不能解析爲變量。 – Vero
你可以顯示你的CellState和CellLocation類嗎? –
我把它發佈爲aswer,因爲它不讓我發表評論。謝謝。 – Vero