script game with java script
Sure! Here's an example of a simple guessing game using JavaScript:
// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;
// Initialize the number of tries
let tries = 0;
// Function to handle the user's guess
function guessNumber() {
// Retrieve the user's guess from the input field
const userGuess = parseInt(document.getElementById("guess").value);
// Increase the number of tries
tries++;
// Check if the user's guess is correct
if (userGuess === randomNumber) {
document.getElementById("result").innerHTML = `Congratulations! You guessed the number in ${tries} tries.`;
} else if (userGuess < randomNumber) {
document.getElementById("result").innerHTML = "Too low! Try again.";
} else {
document.getElementById("result").innerHTML = "Too high! Try again.";
}
}
// Attach event listener to the guess button
document.getElementById("guessButton").addEventListener("click", guessNumber);
In your HTML file, you would need to have the following elements:
<input type="number" id="guess" placeholder="Enter your guess">
<button id="guessButton">Guess</button>
<p id="result"></p>
This code generates a random number between 1 and 100 and prompts the user to guess the number. It keeps track of the number of tries and provides feedback to the user if their guess is too high or too low. Once the user guesses the correct number, it displays a congratulatory message along with the number of tries it took
原文地址: http://www.cveoy.top/t/topic/iWnI 著作权归作者所有。请勿转载和采集!