Share
Explore

w25 Web Technologies lab: Dice Rolling JS Game

References:

Welcome to the Dice Rolling Game!
This game pits you against the mighty computer in a test of chance.
Here's how it works:
Both you and the computer will roll a virtual six-sided die.
Your roll will be determined by clicking a button, which will trigger a random number generator in our JavaScript code. The computer will also use a random number generator to get its roll.
Think of it like this:
javascript
// Example of generating a random number between 1 and 6 (inclusive)
let humanRoll = Math.floor(Math.random() * 6) + 1;
let computerRoll = Math.floor(Math.random() * 6) + 1;
Once both rolls are determined, we'll compare them. If your roll is higher, you win! If the computer's roll is higher, the computer wins. And if you both roll the same number, it's a tie!
We'll display the results of each roll and the winner (or tie) right here on the webpage.
We'll use JavaScript to manipulate the HTML of the page and show you the outcome.
For example, imagine seeing this on the screen:
html
<p>You rolled: 5</p>
<p>Computer rolled: 2</p>
<p>You win!</p>

This simple game will introduce you to key programming concepts like variables (to store the rolls), random number generation, if/else statements (to compare the rolls and determine the winner), and interacting with the HTML DOM (to display the results).
megaphone

Get ready to roll!


image.png
Explanation of the HTML elements:
<h1>Dice Rolling Game</h1>: The main heading of our game.
<button id="rollButton">Roll Dice!</button>: The button the user clicks to roll the dice. The id="rollButton" is crucial. We'll use this ID in our JavaScript to interact with the button.
<div id="results">: This div will contain the results of the game. Again, the id="results" is important for JavaScript manipulation.
<p>Your Roll: <span id="humanRoll">-</span></p>: Displays the human player's roll. The span with id="humanRoll" is where the actual number will be displayed. Initially, it shows a "-" as a placeholder.
<p>Computer's Roll: <span id="computerRoll">-</span></p>: Displays the computer's roll. Similar to above, the span with id="computerRoll" will hold the computer's roll.
<p id="winner">-</p>: Displays the winner of the round (or a tie). The id="winner" allows our JavaScript to update this paragraph with the outcome.
<script src="script.js"></script>: This line links our HTML file to a JavaScript file named script.js. This is where we'll write the game logic. We place it at the end of the <body> so that the HTML elements are loaded before the script tries to interact with them.
This HTML sets up the basic structure of our game's user interface. We'll use JavaScript to make it interactive and display the game results dynamically.

info

JavaScript

image.png
image.png
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.