forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15_2_pausing_the_game.html
More file actions
89 lines (80 loc) · 2.59 KB
/
15_2_pausing_the_game.html
File metadata and controls
89 lines (80 loc) · 2.59 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
<!doctype html>
<base href="http://eloquentjavascript.net/">
<script src="code/game_levels.js"></script>
<script src="code/chapter/15_game.js"></script>
<link rel="stylesheet" href="css/game.css">
<body>
<script>
// To know when to stop and restart the animation, a level that is
// being displayed may be in three states:
//
// * "yes": Running normally.
// * "no": Paused, animation isn't running
// * "pausing": Must pause, but animation is still running
//
// The key handler, when it notices escape being pressed, will do a
// different thing depending on the current state. When running is
// "yes" or "pausing", it will switch to the other of those two
// states. When it is "no", it will restart the animation and switch
// the state to "yes".
//
// The animation function, when state is "pausing", will set the state
// to "no" and return false to stop the animation.
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
var running = "yes";
function handleKey(event) {
if (event.keyCode == 27) {
if (running == "no") {
running = "yes";
runAnimation(animation);
} else if (running == "pausing") {
running = "yes";
} else if (running == "yes") {
running = "pausing";
}
}
}
addEventListener("keydown", handleKey);
var arrows = trackKeys(arrowCodes);
function animation(step) {
if (running == "pausing") {
running = "no";
return false;
}
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
// Here we remove all our event handlers
removeEventListener("keydown", handleKey);
arrows.unregister(); // (see change to trackKeys below)
if (andThen)
andThen(level.status);
return false;
}
}
runAnimation(animation);
}
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var state = event.type == "keydown";
pressed[codes[event.keyCode]] = state;
event.preventDefault();
}
}
addEventListener("keydown", handler);
addEventListener("keyup", handler);
// This is new -- it allows runLevel to clean up its handlers
pressed.unregister = function() {
removeEventListener("keydown", handler);
removeEventListener("keyup", handler);
};
// End of new code
return pressed;
}
runGame(GAME_LEVELS, DOMDisplay);
</script>
</body>