我正在创建一个战舰游戏。除敌方AI外,其他步骤均已完成。目前,当敌人击中船只时,它在另一个随机位置击中。显然这不好,所以我写了一种方法来尝试解决这个问题。

目前,如果最初击中它后错过了飞船,它将进入一个永无止境的循环。

public void compAI() {
    // Randomly goes up, down, left, or right from the previous spot to attempt to sink ship

    // BEWARE, ARRAYLISTOUTOFBOUNDsEXCEPTION WAITING TO HAPPEN!
    // CURRENTLY CREATES NEVER ENDING LOOP IF IT MISSES............
    boolean compAllowed = false;
    int forwards = 0, up = 0;
    while (!compAllowed) {
        int direction = (int) Math.random() * 4;
        if (direction == 0) forwards = 1;
        if (direction == 1) forwards = -1;
        if (direction == 2) up = 1;
        if (direction == 3) up = -1;

        if (playerBoard[savedCompRow + up][savedCompCol + forwards] == '~') {
            playerBoard[savedCompRow + up][savedCompCol + forwards] = 'ø';
            //lastMove = "miss";
            compAllowed = true;
        }
        else if (playerBoard[savedCompRow + up][savedCompCol + forwards] == 'ø')
            compAllowed = false;
        else if (playerBoard[savedCompRow + up][savedCompCol + forwards] == 'X')
            compAllowed = false;
        else {
            playerBoard[savedCompRow + up][savedCompCol + forwards] = 'X';
            lastMove = "hit";
            compAllowed = true;
        }
    }
}


电脑拍摄代码

public void compMove() {
    // Randomly choose locations
    boolean compAllowed = false;
    //if (lastMove.equals("hit")) compAI(); // Calls the compAI method to provide a smart strategy for the computer
    while (!compAllowed) {
        int row = (int) (Math.random() * boardSize);
        int col = (int) (Math.random() * boardSize);

        if (playerBoard[row][col] == '~'){
            playerBoard[row][col] = 'ø';
            compAllowed = true;
        }
        else if (playerBoard[row][col] == 'ø')
            compAllowed = false;    // Already made this move
        else if (playerBoard[row][col] == 'X')
            compAllowed = false;    // Already made this move
        else {      // Must be a hit
            playerBoard[row][col] = 'X';
            /*
            lastMove = "hit";
            savedCompRow = row;
            savedCompCol = col;
             */
            compAllowed = true;
        }
    }
}

最佳答案

您应该考虑一下生成随机数的方式。

int direction = (int) Math.random() * 4;


该语句将Math.random()的返回值强制转换为整数,该值是间隔[0,1)的两倍。此强制转换的结果将始终为0。之后将与4进行乘法运算,因此direction始终被分配为0。

我建议使用内置的Random类。该类提供了重载的方法nextInt()。您可以按照以下方式使用它:

Random random = new Random();
int direction = random.nextInt(4);


其中4是上限。因此,您正在创建间隔[0,4)之外的随机值

编辑:使用随机类还避免了必要的强制转换,也可以避免缺少括号的错误。

09-27 00:27