I need help with my battleship AI code that keeps crashing after a few rounds
I’m building an AI bot to play against my instructor’s battleship game. The problem happens when I use a 2D boolean array to track which spots I’ve already fired at. After the program runs automatically for just a few turns, it stops working and I have to restart it manually.
I think there might be some kind of memory issue or array bounds problem but I can’t figure out what’s wrong. Here’s my code:
public class BattleshipBot {
public String botName = "BattleshipBot";
// tracking array for fired positions
public boolean[][] fired = new boolean[10][10];
@Override
public void execute() {
while (match.isActive()) {
int x = (int) (Math.random() * 10);
int y = (int) (Math.random() * 10);
boolean success;
// fire at checkerboard pattern positions
if (x % 2 == 0 && y % 2 != 0 && fired[x][y] == false) {
success = match.fire(x, y);
fired[x][y] = true;
if (success) {
searchUp(x, y, success);
searchDown(x, y, success);
searchRight(x, y, success);
searchLeft(x, y, success);
}
} else if (x % 2 != 0 && y % 2 == 0 && fired[x][y] == false) {
success = match.fire(x, y);
fired[x][y] = true;
if (success) {
searchUp(x, y, success);
searchDown(x, y, success);
searchRight(x, y, success);
searchLeft(x, y, success);
}
}
}
}
public boolean searchUp(int x, int y, boolean success) {
try {
y--;
while (success) {
success = match.fire(x, y--);
fired[x][y] = true;
}
return success;
} catch (Exception ex) {
return false;
}
}
public boolean searchDown(int x, int y, boolean success) {
try {
y++;
while (success) {
success = match.fire(x, y++);
fired[x][y] = true;
}
return success;
} catch (Exception ex) {
return false;
}
}
}
Any ideas what could be causing this to freeze up?