merge...
[AntiTD.git] / src / se / umu / cs / dit06ajnajs / ATDController.java
blob036e090a934713b73f9e4ef0766ce8408a5da8e9
1 package se.umu.cs.dit06ajnajs;
4 import java.awt.Graphics;
5 import java.awt.event.MouseAdapter;
6 import java.awt.event.MouseEvent;
8 import java.util.ArrayList;
9 import java.util.List;
10 import java.util.logging.Logger;
12 import java.awt.event.ActionEvent;
13 import java.awt.event.ActionListener;
14 import java.awt.event.WindowAdapter;
15 import java.awt.event.WindowEvent;
17 import se.umu.cs.dit06ajnajs.agent.Agent;
18 import se.umu.cs.dit06ajnajs.agent.AgentPrototypeFactory;
19 import se.umu.cs.dit06ajnajs.agent.Unit;
20 import se.umu.cs.dit06ajnajs.map.GoalSquare;
21 import se.umu.cs.dit06ajnajs.map.Level;
22 import se.umu.cs.dit06ajnajs.map.MapSquare;
23 import se.umu.cs.dit06ajnajs.map.StartSquare;
25 public class ATDController {
26 private static Logger logger = Logger.getLogger("AntiTD");
28 private final int FRAMES_PER_SECOND = 20;
30 private ATDModel model;
31 private ATDView view;
33 private boolean running;
34 private boolean clocking;
35 private Thread animationThread;
36 private Thread creditThread;
38 public ATDController(List<Level> levels) {
39 // Create model and view
40 this.model = new ATDModel(levels);
41 this.view = new ATDView(model);
42 connectListeners();
43 newGame();
46 public void newGame() {
47 // TODO: game related init
48 model.newGame();
50 this.running = true;
51 this.clocking = true;
52 this.animationThread = new Thread(new AnimationThread());
53 this.creditThread = new Thread(new CreditThread());
54 animationThread.start();
55 creditThread.start();
58 private class AnimationThread implements Runnable {
59 private long usedTime;
60 public AnimationThread() {
61 // Paint background
63 view.repaintGame();
66 /**
67 * While running, the thread loops through all actions the game can
68 * generate as many times per second determined by the final class
69 * variable FRAMES_PER_SECOND
71 public void run() {
72 // TODO Auto-generated method stub
73 while (running) {
74 long startTime = System.currentTimeMillis();
76 List<Agent> agents = model.getAgents();
77 List<Unit> units = new ArrayList<Unit>();
79 // Check for collisions
80 for (Agent agent : agents) {
81 // Extract all units
82 if (agent instanceof Unit) {
83 units.add((Unit)agent);
87 // Update all agents
88 List<Agent> deadAgents = new ArrayList<Agent>();
89 for (Agent agent : agents) {
90 if (agent.isAlive()) {
91 if (agent instanceof Unit) {
92 // Collisioncheck
93 for (Unit unit : units) {
94 if (agent != unit) {
95 if (((Unit) agent).intersectsNextMove(unit)) {
96 // Collision!
97 ((Unit) agent).collision(unit);
101 agent.act();
102 } else {
103 agent.act();
105 } else {
106 deadAgents.add(agent);
107 logger.info("Dead unit is collected to list deadAgents");
110 if (!deadAgents.isEmpty()) {
111 model.removeAgents(deadAgents);
112 logger.info("Dead agents cleared");
115 // Remove units from goalsquares and count points
116 GoalSquare[] goalSquares = model.getGoalSquares();
117 int credit = 0;
118 int numOfUnits = 0;
119 for (GoalSquare square : goalSquares) {
120 numOfUnits = square.getNumUnits();
121 credit += square.getCredit();
123 if (credit > 0 || numOfUnits > 0) {
124 model.addCredit(credit);
125 model.addGoalUnit(numOfUnits);
126 view.updateScoreboard();
129 // Release Unit from StartSquares
130 StartSquare[] startSquares = model.getStartSquares();
131 for (StartSquare startSquare : startSquares) {
132 Unit unitToStart = startSquare.getUnitToStart();
133 boolean unitToStartCollided = false;
134 if (unitToStart != null) {
135 for (Unit unit : units) {
136 unitToStartCollided = unitToStart.intersects(unit);
137 if (unitToStartCollided) {
138 // Collision
139 break;
142 if (!unitToStartCollided) {
143 // No collision found
144 startSquare.removeUnit(unitToStart);
146 model.releaseUnit(unitToStart);
151 // Repaint all agents
152 Graphics g = view.getGameGraphics();
153 for (Agent agent : agents) {
154 //TODO kan det finnas en agent som inte är paintable?
155 agent.paint(g);
158 // Refresh the game view
159 view.repaintGame();
161 this.usedTime = System.currentTimeMillis() - startTime;
162 // Try to keep a given number of frames per second.
163 try {
164 // TODO think, fps???
165 Thread.sleep((1000 - usedTime) / FRAMES_PER_SECOND);
166 } catch (InterruptedException e) {
167 System.err.println("Error in thread, exiting.");
168 return;
174 private class CreditThread implements Runnable {
175 public CreditThread() {
180 * While running, the thread sleeps for an interval and then calculates
181 * the earned credits from units on the map. The credits are then added
182 * to the player
184 public void run() {
185 while(clocking) {
186 try {
187 // Sleep an interval
188 Thread.sleep(1000);
190 // Calculate earned credits
191 int credit = calculateCredit();
192 if (credit > 0) {
193 model.addCredit(credit);
194 view.updateScoreboard();
197 // Goalcheck
198 if(model.isGoalReached()) {
199 clocking = false;
200 System.out.println("Victory! CreditThread is stopping...");
202 } catch (InterruptedException e) {
203 e.printStackTrace();
208 private int calculateCredit() {
209 List<Agent> agents = model.getAgents();
210 List<Unit> units = new ArrayList<Unit>();
211 for (Agent agent : agents) {
212 // Extract all units
213 if(agent instanceof Unit) {
214 units.add((Unit)agent);
217 int credit = units.size() * 10;
218 return credit;
222 /* Connect listeners to View *************************************/
224 private void connectListeners() {
225 this.view.addMapListener(new MapListener());
226 this.view.addClosingListener(new ClosingListener());
227 this.view.addReleaseUnitListener(new ReleaseUnitListener());
228 this.view.addPauseMenuItemListener(new PausResumeListener());
231 /* Inner Listener classes ****************************************/
233 private class MapListener extends MouseAdapter {
234 @Override
235 public void mouseClicked(MouseEvent me) {
236 final int x = me.getX();
237 final int y = me.getY();
239 // SwingUtilities.invokeLater(new Runnable() {
240 // public void run() {
241 // }
242 // });
243 Level level = model.getLevel();
244 final MapSquare square = level.getMapSquareAtPoint(x, y);
245 logger.info("Mouse clicked @ (" + x + ", " + y + ")");
246 logger.info("MapSquare @ " + square);
247 square.click();
248 view.updateBackgroundImage();
249 //if (square instanceof StartSquare) {}
250 //if (square instanceof TurnSquare) {}
254 private class ClosingListener extends WindowAdapter
255 implements ActionListener {
256 public void actionPerformed(ActionEvent ae) {
257 logger.info("Closing program");
258 System.exit(0);
261 @Override
262 public void windowClosing(WindowEvent we) {
263 logger.info("Closing program");
264 System.exit(0);
268 private class PausResumeListener implements ActionListener {
269 public void actionPerformed(ActionEvent ae) {
270 if (running) {
271 ATDController.this.running = false;
272 ATDController.this.clocking = false;
273 view.updatePauseMenu("Resume");
274 } else {
275 ATDController.this.running = true;
276 ATDController.this.clocking = true;
277 ATDController.this.animationThread
278 = new Thread(new AnimationThread());
279 ATDController.this.creditThread
280 = new Thread(new CreditThread());
281 animationThread.start();
282 creditThread.start();
283 view.updatePauseMenu("Pause");
288 private class ReleaseUnitListener implements ActionListener {
289 public void actionPerformed(ActionEvent ae) {
290 // Release Unit from active StartSquare
291 // TODO: implement
292 System.out.println("hej");
293 AgentPrototypeFactory factory = AgentPrototypeFactory.getInstance();
294 model.addUnit(factory.createUnit(view.getSelectedUnitType()));