-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
589 lines (493 loc) · 19.8 KB
/
script.js
File metadata and controls
589 lines (493 loc) · 19.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
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
document.addEventListener('DOMContentLoaded', () => {
// Sound System
class SoundManager {
constructor() {
this.ctx = new (window.AudioContext || window.webkitAudioContext)();
this.enabled = localStorage.getItem('zen-muted') !== 'true';
}
play(type) {
if (!this.enabled || this.ctx.state === 'suspended') {
if (!this.enabled) return;
this.ctx.resume();
}
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.connect(gain);
gain.connect(this.ctx.destination);
const now = this.ctx.currentTime;
switch (type) {
case 'tick':
osc.type = 'sine';
osc.frequency.setValueAtTime(440, now);
gain.gain.setValueAtTime(0.1, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.1);
osc.start(now);
osc.stop(now + 0.1);
break;
case 'win':
// Cheering Gong: Complex harmonics + modulation
const root = 261.63; // C4
// Main Gong Swing
const osc1 = this.ctx.createOscillator();
osc1.type = 'triangle';
osc1.frequency.setValueAtTime(root, now);
osc1.frequency.exponentialRampToValueAtTime(root * 0.98, now + 1.5);
const gain1 = this.ctx.createGain();
gain1.gain.setValueAtTime(0.3, now);
gain1.gain.exponentialRampToValueAtTime(0.001, now + 2.0);
osc1.connect(gain1);
gain1.connect(this.ctx.destination);
osc1.start(now);
osc1.stop(now + 2.0);
// "Cheer" Shimmy (High frequency cluster)
for (let i = 0; i < 3; i++) {
const oscHigh = this.ctx.createOscillator();
oscHigh.type = 'sine';
oscHigh.frequency.value = root * (2 + i * 0.5) + Math.random() * 20;
const gainHigh = this.ctx.createGain();
gainHigh.gain.setValueAtTime(0.1, now);
gainHigh.gain.exponentialRampToValueAtTime(0.001, now + 0.8);
oscHigh.connect(gainHigh);
gainHigh.connect(this.ctx.destination);
oscHigh.start(now);
oscHigh.stop(now + 0.8);
}
break;
case 'loss':
// Subtle Wind: White noise through Lowpass filter
const bufferSize = this.ctx.sampleRate * 2.0;
const buffer = this.ctx.createBuffer(1, bufferSize, this.ctx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = Math.random() * 2 - 1;
}
const noise = this.ctx.createBufferSource();
noise.buffer = buffer;
const filter = this.ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(400, now);
filter.frequency.linearRampToValueAtTime(100, now + 2.0); // Filter closes down
const noiseGain = this.ctx.createGain();
noiseGain.gain.setValueAtTime(0.15, now);
noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 2.0);
noise.connect(filter);
filter.connect(noiseGain);
noiseGain.connect(this.ctx.destination);
noise.start(now);
break;
case 'tie':
osc.type = 'sine';
osc.frequency.setValueAtTime(330, now);
gain.gain.setValueAtTime(0.1, now);
gain.gain.linearRampToValueAtTime(0, now + 0.3);
osc.start(now);
osc.stop(now + 0.3);
break;
case 'gong':
osc.type = 'sine';
osc.frequency.setValueAtTime(150, now);
gain.gain.setValueAtTime(0.3, now);
gain.gain.exponentialRampToValueAtTime(0.001, now + 2);
osc.start(now);
osc.stop(now + 2);
break;
}
}
toggle() {
this.enabled = !this.enabled;
localStorage.setItem('zen-muted', !this.enabled);
return this.enabled;
}
}
// Network System
class NetworkManager {
constructor() {
this.peer = null;
this.conn = null;
this.myId = null;
this.isHost = false;
}
generateShortId() {
return Math.random().toString(36).substr(2, 6).toUpperCase();
}
initHost(onReady, onConnect) {
this.isHost = true;
this.myId = this.generateShortId();
this.peer = new Peer(this.myId);
this.peer.on('open', (id) => {
console.log('My peer ID is: ' + id);
onReady(id);
});
this.peer.on('connection', (conn) => {
this.conn = conn;
this.setupConnectionHandlers(onConnect);
});
}
initJoin(hostId, onConnect, onError) {
this.isHost = false;
this.peer = new Peer(); // Auto-gen ID for joiner
this.peer.on('open', () => {
this.conn = this.peer.connect(hostId);
this.conn.on('open', () => {
this.setupConnectionHandlers(onConnect);
});
this.conn.on('error', onError);
});
this.peer.on('error', onError);
}
setupConnectionHandlers(onConnect) {
onConnect();
this.conn.on('data', (data) => {
handleNetworkData(data);
});
this.conn.on('close', () => {
alert('Connection lost');
location.reload();
});
}
send(type, payload = {}) {
if (this.conn && this.conn.open) {
this.conn.send({ type, ...payload });
}
}
}
const net = new NetworkManager();
const sounds = new SoundManager();
// Game Logic
let playerScore = 0;
let computerScore = 0;
let isProcessing = false;
let isMultiplayer = false;
let localChoice = null;
let remoteChoice = null;
let isRemoteReady = false; // For replay sync
// UI Handling for Screens
const screens = {
start: document.getElementById('start-screen'),
lobby: document.getElementById('lobby-screen'),
game: document.getElementById('app') // The main game area
};
function showScreen(name) {
screens.start.classList.add('hidden');
screens.lobby.classList.add('hidden');
if (name === 'game') return; // Game is background, just hide others
screens[name].classList.remove('hidden');
}
// Menu Listeners
const cpuBtn = document.getElementById('mode-cpu');
if (cpuBtn) cpuBtn.addEventListener('click', () => {
isMultiplayer = false;
showScreen('game');
});
const friendBtn = document.getElementById('mode-friend');
if (friendBtn) friendBtn.addEventListener('click', () => {
isMultiplayer = true;
showScreen('lobby');
// Auto-generate host ID immediately for convenience
net.initHost((id) => {
document.getElementById('room-code-display').innerText = id;
document.getElementById('host-status').innerText = "Waiting for friend...";
}, () => {
// On Connect
document.getElementById('host-status').innerText = "Connected!";
setTimeout(() => showScreen('game'), 1000);
updatePlayerLabels("HOST", "FRIEND");
});
});
const joinBtn = document.getElementById('join-btn');
if (joinBtn) joinBtn.addEventListener('click', () => {
const code = document.getElementById('join-code-input').value.toUpperCase();
const status = document.getElementById('join-status');
if (code.length < 2) return;
status.innerText = "Connecting...";
net.initJoin(code, () => {
status.innerText = "Connected!";
setTimeout(() => showScreen('game'), 1000);
updatePlayerLabels("FRIEND", "HOST");
}, (err) => {
status.innerText = "Connection Failed";
console.error(err);
});
});
const backBtn = document.getElementById('back-btn');
if (backBtn) backBtn.addEventListener('click', () => showScreen('start'));
const copyBtn = document.getElementById('copy-code-btn');
if (copyBtn) copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(net.myId);
const originalText = copyBtn.innerText;
copyBtn.innerText = "COPIED!";
setTimeout(() => copyBtn.innerText = originalText, 1500);
});
function updatePlayerLabels(p1, p2) {
const pLabel = document.querySelector('#score-container .score-block:first-child .score-label');
const cLabel = document.querySelector('#score-container .score-block:last-child .score-label');
if (pLabel) pLabel.innerText = "YOU";
if (cLabel) cLabel.innerText = "ENEMY";
}
function handleNetworkData(data) {
console.log('Received:', data);
switch (data.type) {
case 'CHOICE_COMMITTED':
// Opponent has picked.
resultText.innerText = "ENEMY READY";
cFighter.classList.add('active'); // Show hidden icon
updateFighter(cFighter, 'hidden');
remoteChoice = 'HIDDEN'; // Placeholder
checkRoundReady();
break;
case 'REVEAL_CHOICE':
remoteChoice = data.choice;
checkRoundReady();
break;
case 'PLAY_AGAIN':
// Opponent wants to play again
isRemoteReady = true;
if (isGameOver) {
document.getElementById('play-again-btn').innerText = "OPPONENT READY";
}
checkResetReady();
break;
}
}
const CHOICES = ['rock', 'paper', 'scissors'];
const WINNING_SCORE = 3;
let isGameOver = false;
// DOM Elements
const pScoreEl = document.getElementById('player-score');
const cScoreEl = document.getElementById('computer-score');
const pFighter = document.getElementById('player-fighter');
const cFighter = document.getElementById('computer-fighter');
const resultText = document.getElementById('result-text');
const buttons = document.querySelectorAll('.choice-btn');
const controls = document.getElementById('controls');
const resetBtn = document.getElementById('reset-btn');
const playAgainBtn = document.getElementById('play-again-btn');
const gameOverOverlay = document.getElementById('game-over-overlay');
// New Polish Elements (Assuming they will be added to HTML)
const muteBtn = document.getElementById('mute-btn');
// Init
// loadScore(); // Disabled: Score resets on refresh
// Event Listeners
buttons.forEach(btn => {
btn.addEventListener('click', () => {
if (isProcessing || isGameOver) return;
playRound(btn.dataset.choice);
});
});
if (playAgainBtn) playAgainBtn.addEventListener('click', resetGame);
if (resetBtn) resetBtn.addEventListener('click', resetGame);
if (muteBtn) {
muteBtn.addEventListener('click', () => {
const isEnabled = sounds.toggle();
muteBtn.classList.toggle('muted', !isEnabled);
});
if (!sounds.enabled) muteBtn.classList.add('muted');
}
// Keyboard Support
window.addEventListener('keydown', (e) => {
if (isProcessing) return;
switch (e.key.toLowerCase()) {
case '1': case 'r': playRound('rock'); break;
case '2': case 'p': playRound('paper'); break;
case '3': case 's': playRound('scissors'); break;
case ' ': if (isGameOver) resetGame(); break;
case 'escape': resetGame(); break;
}
});
function resetGame() {
if (isProcessing) return;
if (isMultiplayer) {
net.send('PLAY_AGAIN');
// Wait for opponent
if (!isRemoteReady) {
resultText.innerText = "WAITING FOR OPPONENT";
document.getElementById('play-again-btn').innerText = "WAITING...";
return;
}
}
doReset();
}
function checkResetReady() {
if (isMultiplayer && isRemoteReady) {
// If I am also at Game Over screen, I can initiate if I clicked too?
// Actually, simplified: both must click play again.
// When play again clicked -> set localReady.
// If localReady && remoteReady -> doReset()
}
}
function doReset() {
playerScore = 0;
computerScore = 0;
isGameOver = false;
controls.classList.remove('disabled');
updateScoreUI();
if (!isMultiplayer) saveScore(); // Only save vs CPU
// Visual feedback
resultText.innerText = "SCORE RESET";
// Hide Overlay logic
if (gameOverOverlay) gameOverOverlay.classList.add('hidden');
setTimeout(() => {
if (!isProcessing) resultText.innerText = "CHOOSE";
}, 1000);
isRemoteReady = false;
if (isMultiplayer) document.getElementById('play-again-btn').innerText = "PLAY AGAIN";
}
// REMOVE OLD playRound function to avoid conflict
// (Consolidated into the one above)
function playRound(playerChoice) {
if (isProcessing) return;
if (isMultiplayer) {
// Multiplayer Flow
if (localChoice) return; // Already picked
localChoice = playerChoice;
updateFighter(pFighter, 'hidden');
pFighter.classList.add('active');
controls.classList.add('disabled'); // Lock temporarily
resultText.innerText = "WAITING...";
// 1. Send Commit signal
net.send('REVEAL_CHOICE', { choice: playerChoice });
checkRoundReady();
} else {
// CPU Flow (Original)
isProcessing = true;
controls.classList.add('disabled');
resetBtn.disabled = true;
resultText.innerText = "";
resultText.style.color = "var(--text-color)";
startShowdown(playerChoice, CHOICES[Math.floor(Math.random() * CHOICES.length)]);
}
}
function checkRoundReady() {
if (!isMultiplayer) return;
// We need both choices to proceed
if (localChoice && remoteChoice && remoteChoice !== 'HIDDEN') {
startShowdown(localChoice, remoteChoice);
// Reset for next round
localChoice = null;
remoteChoice = null;
}
}
function startShowdown(pChoice, cChoice) {
isProcessing = true;
resultText.style.color = "var(--text-color)";
// Setup Arena
updateFighter(pFighter, 'hidden');
updateFighter(cFighter, 'hidden');
pFighter.classList.add('active');
cFighter.classList.add('active');
// Shake
pFighter.classList.add('shaking');
cFighter.classList.add('shaking');
let count = 3;
resultText.innerText = count;
sounds.play('tick');
const interval = setInterval(() => {
count--;
if (count > 0) {
resultText.innerText = count;
sounds.play('tick');
} else {
clearInterval(interval);
// Reveal
pFighter.classList.remove('shaking');
cFighter.classList.remove('shaking');
updateFighter(pFighter, pChoice);
updateFighter(cFighter, cChoice);
pFighter.classList.add('reveal');
cFighter.classList.add('reveal');
const result = getWinner(pChoice, cChoice);
handleResult(result);
setTimeout(() => {
pFighter.classList.remove('reveal');
cFighter.classList.remove('reveal');
isProcessing = false;
controls.classList.remove('disabled');
resetBtn.disabled = false;
}, 1500);
}
}, 1000);
}
function getWinner(p, c) {
if (p === c) return 'tie';
if ((p === 'rock' && c === 'scissors') ||
(p === 'paper' && c === 'rock') ||
(p === 'scissors' && c === 'paper')) {
return 'win';
}
return 'loss';
}
function handleResult(result) {
const bgPulse = document.getElementById('bg-pulse');
// Remove previous classes to restart animation if needed (void trick)
bgPulse.className = '';
void bgPulse.offsetWidth; // Trigger reflow
if (result === 'win') {
playerScore++;
resultText.innerText = "YOU WON";
resultText.style.color = "var(--accent-win)";
bgPulse.classList.add('pulse-win');
sounds.play('win');
} else if (result === 'loss') {
computerScore++;
resultText.innerText = "YOU LOST";
resultText.style.color = "var(--accent-loss)";
bgPulse.classList.add('pulse-loss');
sounds.play('loss');
} else {
resultText.innerText = "DRAW";
resultText.style.color = "var(--accent-tie)";
bgPulse.classList.add('pulse-tie');
sounds.play('tie');
}
updateScoreUI();
saveScore();
// Check Winner
if (playerScore >= WINNING_SCORE) {
endGame('win');
} else if (computerScore >= WINNING_SCORE) {
endGame('loss');
}
}
function endGame(result) {
isGameOver = true;
const bgPulse = document.getElementById('bg-pulse');
// Ensure controls are locked
controls.classList.add('disabled');
if (result === 'win') {
resultText.innerText = "MATCH WON";
resultText.style.color = "var(--accent-win)";
} else {
resultText.innerText = "MATCH LOST";
resultText.style.color = "var(--accent-loss)";
}
sounds.play('gong');
// Show Play Again Overlay
if (gameOverOverlay) gameOverOverlay.classList.remove('hidden');
}
function updateFighter(el, choice) {
el.innerHTML = '';
const template = document.getElementById(`icon-${choice}`);
if (template) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 100 100");
const content = template.innerHTML;
svg.innerHTML = content;
el.appendChild(svg);
}
}
function updateScoreUI() {
if (pScoreEl) pScoreEl.innerText = playerScore;
if (cScoreEl) cScoreEl.innerText = computerScore;
}
function saveScore() {
localStorage.setItem('zen-rps-score', JSON.stringify({ p: playerScore, c: computerScore }));
}
function loadScore() {
const data = JSON.parse(localStorage.getItem('zen-rps-score'));
if (data) {
playerScore = data.p;
computerScore = data.c;
updateScoreUI();
}
}
});