Explorer
project
index.html
index.js
style.css
style.scss
Dependencies
Bootcamp
Study group
Collaborate with peers in your dedicated #study-group channel.
Code reviews
Submit projects for review using the /review
command in your #code-reviews channel
/*
DESCRIPTION:
In this challenge a casino has asked you to make an online dice that works just like
it wold in real life. Using the pre-made dice face that represents ‘one’, make the
faces for ‘two’, ‘three’, ‘four’, ‘five’ and ‘six’. Now when the users clicks the
dice on the screen the dice is expected to show one of the faces randomly.
event listeners, Math.random()
*/
// Write your code here 👇
// Plan:
// on click of the die,
// clear the class
// delete all the dot elements
// generate a random number between 1 and 6
// based on that number,
// asssign a class to the die
// create the appropriate number of dot children and stick them in the die element
// have pre-created styles for each nth dot inside the die of each class
const die = document.querySelector('.dice');
die.addEventListener("click", clickDie);
// start with a random die roll
clickDie();
function clickDie() {
var result = rollDice();
die.classList.remove('one', 'two', 'three', 'four', 'five', 'six');
die.classList.add(result[1]);
removeDots();
createDots(die, result[0]);
reportNum(result[0]);
}
// Generate a random number between 1 and 6
function getNum() {
return Math.ceil(Math.random() * 6);
}
function rollDice() {
var num = getNum();
var dieClass = '';
switch (num) {
case 1:
dieClass = 'one';
break;
case 2:
dieClass = 'two';
break;
case 3:
dieClass = 'three';
break;
case 4:
dieClass = 'four';
break;
case 5:
dieClass = 'five';
break;
default:
dieClass = 'six';
}
return [num, dieClass];
}
function removeDots() {
// find all the dots
var oldDots = document.querySelectorAll('.dice .dot');
// remove each one
for (var i = 0; i < oldDots.length; i++) {
oldDots[i].parentNode.removeChild(oldDots[i]);
}
}
function createDots(die, num) {
var dot = document.createElement("div");
dot.classList.add('dot');
for (var i = 0; i < num; i++) {
die.appendChild(dot.cloneNode(true));
}
}
function reportNum(num) {
if (document.querySelector('.diceNumber') == null || document.querySelector('.diceNumber').length < 1) {
var temp = document.createElement("div");
temp.classList.add('diceNumber');
document.body.appendChild(temp);
}
var diceNum = document.querySelector('.diceNumber');
diceNum.innerHTML = "You rolled a " + num;
}
/*
DETAILED INSTRUCTIONS
1. pick out the neccesary elements from the HTML
2. Create other 5 dice faces in CSS
3. use eventlisteners on the appropriate div
4. Display dice faces randomly on click
STRETCH GOALS:
- Can you show the number you rolled as a integer along-side the dice face?
- Can you improve the overall design?
*/