forked from JuanIrache/eloquent-javascript-exercises
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path16_3_monster.html
71 lines (62 loc) · 1.85 KB
/
16_3_monster.html
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
<link rel="stylesheet" href="css/game.css" />
<style>
.monster {
background: purple;
}
</style>
<body>
<script>
// Complete the constructor, update, and collide methods
class Monster {
constructor(pos, speed) {
this.pos = pos;
this.speed = speed;
}
get type() {
return 'monster';
}
static create(pos) {
return new Monster(pos.plus(new Vec(0, -1)), new Vec(2, 0));
}
update(time, state) {
let direction = 1;
let player = state.actors.filter(a => a.type === 'player')[0];
if (this.pos.x > player.pos.x) direction *= -1;
let newPos = this.pos.plus(this.speed.times(time * direction));
if (!state.level.touches(newPos, this.size, 'wall')) {
return new Monster(newPos, this.speed);
} else {
return new Monster(this.pos, this.speed);
}
}
collide(state) {
let player = state.actors.filter(a => a.type == 'player')[0];
if (player.pos.y + player.size.y / 4 <= this.pos.y - this.size.y / 4) {
let filtered = state.actors.filter(a => a != this);
return new State(state.level, filtered, state.status);
} else {
return new State(state.level, state.actors, 'lost');
}
}
}
Monster.prototype.size = new Vec(1.2, 2);
levelChars['M'] = Monster;
runLevel(
new Level(`
..................................
.################################.
.#..............................#.
.#..............................#.
.#..............................#.
.#...........................o..#.
.#..@...........................#.
.##########..............########.
..........#..o..o..o..o..#........
..........#...........M..#........
..........################........
..................................
`),
DOMDisplay
);
</script>
</body>