[英]2d array for tictactoe class being problematic
對於這個程序,我正在創建板,它將成為我必須制作的tictactoe游戲的基礎。 這將是一個非常簡單的程序,僅使用Java基礎知識。 目前,我無法讓我的setX()和setO()方法正常工作。 這是我得到的用以建立我的兩種方法的確切文本。
public void setX(int index)和public void setO(int index)如果index在board和BLANK的范圍內,則此方法應將X或O分配給board中的適當索引(setX應該放置一個X; setO應該是一個O)。 請記住,TicTacToe傳遞的數字在1-9范圍內,但是木板中的索引比該數字小1(在0-8范圍內)。
我的具體問題是如何將“ x”和“ o”設置為正確的索引。 當我運行單元測試文件時(我正在使用bluejay),使用這些方法會使所有測試用例失敗。 它將返回該數組首先在element [0] [2](或[1] [1]或我的數組中的任何組合)處有所不同; 期望(或),但是:
public class Board
{
// instance variables - replace the example below with your own
public int SIZE = 3;
private char BLANK = 'N';
private char [][] board;
/**
* Constructor for objects of class Board, intializes all elements to BLANK,
* creates board with SIZE elements
*/
public Board()
{
// initialise instance variables
board = new char[SIZE][SIZE];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = BLANK;
}
}
}
/**
* this method returns the board
*/
public char [][] getBoard(){
return board;
}
/**
* prints the elements of the array board in a 3x3 grid
*/
public void display(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
System.out.print(board[i][j]);
}
}
}
/**
* This method assigns X to the appropriate index in board
*/
public void setX(int index){
index = index - 1;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
if((BLANK <= index) && (index <= board[i][j])){
board[i][j] = 'X';
}
}
}
}
/**
* This method assigns O to the appropriate index in board
*/
public void setO(int index){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
if((BLANK <= index) && (index <= board[i][j])){
board[i][j] = 'O';
}
}
}
}
/**
* This method returns true if the index is not occupied by an X or O
*/
public boolean isAvailable(int index){
boolean available = false;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = BLANK;
available = true;
}
}
return available;
}
}
首先,我想知道為什么您甚至需要一個二維數組。 為什么不將板表示為九元素的單個陣列?
除此之外,從1-9位置索引轉換為適當的二維索引的方法是:
int i = (index - 1) / 3;
int j = (index - 1) % 3;
然后只對那對索引處理board[i][j]
。 您的setX
和setO
方法不應循環。
想象您的面板看起來像這樣:行標題是y的“坐標”,列標題是x的“坐標”,表內容是調用setX
或setO
時的索引:
| 0 | 1 | 2
--+---+---+---
0 | 0 | 1 | 2
--+---+---+---
1 | 3 | 4 | 5
--+---+---+---
2 | 6 | 7 | 8
現在,您要做的就是為2d數組計算x和y值:
y = index / 3;
x = index % 3;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.