首页 > 解决方案 > 定位在数组中不匹配

问题描述

我正在使用我在互联网上找到的文档中的二维数组制作一个简单的蛇应用程序。我已经通过了文件TestAsmt1.java中的所有测试。但是,我确信我已按照 PDF 文档中的所有说明进行操作。我错过了什么吗?谁能帮我这个?所以我可以正确使用PlayGame.java。谢谢

问题是,当我移动蛇时,它的头部会重复并在数组中移动一步 - 这没有写在代码中。无法确定位置在哪里图片在这里

这是我到目前为止所做的

源代码 - https://drive.google.com/open?id=1-oxBFusUIjX9bIqG5HhdCNpmIgTEl6mc

pdf 文件 - https://drive.google.com/open?id=1QsyrmDSYhsvaUUkHoTl6jPNsgKfLdWPy

MainApp - PlayGame.java,TestAsmnt.java

public void moveSnake(String direction){
    Position[] arr = new Position[this.snakeBody.length];       

    Position pos = this.newHeadPosition(direction);
    arr[0] = new Position(pos.getRow(), pos.getCol());

    for (int a = 0; a< this.snakeLength; a++){
        arr[a+1] = new Position(this.snakeBody[a].getRow(), this.snakeBody[a].getCol());            
    }

    for (int a = 0; a< this.snakeLength; a++){
        this.snakeBody[a].setRow(arr[a].getRow());
        this.snakeBody[a].setCol(arr[a].getCol());
    }
}

标签: javaarrays

解决方案


发现错误 - 在从 arr 数组恢复元素之前,我没有更新蛇身数组。下面更新方法

public void moveSnake(String direction){
Position[] arr = new Position[this.snakeBody.length];       

Position pos = this.newHeadPosition(direction);
arr[0] = new Position(pos.getRow(), pos.getCol());

for (int a = 0; a< this.snakeLength; a++){
    arr[a+1] = new Position(this.snakeBody[a].getRow(), this.snakeBody[a].getCol());            
}

this.snakeBody = new Position[arr.length];

for (int a = 0; a< this.snakeLength; a++){
    this.snakeBody[a].setRow(arr[a].getRow());
    this.snakeBody[a].setCol(arr[a].getCol());
}
}

推荐阅读