如何在 Java 中为我们的游戏板在 Peg-Solitaire 中编写 "get field" 函数


public class SolitaireBoard {
private static final int empty = 0;
private static final int occupied = 1;
private static final int invalid = 2;
public int col;
public int row;
public SolitaireBoard(){
int [] [] board = {
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
};
}
}

我需要对一个 get 字段函数进行编程,该函数将行和列(列(作为输入并返回特定字段的状态。我无法在网上找到任何解决方案。

您必须将板设置为属性,以便可以从其他方法获取特定字段。如果要访问字段,则必须从零开始计数。例如,如果要从第一行访问字段,则必须键入该行的索引 0。

public class SolitaireBoard {
private static final int empty = 0;
private static final int occupied = 1;
private static final int invalid = 2;
public int[][] board;
public int col;
public int row;
public SolitaireBoard(){
board = new int[][]{
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 0, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
{2, 2, 2, 1, 1, 1, 2, 2, 2},
};
}
public int getField(int row, int column) {
return board[row][column];
}
}

似乎你的类不应该有row,col属性,而应该有一个board属性,比如

public class SolitaireBoard {
private static final int empty = 0;
private static final int occupied = 1;
private static final int invalid = 2;
private int[][] board;
public SolitaireBoard(){
this.board = new int[][]{
{2, 2, 2, 1, 1, 1, 2, 2, 2}, // Should be {invalid, invalid, invalid, occupied, ...}
{2, 2, 2, 1, 1, 1, 2, 2, 2},
...
};
}
}

然后构建一个方法来访问一个盒子

public int getField(int row, int col){
return this.board[row][col];
}

为了更轻松地操作常量,您可以减少它们的名称,例如EM, OC, IN并用它们构建数组

new int[][]{
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
{OC, OC, OC, OC, OC, OC, OC, OC, OC},
{OC, OC, OC, OC, EM, OC, OC, OC, OC},
{OC, OC, OC, OC, OC, OC, OC, OC, OC},
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
{IN, IN, IN, OC, OC, OC, IN, IN, IN},
};

相关内容

  • 没有找到相关文章

最新更新