游戏敌人计算机AI逻辑

时间:2014-11-27 19:47:00

标签: java loops

我正在制作战舰游戏。除敌人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;
        }
    }       
}

1 个答案:

答案 0 :(得分:2)

你应该过度思考你产生随机数的方式。

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

此语句将Math.random()返回的值(它是区间[0,1)的两倍)转换为整数。此转换的结果将始终为0.之后发生乘以4,因此direction始终指定为0。

我建议使用内置的Random-class。该类提供了重载方法nextInt()。在您的情况下,您可以按如下方式使用它:

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

其中4是上限。因此,您要在区间[0,4)

之外创建随机值

编辑:使用Random-class也可以避免必要的强制转换,也可以避免错过括号的错误。