Last active
January 31, 2023 15:52
-
-
Save telagraphic/f32acf021808439f2bfcf7b26e836a74 to your computer and use it in GitHub Desktop.
Dice project
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Dice Library</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<style type="text/css"> | |
body { | |
margin: 0 auto; | |
max-width: 40em; | |
width: 88%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Dice Library</h1> | |
<p>All of the magic here happens in the console.</p> | |
<script> | |
let roll = (function() { | |
/** | |
* Randomly shuffle an array | |
* https://stackoverflow.com/a/2450976/1293256 | |
* @param {Array} array The array to shuffle | |
* @return {Array} The shuffled array | |
*/ | |
function shuffle(array) { | |
let currentIndex = array.length; | |
let temporaryValue, randomIndex; | |
// While there remain elements to shuffle... | |
while (0 !== currentIndex) { | |
// Pick a remaining element... | |
randomIndex = Math.floor(Math.random() * currentIndex); | |
currentIndex -= 1; | |
// And swap it with the current element. | |
temporaryValue = array[currentIndex]; | |
array[currentIndex] = array[randomIndex]; | |
array[randomIndex] = temporaryValue; | |
} | |
return array; | |
} | |
/** | |
* Creates an n-side dice array | |
* @param {Number} dice The number of sides for the dice you want | |
* @return {Array} an array of numbers for the dice | |
*/ | |
function setupDice(dice) { | |
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]; | |
let diceNumbers = numbers.slice(0, dice); | |
return diceNumbers; | |
} | |
function d2() { | |
let d2 = setupDice(2); | |
return shuffle(d2).shift(); | |
} | |
function d4() { | |
let d4 = setupDice(4); | |
return shuffle(d4).shift(); | |
} | |
function d6() { | |
let d6 = setupDice(6); | |
return shuffle(d6).shift(); | |
} | |
function d8() { | |
let d8 = setupDice(8); | |
return shuffle(d8).shift(); | |
} | |
function d10() { | |
let d10 = setupDice(10); | |
return shuffle(d10).shift(); | |
} | |
function d12() { | |
let d12 = setupDice(12); | |
return shuffle(d12).shift(); | |
} | |
function d20() { | |
let d20 = setupDice(20); | |
return shuffle(d20).shift(); | |
} | |
return { | |
d2, | |
d4, | |
d6, | |
d8, | |
d10, | |
d12, | |
d20 | |
} | |
})(); | |
let d2 = roll.d2(); | |
let d4 = roll.d4(); | |
let d6 = roll.d6(); | |
let d8 = roll.d8(); | |
let d10 = roll.d10(); | |
let d12 = roll.d12(); | |
let d20 = roll.d20(); | |
console.log(d2, d4, d6, d8, d10, d12, d20); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment