我正在尝试创建2D拼图滑块游戏。当我计划使用BFS解决它时,我创建了自己的对象gamestate来存储父gamestate和新gamestate。样本数组看起来像
int[][] tArr = {{1,5,2},{3,4,0},{6,8,7}};
这暗示
[1、5、2 3,4,0, 6,8,7]
要存储此状态,我使用了以下for循环,它带来了 indexOutOfBounds exceptions
。
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;
}
关于如何解决此问题的任何想法?
答案 0 :(得分:2)
GameState()
构造函数(默认构造函数):将此state = new int[0][0];
更改为此:state = new int[
3
][
3
{{1 }}。这样,您可以使用(3)x(3)个元素的容量来初始化数组。
];
构造函数:将此GameState(int[][] state, GameState parent)
更改为this.state = new int[0][0];
this.state = new int[
] [ state.length
state.length > 0 ? state[0].length : 0
这样,您可以使用以下容量初始化数组
({];
)x(state.length
或{{1},如果state[0].length
是0
)个元素。
此外,您必须循环使用state.length
和0
直到state.length
和i
。
在state[i].length
构造函数中,如下所示:
j
此外,请注意,它不是GameState
,
但是public GameState(int[][] state, GameState parent) {
//initialize this.state to 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 :(得分:1)
问题出在初始化部分。
this.state = new int[0][0];
此代码将创建一个尺寸为零的二维尺寸。这就是为什么当您尝试在其中设置值时会得到indexOutOfBounds异常的原因。
如果要使用零初始化数组,则正确的语法是:
this.state = {{0,0,0},{0,0,0},{0,0,0}};
请参阅官方文档以获取完整参考: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
答案 2 :(得分:0)
在第3个构造函数中,您正在使用一个空数组初始化this.state
。它没有元素,因此长度为0
。使用for循环访问此数组的任何元素都会引发ArrayIndexOutOfBoundsException
。
由于您要传递state
作为参数,因此您可能希望将其值复制到字段state
。
您可以这样做:
public GameState(int[][] state, GameState parent) {
this.state = new int[state.length][];
for (int i = 0; i < state.length; i++) {
if (state[i] != null) {
this.state[i] = Arrays.copyOf(state[i], state[i].length);
}
}
this.parent = parent;
}
您当然可以调用Arrays.of(state)
,但这不会返回state
的深层副本。对于每个i
,您将有this.state[i] == state[i]
。