-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameWindow.java
445 lines (360 loc) · 12.6 KB
/
GameWindow.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import java.util.Formatter;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class GameWindow extends JFrame implements WindowListener, KeyListener, SnakeAction {
private GamePanel gamePanel;
private JPanel statusPanel;
private Snake gameSnake;
private Rat gameRat;
private JLabel scoreLabel;
private JLabel timeLabel;
private JLabel speedLabel;
// for timer and user controls
private Timer countTimer, gameTimer;
private Direction currentDirection, lastDirection;
private int speed, score, elapsed, counts;
private boolean gameStarted, messageRepeat;
private JRadioButtonMenuItem lowSpeed;
private JRadioButtonMenuItem mediumSpeed;
private JRadioButtonMenuItem highSpeed;
public GameWindow() {
setResizable(false);
setIconImage((new ImageIcon("art/snake_head.png").getImage()));
// it's better to be have a fixed size :D
//setResizable(false);
// for key press
addKeyListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Snake Game");
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.X_AXIS)); // new FlowLayout());
initGamePanel();
initStatusPanel();
initMenuBar();
countTimer = new Timer(800, new CountTimerHandle());
gameTimer = new Timer(1, new GameTimerHandle());
setSpeed(150);
pack();
setSize(getWidth() + 30, getHeight());
setLocationRelativeTo(null);
reset();
}
public void initGamePanel() {
// init game panel
gamePanel = new GamePanel();
add(gamePanel);
}
public void initStatusPanel() {
// init status panel
statusPanel = new JPanel();
scoreLabel = new JLabel("0 x ",
new ImageIcon("art/rat.png"),
JLabel.CENTER);
scoreLabel.setHorizontalTextPosition(JLabel.LEFT);
scoreLabel.setVerticalTextPosition(JLabel.CENTER);
timeLabel = new JLabel("00:00", JLabel.CENTER);
speedLabel = new JLabel("Medium", JLabel.CENTER);
statusPanel.setLayout(new GridLayout(8, 1));//(new BoxLayout(statusPanel, BoxLayout.Y_AXIS)); // new FlowLayout()); //
statusPanel.add(new JLabel("Score", JLabel.CENTER));
statusPanel.add(scoreLabel);
statusPanel.add(new JLabel("________", JLabel.CENTER));
statusPanel.add(new JLabel("Time", JLabel.CENTER));
statusPanel.add(timeLabel);
statusPanel.add(new JLabel("________", JLabel.CENTER));
statusPanel.add(new JLabel("Speed", JLabel.CENTER));
statusPanel.add(speedLabel);
add(statusPanel);
}
public void initMenuBar() {
JMenuBar menuBar = new JMenuBar ();
JMenu gameMenu = new JMenu("Game");
JMenu speedMenu = new JMenu("Speed");
JMenu helpMenu = new JMenu("Help");
JMenuItem newGameItem = new JMenuItem("New game"); //, icon);
JMenuItem exitItem = new JMenuItem("Exit");
ButtonGroup speedGroup = new ButtonGroup();
lowSpeed = new JRadioButtonMenuItem("Low");
lowSpeed.setActionCommand("250");
mediumSpeed = new JRadioButtonMenuItem("Medium");
mediumSpeed.setActionCommand("150");
highSpeed = new JRadioButtonMenuItem("High");
highSpeed.setActionCommand("50");
mediumSpeed.setSelected(true);
speedGroup.add(lowSpeed);
speedGroup.add(mediumSpeed);
speedGroup.add(highSpeed);
JMenuItem showHelpItem = new JMenuItem("How to play");
JMenuItem aboutItem = new JMenuItem("About");
newGameItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
startNewGame();
}
});
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
exitGame();
}
});
showHelpItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "The following keyboard keys:\n\n - Enter: start a new game\n - Space: pause current game\n - Escape: stop current game\n - Arrows: turn", "How to play", JOptionPane.INFORMATION_MESSAGE);
}
});
aboutItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, "Snake Game\nVersion: 0.01\nCoding and Artwork:\n - Sherif Adel\n - Mahmoud Sayed\n - Abdelrahman Ghanem", "About the game", JOptionPane.INFORMATION_MESSAGE);
}
});
SpeedAction speedAction = new SpeedAction();
lowSpeed.addActionListener(speedAction);
mediumSpeed.addActionListener(speedAction);
highSpeed.addActionListener(speedAction);
gameMenu.add(newGameItem);
gameMenu.addSeparator();
gameMenu.add(exitItem);
speedMenu.add(lowSpeed);
speedMenu.add(mediumSpeed);
speedMenu.add(highSpeed);
helpMenu.add(showHelpItem);
helpMenu.add(aboutItem);
menuBar.add(gameMenu);
menuBar.add(speedMenu);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
newGameItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
reset();
}
});
}
private class SpeedAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
// don't change while playing
//if(gameStarted)
// return;
setSpeed(Integer.parseInt(event.getActionCommand()));
String speedText = ((JRadioButtonMenuItem) event.getSource()).getText();
if(speedLabel == null)
return;
speedLabel.setText(speedText);
}
}
public void reset() {
gameSnake = new Snake();
gameSnake.setSnakeActionListener(this);
// move to center
gameSnake.moveTo(Config.snakeX, Config.snakeY);
gameRat = new Rat(Config.panelWidth, Config.panelHeight);
gameRat.escapeFrom(gameSnake);
gamePanel.setSnake(gameSnake);
gamePanel.setRat(gameRat);
score = 0;
elapsed = 0;
counts = 3;
gameStarted = false;
messageRepeat = false;
scoreLabel.setText("0 x ");
updateElapsedTime();
setFocusable(true);
if(!gameStarted)
countTimer.start();
}
public void setSpeed(int s) {
speed = s;
if(gameTimer == null)
return;
gameTimer.setDelay(speed);
}
public void start() {
gameStarted = true;
countTimer.start();
}
public void stop() {
gameTimer.stop();
gameStarted = false;
reset();
}
public void pause() {
if(!gameStarted)
return;
if(gameTimer.isRunning())
gameTimer.stop();
else
gameTimer.start();
}
public void startNewGame() {
reset();
start();
}
public void updateElapsedTime() {
elapsed += speed;
// http://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-e-g-format-hmmss
timeLabel.setText(toTime(elapsed));
}
public String toTime(int msecs) {
int secs = msecs / 1000;
return String.format("%02d:%02d", secs / 60, secs % 60);
}
public void exitGame() {
countTimer.stop();
dispose();
}
@Override
public void keyTyped(KeyEvent event) {
}
// to stop timers when closed
@Override
public void windowClosing(WindowEvent event) {
countTimer.stop();
gameTimer.stop();
}
@Override
public void windowClosed(WindowEvent event) {
}
@Override
public void windowOpened(WindowEvent event) {
}
@Override
public void windowIconified(WindowEvent event) {
}
@Override
public void windowDeiconified(WindowEvent event) {
}
@Override
public void windowActivated(WindowEvent event) {
}
@Override
public void windowDeactivated(WindowEvent event) {
}
@Override
public void keyPressed(KeyEvent event) {
currentDirection = gameSnake.getDirection();
Direction d = currentDirection;
switch(event.getKeyCode()) {
case KeyEvent.VK_UP:
d = Direction.UP;
break;
case KeyEvent.VK_DOWN:
d = Direction.DOWN;
break;
case KeyEvent.VK_LEFT:
d = Direction.LEFT;
break;
case KeyEvent.VK_RIGHT:
d = Direction.RIGHT;
break;
case KeyEvent.VK_SPACE:
pause();
break;
case KeyEvent.VK_ENTER:
if(!gameStarted)
startNewGame();
break;
case KeyEvent.VK_ESCAPE:
if(gameStarted)
stop();
break;
default:
d = currentDirection;
break;
}
// return if the new direction is the same or reverse direction
if(d == currentDirection || d == gameSnake.reverseDirection(currentDirection))
return;
else
{
// this would response faster to user
// actions instead of waiting for timer
// to take the step
// and make the timer step
// if it's in the same direction only
gameSnake.setDirection(d);
gameSnake.step();
}
// step after would make two steps :D
// but if timer iterval is slow
// it would step later
// gameSnake.step();
}
@Override
public void keyReleased(KeyEvent event) {
}
@Override
public void snakeHitsRat() {
gameRat.escapeFrom(gameSnake);
gameSnake.addNormalPart();
scoreLabel.setText(++score + " x");
}
@Override
public void snakeHitsItself() {
stop();
JOptionPane.showMessageDialog(this, "Game Over!", "Try Again!", JOptionPane.ERROR_MESSAGE);
}
@Override
public void snakeHitsBorders() {
stop();
JOptionPane.showMessageDialog(this, "Game Over!", "Try Again!", JOptionPane.ERROR_MESSAGE);
}
@Override
public void partOutOfBorders(SnakePart part) {
}
private class CountTimerHandle implements ActionListener {
public void actionPerformed(ActionEvent event) {
if(!gameStarted) {
if(messageRepeat)
gamePanel.showMessage("Press Enter to Play!");
else
gamePanel.showMessage("");
messageRepeat = !messageRepeat;
}
else {
if(counts == 0) {
gamePanel.removeMessage();
gameTimer.start();
countTimer.stop();
return;
}
gamePanel.showMessage(Integer.toString(counts));
counts--;
}
}
}
private class GameTimerHandle implements ActionListener {
public void actionPerformed(ActionEvent event) {
// check for last direction then step
// if don't step if changed
// and call step() on the key event?
// this is way
// the next way have some delay, because the next step
// would wait the the timer to do
updateElapsedTime();
if(lastDirection == gameSnake.getDirection())
gameSnake.step();
lastDirection = gameSnake.getDirection();
gamePanel.repaint();
}
}
}