-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameController.java
More file actions
126 lines (109 loc) · 3.17 KB
/
GameController.java
File metadata and controls
126 lines (109 loc) · 3.17 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package snake.controller;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.SwingUtilities;
import snake.model.Direction;
import snake.model.Field;
import snake.view.View;
/**
* @author afeher
*/
public class GameController {
private Field[][] court;
private Player player;
private List<Direction> directions;
private boolean autoDirection;
private boolean started;
private Timer timer;
private int delay;
public void init(int width, int height) {
player = new Player();
court = player.introduce(createCourt(width, height));
directions = new LinkedList<>();
autoDirection = false;
started = false;
timer = null;
delay = 80;
}
private Field[][] createCourt(int x, int y) {
Field[][] court = new Field[x][y];
for (int col = 0; col < x; col++) {
for (int row = 0; row < y; row++) {
court[col][row] = new Field(col, row);
}
}
return court;
}
public Field[][] getCourt() {
return court;
}
public void turn(Direction direction) {
if (!directions.isEmpty() && directions.get(directions.size() - 1).isOpposite(direction)) {
return;
}
if (autoDirection) {
directions.clear();
}
directions.add(direction);
autoDirection = false;
}
public void start(final View view) {
started = true;
timer = new Timer("Snake-timer", true);
scheduleTimer(view);
}
private Direction getDirection() {
Direction direction = directions.get(0);
directions.remove(0);
if (directions.isEmpty()) {
directions.add(direction);
autoDirection = true;
}
return direction;
}
public boolean isInProgress() {
return player.isAlive();
}
public boolean isStarted() {
return started;
}
public void togglePause(View view) {
if (player.isAlive()) {
if (started) {
pause();
} else {
start(view);
}
}
}
private void scheduleTimer(final View view) {
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
if (started && player.isAlive()) {
court = player.tick(court, getDirection());
} else {
timer.cancel();
}
view.updateScene();
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}, delay, delay);
}
private void pause() {
timer.cancel();
timer.purge();
started = false;
}
}