fix up game loop to _actually_ be interruptable

This commit is contained in:
Gered 2017-04-14 17:37:48 -04:00
parent 57608ad74a
commit 4ab3980d24

View file

@ -117,64 +117,84 @@ public class Mirror {
* is running. If your code holds a copy of this object anywhere else, do not try to use it
* again after this method returns.
*
* @param autoReconnect
* If true, will run an infinite loop allowing you to keep your bot running as many
* subsequent matches as desired. Will automatically reconnect to a Broodwar instance
* if the connection is interrupted.
* If false, will disconnect from Broodwar and return after the first match ends
* @param returnOnMatchEnd
* If true, will disconnect from Broodwar and return after the first match ends
* (regardless of how it ended). Will not attempt to reconnect to Broodwar if the
* connection is interrupted once the first match has been started. You can call
* {@link #startGame} again to run another match as needed.
* If false, will run an infinite loop allowing you to keep your bot running as many
* subsequent matches as desired. Will automatically reconnect to a Broodwar instance
* if the connection is interrupted.
*/
public void startGame(boolean autoReconnect) {
try
{
public void startGame(boolean returnOnMatchEnd) {
System.out.println("Connecting to Broodwar...");
reconnect();
if (reconnect())
System.out.println("Connection successful, starting match...");
else {
System.out.println("Connection attempt aborted.");
return;
}
game = getInternalGame();
do {
System.out.println("Waiting...");
while (!game.isInGame()) {
update();
if (!isConnected()) {
System.out.println("Reconnecting...");
reconnect();
}
boolean inGame = game.isInGame();
boolean previouslyInGame = inGame;
if (inGame)
System.out.println("Match already running.");
while (true) {
if (Thread.interrupted()) {
System.out.println("Interrupted.");
break;
}
if (!inGame) {
if (previouslyInGame) {
System.out.println("Match ended.");
if (returnOnMatchEnd)
break;
}
update();
} else {
if (!previouslyInGame)
System.out.println("Game ready!!!");
while (game.isInGame()) {
processGameEvents();
update();
}
if (!isConnected()) {
System.out.println("Reconnecting...");
reconnect();
}
previouslyInGame = inGame;
inGame = game.isInGame();
}
System.out.println("Match ended.");
} while(autoReconnect);
System.out.println("Finished.");
System.out.println("Disconnecting from Broodwar...");
System.out.println("Finished. Disconnecting from Broodwar...");
} catch (InterruptedException e) {
System.out.println("Interrupted. Disconnecting from Broodwar...");
}
if (isConnected())
disconnect();
game = null;
System.out.println("Returning...");
}
private void reconnect() throws InterruptedException {
private boolean reconnect() {
while (!connect()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return false;
}
}
return true;
}
/**
* Returns the current connection state to a running Broodwar instance.