diff options
-rw-r--r-- | src/jrummikub/control/turn/BaseAIControl.java | 63 |
1 files changed, 54 insertions, 9 deletions
diff --git a/src/jrummikub/control/turn/BaseAIControl.java b/src/jrummikub/control/turn/BaseAIControl.java index 4e627c3..fc1b97d 100644 --- a/src/jrummikub/control/turn/BaseAIControl.java +++ b/src/jrummikub/control/turn/BaseAIControl.java @@ -1,23 +1,60 @@ package jrummikub.control.turn; +import java.util.ArrayList; +import java.util.List; + import javax.swing.SwingUtilities; +import jrummikub.control.ITurnTimer; +import jrummikub.control.TurnTimer; +import jrummikub.util.Connection; +import jrummikub.util.IListener; +/** + * Base class for AI players + * + */ public class BaseAIControl extends AbstractTurnControl { long startTime; + private ITurnTimer turnTimer; + private List<Connection> connections = new ArrayList<Connection>(); + private Thread computeThread; + + private volatile boolean stopRunning = false; + @Override public void startTurn() { - Thread thread = new Thread(new Runnable() { + turnTimer = new TurnTimer(view); + connections.add(turnTimer.getTimeRunOutEvent().add(new IListener() { + + @Override + public void handle() { + cleanUp(); + endOfTurnEvent.emit(); + } + })); + + computeThread = new Thread(new Runnable() { @Override public void run() { compute(); } }); startTime = System.currentTimeMillis(); - thread.start(); - + + turnTimer.startTimer(); + computeThread.start(); } - + + private void cleanUp() { + turnTimer.stopTimer(); + + for (Connection c : connections) { + c.remove(); + } + stopRunning = true; + } + private void compute() { if (mayRedeal) { emitRedeal(); @@ -29,15 +66,16 @@ public class BaseAIControl extends AbstractTurnControl { } } } - + private void layOut() { emitEndOfTurn(); } - + private void emitRedeal() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { + cleanUp(); redealEvent.emit(); } }); @@ -45,9 +83,10 @@ public class BaseAIControl extends AbstractTurnControl { private void emitEndOfTurn() { long timeElapsed = System.currentTimeMillis() - startTime; - long timeNeeded = Math.min((long)(1000 + Math.random() * hand.getSize() * 100), 50000); + long timeNeeded = Math.min((long) (1000 + Math.random() * hand.getSize() + * 100), 50000); long waitTime = timeNeeded - timeElapsed; - + if (waitTime > 0) { try { Thread.sleep(waitTime); @@ -55,15 +94,21 @@ public class BaseAIControl extends AbstractTurnControl { // This shouldn't happen } } - + SwingUtilities.invokeLater(new Runnable() { @Override public void run() { + cleanUp(); endOfTurnEvent.emit(); } }); } + /** + * Get the factory for the base AI control + * + * @return the factory + */ static public TurnControlFactory getFactory() { return new TurnControlFactory() { @Override |