Repository navigation
Expand file tree
/
Copy pathroll.html
More file actions
952 lines (855 loc) · 37.7 KB
/
Copy pathroll.html
File metadata and controls
952 lines (855 loc) · 37.7 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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SirObiVan's Dice Roller</title>
<style>
body {
font-family: "Times New Roman", serif;
background-image: url('90sstars.png');
background-repeat: repeat;
color: #000000;
margin: 0;
padding: 20px;
}
h1 {
color: #000080; /* Dark blue */
text-align: center;
}
a {
color: #0000FF;
text-decoration: underline;
}
.container {
width: 800px;
margin: 0 auto;
border: 2px solid #000;
background-color: #FFFFFF;
padding: 10px;
}
.nav {
background-color: #FFFFE0; /* Light yellow */
padding: 5px;
margin-bottom: 10px;
text-align: center;
}
.footer {
text-align: center;
font-size: small;
padding: 10px;
background-color: #E0E0E0;
}
.marquee {
color: #FF0000; /* Red scrolling text */
font-weight: bold;
}
.dice-selection {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 5px;
margin-bottom: 15px;
}
.dice-option {
background-color: #E0E0E0;
border: 2px outset #C0C0C0;
padding: 8px;
text-align: center;
cursor: pointer;
font-family: "Times New Roman", serif;
}
.dice-option:hover {
background-color: #D0D0D0;
}
.dice-option.active {
background-color: #000080;
color: white;
border-style: inset;
}
.dice-controls {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
margin-bottom: 15px;
padding: 10px;
background-color: #F0F0F0;
border: 1px solid #C0C0C0;
gap: 10px;
}
.quantity-control {
display: flex;
align-items: center;
gap: 10px;
}
.quantity-control input {
width: 50px;
padding: 5px;
border: 1px solid #808080;
}
.multiplier-control {
display: flex;
align-items: center;
gap: 10px;
}
.multiplier-control input {
width: 50px;
padding: 5px;
border: 1px solid #808080;
}
.toggle-control {
display: flex;
align-items: center;
gap: 10px;
}
button {
background-color: #C0C0C0;
color: black;
border: 2px outset #C0C0C0;
padding: 8px 15px;
cursor: pointer;
font-family: "Times New Roman", serif;
font-weight: bold;
}
button:hover {
background-color: #D0D0D0;
}
button:active {
border-style: inset;
}
.roll-button {
background-color: #008000;
color: white;
border: 2px outset #008000;
font-size: 1.1rem;
padding: 10px 25px;
}
.roll-button:hover {
background-color: #009000;
}
.results {
margin-top: 15px;
min-height: 100px;
border: 1px dashed #808080;
padding: 10px;
background-color: #F9F9F9;
max-height: 200px;
overflow-y: auto;
}
.result-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 5px 0;
border-bottom: 1px dotted #C0C0C0;
}
.result-item:last-child {
border-bottom: none;
}
.total-result {
font-weight: bold;
font-size: 1.1rem;
margin-top: 10px;
padding-top: 10px;
border-top: 2px solid #000080;
color: #FF0000;
}
.multiplied-total {
font-weight: bold;
font-size: 1.2rem;
margin-top: 10px;
padding-top: 10px;
border-top: 2px solid #FF0000;
color: #000080;
}
.stats-box {
background-color: #F0F8FF;
border: 1px solid #87CEEB;
padding: 10px;
margin: 15px 0;
}
.stat-item {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
}
.history {
margin-top: 20px;
}
.history h3 {
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px solid #C0C0C0;
}
.history-list {
max-height: 250px;
overflow-y: auto;
border: 1px solid #C0C0C0;
padding: 10px;
background-color: #F9F9F9;
}
.history-item {
padding: 8px 0;
border-bottom: 1px solid #E0E0E0;
font-size: 0.9rem;
}
.history-item:last-child {
border-bottom: none;
}
.history-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 5px;
font-weight: bold;
}
.history-details {
background-color: #F5F5F5;
padding: 8px;
border-left: 3px solid #000080;
}
.history-results {
font-family: "Courier New", monospace;
font-size: 0.85rem;
line-height: 1.4;
}
.history-total {
font-weight: bold;
color: #FF0000;
margin-top: 5px;
padding-top: 5px;
border-top: 1px solid #C0C0C0;
}
.history-multiplied {
font-weight: bold;
color: #000080;
margin-top: 5px;
}
.buttons {
text-align: center;
margin: 15px 0;
}
.mixed-dice-controls {
margin: 10px 0;
padding: 10px;
background-color: #FFF8DC;
border: 1px solid #C0C0C0;
}
.mixed-dice-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 5px;
}
.mixed-dice-row input {
width: 60px;
padding: 5px;
border: 1px solid #808080;
}
.mixed-dice-row select {
padding: 5px;
border: 1px solid #808080;
}
.add-dice-button {
background-color: #000080;
color: white;
border: 2px outset #000080;
}
.remove-dice-button {
background-color: #800000;
color: white;
border: 2px outset #800000;
}
.toggle-label {
display: flex;
align-items: center;
gap: 5px;
cursor: pointer;
}
.toggle-checkbox {
width: auto;
}
.mixed-dice-buttons {
display: flex;
gap: 10px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>SirObiVan's Dice Roller!</h1>
<!-- Marquee for classic scrolling text -->
<marquee class="marquee">Roll the dice for your tabletop gaming needs! Now with damage multipliers and mixed dice!</marquee>
<!-- Navigation links -->
<div class="nav">
<a href="index.html">Home</a> |
<a href="about.html">About</a> |
<a href="resume.html">Resume</a> |
<a href="contact.html">Contact</a> |
<a href="stars.html">Stars</a> |
<a href="roll.html">Dice Roller</a> |
<a href="simulations.html">Circuit Simulations</a>
</div>
<!-- Main content -->
<table width="100%" cellpadding="10" cellspacing="0" border="1">
<tr>
<td>
<p><b>Welcome to the Dice Roller!</b></p>
<p>This dice roller uses Java Script and displays some statistics for multiple rolls!</p>
<div class="dice-selection">
<div class="dice-option active" data-sides="4">
d4
</div>
<div class="dice-option" data-sides="6">
d6
</div>
<div class="dice-option" data-sides="8">
d8
</div>
<div class="dice-option" data-sides="10">
d10
</div>
<div class="dice-option" data-sides="12">
d12
</div>
<div class="dice-option" data-sides="20">
d20
</div>
<div class="dice-option" data-sides="100">
d100
</div>
<div class="dice-option" data-sides="2">
Coin Flip
</div>
</div>
<!-- Mixed Dice Section -->
<div class="mixed-dice-controls">
<h3>Mixed Dice (for spells and such)</h3>
<div id="mixed-dice-container">
<div class="mixed-dice-row">
<input type="number" min="1" max="100" value="1" class="mixed-quantity">
<select class="mixed-sides">
<option value="4">d4</option>
<option value="6" selected>d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20">d20</option>
<option value="100">d100</option>
</select>
<button class="remove-dice-button" onclick="removeMixedDice(this)" disabled>Remove</button>
</div>
</div>
<div class="mixed-dice-buttons">
<button class="add-dice-button" onclick="addMixedDice()">Add More Dice</button>
<button class="add-dice-button" onclick="addSelectedDice()">Add Selected Dice</button>
</div>
</div>
<div class="dice-controls">
<div class="quantity-control">
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" min="1" max="100" value="1">
</div>
<div class="multiplier-control">
<label for="multiplier">Multiplier:</label>
<input type="number" id="multiplier" min="1" max="100" value="1">
</div>
<div class="toggle-control">
<label class="toggle-label">
<input type="checkbox" id="apply-multiplier" class="toggle-checkbox">
Apply Multiplier
</label>
</div>
<button id="clear-results">Clear Results</button>
<button id="roll-button" class="roll-button">Roll Dice</button>
</div>
<div class="stats-box" id="stats-container">
<p>Roll some dice to see statistics</p>
</div>
<div class="results" id="results-container">
<p>Select dice and click "Roll Dice" to get started!</p>
</div>
<div class="history">
<div style="display: flex; justify-content: space-between; align-items: center;">
<h3>Roll History</h3>
<div class="toggle-control">
<label class="toggle-label">
<input type="checkbox" id="cumulative-stats" class="toggle-checkbox" checked>
Cumulative Statistics
</label>
</div>
</div>
<div class="history-list" id="history-container">
<!-- History items will be added here -->
</div>
</div>
<img src="dice.gif" alt="dice" align="right" style="border: 2px solid #000; image-rendering: pixelated;">
</td>
</tr>
</table>
<!-- 80x15 GIF Buttons Section -->
<div class="buttons">
<a href="osu.gi"><img src="osu.gif" alt="osu" width="80" height="15"></a>
<a href="9_eire.png"><img src="9_eire.png" alt="eire" width="80" height="15"></a>
<a href="ilovemusic.png"><img src="ilovemusic.png" alt="music" width="80" height="15"></a>
<a href="xp.gif"><img src="xp.gif" alt="xp" width="80" height="15"></a>
<a href="coffeepower.png"><img src="coffeepower.png" alt="coffee" width="80" height="15"></a>
<a href="loveani.gif"><img src="loveani.gif" alt="love" width="80" height="15"></a>
<a href="ibm.gif"><img src="ibm.gif" alt="ibm" width="80" height="15"></a>
</div>
<div class="footer">
<p>Copyright © 2024 Preston Parsons. All rights reserved.</p>
<p><a href="mailto:ogaugeandcode@gmail.com">Email Me</a></p>
</div>
</div>
<script>
// Mixed dice functions
function addMixedDice() {
const container = document.getElementById('mixed-dice-container');
const newRow = document.createElement('div');
newRow.className = 'mixed-dice-row';
newRow.innerHTML = `
<input type="number" min="1" max="100" value="1" class="mixed-quantity">
<select class="mixed-sides">
<option value="4">d4</option>
<option value="6" selected>d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20">d20</option>
<option value="100">d100</option>
</select>
<button class="remove-dice-button" onclick="removeMixedDice(this)">Remove</button>
`;
container.appendChild(newRow);
// Enable remove buttons if there's more than one row
const removeButtons = container.querySelectorAll('.remove-dice-button');
if (removeButtons.length > 1) {
removeButtons.forEach(btn => btn.disabled = false);
}
}
function removeMixedDice(button) {
const container = document.getElementById('mixed-dice-container');
const rows = container.querySelectorAll('.mixed-dice-row');
if (rows.length > 1) {
button.parentElement.remove();
// Disable remove button if only one row left
const remainingButtons = container.querySelectorAll('.remove-dice-button');
if (remainingButtons.length === 1) {
remainingButtons[0].disabled = true;
}
}
}
function addSelectedDice() {
const activeDice = document.querySelector('.dice-option.active');
if (!activeDice) return;
const sides = parseInt(activeDice.getAttribute('data-sides'));
const quantity = parseInt(document.getElementById('quantity').value) || 1;
const container = document.getElementById('mixed-dice-container');
const newRow = document.createElement('div');
newRow.className = 'mixed-dice-row';
newRow.innerHTML = `
<input type="number" min="1" max="100" value="${quantity}" class="mixed-quantity">
<select class="mixed-sides">
<option value="4" ${sides === 4 ? 'selected' : ''}>d4</option>
<option value="6" ${sides === 6 ? 'selected' : ''}>d6</option>
<option value="8" ${sides === 8 ? 'selected' : ''}>d8</option>
<option value="10" ${sides === 10 ? 'selected' : ''}>d10</option>
<option value="12" ${sides === 12 ? 'selected' : ''}>d12</option>
<option value="20" ${sides === 20 ? 'selected' : ''}>d20</option>
<option value="100" ${sides === 100 ? 'selected' : ''}>d100</option>
</select>
<button class="remove-dice-button" onclick="removeMixedDice(this)">Remove</button>
`;
container.appendChild(newRow);
// Enable remove buttons if there's more than one row
const removeButtons = container.querySelectorAll('.remove-dice-button');
if (removeButtons.length > 1) {
removeButtons.forEach(btn => btn.disabled = false);
}
}
document.addEventListener('DOMContentLoaded', function() {
// DOM elements
const diceOptions = document.querySelectorAll('.dice-option');
const quantityInput = document.getElementById('quantity');
const multiplierInput = document.getElementById('multiplier');
const applyMultiplierCheckbox = document.getElementById('apply-multiplier');
const cumulativeStatsCheckbox = document.getElementById('cumulative-stats');
const rollButton = document.getElementById('roll-button');
const clearButton = document.getElementById('clear-results');
const resultsContainer = document.getElementById('results-container');
const historyContainer = document.getElementById('history-container');
const statsContainer = document.getElementById('stats-container');
// State variables
let selectedSides = 4;
let rollHistory = [];
let allRolls = []; // For cumulative statistics
// Initialize dice selection
diceOptions.forEach(option => {
option.addEventListener('click', function() {
// Remove active class from all options
diceOptions.forEach(opt => opt.classList.remove('active'));
// Add active class to clicked option
this.classList.add('active');
// Update selected sides
selectedSides = parseInt(this.getAttribute('data-sides'));
});
});
// Roll button event listener
rollButton.addEventListener('click', function() {
const quantity = parseInt(quantityInput.value);
const multiplier = parseInt(multiplierInput.value);
if (isNaN(quantity) || quantity < 1) {
alert('Please enter a valid quantity (1-100)');
return;
}
if (quantity > 100) {
alert('Maximum 100 dice at a time for performance');
return;
}
if (isNaN(multiplier) || multiplier < 1) {
alert('Please enter a valid multiplier (1-100)');
return;
}
// Check if we have mixed dice configured
const mixedRows = document.querySelectorAll('.mixed-dice-row');
if (mixedRows.length > 0) {
rollMixedDice(multiplier);
} else {
rollDice(selectedSides, quantity, multiplier);
}
});
// Clear results button
clearButton.addEventListener('click', function() {
resultsContainer.innerHTML = '<p>Select dice and click "Roll Dice" to get started!</p>';
statsContainer.innerHTML = '<p>Roll some dice to see statistics</p>';
rollHistory = [];
allRolls = [];
updateHistoryDisplay();
});
// SIMPLIFIED AND CORRECTED random number generator
async function getSecureRandomInt(min, max) {
// Use Web Crypto API directly with proper range handling
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
// Simple, reliable range conversion
const range = max - min + 1;
const maxRange = 0xFFFFFFFF; // Maximum 32-bit unsigned integer
// Ensure we don't have modulo bias by using rejection sampling
const maxUnbiased = maxRange - (maxRange % range);
let value;
do {
window.crypto.getRandomValues(randomBuffer);
value = randomBuffer[0];
} while (value >= maxUnbiased);
// Convert to desired range and add min
const result = min + (value % range);
// Final validation to ensure result is within bounds
if (result < min || result > max) {
console.error('Random number out of bounds:', result, 'Expected:', min, '-', max);
// Fallback: use Math.random() as backup (less secure but correct range)
return Math.floor(Math.random() * range) + min;
}
return result;
}
// Function to roll mixed dice (for spells like Meteor Swarm)
async function rollMixedDice(multiplier) {
// Clear previous results
resultsContainer.innerHTML = '';
// Get mixed dice configuration
const mixedRows = document.querySelectorAll('.mixed-dice-row');
const diceConfigs = [];
mixedRows.forEach(row => {
const quantity = parseInt(row.querySelector('.mixed-quantity').value);
const sides = parseInt(row.querySelector('.mixed-sides').value);
if (!isNaN(quantity) && quantity > 0 && quantity <= 100) {
diceConfigs.push({ quantity, sides });
}
});
if (diceConfigs.length === 0) {
alert('Please configure at least one set of dice');
return;
}
// Show rolling animation
let description = diceConfigs.map(config => `${config.quantity}d${config.sides}`).join(' + ');
resultsContainer.innerHTML = `<p>Rolling ${description}...</p>`;
try {
const allResults = [];
const rollDetails = [];
// Roll each type of dice
for (const config of diceConfigs) {
const { quantity, sides } = config;
const results = [];
// Create promises for all dice rolls of this type
const rollPromises = [];
for (let i = 0; i < quantity; i++) {
rollPromises.push(getSecureRandomInt(1, sides));
}
// Wait for all rolls to complete
const typeResults = await Promise.all(rollPromises);
results.push(...typeResults);
// Store details for display
rollDetails.push({
sides: sides,
quantity: quantity,
results: typeResults,
total: typeResults.reduce((sum, val) => sum + val, 0)
});
allResults.push(...typeResults);
}
// Calculate totals
const baseTotal = allResults.reduce((sum, value) => sum + value, 0);
const finalTotal = applyMultiplierCheckbox.checked ? baseTotal * multiplier : baseTotal;
// Display results
resultsContainer.innerHTML = '';
rollDetails.forEach(detail => {
const typeHeader = document.createElement('div');
typeHeader.className = 'result-item';
typeHeader.innerHTML = `<strong>${detail.quantity}d${detail.sides}:</strong>`;
resultsContainer.appendChild(typeHeader);
detail.results.forEach((result, index) => {
const resultItem = document.createElement('div');
resultItem.className = 'result-item';
resultItem.innerHTML = `
<span>d${detail.sides} ${index + 1}:</span>
<span>${result}</span>
`;
resultsContainer.appendChild(resultItem);
});
const typeTotal = document.createElement('div');
typeTotal.className = 'result-item';
typeTotal.innerHTML = `
<span><em>Subtotal:</em></span>
<span><em>${detail.total}</em></span>
`;
resultsContainer.appendChild(typeTotal);
});
// Display totals
const totalElement = document.createElement('div');
totalElement.className = 'total-result';
totalElement.textContent = `Base Total: ${baseTotal}`;
resultsContainer.appendChild(totalElement);
if (applyMultiplierCheckbox.checked) {
const multipliedElement = document.createElement('div');
multipliedElement.className = 'multiplied-total';
multipliedElement.textContent = `Final Damage: ${baseTotal} × ${multiplier} = ${finalTotal}`;
resultsContainer.appendChild(multipliedElement);
}
// Update statistics
updateStatistics(allResults, 'Mixed', baseTotal);
// Add to history
const historyEntry = {
timestamp: new Date().toLocaleString(),
type: 'mixed',
configs: diceConfigs,
results: rollDetails,
baseTotal: baseTotal,
multiplier: applyMultiplierCheckbox.checked ? multiplier : 1,
finalTotal: finalTotal
};
rollHistory.unshift(historyEntry);
if (rollHistory.length > 10) {
rollHistory.pop();
}
updateHistoryDisplay();
} catch (error) {
console.error('Error rolling mixed dice:', error);
resultsContainer.innerHTML = `<p style="color: #FF0000;">Error: ${error.message}. Please try again.</p>`;
}
}
// Function to roll dice
async function rollDice(sides, quantity, multiplier) {
// Clear previous results
resultsContainer.innerHTML = '';
// Show rolling animation
resultsContainer.innerHTML = `<p>Rolling ${quantity}d${sides}...</p>`;
try {
// Create an array of promises for all dice rolls
const rollPromises = [];
for (let i = 0; i < quantity; i++) {
rollPromises.push(getSecureRandomInt(1, sides));
}
// Wait for all rolls to complete
const results = await Promise.all(rollPromises);
// Validate all results are within expected range
const invalidResults = results.filter(result => result < 1 || result > sides);
if (invalidResults.length > 0) {
console.error('Invalid dice results detected:', invalidResults);
throw new Error(`Generated ${invalidResults.length} invalid dice results`);
}
// Calculate totals
const baseTotal = results.reduce((sum, value) => sum + value, 0);
const finalTotal = applyMultiplierCheckbox.checked ? baseTotal * multiplier : baseTotal;
// Display results
resultsContainer.innerHTML = '';
results.forEach((result, index) => {
const resultItem = document.createElement('div');
resultItem.className = 'result-item';
// Special display for coin flip
if (sides === 2) {
const coinResult = result === 1 ? 'Heads' : 'Tails';
resultItem.innerHTML = `
<span>Coin ${index + 1}:</span>
<span>${coinResult}</span>
`;
} else {
resultItem.innerHTML = `
<span>d${sides} ${index + 1}:</span>
<span>${result}</span>
`;
}
resultsContainer.appendChild(resultItem);
});
// Display totals
if (quantity > 1) {
const totalElement = document.createElement('div');
totalElement.className = 'total-result';
totalElement.textContent = `Base Total: ${baseTotal}`;
resultsContainer.appendChild(totalElement);
}
if (applyMultiplierCheckbox.checked && multiplier > 1) {
const multipliedElement = document.createElement('div');
multipliedElement.className = 'multiplied-total';
multipliedElement.textContent = `Final Damage: ${baseTotal} × ${multiplier} = ${finalTotal}`;
resultsContainer.appendChild(multipliedElement);
}
// Update statistics
updateStatistics(results, sides, baseTotal);
// Add to history
const historyEntry = {
timestamp: new Date().toLocaleString(),
type: 'single',
sides: sides,
quantity: quantity,
results: results,
baseTotal: baseTotal,
multiplier: applyMultiplierCheckbox.checked ? multiplier : 1,
finalTotal: finalTotal
};
rollHistory.unshift(historyEntry);
if (rollHistory.length > 10) {
rollHistory.pop();
}
updateHistoryDisplay();
} catch (error) {
console.error('Error rolling dice:', error);
resultsContainer.innerHTML = `<p style="color: #FF0000;">Error: ${error.message}. Please try again.</p>`;
}
}
// Function to update statistics display
function updateStatistics(results, sides, baseTotal) {
// Add to cumulative rolls if enabled
if (cumulativeStatsCheckbox.checked) {
allRolls.push(...results);
} else {
allRolls = [...results]; // Only keep current rolls
}
// Calculate statistics
const mean = allRolls.reduce((a, b) => a + b, 0) / allRolls.length;
const variance = allRolls.reduce((a, b) => a + Math.pow(b - mean, 2), 0) / allRolls.length;
const stdDev = Math.sqrt(variance);
// Expected values for fair dice (only for single dice type)
let expectedMean, expectedStdDev;
if (sides !== 'Mixed') {
expectedMean = (sides + 1) / 2;
expectedStdDev = Math.sqrt((Math.pow(sides, 2) - 1) / 12);
}
// Update stats display
let statsHTML = `
<div class="stat-item">
<span>Mean:</span>
<span>${mean.toFixed(2)}</span>
</div>
<div class="stat-item">
<span>Std Dev:</span>
<span>${stdDev.toFixed(2)}</span>
</div>
<div class="stat-item">
<span>Rolls:</span>
<span>${allRolls.length}</span>
</div>
<div class="stat-item">
<span>Last Roll Total:</span>
<span>${baseTotal}</span>
</div>
`;
if (sides !== 'Mixed') {
statsHTML += `
<div class="stat-item">
<span>Expected Mean:</span>
<span>${expectedMean.toFixed(2)}</span>
</div>
`;
}
if (cumulativeStatsCheckbox.checked) {
statsHTML += `<div class="stat-item"><span><em>Cumulative Stats</em></span></div>`;
} else {
statsHTML += `<div class="stat-item"><span><em>Current Roll Stats</em></span></div>`;
}
statsContainer.innerHTML = statsHTML;
}
// Function to update history display
function updateHistoryDisplay() {
historyContainer.innerHTML = '';
if (rollHistory.length === 0) {
historyContainer.innerHTML = '<p>No rolls yet</p>';
return;
}
rollHistory.forEach((entry, index) => {
const historyItem = document.createElement('div');
historyItem.className = 'history-item';
let resultsText, rollDescription;
if (entry.type === 'mixed') {
// Format mixed dice results
const typeResults = entry.results.map(result =>
`${result.quantity}d${result.sides}: [${result.results.join(', ')}] = ${result.total}`
);
resultsText = typeResults.join('<br>');
rollDescription = entry.configs.map(config => `${config.quantity}d${config.sides}`).join(' + ');
} else {
// Format single dice type results
if (entry.sides === 2) {
const coinResults = entry.results.map(r => r === 1 ? 'Heads' : 'Tails');
resultsText = coinResults.join(', ');
} else {
resultsText = `[${entry.results.join(', ')}]`;
}
rollDescription = `${entry.quantity}d${entry.sides}`;
}
// Create the history entry
historyItem.innerHTML = `
<div class="history-header">
<span>${entry.timestamp}</span>
<span>${rollDescription}</span>
</div>
<div class="history-details">
<div class="history-results">
${resultsText}
</div>
<div class="history-total">Base Total: ${entry.baseTotal}</div>
${entry.multiplier > 1 ? `<div class="history-multiplied">Final Damage: ${entry.baseTotal} × ${entry.multiplier} = ${entry.finalTotal}</div>` : ''}
</div>
`;
historyContainer.appendChild(historyItem);
});
}
// Add event listener for cumulative stats toggle
cumulativeStatsCheckbox.addEventListener('change', function() {
if (allRolls.length > 0) {
// Recalculate statistics with current settings
const currentEntry = rollHistory[0];
if (currentEntry) {
if (currentEntry.type === 'mixed') {
const allResults = currentEntry.results.flatMap(r => r.results);
updateStatistics(allResults, 'Mixed', currentEntry.baseTotal);
} else {
updateStatistics(currentEntry.results, currentEntry.sides, currentEntry.baseTotal);
}
}
}
});
});
</script>
</body>
</html>