-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.java
More file actions
70 lines (62 loc) · 2.39 KB
/
Copy pathSnakeGame.java
File metadata and controls
70 lines (62 loc) · 2.39 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
package Phase7_Concurrency.Multithreading.SnakeGame;
import javax.swing.*;
/**
* SnakeGame — main runner.
* <p>
*
* Demonstrates the canonical "GUI + simulation" thread split:
* <p>
*
* - Swing's EVENT-DISPATCH THREAD (EDT) builds the JFrame, owns the
* SnakeBoard, dispatches input, paints frames.
* - A SEPARATE GAME-LOOP THREAD ticks the simulation at a steady rate
* and asks the EDT to repaint via SwingUtilities.invokeLater.
* - The shared GameState is guarded by a ReentrantLock so the two
* threads never tear each other's view of the world.
* <p>
*
* Lifecycle
* ---------
* 1. main() invokeAndWait's onto the EDT to build the UI.
* 2. Once the JFrame is visible, main starts the GameLoop thread.
* 3. On window close, main stops the loop and joins the thread.
* <p>
*
* Tweakables
* ----------
* - TICK_MS is the simulation period (lower = harder).
*/
public final class SnakeGame {
private static final long TICK_MS = 110;
public static void main(String[] args) throws Exception {
// 1. Build the UI on the EDT.
GameState state = new GameState();
SnakeBoard board = new SnakeBoard(state);
JFrame[] frameHolder = new JFrame[1];
SwingUtilities.invokeAndWait(() -> {
JFrame f = new JFrame("Snake — multithreading demo");
f.add(board);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setVisible(true);
board.requestFocusInWindow();
frameHolder[0] = f;
});
// 2. Spin the simulation thread.
GameLoop loop = new GameLoop(state, board, TICK_MS);
Thread loopThread = new Thread(loop, "snake-game-loop");
loopThread.setDaemon(false); // don't let the JVM kill it mid-frame
loopThread.start();
// 3. Stop the loop cleanly when the window closes.
frameHolder[0].addWindowListener(new java.awt.event.WindowAdapter() {
@Override public void windowClosed(java.awt.event.WindowEvent e) {
loop.stop();
loopThread.interrupt();
try { loopThread.join(); } catch (InterruptedException ignored) {}
}
});
// Reset hook so the board can refocus after R is pressed.
board.setOnReset(board::requestFocusInWindow);
}
}