summaryrefslogtreecommitdiffstats
path: root/src/jrummikub/control/TurnTimer.java
blob: ad55d9a33185cc3af5bf3830189b30681575e42a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package jrummikub.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import jrummikub.util.Event;
import jrummikub.util.IEvent;
import jrummikub.view.IView;

/**
 * Count-down timer used to limit the turn time
 */
public class TurnTimer implements ActionListener, ITurnTimer {
	private IView view;
	private int timeLeft;
	private int totalTime;
	private Timer timer;
	private Event timeRunOutEvent = new Event();

	/**
	 * Create a new timer using a given view to display the current time left
	 * 
	 * @param view
	 *            view to display
	 * @param totalTime
	 *            total time for turn
	 */
	public TurnTimer(IView view, int totalTime) {
		this.view = view;
		timeLeft = totalTime;
		this.totalTime = totalTime;
		timer = new Timer(1000, this);
		timer.setRepeats(true);
		timer.setCoalesce(false);
		view.getPlayerPanel().setTime(timeLeft, totalTime);
	}

	@Override
	public void startTimer() {
		timer.start();
	}

	@Override
	public void stopTimer() {
		timer.stop();
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		timeLeft--;
		view.getPlayerPanel().setTime(timeLeft, totalTime);
		if (timeLeft == 0) {
			timer.stop();
			timeRunOutEvent.emit();
		}
	}

	@Override
	public IEvent getTimeRunOutEvent() {
		return timeRunOutEvent;
	}
}