-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScene.ts
More file actions
647 lines (528 loc) · 22.6 KB
/
Scene.ts
File metadata and controls
647 lines (528 loc) · 22.6 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
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import { GameConstants } from './GameConstants';
import { Ship } from './Ship';
import { RobotShip } from './RobotShip';
import { GameInterface } from './GameInterface';
import { Sounds } from './Sounds';
const enum GameState {
BeforeStart,
Running,
Respawning,
GameOver
}
interface TorpedoProperties {
targetX: number;
targetY: number;
destinationMarker?: Phaser.GameObjects.Graphics;
emitter: Phaser.GameObjects.Particles.ParticleEmitter;
}
type ArcadeBody = Phaser.Types.Physics.Arcade.GameObjectWithBody | Phaser.Physics.Arcade.Body | Phaser.Physics.Arcade.StaticBody | Phaser.Tilemaps.Tile;
export class Scene extends Phaser.Scene implements GameInterface {
public player!: Ship;
public readonly torpedoes = new Map<Phaser.GameObjects.Graphics, TorpedoProperties>();
private readonly robotPlayers = new Array<RobotShip>();
private starfield!: Phaser.GameObjects.Graphics;
private asteroids!: Phaser.Physics.Arcade.StaticGroup;
private torpedoGroup!: Phaser.Physics.Arcade.Group;
private readonly explosions = new Set<Phaser.Math.Vector2>();
private gameState = GameState.BeforeStart;
public difficulty = 'easy';
public enemyCount = GameConstants.enemyShipCount;
private readonly lastPointerDown = new Phaser.Math.Vector2(-1, -1);
private static readonly shipDimensions = [7.5, 0, 0, 25, 15, 25]
private readonly gameEvents = new Phaser.Events.EventEmitter();
private readonly sounds = new Sounds(this.gameEvents);
constructor() {
super({
key: 'game',
});
}
init(data: { difficulty: string, enemyCount: number }) {
this.difficulty = data.difficulty;
this.enemyCount = data.enemyCount;
console.log(`Difficulty: ${this.difficulty}, Enemy count: ${this.enemyCount}`);
}
preload() {
if (!this.textures.exists('red')) {
const canvas = this.textures.createCanvas('red', 2, 2);
if (canvas !== null) {
const context = canvas.getContext();
// Draw 4 red pixels
context.fillStyle = '#FF0000';
context.fillRect(0, 0, 2, 2);
// Refresh the texture to apply the changes
canvas.refresh();
}
}
if (!this.textures.exists('asteroid_0')) {
for (let i = 0; i < 5; i++) {
this.createAsteroidTexture(`asteroid_${i}`);
}
}
this.sounds.preload(this);
}
createAsteroidTexture(key: string) {
const size = 100;
const canvas = this.textures.createCanvas(key, size, size);
if (canvas === null) return;
const context = canvas.getContext();
const centerX = size / 2;
const centerY = size / 2;
const radius = size / 2 - 5; // Leave some padding
// Draw jagged asteroid shape
context.fillStyle = '#888888';
context.beginPath();
const points = 16;
for (let i = 0; i < points; i++) {
const angle = (i / points) * Math.PI * 2;
const variance = Phaser.Math.FloatBetween(0.9, 1.0);
const r = radius * variance;
const x = centerX + Math.cos(angle) * r;
const y = centerY + Math.sin(angle) * r;
if (i === 0) context.moveTo(x, y);
else context.lineTo(x, y);
}
context.closePath();
context.fill();
// Add craters
context.globalCompositeOperation = 'source-atop';
const craterCount = Phaser.Math.Between(3, 6);
for (let i = 0; i < craterCount; i++) {
const cx = Phaser.Math.Between(10, size - 10);
const cy = Phaser.Math.Between(10, size - 10);
const cr = Phaser.Math.Between(5, 15);
context.fillStyle = '#666666';
context.beginPath();
context.arc(cx, cy, cr, 0, Math.PI * 2);
context.fill();
// Crater shadow
context.fillStyle = '#555555';
context.beginPath();
context.arc(cx + 2, cy + 2, cr * 0.8, 0, Math.PI * 2);
context.fill();
}
// Add surface noise/texture
for (let i = 0; i < 100; i++) {
const nx = Phaser.Math.Between(0, size);
const ny = Phaser.Math.Between(0, size);
context.fillStyle = Phaser.Math.RND.pick(['#777777', '#999999']);
context.fillRect(nx, ny, 2, 2);
}
context.globalCompositeOperation = 'source-over';
canvas.refresh();
}
create() {
this.gameState = GameState.BeforeStart;
// Create starfield background
this.starfield = this.add.graphics();
for (let i = 0; i < 6000; i++) {
const x = Phaser.Math.Between(0, GameConstants.boundaryWidth);
const y = Phaser.Math.Between(0, GameConstants.boundaryHeight);
const greyValue = Phaser.Math.Between(100, 255); // Random grey value
this.starfield.fillStyle(Phaser.Display.Color.GetColor(greyValue, greyValue, greyValue), 1);
this.starfield.fillPoint(x, y, 2);
}
// Create asteroids
this.asteroids = this.physics.add.staticGroup();
this.torpedoGroup = this.physics.add.group();
const safeZones: { x: number, y: number, radius: number }[] = [];
// Player safe zone
safeZones.push({ x: GameConstants.boundaryWidth / 2, y: GameConstants.boundaryHeight / 2, radius: 200 });
// Robot ships safe zones
const center = new Phaser.Math.Vector2(GameConstants.boundaryWidth / 2, GameConstants.boundaryHeight / 2);
const angleStep = Math.PI * 2 / this.enemyCount;
const radius = 400;
for (let i = 0; i < this.enemyCount; i++) {
const angle = angleStep * i;
const position = center.clone().setToPolar(angle, radius);
safeZones.push({ x: position.x, y: position.y, radius: 200 });
}
for (let i = 0; i < GameConstants.asteroidCount; i++) {
let x = 0;
let y = 0;
let safe = false;
while (!safe) {
x = Phaser.Math.Between(0, GameConstants.boundaryWidth);
y = Phaser.Math.Between(0, GameConstants.boundaryHeight);
safe = true;
for (const zone of safeZones) {
if (Phaser.Math.Distance.Between(x, y, zone.x, zone.y) < zone.radius) {
safe = false;
break;
}
}
}
const size = Phaser.Math.Between(10, 50); // Random size
const textureKey = `asteroid_${Phaser.Math.Between(0, 4)}`;
const asteroid = this.asteroids.create(x, y, textureKey);
asteroid.setDisplaySize(size * 2, size * 2);
asteroid.refreshBody();
const scale = (size * 2) / 100;
asteroid.setCircle(40 * scale, 10 * scale, 10 * scale);
}
this.physics.add.overlap(this.torpedoGroup, this.asteroids, this.handleTorpedoAsteroidCollision, undefined, this);
const poly = this.add.polygon(GameConstants.boundaryWidth / 2, GameConstants.boundaryHeight / 2, Scene.shipDimensions, 0xaaaaaa);
this.physics.add.existing(poly);
this.player = new Ship(poly, this.add.graphics());
this.physics.add.collider(this.player.polygon, this.asteroids, this.handleAsteroidCollision, undefined, this);
this.addRobotShips();
this.input.on('pointerdown', (pointer: Phaser.Input.Pointer) => { this.onPointerDown(pointer); });
this.input.on('pointerup', (pointer: Phaser.Input.Pointer) => { this.onPointerUp(pointer); });
// Make the camera follow the player
this.cameras.main.startFollow(this.player.polygon);
this.cameras.main.setDeadzone(100, 100);
for (const robotPlayer of this.robotPlayers) {
robotPlayer.start(this, this);
}
this.sounds.create(this);
this.gameState = GameState.Running;
}
onPointerDown(pointer: Phaser.Input.Pointer) {
if (this.gameState !== GameState.Running) {
return;
}
this.lastPointerDown.set(pointer.x, pointer.y);
}
onPointerUp(pointer: Phaser.Input.Pointer) {
if (this.gameState !== GameState.Running) {
return;
}
// last pointer down is not from this game
if (this.lastPointerDown.x === -1 && this.lastPointerDown.y === -1) {
return;
}
const pointerUp = new Phaser.Math.Vector2(pointer.x, pointer.y);
if (Phaser.Math.Distance.BetweenPointsSquared(this.lastPointerDown, pointerUp) < 225) {
this.launchTorpedo(this.player, pointer.worldX, pointer.worldY);
return;
}
const angle = Phaser.Math.Angle.BetweenPoints(this.lastPointerDown, pointerUp);
this.player.desiredRotation = angle + Math.PI / 2;
const velocity = this.physics.velocityFromRotation(angle, GameConstants.maxShipVelocity);
this.player.desiredVelocity = new Phaser.Math.Vector2(velocity.x, velocity.y);
}
addRobotShips() {
const center = new Phaser.Math.Vector2(GameConstants.boundaryWidth / 2, GameConstants.boundaryHeight / 2);
const angleStep = Math.PI * 2 / this.enemyCount;
const radius = 400;
const colorPalette = [
0xFF0000, // Bright Red
0xFF7F00, // Bright Orange
0xFFFF00, // Bright Yellow
0x7FFF00, // Bright Chartreuse Green
0x00FF00, // Bright Green
0x00FF7F, // Bright Spring Green
0x00FFFF, // Bright Cyan
0x007FFF, // Bright Azure
0x0000FF, // Bright Blue
0x7F00FF, // Bright Violet
0xFF00FF, // Bright Magenta
0xFF007F, // Bright Rose
0xFFFFFF, // Bright White
0xFFFF7F // Bright Light Yellow
];
for (let i = 0; i < this.enemyCount; i++) {
const angle = angleStep * i;
const position = center.clone().setToPolar(angle, radius);
const color = colorPalette[i % colorPalette.length];
this.addRobotShip(position.x, position.y, color);
}
}
addRobotShip(x: number, y: number, color: number) {
const polygon = this.add.polygon(GameConstants.boundaryWidth / 2 + x, GameConstants.boundaryHeight / 2 + y, Scene.shipDimensions, color);
this.physics.add.existing(polygon);
const robotPlayer = new RobotShip(polygon, this.add.graphics());
this.robotPlayers.push(robotPlayer);
this.physics.add.collider(this.player.polygon, polygon, this.handleShipCollision, undefined, this);
this.physics.add.collider(polygon, this.asteroids, this.handleAsteroidCollision, undefined, this);
}
handleTorpedoAsteroidCollision(torpedo: ArcadeBody, asteroid: ArcadeBody) {
this.explodeTorpedo(torpedo as Phaser.GameObjects.Graphics);
}
handleShipCollision(player: ArcadeBody, robot: ArcadeBody) {
if (this.gameState !== GameState.Running) {
return;
}
const robotPlayer = this.robotPlayers.find(robotPlayer => robotPlayer.polygon === robot);
if (robotPlayer?.polygon.active === false || this.player.polygon.active === false) {
return;
}
this.explodePlayer();
this.explodeRobotPlayer(robotPlayer!);
}
handleAsteroidCollision(shipPolygon: ArcadeBody, asteroid: ArcadeBody) {
if (this.gameState !== GameState.Running) {
return;
}
let ship: Ship | undefined = undefined;
if (shipPolygon === this.player.polygon) {
ship = this.player;
} else {
ship = this.robotPlayers.find(robotPlayer => robotPlayer.polygon === shipPolygon);
}
if (ship) {
const bounceVelocity = ship.lastVelocity.clone().negate();
ship.body.setVelocity(bounceVelocity.x, bounceVelocity.y);
ship.desiredVelocity = bounceVelocity;
}
}
launchTorpedo(ship: Ship, targetX: number, targetY: number) {
if (!ship.reloadTorpedoBay()) {
// No torpedoes left
return;
}
const torpedo = this.add.graphics();
torpedo.fillStyle(0xff0000, 1);
torpedo.fillRect(-1, -5, 2, 10);
torpedo.x = ship.polygon.x;
torpedo.y = ship.polygon.y;
let destinationMarker: Phaser.GameObjects.Graphics | undefined = undefined;
if (ship === this.player) {
destinationMarker = this.add.graphics();
destinationMarker.lineStyle(2, 0x770000, 1);
destinationMarker.beginPath();
destinationMarker.moveTo(-4, -4);
destinationMarker.lineTo(4, 4);
destinationMarker.moveTo(4, -4);
destinationMarker.lineTo(-4, 4);
destinationMarker.closePath();
destinationMarker.strokePath();
destinationMarker.x = targetX;
destinationMarker.y = targetY;
}
// Add torpedo to the physics system
this.torpedoGroup.add(torpedo);
const torpedoBody = torpedo.body as Phaser.Physics.Arcade.Body;
torpedoBody.setCollideWorldBounds(false);
torpedoBody.setCircle(2, -2, -2);
torpedoBody.setMaxSpeed(GameConstants.torpedoSpeed);
this.physics.moveTo(torpedo, targetX, targetY, GameConstants.torpedoSpeed);
const angle = Phaser.Math.Angle.Between(torpedo.x, torpedo.y, targetX, targetY);
torpedo.rotation = angle + Math.PI / 2;
const emitter = this.add.particles(0, 0, 'red', {
lifespan: 250,
speed: 1,
blendMode: Phaser.BlendModes.ADD,
tint: { start: 0xff0000, end: 0x000000 }
});
emitter.startFollow(torpedo);
emitter.emitting = true;
this.torpedoes.set(torpedo, { targetX, targetY, destinationMarker, emitter });
const timeout = 30 * 1000;
this.time.delayedCall(timeout, () => {
if (torpedo.active) {
this.explodeTorpedo(torpedo);
}
}, [], this);
this.gameEvents.emit('torpedo-launched', ship === this.player);
}
explodeTorpedo(torpedo: Phaser.GameObjects.Graphics) {
const explosion = new Phaser.Math.Vector2(torpedo.x, torpedo.y);
const lifespan = 500;
const fireEmitter = this.add.particles(0, 0, 'red', {
x: torpedo.x,
y: torpedo.y,
// make sure the particles don't travel outside the explosion radius
// but add a little more slack so the edges will still be visible
speed: (GameConstants.explosionRadius / (lifespan / 1000)) * 1.2,
radial: true,
scale: { start: 1, end: 0 },
blendMode: Phaser.BlendModes.ADD,
lifespan,
quantity: 50,
// tint: { start: 0xff0000, end: 0x000000, ease: Phaser.Math.Easing.Linear }, // Bright yellow to dark red
// tintFill: true,
duration: GameConstants.torpedoBlastTime
});
fireEmitter.once("complete", () => {
this.explosions.delete(explosion);
fireEmitter.destroy();
});
this.explosions.add(explosion);
torpedo.destroy();
const { emitter, destinationMarker } = this.torpedoes.get(torpedo) ?? {};
emitter?.destroy();
destinationMarker?.destroy();
this.torpedoes.delete(torpedo);
}
updateTorpedoes() {
for (const [torpedo, { targetX, targetY }] of this.torpedoes) {
// Check if torpedo reached the target position
if (Phaser.Math.Distance.Squared(torpedo.x, torpedo.y, targetX, targetY) < 4) {
this.explodeTorpedo(torpedo);
} else {
for (const explosions of this.explosions) {
if (Phaser.Math.Distance.Between(torpedo.x, torpedo.y, explosions.x, explosions.y) < GameConstants.explosionRadius) {
this.explodeTorpedo(torpedo);
break;
}
}
}
}
for (const explosion of this.explosions) {
if (this.player.polygon.active && Phaser.Math.Distance.BetweenPointsSquared(this.player.polygon.getCenter(), explosion) < GameConstants.explosionRadius ** 2) {
this.explodePlayer();
}
for (const robotPlayer of this.robotPlayers) {
if (robotPlayer.polygon.active && Phaser.Math.Distance.BetweenPointsSquared(robotPlayer.polygon.getCenter(), explosion) < GameConstants.explosionRadius ** 2) {
this.explodeRobotPlayer(robotPlayer);
}
}
}
}
explodePlayer() {
this.gameEvents.emit('player-exploded');
this.createDebris(this.player);
this.player.body.setVelocity(0, 0);
this.player.desiredVelocity = new Phaser.Math.Vector2(0, 0);
this.player.polygon.active = false;
this.player.polygon.visible = false;
}
explodeRobotPlayer(robotPlayer: RobotShip) {
robotPlayer.destroy();
this.createDebris(robotPlayer);
}
update() {
if (this.gameState !== GameState.Running && this.gameState !== GameState.Respawning) {
return;
}
this.player.update();
this.robotPlayers.forEach(robotPlayer => robotPlayer.update());
this.updateTorpedoes();
const isGameOver = this.robotPlayers.every(robotPlayer => !robotPlayer.polygon.active);
if (isGameOver) {
this.gameOver(true);
}
const respawnRequired = !this.player.polygon.active;
if (respawnRequired) {
this.respawnPlayer();
}
// Update marker position and visibility
const camera = this.cameras.main;
for (const robotPlayer of this.robotPlayers) {
robotPlayer.updateMarker(camera, this.player);
}
}
private createDebris(ship: Ship) {
const x = ship.polygon.x;
const y = ship.polygon.y;
for (let i = 0; i < 20; i++) {
const points = [
{ x: Phaser.Math.Between(-5, 5), y: Phaser.Math.Between(-5, 5) },
{ x: Phaser.Math.Between(-5, 5), y: Phaser.Math.Between(-5, 5) },
{ x: Phaser.Math.Between(-5, 5), y: Phaser.Math.Between(-5, 5) }
];
const debris = this.add.polygon(x, y, points, ship.polygon.fillColor);
const rotationSpeed = Phaser.Math.Between(-180, 180); // degrees per second
const duration = 3000;
const velocityScale = 0.4; // Scale down the ship's velocity influence
const targetX = debris.x + Phaser.Math.Between(-50, 50) + ship.body.velocity.x * velocityScale * (duration / 1000);
const targetY = debris.y + Phaser.Math.Between(-50, 50) + ship.body.velocity.y * velocityScale * (duration / 1000);
this.tweens.add({
targets: debris,
ease: 'Power2',
duration: duration,
x: targetX,
y: targetY,
angle: debris.angle + rotationSpeed,
alpha: 0,
onComplete: () => {
debris.destroy();
}
});
}
}
private cleanup() {
this.player.destroy();
this.player.body.velocity.set(0, 0);
this.player.desiredVelocity.set(0, 0);
for (const robotPlayer of this.robotPlayers) {
robotPlayer.destroy();
robotPlayer.body.velocity.set(0, 0);
this.player.desiredVelocity.set(0, 0);
}
for (const [torpedo, { destinationMarker, emitter }] of this.torpedoes.entries()) {
torpedo.destroy();
destinationMarker?.destroy();
emitter.destroy();
}
this.torpedoes.clear();
this.explosions.clear();
this.starfield.clear();
this.lastPointerDown.set(-1, -1);
}
private finishRespawn() {
this.player.polygon.active = true;
this.player.polygon.visible = true;
this.gameState = GameState.Running;
}
private playRespawnAnimation() {
// Ensure the player is invisible initially
this.player.polygon.visible = true;
this.player.polygon.alpha = 0;
// Create a fade-in tween animation
this.tweens.add({
targets: this.player.polygon,
alpha: 1,
duration: 1000, // 1 second duration
ease: 'Quint.easeIn',
onComplete: () => {
}
});
}
private respawnPlayer() {
if (this.gameState === GameState.Respawning || this.gameState === GameState.GameOver) {
return;
}
this.gameState = GameState.Respawning;
let countdown = GameConstants.respawnTime;
const timerText = this.add.text(this.scale.width / 2, this.scale.height / 2, "", {
fontSize: '64px',
color: '#ffffff', // Change color to white for better visibility
wordWrap: { width: this.scale.width - 100 }
});
timerText.setOrigin(0.5, 0.5); // Center the text
timerText.setScrollFactor(0); // Ensure the text is fixed on the screen
const timerEvent = this.time.addEvent({
delay: 1000, // 1 second
callback: () => {
countdown--;
timerText.setText(`Respawning in ${countdown}...`);
if (countdown === 1) {
this.playRespawnAnimation();
}
if (countdown <= 0) {
timerEvent.remove();
timerText.destroy();
this.finishRespawn();
}
},
callbackScope: this,
loop: true
});
}
private gameOver(win: boolean) {
this.gameState = GameState.GameOver;
this.physics.pause();
const message = win ? 'You win!' : 'You lose!';
// Add "Game Over" text
const gameOverText = this.add.text(this.scale.width / 2, this.scale.height / 2, message, {
fontSize: '64px',
color: '#ffffff' // Change color to white for better visibility
});
gameOverText.setOrigin(0.5, 0.5); // Center the text
gameOverText.setScrollFactor(0); // Ensure the text is fixed on the screen
// Fade out the text
this.tweens.add({
targets: gameOverText,
alpha: 0,
duration: 3000,
ease: 'Power1',
onComplete: () => {
this.enemyCount += win ? 1 : 0;
gameOverText.destroy();
this.cleanup();
this.scene.restart();
}
});
}
}