Lesson 151 – Complete 2020 Web Development Bootcamp

Lesson 151 – Solution to the Dicee Challenge

This is the solution to the Dicee Challenge –

var randomNumber1 = Math.floor(Math.random() * 6) + 1;

var randomDiceImage = "dice" + randomNumber1 + ".png"; //dice1.png to dice6.png

var randomImageSource = "images/" + randomDiceImage;//images/dice1.png to images/dice6.png

var image1 = document.getElementsByTagName("img")[0];

image1.setAttribute("src", randomImageSource);

var randomNumber2 = Math.floor(Math.random() * 6) + 1;

var randomImageSource2 = "images/dice" + randomNumber2 + ".png";

document.getElementsByTagName("img")[1].setAttribute("src", randomImageSource2);

//if player 1 winds
if (randomNumber1 > randomNumber2) {
	document.querySelector("h1").innerHTML = "🚩 Player 1 Wins!";

//if player 2 wins
else if (randomNumber2 > randomNumber1) {
	document.querySelector("h1").innerHTML = "Player 2 Wins! 🚩";

//if there is a draw
else {
	document.querySelector("h1").innerHTML = "Draw!";

My solution is in my previous post.

Comparing my solution to the given solution is humbling! 😂

The method used in the given solution to change the dice images based on a random number is so much more concise than my method of using an if loop to change the images.

My method does incorporate some things that aren’t incorporated in the given solution. For example, I set an event listener on the headings “Player 1” and “Player 2” so that when one of these two items is clicked the code will run. The given example, didn’t do this and the program only runs when the web page is refreshed.

It seems I got a bit ahead of myself.

Anyway, it was a great exercise and even though I used much more code than needed, at least I got the program working! 😀