Java 游戏敌人计算机AI逻辑
我正在制作一个战舰游戏。它是完整的,除了敌人的AI。目前,当敌人击中一艘船时,它会在另一个随机地点击中。显然,这是不好的,所以我写了一个方法来尝试和处理这个问题 目前,如果它在最初撞到船后错过了它,它将进入一个永无止境的循环Java 游戏敌人计算机AI逻辑,java,loops,Java,Loops,我正在制作一个战舰游戏。它是完整的,除了敌人的AI。目前,当敌人击中一艘船时,它会在另一个随机地点击中。显然,这是不好的,所以我写了一个方法来尝试和处理这个问题 目前,如果它在最初撞到船后错过了它,它将进入一个永无止境的循环 public void compAI() { // Randomly goes up, down, left, or right from the previous spot to attempt to sink ship // BEWARE, ARRAY
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的乘法发生在后面,因此方向始终被指定为0
我建议使用内置的Random类。该类提供重载方法nextInt()
。在您的情况下,可以按如下方式使用它:
Random random = new Random();
int direction = random.nextInt(4);
其中4是一个上界。所以你在区间[0,4]之外创建随机值
编辑:使用Random类还可以避免必要的强制转换,也可以避免缺少括号造成的错误。命中的位在哪里?我很确定,当出现错误时,您希望将compAllowed设置为falsemiss@MatthewRowlands对不起,我已经添加了这个方法。对于从pl中随机移动没有任何保护ayerBoard。但是,我会首先将所有可能成为目标的坐标添加到一个列表中,然后随机选择其中一个作为下一次尝试。提示:(int)Math.random()*4;
和(int)(Math.random()*4);
是不同的语句。您可能需要尝试并仔细查看AI的第一次攻击位置。