For a coding challenge, I decided to make the game battleship. However, when calling the runGameAgainstAi() method, it refuses to work and simply draws the grid instead of allowing functionality, It may be stuck in the while loop but I have been unable to pinpoint the exact issue. Any idea is appreciated.
runGameAgainstAI code:
public void runGameAgainstAI() throws IOException, InterruptedException {
// create the CPU object and initialize variables for the game
cpu = new CPU();
title.setText("Player 1");
cpuGameTurn = "Picking";
btnFire.setEnabled(true);
boolean hasWon = false;
// game loop
while (true) {
sleep(100);
// this is reserved for when the human player is selecting a cell
// by firing a valid shot, cpuGameTurn is set to "Picked"
if (cpuGameTurn.equals("Picking")) {
servermsg.setText("Select a cell and fire!");
}
// upon shooting, the cpu checks if the shot hit
// this condition is met when the btnFire is clicked
// while selecting a valid cell
else if (cpuGameTurn.equals("Picked")) {
// check if the shot hit the cpu ships
boolean hit = cpu.checkHit(eb.getRclick(), eb.getCclick());
// place a corresponding marker
if (hit) {
eb.placeHitMarker(eb.getRclick(), eb.getCclick());
} else {
eb.placeMissMarker(eb.getRclick(), eb.getCclick());
}
// create the shot record
sl.insert(new ShotRecord(eb.getRclick(), eb.getCclick(), hit, "You"));
txaSList.setText(sl.toString());
// if the cpu lost break, hasWon will be true
hasWon = cpu.checkLost();
if (hasWon) {
break;
}
// set the turn to cpu
cpuGameTurn = "cpu";
}
// when it is the cpu turn
else if (cpuGameTurn.equals("cpu")) {
// get the cpu shot, and check if it hit
int shot[] = cpu.shoot();
boolean hit = pb.checkEnemyShot(shot[0], shot[1]);
// create the shot record
sl.insert(new ShotRecord(shot[0], shot[1], hit, "CPU"));
txaSList.setText(sl.toString());
// if the cpu won break, hasWon will be false
if (pb.hasLost()) {
break;
}
// set the turn back to waiting for human to shoot
cpuGameTurn = "Picking";
}
}
if (hasWon) {
servermsg.setText("You won!");
} else {
servermsg.setText("You lost!");
}
}
Self Testing main method for run game against ai:
else {
try {
cui = new ClientUI();
cui.runGameAgainstAI();
}
Main-menu code in separate class trying to call the runGameAgainstAI Method
else if (evt.getSource() == btnSinglePlayer) {
try {
ClientUI c = new ClientUI();
c.runGameAgainstAI();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
At first glance, the code will be endlessly in this loop. Need to update cpuGameTurn inside the if...
cpuGameTurn = "Picking";
while (true) {
sleep(100);
if (cpuGameTurn.equals("Picking")) {
servermsg.setText("Select a cell and fire!");
}
.
.
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.