-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
495 lines (426 loc) · 12.8 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
;(function() {
function Game(canvas) {
var screen = canvas.getContext('2d');
this.size = { x: canvas.width, y: canvas.height };
this.color = this.COLORS.PURPLE;
this.bodies = [];
this.ship = new Ship(this);
this.addBody(this.ship);
this.lives = 3;
this.lastEarnedLife = 0;
this.score = 0;
this.level = 1;
this.numberOfEnemies = 0;
this.startLevel();
var _this = this;
// Infinite game loop.
function tick() {
// Update game state.
_this.update();
// Draw game bodies.
_this.draw(screen);
// Add next tick to browser queue.
requestAnimationFrame(tick);
}
// Call the first game tick.
tick();
}
Game.prototype = {
FULL_ROTATION: 2 * Math.PI,
POINTS_TO_NEXT_LIFE: 10000,
COLORS: {
PURPLE: '#504b6a',
TEAL: '#659893',
GREEN: '#acd268',
YELLOW: '#fdd284'
},
/**
* Updates the state of the game.
*/
update: function() {
var _this = this;
// Update each body.
this.bodies.forEach(function(body) {
body.update();
_this.wrapScreen(body);
});
// Check for collisions between any two bodies.
var collidingPairs = [];
this.pairsOfOpponents().forEach(function(pair) {
if (_this.colliding(pair[0], pair[1])) {
collidingPairs.push(pair);
}
});
// Kill each of the colliding bodies.
collidingPairs.forEach(function(pair) {
// Bullet can only destroy one object at a time.
if (!!pair[0].isDead || !!pair[1].isDead) return;
pair.forEach(function(body) {
body.die();
});
});
// Start the next level if the current level has been completed.
if (this.levelCompleted()) {
this.level++;
this.startLevel();
}
// Game over if there are no lives left.
if (this.lives <= 0) {
this.over();
}
},
/**
* Draws the game to the screen.
*/
draw: function(screen) {
screen.fillStyle = this.color;
screen.fillRect(0, 0, this.size.x, this.size.y);
// Draw each body.
this.bodies.forEach(function(body) {
body.draw(screen);
});
// Draw the ship lives.
for (var l = 0; l < this.lives; l++) {
var points = [
{ x: 22.5 + 20 * l, y: 20 + 5 },
{ x: 22.5 - 5 + 20 * l, y: 20 + 7.5 },
{ x: 22.5 + 20 * l, y: 20 - 7.5 },
{ x: 22.5 + 5.5 + 20 * l, y: 20 + 7.5 }
];
screen.lineWidth = 1;
screen.strokeStyle = this.COLORS.GREEN;
screen.beginPath();
screen.moveTo(points[0].x, points[0].y);
for (var i = 1; i < points.length; i++) {
screen.lineTo(points[i].x, points[i].y);
}
screen.closePath();
screen.stroke();
}
// Draw the score and level.
screen.font = '16px Helvetica';
screen.fillStyle = this.COLORS.YELLOW;
screen.fillText('score: ' + this.score, 15, 50);
screen.fillText('level: ' + this.level, 15, 70);
},
/**
* Adds a body to the list of game bodies.
*/
addBody: function(body) {
if (body.isEnemy) {
this.numberOfEnemies++;
}
this.bodies.push(body);
},
/**
* Removes a body from the list of game bodies.
*/
removeBody: function(body) {
if (body instanceof Ship) {
this.lives--;
// Create a new ship if there are lives remaining.
if (this.lives > 0) {
this.ship = new Ship(this);
this.addBody(this.ship);
}
} else if (body.isEnemy) {
this.numberOfEnemies--;
}
var i = this.bodies.indexOf(body);
this.bodies.splice(i, 1);
},
/**
* Returns a list of pairs of bodies where
* one is a friend and the other is an enemy.
*/
pairsOfOpponents: function() {
var pairs = [];
var friends = [];
var enemies = [];
this.bodies.forEach(function(body) {
if (body.isEnemy) {
enemies.push(body);
} else {
friends.push(body);
}
});
friends.forEach(function(friend) {
enemies.forEach(function(enemy) {
pairs.push([friend, enemy]);
});
});
return pairs;
},
/**
* Returns true if the body center is off-screen.
*/
offScreen: function(body) {
return body.center.x < 0 || body.center.x > this.size.x ||
body.center.y < 0 || body.center.y > this.size.y;
},
/**
* Wraps bodies around the screen while preserving the angle of the body.
*/
wrapScreen: function(body) {
if (this.offScreen(body)) {
// Wrap horizontally.
if (body.center.x < 0) {
body.center.x = this.size.x;
} else if (body.center.x > this.size.x) {
body.center.x = 0;
}
// Wrap vertically.
if (body.center.y < 0) {
body.center.y = this.size.y;
} else if (body.center.y > this.size.y) {
body.center.y = 0;
}
// Reset points and lines about the new center.
body.resetPoints();
body.resetLineSegments();
// Maintain the angle of the body.
this.trig.rotatePoints(body.points, body.center,
-body.angle + Math.PI / 2);
}
},
/**
* Checks if two bodies are colliding.
*/
colliding: function(b1, b2) {
var _this = this;
// Return true if some lines l1 and l2 intersect.
return b1.lineSegments.some(function(l1) {
return b2.lineSegments.some(function(l2) {
return _this.trig.lineIntersection(l1, l2);
});
});
},
/**
* Starts the current level.
*/
startLevel: function() {
// Add asteroids to the list of game bodies.
for (var i = 0; i < this.level; i++) {
this.addBody(new Asteroid(this, this.randomPoint(), 3));
}
// Add aliens to the list of game bodies.
if (this.level > 1) {
this.addBody(new Alien(this, 2));
this.addBody(new Alien(this, 1));
}
},
/**
* Returns true if the level has been completed.
*/
levelCompleted: function() {
return this.numberOfEnemies === 0;
},
/**
* Adds points to the game score.
*/
addToScore: function(points) {
this.score += points;
// Add a life if it has been earned.
if (this.earnedLife()) {
this.lives++;
this.lastEarnedLife = Math.round(this.score / this.POINTS_TO_NEXT_LIFE)
* this.POINTS_TO_NEXT_LIFE;
}
},
/**
* Returns true if player earned a life.
* One life is added for every POINTS_TO_NEXT_LIFE points.
*/
earnedLife: function() {
return this.score - this.lastEarnedLife >= this.POINTS_TO_NEXT_LIFE;
},
/**
* Handles events occurring when the game is over.
*/
over: function() {
// Stop updating the game.
this.update = function() {};
// Draw the game over screen.
this.draw = function(screen) {
screen.fillStyle = this.COLORS.TEAL;
screen.fillRect(0, 0, this.size.x, this.size.y);
screen.font = '20px Helvetica';
screen.fillStyle = 'white';
screen.fillText('game over', 250, 300);
// Draw the score and level.
screen.font = '16px Helvetica';
screen.fillStyle = this.COLORS.YELLOW;
screen.fillText('score: ' + this.score, 250, 320);
};
},
/**
* Returns a random point on the game screen.
*/
randomPoint: function() {
var randX = Math.random() * this.size.x;
var randY = Math.random() * this.size.y;
return { x: randX, y: randY };
},
/**
* Returns a random speed between 0 and 1.
*/
randomSpeed: function() {
return Math.random();
},
/**
* Returns a random angle between 0 and 2 PI.
*/
randomAngle: function() {
return Math.random() * this.FULL_ROTATION;
},
/**
* Returns a random angle, avoiding sharp horizontal or vertical axes.
*/
validAngle: function() {
/**
* Returns true if the given angle is in a 'bad' range.
*/
function inBadRange(angle) {
var e = Math.PI / 36;
var badRanges = [[ 0, 0 + e],
[ Math.PI / 2 - e, Math.PI / 2 + e],
[ Math.PI - e, Math.PI + e],
[3 * Math.PI / 2 - e, 3 * Math.PI / 2 + e],
[ 2 * Math.PI - e, 2 * Math.PI]];
return badRanges.some(function(range) {
return angle >= range[0] && angle <= range[1];
});
}
// Ensure that the angle returned is not in a 'bad' range.
var angle = 0;
do {
angle = this.randomAngle();
} while (inBadRange(angle))
return angle;
},
// Set of trig utility functions.
trig: {
/**
* Rotates a point about the center by the given angle.
*/
rotatePoint: function(point, center, angle) {
var p = { x: point.x, y: point.y };
point.x = Math.cos(angle) * (p.x - center.x)
- Math.sin(angle) * (p.y - center.y) + center.x;
point.y = Math.sin(angle) * (p.x - center.x)
+ Math.cos(angle) * (p.y - center.y) + center.y;
},
/**
* Performs rotatePoint on each point in points.
*/
rotatePoints: function(points, center, angle) {
var _this = this;
points.forEach(function(point) {
_this.rotatePoint(point, center, angle);
});
},
/**
* Moves a point with a certain speed and angle.
*/
translatePoint: function(point, speed, angle) {
point.x += speed * Math.cos(angle);
point.y += speed * -Math.sin(angle);
},
/**
* Performs translatePoint on each point in points.
*/
translatePoints: function(points, speed, angle) {
var _this = this;
points.forEach(function(point) {
_this.translatePoint(point, speed, angle);
});
},
/**
* Returns true if point p is on infinite line l.
*/
pointOnLine: function(p, l) {
var A = l.p2.y - l.p1.y;
var B = l.p1.x - l.p2.x;
var C = A * l.p1.x + B * l.p1.y;
var d = Math.abs(A * p.x + B * p.y - C);
var e = 1;
return this.pointInBounds(p, l) && d < e;
},
/**
* Returns true if point p is in the bounds of line segment l.
*/
pointInBounds: function(p, l) {
var x = p.x;
var y = p.y;
return x >= Math.min(l.p1.x, l.p2.x) &&
x <= Math.max(l.p1.x, l.p2.x) &&
y >= Math.min(l.p1.y, l.p2.y) &&
y <= Math.max(l.p1.y, l.p2.y);
},
/**
* Returns true if lines l1 and l2 intersect.
*/
lineIntersection: function(l1, l2) {
var A1 = l1.p2.y - l1.p1.y;
var B1 = l1.p1.x - l1.p2.x;
var C1 = A1 * l1.p1.x + B1 * l1.p1.y;
var A2 = l2.p2.y - l2.p1.y;
var B2 = l2.p1.x - l2.p2.x;
var C2 = A2 * l2.p1.x + B2 * l2.p1.y;
var det = A1 * B2 - A2 * B1;
if (det === 0) {
return null;
} else {
var x = (B2 * C1 - B1 * C2) / det;
var y = (A1 * C2 - A2 * C1) / det;
var intersection = { x: x, y: y };
if (this.pointInBounds(intersection, l1) &&
this.pointInBounds(intersection, l2)) {
return intersection;
}
}
},
/**
* Returns the coordinates of the given point relative to the given origin.
*/
relativeCoordinates: function(origin, point) {
return { x: point.x - origin.x, y: point.y - origin.y };
},
/**
* Returns the quadrant of the given relative point.
*/
relativeQuadrant: function(relativePoint) {
if (relativePoint.y <= 0) {
return relativePoint.x <= 0 ? 2 : 1;
} else {
return relativePoint.x <= 0 ? 3 : 4;
}
},
/**
* Returns the angle from the origin to the point in radians.
*/
angleToPoint: function(origin, point) {
var rel = this.relativeCoordinates(origin, point);
var quadrant = this.relativeQuadrant(rel);
var angle = Math.atan(-rel.y / rel.x);
switch (quadrant) {
case 1:
return angle;
case 2:
return angle + Math.PI;
case 3:
return angle + Math.PI;
case 4:
return angle + 2 * Math.PI;
default:
return Game.prototype.randomAngle();
}
}
}
};
// Start game.
window.onload = function() {
var canvas = document.getElementById('screen');
new Game(canvas);
};
})();