-
Notifications
You must be signed in to change notification settings - Fork 2
/
SpaceInvaders.dart
61 lines (53 loc) · 1.5 KB
/
SpaceInvaders.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
#import('dart:html');
#source('Game.dart');
#source('Player.dart');
#source('Rocket.dart');
#source('Enemy.dart');
#source('EnemyRow.dart');
#source('GameDrawer.dart');
#source('Directions.dart');
#source('ScreenObject.dart');
CanvasElement canvas;
ButtonElement startButton, stopButton;
Game game;
void main() {
canvas = query('#canvas');
startButton = query('#start-button');
startButton.on.click.add(startGame);
stopButton = query('#stop-button');
stopButton.on.click.add(stopGame);
}
void startGame(MouseEvent event) {
toggleButtons();
/* Start game when images are done loading. */
loadImages(['player', 'enemy', 'rocket'], (images) {
game = new Game(canvas, images['player'], images['enemy'], images['rocket']);
game.setup();
game.start();
});
}
void stopGame(MouseEvent event) {
toggleButtons();
game.stop();
game = null;
}
/**
* Since images are not loaded in the constructor of ImageElement
* we have to wait for them to load and use a callback when all
* images have been loaded.
*/
void loadImages(List<String> sources, callback) {
Map<String, ImageElement> images = new Map<String, ImageElement>();
for (String source in sources) {
ImageElement img = new ImageElement('img/${source}.png');
img.on.load.add((event) {
images.putIfAbsent(source, () => img);
if (images.length == sources.length)
callback(images);
});
}
}
void toggleButtons() {
startButton.disabled = ! startButton.disabled;
stopButton.disabled = ! stopButton.disabled;
}