-
Notifications
You must be signed in to change notification settings - Fork 0
/
Controller.java
116 lines (100 loc) · 2.74 KB
/
Controller.java
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
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Timer;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
@SuppressWarnings("serial")
public class Controller {
// Create instances of the Model and View classes
private Model model;
private View view;
private boolean isStarted = false;
// Draw Delay between frames
private final int drawDelay = 50;
// The Action to be taken after every update
private Action drawAction;
public Controller(){
// Create new instances of Model and View
view = new View();
model = new Model(view.getWidth(), view.getHeight(), view.getImageWidth(), view.getImageHeight());
view.addStartStopListener(new StartStopListener());
view.addReverseListener(new ReverseListener());
view.addKeyInput(new KeyInput());
// Make our draw action update the Model and the View whenever called
drawAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (!isStarted){}
else {
model.updateLocationAndDirection();
view.update(model.getX(), model.getY(), model.getDirect());
}
}
};
}
// Key Input Listener
class KeyInput implements KeyListener{
@Override
public void keyPressed(KeyEvent keyEvent) {
int code = keyEvent.getKeyCode();
System.out.println(code);
if(code == 38){
//moveUp()
model.setDirect(Direction.NORTH);
}
else if(code == 37){
//moveLeft()
model.setDirect(Direction.WEST);
}
else if(code == 39){
//moveRight
model.setDirect(Direction.EAST);
}
else if(code == 40){
//moveDown()
model.setDirect(Direction.SOUTH);
}
else if(keyEvent.getKeyCode() == 68 /* D */ ){
//killOrc();
}
else if(keyEvent.getKeyCode() == 70 /* F */ ){
view.fire();
}
else if(keyEvent.getKeyCode() == 74 /* J */){
view.jump();
}
}
@Override
public void keyReleased(KeyEvent keyEvent) {
}
@Override
public void keyTyped(KeyEvent keyEvent){
}
}
// Listener
class ReverseListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
model.reverseDir();
view.refocus();
}
}
class StartStopListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
isStarted = !isStarted;
view.refocus();
}
}
//run the simulation
public void start(){
EventQueue.invokeLater(new Runnable(){
public void run() {
// Creates a timer that calls our drawAction every 50 ms.
Timer t = new Timer(drawDelay, drawAction);
// Starts the timer.
t.start();
}
});
}
}