我正在尝试创建一个2D拼图滑块游戏.我创建了自己的对象调用游戏状态来存储父游戏状态和新的游戏状态,因为我打算使用BFS解决它.示例数组看起来像
int[][] tArr = {{1,5,2},{3,4,0},{6,8,7}};
这暗示着
[1,2,
3,
6,7]
为了存储这个状态,我使用了以下for循环,它带来了indexOutOfBounds异常.
public class GameState {
public int[][] state; //state of the puzzle
public GameState parent; //parent in the game tree
public GameState() {
//initialize state to zeros,parent to null
state = new int[0][0];
parent = null;
}
public GameState(int[][] state) {
//initialize this.state to state,parent to null
this.state = state;
parent = null;
}
public GameState(int[][] state,GameState parent) {
//initialize this.state to state,this.parent to parent
this.state = new int[0][0];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++) {
this.state[i][j] = state[i][j];
}
}
this.parent = parent;
}
有想法该怎么解决这个吗?
最佳答案
>对于GameState()构造函数(默认构造函数):
原文链接:https://www.f2er.com/java/437514.html改变这个状态= new int [0] [0];对此:state = new int [3] [3] ;.这样就可以初始化具有(3)x(3)元素容量的数组.
>对于GameState(int [] []状态,GameState父)构造函数:
改变这个this.state = new int [0] [0]; to this.state = new int [state.length] [state.length> 0? state [0] .length:0];
这样,您可以初始化具有容量的阵列
(state.length)x(state [0] .length或0如果state.length为0)元素.
此外,你必须循环到state.length与i,直到state [i] .length与j.
在GameState构造函数中,如下所示:
public GameState(int[][] state,this.parent to parent
this.state = new int[state.length][state.length > 0 ? state[0].length : 0];
for (int i = 0; i < state.length; i++){
for (int j = 0; j < state[i].length; j++) {
this.state[i][j] = state[i][j];
}
}
this.parent = parent;
}
另外,作为附注,它不是[1,3,6,7],
但是[[1,2],[3,0],[6,7]].