-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
598 lines (556 loc) · 27.6 KB
/
game.js
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*
Based on Dark Blue by Thomas Palef.
Plans are submitted as an array of strings that forms a grid.
@ = Player start position
o = Coins
x = Solid surfaces
! = Non-moving lava
= = Vertical moving lava
v = Dripping lava
| = Horizontal moving lava
*/
var simpleLevelPlan = [
" ",
" ",
" x = x ",
" x o o x ",
" x @ xxxxx x ",
" xxxxx x ",
" x!!!!!!!!!!!!x ",
" xxxxxxxxxxxxxx ",
" "
];
var GAME_LEVELS = [
[" ",
" ",
" ",
" ",
" ",
" ",
" xxx ",
" xx xx xx!xx ",
" o o xx x!!!x ",
" xx!xx ",
" xxxxx xvx ",
" xx ",
" xx o o x ",
" x o x ",
" x xxxxx o x ",
" x xxxx o x ",
" x @ x x xxxxx x ",
" xxxxxxxxxxxx xxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx xxxxxxx xxxxxxxxx ",
" x x x x ",
" x!!!x x!!!!!x ",
" x!!!x x!!!!!x ",
" xxxxx xxxxxxx ",
" ",
" "],
[" x!!x xxxxxxx x!x ",
" x!!x xxxx xxxx x!x ",
" x!!xxxxxxxxxx xx xx x!x ",
" xx!!!!!!!!!!xx xx xx x!x ",
" xxxxxxxxxx!!x x o o o x!x ",
" xx!x x o o xx!x ",
" x!x x xxxxxxxxxxxxxxx!!x ",
" xvx x x x !!!!!!!!!!!!!!xx ",
" xx | | | xx xxxxxxxxxxxxxxxxxxxxx ",
" xx!!!!!!!!!!!xx v ",
" xxxx!!!!!xxxx ",
" x x xxxxxxx xxx xxx ",
" x x x x x x ",
" x x x x ",
" x x xx x ",
" xx x x x ",
" x x o o x x x x ",
" xxxxxxx xxx xxx x x x x x x ",
" xx xx x x x x xxxxxx x x xxxxxxxxx x ",
" xx xx x o x x xx x x x x ",
" @ x x x x x x x x x x ",
" xxx x x x x x x x xxxxx xxxxxx x ",
" x x x x xx o xx x x x o x x x ",
"!!!!x x!!!!!!x x!!!!!!xx xx!!!!!!!!xx x!!!!!!!!!! x = x x x ",
"!!!!x x!!!!!!x x!!!!!xx xxxxxxxxxx x!!!!!!!xx! xxxxxxxxxxxxx xx o o xx ",
"!!!!x x!!!!!!x x!!!!!x o xx!!!!!!xx ! xx xx ",
"!!!!x x!!!!!!x x!!!!!x xx!!!!!!xx ! xxxxxxx ",
"!!!!x x!!!!!!x x!!!!!xx xxxxxxxxxxxxxx!!!!!!xx ! ",
"!!!!x x!!!!!!x x!!!!!!xxxxxxxxx!!!!!!!!!!!!!!!!!!xx ! ",
"!!!!x x!!!!!!x x!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!xx ! "],
[" ",
" ",
" ",
" ",
" ",
" o ",
" ",
" x ",
" x ",
" x ",
" x ",
" xxx ",
" x x !!! !!! xxx ",
" x x !x! !x! ",
" xxx xxx x x ",
" x x x oooo x xxx ",
" x x x x x!!!x ",
" x x xxxxxxxxxxxx xxx ",
" xx xx x x x ",
" x xxxxxxxxx xxxxxxxx x x ",
" x x x x!!!x ",
" x x x xxx ",
" xx xx x ",
" x x= = = = x xxx ",
" x x x x!!!x ",
" x x = = = =x o xxx xxx ",
" xx xx x x!!!x ",
" o o x x x x xxv xxx ",
" x x x x x!!!x ",
" xxx xxx xxx xxx o o x!!!!!!!!!!!!!!x vx ",
" x xxx x x xxx x x!!!!!!!!!!!!!!x ",
" x x xxxxxxxxxxxxxxxxxxxxxxx ",
" xx xx xxx ",
" xxx x x x x!!!x xxx ",
" x x x xxx x xxx x x ",
" x x xxx xxxxxxx xxxxx x ",
" x x x x x x ",
" x xx x x x x x ",
" x x |xxxx| |xxxx| xxx xxx x ",
" x xxx o o x x xxx x ",
" x xxxxx xx x xxx x!!!x x x ",
" x oxxxo x xxx x x x xxx xxx x ",
" x xxx xxxxxxxxxxxxx x oo x x oo x x oo xx xx xxx x ",
" x @ x x x!!x x!!!!x x!!!!x xx xx x x ",
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ",
" ",
" "],
[" xxx x ",
" x ",
" xxxxx ",
" x ",
" x xxx ",
" o x x x ",
" o o oxxx x ",
" xxx x ",
" ! o ! xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx ",
" x x x x x x x x x x x x x x x ",
" x= o x x xxx x xxx x xxx x xxx x xxx x xxx x xxxxx ",
" x x x x x x x x x x x x x x x ",
" ! o ! o xxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxxxx ",
" ",
" o xxx xx ",
" ",
" ",
" xx ",
" xxx xxx ",
" ",
" o x x ",
" xx xx ",
" xxx xxx xxx x x ",
" ",
" || ",
" xxxxxxxxxxx ",
" x x o xxxxxxxxx o xxxxxxxxx o xx x ",
" x x x x x x x || x x ",
" x @ xxxxx o xxxxx o xxxxx ",
" xxxxxxx xxxxx xx xx xxx ",
" x= = =x x xxx ",
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx x!!!!!!!!!!!!!!!!!!!!!xxx!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",
" xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
" "]
];
// Assumes the plan is valid (add validation for production)
function Level(plan) {
this.width = plan[0].length;
this.height = plan.length;
// Array of arrays, each position containing null or a character
this.grid = [];
// Contains all of the dynamic objects (lava, coin or player),
// along with their position and state
this.actors = [];
for (var y = 0; y < this.height; y++) {
var line = plan[y], gridLine = [];
for (var x = 0; x < this.width; x++) {
var ch = line[x], fieldType = null;
var Actor = actorChars[ch];
if (Actor)
// This constructs the referenced moving object in
// actorChars and pushes it to the actors array
this.actors.push(new Actor(new Vector(x, y), ch));
else if (ch == 'x')
// Wall
fieldType = 'wall';
else if (ch == '!')
// Stationary lava
fieldType = 'lava';
gridLine.push(fieldType);
}
this.grid.push(gridLine);
}
// Find the Player actor
this.player = this.actors.filter(function(actor) {
return actor.type == 'player';
})[0];
// Track whether the player has won or lost;
// finishDelay keeps the level active for a brief period of time
this.status = this.finishDelay = null;
}
// Figure out if the level is finished
Level.prototype.isFinished = function() {
return this.status != null && this.finishDelay < 0;
};
// Figure out the collision area of an actor
Level.prototype.obstacleAt = function(pos, size) {
var xStart = Math.floor(pos.x);
var xEnd = Math.ceil(pos.x + size.x);
var yStart = Math.floor(pos.y);
var yEnd = Math.ceil(pos.y + size.y);
// The upper and side bounds of the level return a wall
if (xStart < 0 || xEnd > this.width || yStart < 0)
return 'wall';
// The bottom bound returns lava
if (yEnd > this.height)
return 'lava';
// Check what's on the grid around the collision box
for (var y = yStart; y < yEnd; y++) {
for (var x = xStart; x < xEnd; x++) {
var fieldType = this.grid[y][x];
// returns 'wall' or 'lava'
if (fieldType) return fieldType;
}
}
};
// Track what actors overlap a given actor
Level.prototype.actorAt = function(actor) {
for (var i = 0; i < this.actors.length; i++) {
var other = this.actors[i];
if (other != actor &&
actor.pos.x + actor.size.x > other.pos.x &&
actor.pos.x < other.pos.x + other.size.x &&
actor.pos.y + actor.size.y > other.pos.y &&
actor.pos.y < other.pos.y + other.size.y)
return other;
}
};
// Time increment for Level.animate()
var maxStep = 0.05;
// Animate the level
// step will be given in seconds, keys is an object that
// contains info about the arrow keys the player has pressed.
Level.prototype.animate = function(step, keys) {
// Used for the delay at the end of a game
if (this.status != null)
this.finishDelay -= step;
while (step > 0) {
var thisStep = Math.min(step, maxStep);
this.actors.forEach(function(actor) {
actor.act(thisStep, this, keys);
}, this);
step -= thisStep;
}
};
// Handle collisions between actors
Level.prototype.playerTouched = function(type, actor) {
// Lava's been touched
if (type == 'lava' && this.status == null) {
this.status = 'lost';
this.finishDelay = 1;
} else if (type == 'coin') { // a coin's been touched
// Remove the coin that's been collected from actors array
this.actors = this.actors.filter(function(other) {
return other != actor;
});
// No more coins = you've won
if (!this.actors.some(function(actor) {
return actor.type == 'coin';
})) {
this.status = 'won';
this.finishDelay = 1;
}
}
}
var actorChars = {
'@': Player,
'o': Coin,
'=': Lava, '|': Lava, 'v': Lava
};
// Vector stores the position and size of an actor
function Vector(x, y) {
this.x = x; this.y = y;
}
Vector.prototype.plus = function(other) {
return new Vector(this.x + other.x, this.y + other.y);
}
Vector.prototype.times = function(factor) {
return new Vector(this.x * factor, this.y * factor);
}
// Player constructor
function Player(pos) {
// This properly aligns the bottom of the player
// to the square below (adjusts for player height)
this.pos = pos.plus(new Vector(0, -0.5));
this.size = new Vector(0.8, 1.5);
this.speed = new Vector(0, 0);
}
Player.prototype.type = 'player';
// X and Y movement are handled independently because
// a wall shouldn't stop the up and down motion of jumping
// and a floor shouldn't stop side to side movement
var playerXSpeed = 7;
Player.prototype.moveX = function(step, level, keys) {
this.speed.x = 0;
if (keys.left) this.speed.x -= playerXSpeed;
if (keys.right) this.speed.x += playerXSpeed;
var motion = new Vector(this.speed.x * step, 0);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle)
level.playerTouched(obstacle);
else
this.pos = newPos;
};
var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function(step, level, keys) {
this.speed.y += step * gravity;
var motion = new Vector(0, this.speed.y * step);
var newPos = this.pos.plus(motion);
var obstacle = level.obstacleAt(newPos, this.size);
if (obstacle) {
level.playerTouched(obstacle);
if (keys.up && this.speed.y > 0)
this.speed.y = -jumpSpeed;
else
this.speed.y = 0;
} else {
this.pos = newPos;
}
};
Player.prototype.act = function(step, level, keys) {
this.moveX(step, level, keys);
this.moveY(step, level, keys);
var otherActor = level.actorAt(this);
if (otherActor)
level.playerTouched(otherActor.type, otherActor);
// Losing animation
if (level.status == 'lost') {
this.pos.y += step;
this.size.y -=step;
}
};
// Lava constructor
function Lava(pos, ch) {
this.pos = pos;
this.size = new Vector(1, 1);
if (ch == "=") {
// I'm guessing that speed will be added to this.pos
// in a moving method added later
this.speed = new Vector(2, 0);
} else if (ch == '|') {
this.speed = new Vector(0, 2);
} else if (ch == 'v') {
this.speed = new Vector(0, 3);
this.repeatPos = pos;
}
}
Lava.prototype.type = 'lava';
// Action
Lava.prototype.act = function(step, level) {
var newPos = this.pos.plus(this.speed.times(step));
if (!level.obstacleAt(newPos, this.size))
this.pos = newPos;
else if (this.repeatPos)
this.pos = this.repeatPos;
else
this.speed = this.speed.times(-1);
};
// Coin constructor
function Coin(pos) {
this.basePos = this.pos = pos.plus(new Vector(0.2, 0.1));
this.size = new Vector(0.6, 0.6);
this.wobble = Math.random() * Math.PI * 2;
}
Coin.prototype.type = 'coin';
var wobbleSpeed = 8, wobbleDist = 0.07;
// Action
Coin.prototype.act = function(step) {
this.wobble += step * wobbleSpeed;
var wobblePos = Math.sin(this.wobble) * wobbleDist;
this.pos = this.basePos.plus(new Vector(0, wobblePos));
};
// Helper function that creates an element
// and gives it a class
function elt(name, className) {
var elt = document.createElement(name);
if (className) elt.className = className;
return elt;
}
// Tracking keypresses for player movement
var arrowCodes = {37: 'left', 38: 'up', 39: 'right'};
function trackKeys(codes) {
var pressed = Object.create(null);
function handler(event) {
if (codes.hasOwnProperty(event.keyCode)) {
var down = event.type == 'keydown';
pressed[codes[event.keyCode]] = down;
event.preventDefault();
}
}
addEventListener('keydown', handler);
addEventListener('keyup', handler);
pressed.unregister = function() {
removeEventListener('keydown', handler);
removeEventListener('keyup', handler);
};
return pressed;
}
// Run the animation
function runAnimation(frameFunc) {
var lastTime = null;
function frame(time) {
var stop = false;
if (lastTime != null) {
var timeStep = Math.min(time - lastTime, 100) / 1000;
stop = frameFunc(timeStep) === false;
}
lastTime = time;
if (!stop)
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
// Run the level
var arrows = trackKeys(arrowCodes);
function runLevel(level, Display, andThen) {
var display = new Display(document.body, level);
// Used for storing pause state of the game
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);
function animation(step) {
if (running == 'pausing') {
running = 'no';
return false;
}
level.animate(step, arrows);
display.drawFrame(step);
if (level.isFinished()) {
display.clear();
// Remove the watch on the esc key
//removeEventListener('keydown', handleKey);
// Unregister the arrow key listeners
//arrows.unregister();
if (andThen)
andThen(level.status);
return false;
}
}
runAnimation(animation);
}
// Run the game
function runGame(plans, Display) {
var lives = 3;
var livesSpan = document.getElementById('lives');
var gameStatus = document.getElementById('status');
function startLevel(n) {
livesSpan.textContent = lives;
runLevel(new Level(plans[n]), Display, function(status) {
if (status == 'lost') {
lives--;
if (lives == 0) {
gameStatus.textContent = 'Game Over';
console.log('Game over');
}
else
startLevel(n);
}
else if (n < plans.length - 1)
startLevel(n + 1);
else
console.log('You win!');
});
}
startLevel(0);
}
// DOMDisplay uses the DOM to draw the program out
function DOMDisplay(parent, level) {
this.wrap = parent.appendChild(elt('div', 'game'));
this.level = level;
// Background is drawn only once
this.wrap.appendChild(this.drawBackground());
// The actorLayer is animated in the drawFrame() method
this.actorLayer = null;
this.drawFrame();
}
// Set the scale of 1 grid unit
var scale = 20;
// Draw the background
DOMDisplay.prototype.drawBackground = function() {
var table = elt('table', 'background');
table.style.width = this.level.width * scale + 'px';
this.level.grid.forEach(function(row) {
var rowElt = table.appendChild(elt('tr'));
rowElt.style.height = scale + 'px';
row.forEach(function(type) {
rowElt.appendChild(elt('td', type));
});
});
return table;
};
// Draw the actors
DOMDisplay.prototype.drawActors = function() {
var wrap = elt('div');
this.level.actors.forEach(function(actor) {
var rect = wrap.appendChild(elt('div', 'actor ' + actor.type));
rect.style.width = actor.size.x * scale + 'px';
rect.style.height = actor.size.y * scale + 'px';
rect.style.left = actor.pos.x * scale + 'px';
rect.style.top = actor.pos.y * scale + 'px';
});
return wrap;
};
// Redraw the actors
DOMDisplay.prototype.drawFrame = function() {
if (this.actorLayer)
this.wrap.removeChild(this.actorLayer);
this.actorLayer = this.wrap.appendChild(this.drawActors());
// The status class is used to style the player based on
// the state of the game (won or lost)
this.wrap.className = 'game ' + (this.level.status || '');
this.scrollPlayerIntoView();
};
// Make sure the player's always on screen
DOMDisplay.prototype.scrollPlayerIntoView = function() {
var width = this.wrap.clientWidth;
var height = this.wrap.clientHeight;
var margin = width / 3;
// The viewport
var left = this.wrap.scrollLeft, right = left + width;
var top = this.wrap.scrollTop, bottom = top + height;
// center makes use of the Vector methods defined earlier
var player = this.level.player;
var center = player.pos.plus(player.size.times(0.5))
.times(scale);
if (center.x < left + margin)
this.wrap.scrollLeft = center.x - margin;
else if (center.x > right - margin)
this.wrap.scrollLeft = center.x + margin - width;
if (center.y < top + margin)
this.wrap.scrollTop = center.y - margin;
else if (center.y > bottom - margin)
this.wrap.scrollTop = center.y + margin - height;
}
// Clear the level
DOMDisplay.prototype.clear = function() {
this.wrap.parentNode.removeChild(this.wrap);
};
runGame(GAME_LEVELS, DOMDisplay);