-
Notifications
You must be signed in to change notification settings - Fork 118
/
game.dart
134 lines (114 loc) · 2.5 KB
/
game.dart
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
import 'package:win32/win32.dart';
import 'canvas.dart';
import 'level.dart';
//
// Game flow
// Only Game and Canvas are exposed to main().
//
class Game {
final Canvas canvas;
Level level;
bool isPaused;
Game(this.canvas)
: isPaused = false,
level = Level(canvas);
bool get isGameOver => level.isGameOver;
/// Handles player's key press
bool keyPress(int vk) {
// When pausing, ignore keys other than PAUSE and ENTER
if (vk != VIRTUAL_KEY.VK_PAUSE && vk != VIRTUAL_KEY.VK_RETURN && isPaused) {
return false;
}
switch (vk) {
case VIRTUAL_KEY.VK_UP:
level.rotate();
case VIRTUAL_KEY.VK_DOWN:
level.move(0, -1);
case VIRTUAL_KEY.VK_LEFT:
level.move(-1, 0);
case VIRTUAL_KEY.VK_RIGHT:
level.move(1, 0);
case VIRTUAL_KEY.VK_SPACE:
level.rotate();
case VIRTUAL_KEY.VK_PAUSE:
if (isPaused) {
resumeGame();
} else {
pauseGame();
}
case VIRTUAL_KEY.VK_RETURN:
// You can only restart on game over
if (isGameOver) {
restart();
}
default:
return false;
}
return true;
}
void pauseGame() {
// Don't pause if game is over
if (isGameOver) return;
isPaused = true;
drawPause();
level
..drawScore()
..drawSpeed();
}
void resumeGame() {
if (isGameOver) return;
isPaused = false;
level
..drawScore()
..drawSpeed();
}
/// Called on WM_PAINT
void repaint() {
canvas.drawInterface();
level
..drawScore()
..drawSpeed()
..drawNextPiece()
..drawBoard();
if (isGameOver) {
drawGameOver();
} else if (isPaused) {
drawPause();
}
}
/// Updates data or graphics
void timerUpdate() {
// Don't update game when pausing
if (isPaused) {
return;
}
// If game is over, show GAME OVER
if (isGameOver) {
isPaused = true;
drawGameOver();
return;
}
// Update game data and redraw
level
..timerUpdate()
..drawBoard();
}
/// Restarts the game
void restart() {
level = Level(canvas);
isPaused = false;
repaint();
}
/// Shows GAME OVER message
void drawGameOver() {
canvas
..drawText('GAME OVER', 3, 10)
..drawText('Press ENTER to restart', 2, 9);
}
/// Shows PAUSE message
void drawPause() {
canvas
..drawText('PAUSE', 4, 10)
..drawText('Press PAUSE again to continue', 1, 9);
}
}