-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
475 lines (380 loc) · 16.6 KB
/
script.js
File metadata and controls
475 lines (380 loc) · 16.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
class MechanicalBinaryCounter {
constructor() {
this.bits = [];
this.currentValue = 0;
this.bitCount = 4; // Start with 4 bits
this.maxValue = Math.pow(2, this.bitCount) - 1;
this.isAnimating = false;
// Audio context for sound effects
this.audioContext = null;
this.soundEnabled = true;
// DOM elements
this.bitContainer = document.getElementById('bitContainer');
this.binaryDisplay = document.getElementById('binaryDisplay');
this.decimalDisplay = document.getElementById('decimalDisplay');
this.maxDisplay = document.getElementById('maxDisplay');
this.incrementBtn = document.getElementById('incrementBtn');
this.resetBtn = document.getElementById('resetBtn');
this.addBitBtn = document.getElementById('addBitBtn');
this.removeBitBtn = document.getElementById('removeBitBtn');
this.bitInput = document.getElementById('bitInput');
this.statusMessage = document.getElementById('statusMessage');
this.overflowIndicator = document.getElementById('overflowIndicator');
this.init();
}
async init() {
await this.initAudio();
this.createBits();
this.updateDisplays();
this.bindEvents();
this.checkOverflowReady();
// Welcome message
this.showStatus('Binary counter initialized with ' + this.bitCount + ' bits', 'success');
}
async initAudio() {
try {
// Initialize on user interaction to comply with browser policies
document.addEventListener('click', async () => {
if (!this.audioContext) {
this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
if (this.audioContext.state === 'suspended') {
await this.audioContext.resume();
}
}
}, { once: true });
} catch (error) {
console.warn('Web Audio API not supported:', error);
this.soundEnabled = false;
}
}
createBits() {
this.bitContainer.innerHTML = '';
this.bits = [];
// Create bits from left to right (most significant to least significant)
for (let i = this.bitCount - 1; i >= 0; i--) {
const bitElement = this.createBitElement(i);
this.bitContainer.appendChild(bitElement);
this.bits[i] = {
element: bitElement,
value: 0,
position: i
};
// Initialize bit faces to show 0 (front face visible)
const front = bitElement.querySelector('.bit-front');
const back = bitElement.querySelector('.bit-back');
front.style.transform = 'rotateX(0deg)';
back.style.transform = 'rotateX(90deg)';
}
}
createBitElement(position) {
const bit = document.createElement('div');
bit.className = 'bit';
bit.dataset.position = position;
const front = document.createElement('div');
front.className = 'bit-face bit-front';
front.textContent = '0';
const back = document.createElement('div');
back.className = 'bit-face bit-back';
back.textContent = '1';
const label = document.createElement('div');
label.className = 'bit-label';
label.textContent = `2^${position}`;
bit.appendChild(front);
bit.appendChild(back);
bit.appendChild(label);
return bit;
}
bindEvents() {
this.incrementBtn.addEventListener('click', () => this.increment());
this.resetBtn.addEventListener('click', () => this.reset());
this.addBitBtn.addEventListener('click', () => this.addBits());
this.removeBitBtn.addEventListener('click', () => this.removeBits());
// Allow Enter key on bit input
this.bitInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.addBits();
}
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.target.tagName.toLowerCase() === 'input') return;
switch (e.key) {
case ' ':
case 'Enter':
e.preventDefault();
this.increment();
break;
case 'r':
case 'R':
this.reset();
break;
case '+':
case '=':
e.preventDefault();
this.addBits();
break;
case '-':
case '_':
e.preventDefault();
this.removeBits();
break;
}
});
}
async increment() {
if (this.isAnimating) return;
const nextValue = this.currentValue + 1;
// Check for overflow
if (nextValue > this.maxValue) {
await this.handleOverflow();
return;
}
await this.setValue(nextValue);
}
async setValue(newValue) {
if (this.isAnimating) return;
this.isAnimating = true;
const oldValue = this.currentValue;
this.currentValue = newValue;
// Determine which bits need to flip
const changedBits = [];
for (let i = 0; i < this.bitCount; i++) {
const oldBit = (oldValue >> i) & 1;
const newBit = (newValue >> i) & 1;
if (oldBit !== newBit) {
changedBits.push(i);
}
}
// Play single domino sound for the entire operation
if (changedBits.length > 0) {
this.playDominoSound();
}
// Animate bit flips with staggered timing
const flipPromises = changedBits.map((bitIndex, index) => {
return new Promise((resolve) => {
setTimeout(async () => {
await this.flipBit(bitIndex, false); // Pass false to skip individual sounds
resolve();
}, index * 100); // Stagger flips by 100ms
});
});
await Promise.all(flipPromises);
this.updateDisplays();
this.checkOverflowReady();
this.isAnimating = false;
// Show success message for significant milestones
if (newValue === this.maxValue) {
this.showStatus('Maximum value reached! Next increment will cause overflow.', 'warning');
} else if (newValue === 0 && oldValue > 0) {
this.showStatus('Counter reset to zero', 'success');
}
}
async flipBit(bitIndex, playSound = true) {
const bit = this.bits[bitIndex];
if (!bit) return;
const newValue = (this.currentValue >> bitIndex) & 1;
// Only play sound if explicitly requested (for individual operations)
if (playSound) {
this.playDominoSound();
}
const front = bit.element.querySelector('.bit-front');
const back = bit.element.querySelector('.bit-back');
// Determine which face should be visible
if (newValue === 1) {
// Show the "1" face (back)
front.style.transform = 'rotateX(-90deg)';
back.style.transform = 'rotateX(0deg)';
} else {
// Show the "0" face (front)
front.style.transform = 'rotateX(0deg)';
back.style.transform = 'rotateX(90deg)';
}
bit.value = newValue;
return new Promise(resolve => setTimeout(resolve, 600));
}
async handleOverflow() {
this.showStatus('Integer overflow! Counter wrapping to zero...', 'warning');
// Visual effect for overflow
this.overflowIndicator.classList.add('ready');
setTimeout(() => {
this.overflowIndicator.classList.remove('ready');
}, 1000);
await this.setValue(0);
this.showStatus('Overflow complete. Counter reset to zero.', 'success');
}
reset() {
if (this.isAnimating) return;
this.setValue(0);
this.showStatus('Counter manually reset', 'success');
}
addBits() {
if (this.isAnimating) return;
const bitsToAdd = parseInt(this.bitInput.value) || 1;
const newBitCount = this.bitCount + bitsToAdd;
if (newBitCount > 16) {
this.showStatus('Maximum 16 bits allowed', 'error');
return;
}
if (bitsToAdd < 1) {
this.showStatus('Must add at least 1 bit', 'error');
return;
}
this.bitCount = newBitCount;
this.maxValue = Math.pow(2, this.bitCount) - 1;
// Add new bits with animation
for (let i = this.bitCount - bitsToAdd; i < this.bitCount; i++) {
const bitElement = this.createBitElement(i);
bitElement.classList.add('new');
this.bitContainer.insertBefore(bitElement, this.bitContainer.firstChild);
this.bits[i] = {
element: bitElement,
value: 0,
position: i
};
// Initialize new bit faces to show 0 (front face visible)
const front = bitElement.querySelector('.bit-front');
const back = bitElement.querySelector('.bit-back');
front.style.transform = 'rotateX(0deg)';
back.style.transform = 'rotateX(90deg)';
}
this.updateDisplays();
this.checkOverflowReady();
this.showStatus(`Added ${bitsToAdd} bit${bitsToAdd > 1 ? 's' : ''}. New capacity: ${this.maxValue + 1} values`, 'success');
// Reset bit input
this.bitInput.value = 1;
}
removeBits() {
if (this.isAnimating) return;
const bitsToRemove = parseInt(this.bitInput.value) || 1;
const newBitCount = this.bitCount - bitsToRemove;
if (newBitCount < 1) {
this.showStatus('Must have at least 1 bit', 'error');
return;
}
if (bitsToRemove < 1) {
this.showStatus('Must remove at least 1 bit', 'error');
return;
}
// Check if current value would exceed new maximum
const newMaxValue = Math.pow(2, newBitCount) - 1;
if (this.currentValue > newMaxValue) {
this.showStatus(`Current value (${this.currentValue}) exceeds new maximum (${newMaxValue}). Reset counter first.`, 'error');
return;
}
// Remove bits from the left (most significant bits)
for (let i = this.bitCount - 1; i >= newBitCount; i--) {
const bitToRemove = this.bits[i];
if (bitToRemove && bitToRemove.element) {
// Add remove animation
bitToRemove.element.style.animation = 'slideOut 0.5s ease-in forwards';
setTimeout(() => {
if (bitToRemove.element && bitToRemove.element.parentNode) {
bitToRemove.element.parentNode.removeChild(bitToRemove.element);
}
}, 500);
delete this.bits[i];
}
}
this.bitCount = newBitCount;
this.maxValue = newMaxValue;
this.updateDisplays();
this.checkOverflowReady();
this.showStatus(`Removed ${bitsToRemove} bit${bitsToRemove > 1 ? 's' : ''}. New capacity: ${this.maxValue + 1} values`, 'success');
// Reset bit input
this.bitInput.value = 1;
}
updateDisplays() {
// Update binary display
const binaryString = this.currentValue.toString(2).padStart(this.bitCount, '0');
this.binaryDisplay.textContent = binaryString;
// Update decimal display
this.decimalDisplay.textContent = this.currentValue.toLocaleString();
// Update max value display
this.maxDisplay.textContent = this.maxValue.toLocaleString();
}
checkOverflowReady() {
if (this.currentValue === this.maxValue) {
this.overflowIndicator.classList.add('ready');
this.overflowIndicator.querySelector('.indicator-text').textContent = 'Overflow Ready!';
} else {
this.overflowIndicator.classList.remove('ready');
this.overflowIndicator.querySelector('.indicator-text').textContent = 'Overflow Ready';
}
}
showStatus(message, type = '') {
this.statusMessage.textContent = message;
this.statusMessage.className = 'status-message' + (type ? ' ' + type : '');
// Clear message after 3 seconds
setTimeout(() => {
this.statusMessage.textContent = '';
this.statusMessage.className = 'status-message';
}, 3000);
}
playDominoSound() {
if (!this.soundEnabled || !this.audioContext) return;
try {
// Create a domino-like clicking sound
const now = this.audioContext.currentTime;
// Sharp click attack
const clickOsc = this.audioContext.createOscillator();
const clickGain = this.audioContext.createGain();
clickOsc.type = 'square';
clickOsc.frequency.setValueAtTime(2000, now);
clickOsc.frequency.exponentialRampToValueAtTime(800, now + 0.02);
clickGain.gain.setValueAtTime(0.2, now);
clickGain.gain.exponentialRampToValueAtTime(0.001, now + 0.03);
clickOsc.connect(clickGain);
clickGain.connect(this.audioContext.destination);
clickOsc.start(now);
clickOsc.stop(now + 0.03);
// Wooden tap resonance
const resonanceOsc = this.audioContext.createOscillator();
const resonanceGain = this.audioContext.createGain();
resonanceOsc.type = 'triangle';
resonanceOsc.frequency.setValueAtTime(400, now + 0.01);
resonanceOsc.frequency.exponentialRampToValueAtTime(300, now + 0.08);
resonanceGain.gain.setValueAtTime(0.15, now + 0.01);
resonanceGain.gain.exponentialRampToValueAtTime(0.001, now + 0.08);
resonanceOsc.connect(resonanceGain);
resonanceGain.connect(this.audioContext.destination);
resonanceOsc.start(now + 0.01);
resonanceOsc.stop(now + 0.08);
// Brief noise for texture (like domino surface)
const bufferSize = this.audioContext.sampleRate * 0.02;
const buffer = this.audioContext.createBuffer(1, bufferSize, this.audioContext.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (bufferSize * 0.3)) * 0.1;
}
const noiseSource = this.audioContext.createBufferSource();
const noiseGain = this.audioContext.createGain();
const noiseFilter = this.audioContext.createBiquadFilter();
noiseSource.buffer = buffer;
noiseFilter.type = 'highpass';
noiseFilter.frequency.value = 1500;
noiseGain.gain.setValueAtTime(0.08, now);
noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.02);
noiseSource.connect(noiseFilter);
noiseFilter.connect(noiseGain);
noiseGain.connect(this.audioContext.destination);
noiseSource.start(now);
noiseSource.stop(now + 0.02);
} catch (error) {
console.warn('Could not play sound:', error);
}
}
}
// Initialize the counter when the page loads
document.addEventListener('DOMContentLoaded', () => {
window.binaryCounter = new MechanicalBinaryCounter();
});
// Handle visibility change to pause/resume audio context
document.addEventListener('visibilitychange', () => {
if (window.binaryCounter && window.binaryCounter.audioContext) {
if (document.hidden) {
window.binaryCounter.audioContext.suspend();
} else {
window.binaryCounter.audioContext.resume();
}
}
});