This JavaScript code simulates a dice game between two players. The code generates random numbers to determine the outcome of the game and updates the HTML content accordingly.
-
The code generates a random number between 1 and 6 for the first player using the
Math.random()function. The result is stored in the variablerandomNumber1. -
The code selects the first
<img>element in the HTML using thedocument.querySelectorAll("img")[0]selector and stores it in the variableimg1. It does the same for the second<img>element and stores it in the variableimg2. -
It creates a filename for the dice image by appending
randomNumber1to the string "dice" and then appending ".png". The resulting filename will be "dice1.png" to "dice6.png" based on the value ofrandomNumber1. The filename is stored in the variablerandomDiceImage. -
It creates the complete image source path by appending "images/" to the
randomDiceImage. The resulting path will be "images/dice1.png" to "images/dice6.png". The path is stored in the variablerandomImageSource. -
It sets the
srcattribute ofimg1torandomImageSourceusing thesetAttribute()method. This updates the displayed image of the first player's dice. -
The code generates a random number between 1 and 6 for the second player and stores it in the variable
randomNumber2. -
It creates the image source path for the second player's dice using the filename pattern "images/dice" +
randomNumber2+ ".png". The path is stored in the variablerandomImageSource2. -
It sets the
srcattribute ofimg2torandomImageSource2, updating the displayed image of the second player's dice. -
It compares
randomNumber1andrandomNumber2to determine the winner of the game. IfrandomNumber1is greater thanrandomNumber2, it sets the text content of the first<h1>element to "Player 1 Wins!!". IfrandomNumber2is greater, it sets the text content to "Player 2 Wins!!". Otherwise, if both numbers are equal, it sets the text content to "DRAW".
To use this code, follow these steps:
-
Create an HTML file and link it with a JavaScript file.
-
Copy and paste the provided code into the JavaScript file.
-
Create the necessary HTML elements in the HTML file. You will need two
<img>elements to display the dice images and one<h1>element to display the game result. -
Create a folder named "images" and place the dice images (dice1.png to dice6.png) inside it.
-
Open the HTML file in a web browser.
-
Each time you refresh the page, the code will generate random numbers and update the dice images and game result accordingly.
Example output when the first player's random number is 4 and the second player's random number is 2:
Player 1 Wins!!
Example output when the first player's random number is 3 and the second player's random number is 5:
Player 2 Wins!!
Example output when the first player's random number is 2 and the second player's random number is 2:
DRAW
This code is a simple implementation of a dice game using JavaScript. Feel free to modify and expand it according to your requirements.