java - Java 中的 gem 棋游戏 - 在 while 循环中使用 int 数组

标签 java arrays junit while-loop

我正在从事 gem 棋游戏项目。如果您对 GUI 感兴趣,请看这里:

https://s32.postimg.org/hxzmhxt1x/mancala.png

我正在研究一种方法,让计算机玩家选择离他们的商店最近的坑,从而允许它从人类玩家那里捕获石头。当最后一 block 石头落在一个空坑中时,捕获就被捕获了,空坑正对着另一侧有石头的坑。我在下面包括相关方法。参数“theBoard”是一个 int 数组,表示所有的坑,包括商店以及数组的每个坑中包含多少 block 石头。这是我的方法代码:

public int selectPit(int[] theBoard) {
        int pitChoice = theBoard.length - 2;        

        while (pitChoice >= theBoard.length / 2) {
            int destinationPit = theBoard[pitChoice] + pitChoice;
            int opposite = (theBoard.length - 2) - destinationPit;
            if (theBoard[destinationPit] == 0 && theBoard[opposite] > 0 && destinationPit <= (theBoard.length - 2) && destinationPit > (theBoard.length / 2)) {
                return pitChoice;
            } else {
                pitChoice--;
            }
        }
        return this.selectClosestPitWithStones(theBoard);
    }

调用 selectClosestPitWithStones 的最后一行是对备份方法的调用,以防万一没有允许捕获的选项。此备份方法的功能按预期工作。但是,我的 selectPit 方法不断返回不正确的结果或“ArrayIndexOutOfBoundsException:-1”。

我正在使用正确编写的 JUnit 测试来测试此方法。这是一个这样的测试:

@Test
    public void testCapturePit0() {
        this.setUp();
        int[] theBoard = {6, 0, 0, 0, 2, 0, 0, 0};
        assertEquals(4, this.strategy.selectPit(theBoard));
    } 

关于什么可能导致不正确的结果有什么想法吗?

最佳答案

调试它并验证变量是否具有您期望的值。

目前的问题是其中一个变量超出了数组的范围。请记住,数组索引从 0 到长度减一。 int destinationPit = theBoard[pitChoice] + pitChoice;int destinationPit = theBoard[pitChoice] + pitChoice; 都可能越界,具体取决于输入或数组。

关于java - Java 中的 gem 棋游戏 - 在 while 循环中使用 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465879/

相关文章:

java - 将数组传递给构造函数

java - 使用递归方法对数组进行排序

javascript - 在循环中为我的数组缩进并创建新空间

java - assert(false) 不会停止执行

unit-testing - 您如何 mock 平等?

java - 鉴别器但不是 int single table

java - Android 中的 OpenCV 旋转(去偏斜)- C++ 到 Java 的转换

junit - 我们现在可以用 Mockito 2 模拟静态方法吗?

c# - 为什么 "abcd".StartsWith ("") 返回真?

java - 可观察链死亡和 Intellij 滞后/卡住