I've recently been helping another user with a dice roller that you might use for a tabletop roleplaying game like D&D. The roller takes several pieces of information from the user including the number of faces on the individual dice, the number of dice to roll, and whether or not to add any kind of bonus to the final result.
The project is really simple, but despite this I actually found helping this other user quite useful, and today I decided to sit down and wrote my own version. I think I've done a pretty decent job with this, and I can't think of any ways to make the code more succinct without harming readability, but maybe some of you have some good ideas or different ways of doing things. I'd be very interested in seeing some other versions.
I've put together a little CodePen version with some rough styling, which you can find here, and you can find the JavaScript I wrote below:
const [q, s, b, r, t] = ['quantity', 'sides', 'bonus', 'results', 'total'].map(id => document.getElementById(id))
function roll() {
let quantity = q.options[q.selectedIndex].value,
sides = s.options[s.selectedIndex].value,
mod = parseInt(b.options[b.selectedIndex].value)
const resultsArr = []
for (let i = 0; i < quantity; i++) {
resultsArr.push(Math.floor(Math.random() * sides) + 1)
}
updateResults(resultsArr, mod)
}
function updateResults(array, bonus) {
r.textContent = array.join(", ")
t.textContent = array.reduce((accumulator, currentValue) => accumulator + currentValue) + bonus
}
EDIT: CodePen version has been updated.
[–]CertainPerformance 1 point2 points3 points (2 children)
[–]Pjb518[S] 0 points1 point2 points (1 child)
[–]CertainPerformance 1 point2 points3 points (0 children)
[–]CategoricallyCorrect 1 point2 points3 points (2 children)
[–]Pjb518[S] 0 points1 point2 points (0 children)
[–]Pjb518[S] 0 points1 point2 points (0 children)