forked from maitri-vv/3D-Blockstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
623 lines (526 loc) · 17.2 KB
/
script.js
File metadata and controls
623 lines (526 loc) · 17.2 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
window.focus(); // Ensure keys are captured
// ----- Globals -----
let camera, scene, renderer;
let world;
let lastTime;
let stack = [];
let overhangs = [];
const boxHeight = 1;
let originalBoxSize = 3;
let autopilot = true;
let gameEnded = false;
let robotPrecision;
// UI elements
const scoreElement = document.getElementById("score");
const instructionsElement = document.getElementById("instructions");
const resultsElement = document.getElementById("results");
const endScoreElement = document.getElementById("end-score");
const endHighScoreElement = document.getElementById("end-high-score");
const restartTextElement = document.getElementById("restart-text");
// High score
const HIGH_SCORE_KEY = "stackerHighScore";
let highScore = 0;
// Audio
const sounds = {
place: new Audio("sound/put.bg.mp3"),
fail: new Audio("sound/fall.bg.mp3"),
bgm: new Audio("sound/bg.mp3.mp3"),
};
Object.values(sounds).forEach((s) => s.load());
sounds.bgm.volume = 0.2;
sounds.bgm.loop = true;
let muted = false;
// ----- Utility Functions -----
function isTouchDevice() {
return "ontouchstart" in window || navigator.maxTouchPoints > 0;
}
function updateRestartMessage() {
if (!restartTextElement) return;
restartTextElement.innerHTML = isTouchDevice()
? "Tap anywhere to restart"
: "Press <kbd>R</kbd> to restart";
}
// Load and save high score from localStorage
function loadHighScore() {
try {
const saved = localStorage.getItem(HIGH_SCORE_KEY);
highScore = saved ? Math.max(0, parseInt(saved, 10) || 0) : 0;
} catch (_) {
highScore = 0;
}
}
// save high score to localStorage
function saveHighScore(value) {
try {
localStorage.setItem(HIGH_SCORE_KEY, String(Math.max(0, value | 0)));
} catch (_) {}
}
// Initialize the game
init();
// Determines how precise the game is on autopilot
function setRobotPrecision() {
robotPrecision = Math.random() - 0.5;
}
// Create a canvas for the gradient texture
function createGradientBackground(colors) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
// Set canvas size
canvas.width = 512;
canvas.height = 512;
// Create a gradient using theme colors
const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
gradient.addColorStop(0, colors.top);
gradient.addColorStop(0.5, colors.middle);
gradient.addColorStop(1, colors.bottom);
// Apply gradient to canvas
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Create texture from canvas
const texture = new THREE.CanvasTexture(canvas);
return texture;
}
// Function to update scene colors based on current theme
function updateSceneColors() {
if (!scene) return; // Scene not initialized yet
const themeColors = window.themeManager.getCurrentThemeColors();
// Update scene background
scene.background = createGradientBackground(themeColors.sceneBackground);
// Update particle colors if they exist
if (particleData && particleData.particles) {
particleData.particles.material.color.set(themeColors.particleSpecialColor);
}
// We don't update existing blocks' colors, only new ones will use the new theme
}
// Main init function
function init() {
autopilot = true;
gameEnded = false;
lastTime = 0;
stack = [];
overhangs = [];
setRobotPrecision();
// Compute responsive box size based on viewport
setResponsiveBoxSize();
// Load high score on initial game setup
loadHighScore();
function createParticleBackground(scene) {
const particleCount = 500;
const particlesGeometry = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount; i++) {
positions[i * 3] = (Math.random() - 0.5) * 10; // X
positions[i * 3 + 1] = (Math.random() - 0.5) * 10; // Y
positions[i * 3 + 2] = (Math.random() - 0.5) * 10; // Z
}
particlesGeometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
// Get theme colors for particles
const themeColors = window.themeManager.getCurrentThemeColors();
const particlesMaterial = new THREE.PointsMaterial({
color: themeColors.particleColor,
size: 0.05,
transparent: true,
opacity: 0.5,
depthWrite: false
});
const particleSystem = new THREE.Points(particlesGeometry, particlesMaterial);
particleSystem.renderOrder = -1; // Ensure it renders behind game objects
scene.add(particleSystem);
// Animation function
function animateParticles() {
requestAnimationFrame(animateParticles);
particleSystem.rotation.y += 0.001;
}
animateParticles();
}
// Initialize CannonJS
world = new CANNON.World();
world.gravity.set(0, -10, 0); // Gravity pulls things down
world.broadphase = new CANNON.NaiveBroadphase();
world.solver.iterations = 40;
// Initialize ThreeJs
const aspect = window.innerWidth / window.innerHeight;
const width = 10;
const height = width / aspect;
camera = new THREE.OrthographicCamera(
width / -2, // left
width / 2, // right
height / 2, // top
height / -2, // bottom
0, // near plane
100 // far plane
);
/*
// If you want to use perspective camera instead, uncomment these lines
camera = new THREE.PerspectiveCamera(
45, // field of view
aspect, // aspect ratio
1, // near plane
100 // far plane
);
*/
camera.position.set(3, 3, 3);
camera.lookAt(0, 0, 0);
scene = new THREE.Scene();
// Apply initial theme colors
const initialThemeColors = window.themeManager.getCurrentThemeColors();
scene.background = createGradientBackground(initialThemeColors.sceneBackground);
// Foundation
addLayer(0, 0, originalBoxSize, originalBoxSize);
// First layer
addLayer(-10, 0, originalBoxSize, originalBoxSize, "x");
// Set up lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(10, 20, 0);
scene.add(dirLight);
// Set up renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setAnimationLoop(animation);
document.body.appendChild(renderer.domElement);
createParticleBackground(scene);
camera.position.z = 3;
}
// Start or restart the game
function startGame() {
autopilot = false;
gameEnded = false;
lastTime = 0;
stack = [];
overhangs = [];
// Recompute box size in case viewport changed before restarting
setResponsiveBoxSize();
if (instructionsElement) instructionsElement.style.display = "none";
if (resultsElement) resultsElement.style.display = "none";
if (scoreElement) scoreElement.innerText = 0;
if (world) {
// Remove every object from world
while (world.bodies.length > 0) {
world.remove(world.bodies[0]);
}
}
if (scene) {
// Remove every Mesh from the scene
while (scene.children.find((c) => c.type == "Mesh")) {
const mesh = scene.children.find((c) => c.type == "Mesh");
scene.remove(mesh);
}
// Restore theme colors
updateSceneColors();
// Foundation
addLayer(0, 0, originalBoxSize, originalBoxSize);
// First layer
addLayer(-10, 0, originalBoxSize, originalBoxSize, "x");
}
if (camera) {
// Reset camera positions
camera.position.set(4, 4, 4);
camera.lookAt(0, 0, 0);
}
}
// Compute responsive box size based on viewport dimensions
function setResponsiveBoxSize() {
const vw = Math.max(window.innerWidth, 320);
const vh = Math.max(window.innerHeight, 320);
const minDim = Math.min(vw, vh);
if (minDim < 420) originalBoxSize = 1.8;
else if (minDim < 768) originalBoxSize = 2.6;
else originalBoxSize = 4;
}
// Function to create a ring effect at (x, y, z)
function createRingEffect(x, y, z) {
const ringGeometry = new THREE.RingGeometry(0.8, 1.5, 32);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xffd700, // Golden yellow
transparent: true,
opacity: 0.8,
});
const ring = new THREE.Mesh(ringGeometry, ringMaterial);
ring.position.set(x, y + boxHeight / 2, z);
ring.rotation.x = Math.PI / 2;
scene.add(ring);
// Remove ring after animation
setTimeout(() => {
scene.remove(ring);
}, 600);
}
function createParticles() {
const particleCount = 200;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount * 3; i += 3) {
positions[i] = (Math.random() - 0.5) * 50;
positions[i + 1] = Math.random() * 30;
positions[i + 2] = (Math.random() - 0.5) * 50;
}
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({
color: 0xffd700,
size: 0.5,
transparent: true,
opacity: 0.8,
depthWrite: false,
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);
return { particles, geometry };
}
function animateParticles(particleData) {
const positions = particleData.geometry.attributes.position.array;
for (let i = 1; i < positions.length; i += 3) {
positions[i] += Math.sin(Date.now() * 0.001 + i) * 0.02;
if (positions[i] > 100) positions[i] = -100;
if (positions[i] < -100) positions[i] = 100;
}
particleData.geometry.attributes.position.needsUpdate = true;
}
// Initialize Particles
const particleData = createParticles();
// Helper function to generate a box (both in ThreeJS and CannonJS)
function generateBox(x, y, z, width, depth, falls) {
const geometry = new THREE.BoxGeometry(width, boxHeight, depth);
// Get current theme colors for block generation
const themeColors = window.themeManager.getCurrentThemeColors();
const hueBase = themeColors.blockHueBase || 30;
// Create color with theme-based hue
const color = new THREE.Color(`hsl(${hueBase + stack.length * 4}, 100%, 50%)`);
const material = new THREE.MeshLambertMaterial({ color });
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(x, y, z);
scene.add(mesh);
const shape = new CANNON.Box(
new CANNON.Vec3(width / 2, boxHeight / 2, depth / 2)
);
let mass = falls ? 5 : 0;
mass *= width / originalBoxSize;
mass *= depth / originalBoxSize;
const body = new CANNON.Body({ mass, shape });
body.position.set(x, y, z);
world.addBody(body);
return { threejs: mesh, cannonjs: body, width, depth };
}
function addLayer(x, z, width, depth, direction) {
const y = boxHeight * stack.length;
const layer = generateBox(x, y, z, width, depth, false);
layer.direction = direction;
stack.push(layer);
createRingEffect(x, y, z);
}
function addOverhang(x, z, width, depth) {
const y = boxHeight * (stack.length - 1);
const overhang = generateBox(x, y, z, width, depth, true);
overhangs.push(overhang);
}
// Function to cut the top layer and return the overlap
function cutBox(topLayer, overlap, size, delta) {
const dir = topLayer.direction;
const newWidth = dir === "x" ? overlap : topLayer.width;
const newDepth = dir === "z" ? overlap : topLayer.depth;
topLayer.width = newWidth;
topLayer.depth = newDepth;
topLayer.threejs.scale[dir] = overlap / size;
topLayer.threejs.position[dir] -= delta / 2;
topLayer.cannonjs.position[dir] -= delta / 2;
const shape = new CANNON.Box(
new CANNON.Vec3(newWidth / 2, boxHeight / 2, newDepth / 2)
);
topLayer.cannonjs.shapes = [];
topLayer.cannonjs.addShape(shape);
}
// Function to split the block and add the next one if it overlaps
function splitBlockAndAddNextOneIfOverlaps() {
if (gameEnded) return;
const top = stack[stack.length - 1];
const prev = stack[stack.length - 2];
const dir = top.direction;
const size = dir === "x" ? top.width : top.depth;
const delta = top.threejs.position[dir] - prev.threejs.position[dir];
const overhangSize = Math.abs(delta);
const overlap = size - overhangSize;
if (overlap > 0) {
cutBox(top, overlap, size, delta);
const shift = (overlap / 2 + overhangSize / 2) * Math.sign(delta);
const ox =
dir === "x" ? top.threejs.position.x + shift : top.threejs.position.x;
const oz =
dir === "z" ? top.threejs.position.z + shift : top.threejs.position.z;
const ow = dir === "x" ? overhangSize : top.width;
const od = dir === "z" ? overhangSize : top.depth;
addOverhang(ox, oz, ow, od);
const nx = dir === "x" ? top.threejs.position.x : -10;
const nz = dir === "z" ? top.threejs.position.z : -10;
addLayer(nx, nz, top.width, top.depth, dir === "x" ? "z" : "x");
playPlaceSound();
if (scoreElement) scoreElement.innerText = `${stack.length - 1} ◆`;
addLayer(nextX, nextZ, newWidth, newDepth, nextDirection);
} else {
missedTheSpot();
}
}
// Function to handle game over scenario
function missedTheSpot() {
const top = stack[stack.length - 1];
addOverhang(
top.threejs.position.x,
top.threejs.position.z,
top.width,
top.depth
);
world.remove(top.cannonjs);
scene.remove(top.threejs);
gameEnded = true;
// Evaluate and update high score
const currentScore = Math.max(0, stack.length - 2); // Exclude foundation and first moving layer
if (currentScore > highScore) {
highScore = currentScore;
saveHighScore(highScore);
}
if (endScoreElement) endScoreElement.innerText = `${currentScore} ◆`;
if (endHighScoreElement) endHighScoreElement.innerText = `${highScore} ◆`;
updateRestartMessage();
// Show results dialog when game ends
if (resultsElement) {
setTimeout(() => {
resultsElement.style.display = "flex";
}, 300);
}
playFailSound();
}
// ----- Audio Controls -----
const muteBtn = document.createElement("button");
muteBtn.id = "muteBtn";
muteBtn.textContent = "🔊";
Object.assign(muteBtn.style, {
position: "absolute",
top: "20px",
left: "20px",
background: "rgba(255,255,255,0.7)",
border: "none",
borderRadius: "8px",
fontSize: "20px",
padding: "5px 10px",
cursor: "pointer",
zIndex: "1000",
});
document.body.appendChild(muteBtn);
muteBtn.addEventListener("click", () => {
muted = !muted;
sounds.bgm.muted = muted;
muteBtn.textContent = muted ? "🔇" : "🔊";
});
function enableBackgroundMusic() {
sounds.bgm.play().catch(() => {});
}
["mousedown", "touchstart", "keydown"].forEach((evt) =>
window.addEventListener(evt, enableBackgroundMusic, { once: true })
);
function playPlaceSound() {
if (!muted) {
const s = sounds.place.cloneNode();
s.volume = 0.7;
s.play().catch(() => {});
}
}
function playFailSound() {
if (!muted) {
const s = sounds.fail.cloneNode();
s.volume = 0.7;
s.play().catch(() => {});
}
}
// ----- Event Handlers -----
function eventHandler() {
autopilot ? startGame() : splitBlockAndAddNextOneIfOverlaps();
}
window.addEventListener("mousedown", (e) => {
window.focus();
eventHandler();
});
document.addEventListener("keydown", (e) => {
if (e.key === " ") {
e.preventDefault();
eventHandler();
}
if (e.key === "r" || e.key === "R") {
e.preventDefault();
if (gameEnded || autopilot) {
startGame();
}
}
}, true);
window.addEventListener(
"touchstart",
(e) => {
if (e.target.closest(".twitter-link")){
return;
}
e.preventDefault();
gameEnded ? startGame() : eventHandler();
},
{ passive: false }
);
// Close results dialog button
const closeResultsBtn = document.getElementById("close-results");
if (closeResultsBtn) {
closeResultsBtn.addEventListener("click", () => {
if (resultsElement) {
resultsElement.style.display = "none";
}
});
}
window.addEventListener("resize", () => {
setResponsiveBoxSize();
const aspect = window.innerWidth / window.innerHeight;
const width = 10;
const height = width / aspect;
camera.left = -width / 2;
camera.right = width / 2;
camera.top = height / 2;
camera.bottom = -height / 2;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
if (particleData?.geometry)
particleData.geometry.attributes.position.needsUpdate = true;
renderer.render(scene, camera);
});
// ----- Physics Update -----
function updatePhysics(deltaTime) {
world.step(deltaTime / 1000);
overhangs.forEach((e) => {
e.threejs.position.copy(e.cannonjs.position);
e.threejs.quaternion.copy(e.cannonjs.quaternion);
});
}
// ----- Animation Loop -----
function animation(time) {
if (lastTime) {
const deltaTime = time - lastTime;
TWEEN.update();
const top = stack[stack.length - 1];
const prev = stack[stack.length - 2];
const moveBox =
!gameEnded &&
(!autopilot ||
(autopilot &&
top.threejs.position[top.direction] <
prev.threejs.position[top.direction] + robotPrecision));
if (moveBox) {
top.threejs.position[top.direction] += 0.008 * deltaTime;
top.cannonjs.position[top.direction] += 0.008 * deltaTime;
if (top.threejs.position[top.direction] > 10) missedTheSpot();
} else if (autopilot) {
splitBlockAndAddNextOneIfOverlaps();
setRobotPrecision();
}
if (camera.position.y < boxHeight * (stack.length - 2) + 4)
camera.position.y += 0.008 * deltaTime;
updatePhysics(deltaTime);
animateParticles(particleData);
renderer.render(scene, camera);
}
lastTime = time;
}