Here is what your game should look like:
This code includes:
HTML structure: Sets up the basic layout with input field, button, and result display areas.
CSS styling: Provides basic styling for the elements.
JavaScript logic:
Event listener: Triggers the game logic when the "Play Now" button is clicked.
Error handling: Checks for invalid inputs and displays appropriate error messages.
Random number generation: Generates a random number for the computer.
Winner determination: Compares user and computer values to determine the winner.
Result display: Displays the user's value, computer's value, and the winner.
Dice display: Uses a displayDice function to visually represent the dice with dots.
Game history: Stores the results of each game and displays them in a list.
This code addresses all the requirements of the practice exercise and provides a functional dice rolling game with error handling and game history.
JavaScript Coding Tutorial
Level 1 JavaScript Tutorial: The Basics
This tutorial will introduce you to the fundamental building blocks of JavaScript: variables, if/then statements, loops, and arrays.
1. Variables
Think of variables as containers that hold information. In JavaScript, you can create a variable using the var, let, or const keyword.
JavaScriptvar name = "Alice"; let age = 30; const pi = 3.14159;
In this example, we've created three variables:
name stores the string "Alice". age stores the number 30. pi stores the number 3.14159. You can use these variables later in your code.
JavaScriptconsole.log("My name is " + name + " and I am " + age + " years old.");
This will print "My name is Alice and I am 30 years old." to the console.
2. If/Then Statements
if/then statements allow your code to make decisions. Here's the basic structure:
JavaScriptif (condition) { // code to execute if the condition is true } else { // code to execute if the condition is false }
For example:
JavaScriptlet temperature = 25; if (temperature > 20) { console.log("It's a warm day!"); } else { console.log("It's a bit chilly."); }
This code will print "It's a warm day!" to the console because the temperature (25) is greater than 20.
3. Loops
Loops allow you to repeat a block of code multiple times. A common type of loop is the for loop:
JavaScriptfor (let i = 0; i < 5; i++) { // code to execute repeatedly }
This loop will run 5 times. Here's how it works:
let i = 0;: This initializes a counter variable i to 0. i < 5;: This is the condition. The loop continues as long as i is less than 5. i++: This increments i by 1 after each iteration. Here's an example that prints numbers from 0 to 4:
JavaScriptfor (let i = 0; i < 5; i++) { console.log(i); }
4. Arrays
Arrays are used to store lists of items. Here's how you create an array:
JavaScriptlet colors = ["red", "green", "blue"];
This creates an array called colors containing three strings. You can access individual elements of the array using their index (starting from 0):
JavaScriptconsole.log(colors[0]); // prints "red" console.log(colors[1]); // prints "green"
You can also use loops to iterate over the elements in an array:
JavaScriptfor (let i = 0; i < colors.length; i++) { console.log(colors[i]); }
This will print each color in the colors array.
This is just a basic introduction to JavaScript. There's much more to learn, but this should give you a good foundation to build upon. Happy coding!
<!DOCTYPE html>
<html>
<head>
<title>Dice Rolling Game</title>
<style>
body {
font-family: sans-serif;
}
.container {
width: 500px;
margin: 0 auto;
text-align: center;
}
.dice {
width: 100px;
height: 100px;
background-color: #f0f0f0;
border: 1px solid #ccc;
margin: 20px;
display: inline-block;
}
.dot {
width: 20px;
height: 20px;
background-color: #000;
border-radius: 50%;
position: absolute;
}
#results {
margin-top: 20px;
}
#history {
margin-top: 20px;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h1>Dice Rolling Game</h1>
<p>Instructions:</p>
<ul>
<li>Enter a value between 1 and 6</li>
<li>Computer will randomly select a value between 1 and 6</li>
<li>Whoever has the higher number wins!</li>
</ul>
<input type="text" id="user-input" placeholder="Enter a value between 1-6">
<button id="play-button">Play Now</button>
<div id="error"></div>
<div id="results">
<div class="dice" id="user-dice"></div>
<div class="dice" id="computer-dice"></div>
<p>Player value: <span id="player-value"></span></p>
<p>Computer value: <span id="computer-value"></span></p>
<p>Winner is: <span id="winner"></span></p>
</div>
<div id="history">
<h2>Game History</h2>
<ul id="history-list"></ul>
</div>
</div>
<script>
const userInput = document.getElementById("user-input");
const playButton = document.getElementById("play-button");
const errorDiv = document.getElementById("error");
const resultsDiv = document.getElementById("results");
const userDiceDiv = document.getElementById("user-dice");
const computerDiceDiv = document.getElementById("computer-dice");
const playerValueSpan = document.getElementById("player-value");
const computerValueSpan = document.getElementById("computer-value");
const winnerSpan = document.getElementById("winner");
const historyList = document.getElementById("history-list");
let gameHistory = [];
playButton.addEventListener("click", () => {
const userValue = parseInt(userInput.value);
// Error handling
if (isNaN(userValue)) {
errorDiv.textContent = "Please enter a valid number.";
resultsDiv.style.display = "none";
return;
}
if (userValue < 1 || userValue > 6) {
errorDiv.textContent = "Please enter a number between 1 and 6.";
resultsDiv.style.display = "none";
return;
}
errorDiv.textContent = ""; // Clear any previous errors
resultsDiv.style.display = "block";
const computerValue = Math.floor(Math.random() * 6) + 1;
playerValueSpan.textContent = userValue;
computerValueSpan.textContent = computerValue;
displayDice(userDiceDiv, userValue);
displayDice(computerDiceDiv, computerValue);
let winner = "";
if (userValue > computerValue) {
winner = "user";
} else if (userValue < computerValue) {
winner = "computer";
} else {
winner = "tie";
}
winnerSpan.textContent = winner;
// Update game history
gameHistory.push({ user: userValue, computer: computerValue, winner: winner });
updateHistoryList();
});
function displayDice(diceDiv, value) {
diceDiv.innerHTML = ""; // Clear previous dots
diceDiv.className = "dice"; // Reset class name
const dotPositions = {
1: [[50, 50]],
2: [[20, 20], [80, 80]],
3: [[20, 20], [50, 50], [80, 80]],
4: [[20, 20], [80, 20], [20, 80], [80, 80]],
5: [[20, 20], [80, 20], [50, 50], [20, 80], [80, 80]],
6: [[20, 20], [80, 20], [20, 50], [80, 50], [20, 80], [80, 80]],
};
dotPositions[value].forEach(([x, y]) => {
const dot = document.createElement("div");
dot.className = "dot";
dot.style.left = `${x}%`;
dot.style.top = `${y}%`;
diceDiv.appendChild(dot);
});
}
function updateHistoryList() {
historyList.innerHTML = "";
gameHistory.forEach((game) => {
const listItem = document.createElement("li");
listItem.textContent = `Computer ${game.computer}, User ${game.user} - Winner: ${game.winner}`;
historyList.appendChild(listItem);
});
}
</script>
</body>
</html>