001 /**
002 * TimerBox keeps track of Timer-related tasks. It has a separate Stopwatch for
003 * the black and white players.
004 */
005
006 package ui;
007
008 import java.util.Timer;
009
010 import core.Color;
011
012
013 public class TimerBox {
014 private Stopwatch whiteWatch;
015 private Stopwatch blackWatch;
016 private GameThread gameThread;
017 private Timer timer;
018
019 /**
020 * Constructor.
021 */
022 public TimerBox(GameThread g) {
023 gameThread = g;
024 }
025
026 /**
027 * Resets the TimerBox's Stopwatches. Used when starting or loading a game.
028 */
029 public void setWatches(int whiteTime, int blackTime) {
030 if (timer != null) {
031 timer.cancel();
032 }
033 if (whiteWatch != null) {
034 whiteWatch.removeStopwatchListener(gameThread);
035 }
036 if (blackWatch != null) {
037 blackWatch.removeStopwatchListener(gameThread);
038 }
039
040 whiteWatch = new Stopwatch(whiteTime);
041 blackWatch = new Stopwatch(blackTime);
042
043 timer = new Timer();
044 timer.scheduleAtFixedRate(whiteWatch, 100, 100);
045 timer.scheduleAtFixedRate(blackWatch, 100, 100);
046
047 whiteWatch.addStopwatchListener(gameThread);
048 blackWatch.addStopwatchListener(gameThread);
049 }
050
051 /**
052 * Switches the clock to the specified color. If the argument is Color.NONE,
053 * stops both watches.
054 */
055 public void switchClockTo(Color color) {
056 if (color == Color.WHITE) {
057 blackWatch.stop();
058 whiteWatch.start();
059 }
060 else if (color == Color.BLACK) {
061 whiteWatch.stop();
062 blackWatch.start();
063 }
064 else {
065 blackWatch.stop();
066 whiteWatch.stop();
067 }
068 }
069
070 /**
071 * Returns the Stopwatch object keeping track of white's time left.
072 */
073 public Stopwatch getWhiteWatch() {
074 return whiteWatch;
075 }
076
077 /**
078 * Returns the Stopwatch object keeping track of black's time left.
079 */
080 public Stopwatch getBlackWatch() {
081 return blackWatch;
082 }
083 }