-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
480 lines (403 loc) · 14.8 KB
/
Copy pathscript.js
File metadata and controls
480 lines (403 loc) · 14.8 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
class Vector2 {
constructor(x, y) {
this.x = x;
this.y = y;
}
add(v) { return new Vector2(this.x + v.x, this.y + v.y); }
sub(v) { return new Vector2(this.x - v.x, this.y - v.y); }
mult(n) { return new Vector2(this.x * n, this.y * n); }
div(n) { return new Vector2(this.x / n, this.y / n); }
mag() { return Math.sqrt(this.x * this.x + this.y * this.y); }
normalize() {
const m = this.mag();
return m === 0 ? new Vector2(0, 0) : new Vector2(this.x / m, this.y / m);
}
static dist(v1, v2) { return v1.sub(v2).mag(); }
copy() { return new Vector2(this.x, this.y); }
}
const GAME_STATE = {
IDLE: 'IDLE', // Creating trajectory
FLYING: 'FLYING', // Physics active
ENDED: 'ENDED' // Win/Loss
};
class Ship {
constructor(x, y) {
this.pos = new Vector2(x, y);
this.vel = new Vector2(0, 0);
this.acc = new Vector2(0, 0);
this.radius = 8;
this.color = '#ffffff';
this.trail = [];
this.maxTrailLength = 20;
}
applyForce(force) {
this.acc = this.acc.add(force);
}
update(dt, planets) {
this.acc = new Vector2(0, 0); // Reset acceleration
// Gravity Physics
for (let planet of planets) {
let dir = planet.pos.sub(this.pos);
let d = dir.mag();
let epsilon = 5.0; // Prevent division by zero
// F = G / (d + e) -- Simplified as per specs
// Assuming ship mass = 1
if (d < planet.influenceRadius) {
let strength = planet.gravity / (d + epsilon);
let force = dir.normalize().mult(strength);
this.applyForce(force);
}
}
// Symplectic Euler Integration (better stability)
this.vel = this.vel.add(this.acc.mult(dt));
this.pos = this.pos.add(this.vel.mult(dt));
// Trail effect
if (GlobalGame.frameCount % 5 === 0) {
this.trail.push(this.pos.copy());
if (this.trail.length > this.maxTrailLength) this.trail.shift();
}
}
draw(ctx) {
// Draw Trail
if (this.trail.length > 1) {
ctx.beginPath();
ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
ctx.lineWidth = 2;
ctx.moveTo(this.trail[0].x, this.trail[0].y);
for (let i = 1; i < this.trail.length; i++) {
ctx.lineTo(this.trail[i].x, this.trail[i].y);
}
ctx.stroke();
}
// Draw Ship (Spaceship shape)
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
// Rotate towards direction of movement
let angle = 0;
if (this.vel.mag() > 0.1) {
angle = Math.atan2(this.vel.y, this.vel.x);
}
ctx.rotate(angle);
ctx.beginPath();
const r = this.radius;
// Triangle pointing right (0 rad)
ctx.moveTo(r + 2, 0);
ctx.lineTo(-r, r - 2);
ctx.lineTo(-r + 3, 0); // Engine notch
ctx.lineTo(-r, -r + 2);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.shadowBlur = 10;
ctx.shadowColor = 'white';
ctx.fill();
ctx.restore();
}
}
class Planet {
constructor(x, y, radius, gravity, influenceRadius) {
this.pos = new Vector2(x, y);
this.radius = radius;
this.gravity = gravity;
this.influenceRadius = influenceRadius;
this.color = '#4cc9f0'; // Cyber blue
}
draw(ctx) {
// Draw influence area (faint)
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.influenceRadius, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(76, 201, 240, 0.1)';
ctx.setLineDash([5, 5]);
ctx.stroke();
ctx.setLineDash([]);
// Draw gravity well gradient
let gradient = ctx.createRadialGradient(this.pos.x, this.pos.y, this.radius, this.pos.x, this.pos.y, this.influenceRadius * 0.5);
gradient.addColorStop(0, 'rgba(76, 201, 240, 0.2)');
gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.influenceRadius * 0.5, 0, Math.PI * 2);
ctx.fill();
// Draw Planet Body
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
// Glow
ctx.shadowBlur = 15;
ctx.shadowColor = this.color;
ctx.stroke(); // Stroke to emphasize edge
ctx.shadowBlur = 0;
}
}
class Goal {
constructor(x, y, radius) {
this.pos = new Vector2(x, y);
this.radius = radius;
this.pulse = 0;
}
draw(ctx) {
this.pulse += 0.05;
const glowRadius = this.radius + Math.sin(this.pulse) * 5;
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, this.radius, 0, Math.PI * 2);
ctx.strokeStyle = '#fca311'; // Orange
ctx.lineWidth = 3;
ctx.stroke();
ctx.beginPath();
ctx.arc(this.pos.x, this.pos.y, glowRadius, 0, Math.PI * 2);
ctx.strokeStyle = 'rgba(252, 163, 17, 0.3)';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fillStyle = 'rgba(252, 163, 17, 0.1)';
ctx.fill();
}
}
class Game {
constructor() {
this.canvas = document.getElementById('gameCanvas');
this.ctx = this.canvas.getContext('2d');
this.uiStage = document.getElementById('stage-number');
this.uiMessages = document.getElementById('messages');
this.retryBtn = document.getElementById('retry-btn');
this.shuffleBtn = document.getElementById('shuffle-btn');
this.resize();
window.addEventListener('resize', () => this.resize());
this.currentLevel = 1;
this.currentLevelConfig = null; // Store current config
this.retryBtn.onclick = () => this.restartLevel();
this.shuffleBtn.onclick = () => this.shuffleLevel();
// Input Handling
this.isDragging = false;
this.dragStart = null;
this.dragCurrent = null;
this.canvas.addEventListener('mousedown', (e) => this.onMouseDown(e));
document.addEventListener('mousemove', (e) => this.onMouseMove(e));
document.addEventListener('mouseup', (e) => this.onMouseUp(e));
// Game Entities
this.ship = null;
this.planets = [];
this.goal = null;
this.state = GAME_STATE.IDLE;
// Levels Config
this.levels = {
1: (w, h) => ({
ship: new Vector2(100, h - 100),
goal: { pos: new Vector2(w - 100, 100), r: 30 },
planets: [
new Planet(w / 2, h / 2, 40, 5000, 300)
]
}),
2: (w, h) => ({
ship: new Vector2(100, h / 2),
goal: { pos: new Vector2(w - 100, h / 2), r: 30 },
planets: [
new Planet(w / 3, h / 2 - 150, 35, 4000, 250),
new Planet(2 * w / 3, h / 2 + 150, 35, 4000, 250)
]
}),
3: (w, h) => ({
ship: new Vector2(100, h / 2),
goal: { pos: new Vector2(w - 100, h / 2), r: 25 },
planets: [
new Planet(w / 2, h / 2, 60, 8000, 400), // Big strong one
new Planet(w - 200, h / 2 - 150, 20, 2000, 150), // Trap
new Planet(w - 200, h / 2 + 150, 20, 2000, 150) // Trap
]
})
};
this.initLevel(1);
this.lastTime = 0;
this.frameCount = 0;
window.GlobalGame = this;
this.loop = this.loop.bind(this);
requestAnimationFrame(this.loop);
}
resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
}
getMousePos(e) {
const rect = this.canvas.getBoundingClientRect();
return new Vector2(e.clientX - rect.left, e.clientY - rect.top);
}
generateRandomLevel(w, h) {
const planetCount = Math.floor(Math.random() * 3) + 1; // 1 to 3 planets
const planets = [];
for (let i = 0; i < planetCount; i++) {
const r = 20 + Math.random() * 40;
const x = 200 + Math.random() * (w - 400);
const y = 100 + Math.random() * (h - 200);
const gravity = r * 100;
const influence = r * 6;
planets.push(new Planet(x, y, r, gravity, influence));
}
return {
ship: new Vector2(100, h / 2 + (Math.random() * 200 - 100)),
goal: { pos: new Vector2(w - 100, h / 2 + (Math.random() * 200 - 100)), r: 30 },
planets: planets
};
}
initLevel(levelNum) {
this.currentLevel = levelNum;
if (this.levels[levelNum]) {
this.currentLevelConfig = this.levels[levelNum](this.canvas.width, this.canvas.height);
this.shuffleBtn.classList.add('hidden');
} else {
this.currentLevelConfig = this.generateRandomLevel(this.canvas.width, this.canvas.height);
this.shuffleBtn.classList.remove('hidden');
this.shuffleBtn.style.display = 'block';
}
this.startFromConfig();
}
shuffleLevel() {
this.initLevel(this.currentLevel);
}
restartLevel() {
this.startFromConfig();
}
startFromConfig() {
const config = this.currentLevelConfig;
this.state = GAME_STATE.IDLE;
this.uiMessages.classList.add('hidden');
this.uiStage.innerText = this.currentLevel >= 4 ? `${this.currentLevel} (Random)` : this.currentLevel;
this.retryBtn.innerText = "RETRY";
this.retryBtn.onclick = () => this.restartLevel();
this.ship = new Ship(config.ship.x, config.ship.y);
this.planets = config.planets;
this.goal = new Goal(config.goal.pos.x, config.goal.pos.y, config.goal.r);
this.ship.vel = new Vector2(0, 0);
this.ship.acc = new Vector2(0, 0);
this.ship.trail = [];
}
onMouseDown(e) {
if (this.state !== GAME_STATE.IDLE) return;
const pos = this.getMousePos(e);
this.isDragging = true;
this.dragStart = pos;
this.dragCurrent = pos;
}
onMouseMove(e) {
if (!this.isDragging) return;
this.dragCurrent = this.getMousePos(e);
}
onMouseUp(e) {
if (!this.isDragging) return;
this.isDragging = false;
const dragVector = this.dragStart.sub(this.dragCurrent);
const power = 3.0; // Multiplier
let launchVel = dragVector.mult(0.1 * power); // scaling
this.ship.vel = launchVel;
this.state = GAME_STATE.FLYING;
}
update(dt) {
this.frameCount++;
if (this.state === GAME_STATE.FLYING) {
// Slow motion for better observation (20 instead of 60)
this.ship.update(dt * 20, this.planets);
// Collision Detection
this.checkCollisions();
}
}
checkCollisions() {
// Goal
if (Vector2.dist(this.ship.pos, this.goal.pos) < this.goal.radius + this.ship.radius) {
this.gameWin();
}
// Planets
for (let p of this.planets) {
if (Vector2.dist(this.ship.pos, p.pos) < p.radius + this.ship.radius) {
this.gameLoss("CRASHED!");
}
}
// Out of bounds
const m = 0; // Margin
if (this.ship.pos.x < -m || this.ship.pos.x > this.canvas.width + m ||
this.ship.pos.y < -m || this.ship.pos.y > this.canvas.height + m) {
this.gameLoss("LOST IN SPACE");
}
}
gameWin() {
this.state = GAME_STATE.ENDED;
this.uiMessages.innerText = "COURSE CLEAR!";
this.uiMessages.style.color = "#4cc9f0";
this.uiMessages.classList.remove('hidden');
this.retryBtn.innerText = "NEXT LEVEL";
this.retryBtn.onclick = () => {
this.currentLevel++;
this.initLevel(this.currentLevel);
};
// Also hide shuffle btn on win screen? No, keep it if they want to re-roll next level immediately?
// Actually next level is not generated yet.
}
gameLoss(msg) {
this.state = GAME_STATE.ENDED;
this.uiMessages.innerText = msg;
this.uiMessages.style.color = "#ef233c";
this.uiMessages.classList.remove('hidden');
}
draw() {
// Background update handled by CSS, but we clear canvas
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
// Draw Predict Line (Trajectory) if Dragging
if (this.state === GAME_STATE.IDLE && this.isDragging) {
this.drawTrajectory();
}
// Draw Entities
this.goal.draw(this.ctx);
for (let p of this.planets) p.draw(this.ctx);
this.ship.draw(this.ctx);
}
drawTrajectory() {
// Slingshot vector
const dragVector = this.dragStart.sub(this.dragCurrent);
const power = 3.0;
const launchVel = dragVector.mult(0.1 * power);
let simPos = this.ship.pos.copy();
let simVel = launchVel.copy();
let simAcc = new Vector2(0, 0);
this.ctx.beginPath();
this.ctx.moveTo(simPos.x, simPos.y);
this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)';
this.ctx.setLineDash([5, 5]);
const steps = 100; // How far to predict
const simDt = 1; // 1 frame per step equivalent
for (let i = 0; i < steps; i++) {
simAcc = new Vector2(0, 0);
for (let planet of this.planets) {
let dir = planet.pos.sub(simPos);
let d = dir.mag();
let epsilon = 5.0;
if (d < planet.influenceRadius) {
let strength = planet.gravity / (d + epsilon);
let force = dir.normalize().mult(strength);
simAcc = simAcc.add(force);
}
}
simVel = simVel.add(simAcc.mult(simDt));
simPos = simPos.add(simVel.mult(simDt));
this.ctx.lineTo(simPos.x, simPos.y);
// Check collision in future (optional visual cue)
for (let p of this.planets) {
if (Vector2.dist(simPos, p.pos) < p.radius) break;
}
}
this.ctx.stroke();
this.ctx.setLineDash([]);
// Draw Drag Line
this.ctx.beginPath();
this.ctx.moveTo(this.ship.pos.x, this.ship.pos.y);
this.ctx.lineTo(this.ship.pos.x - dragVector.x, this.ship.pos.y - dragVector.y);
this.ctx.strokeStyle = '#fca311';
this.ctx.stroke();
}
loop(timestamp) {
const dt = (timestamp - this.lastTime) / 1000;
this.lastTime = timestamp;
this.update(dt);
this.draw();
requestAnimationFrame(this.loop);
}
}
window.onload = () => {
new Game();
};