I'm pretty new at Javascript and I've built a simple number guessing game. The program generates a random number between 1-10 and prompts you if your guess is too high or too low. If you guess right, you win.
I'd like to improve on this current version by giving the player 3 guesses, after which the player either wins, or loses. I know this is done with loops, but I can't for the life of me figure out how. I've tried using while loops but it doesn't work. Here is my code and thank you all for your help:
<script>
var rannum = Math.floor((Math.random() * 10) + 1); //generates a random number and stores it in the rannum variable
function submitanswer(){ //This function analyzes player response and is called by the submit button
var playerguess = document.getElementById("guess"); //grabs whatever the player types in and stores it in the playerguess variable
if (playerguess.value == rannum){ //if the value of playerguess is the same as rannum then the player wins
alert("You win!");
location.reload();
}
if (playerguess.value > rannum){ //if the player's guess is higher than the random number alert too high
alert("Too high!");
document.getElementById("guess").value='';
}
else if (playerguess.value < rannum){ //if the player's guess is lower than the random number alert too low
alert("Too low!");
document.getElementById("guess").value='';
}
}
function reloaD(){ //start over by generating a new number
document.getElementById("guess").value='';
location.reload();
}
</script>
</body>
</html>
So here is how i went on about your game.. i will try my best to make you understand my logic.
First of all, you need an input box where user will input his/her guess and a button to submit that guess:
Your Guess: <input type='text' id='guess'>
<button id="checkBtn">Check</button>
Then an event listener on button click. In that, im getting the value of the user's guess from input box and sending it to another function which will check whether the guess is correct, low or high. Also i am keeping a counter which will increment on each button click. And the user will be able to check only till maxGuesses, initially 3. When counter equals max guesses, that's when the game ends and im disabling the button so no more input.
document.getElementById('checkBtn').onclick = function (){
var guess = document.getElementById('guess').value;
checkGuess(guess);
counter++;
if(counter == maxGuesses) {
alert("Game Over");
document.getElementById("checkBtn").disabled = true;
}
}
checking the guess for too high, low or correct guess is simple logic as used by you, three conditions. On the correct guess, user will be displayed "You Win!" and the button will get disabled again because game ended now.
function checkGuess(guess){
if (guess == rannum){ //if the value of playerguess is the same as rannum then the player wins
alert("You win!");
document.getElementById("checkBtn").disabled = true;
}
if (guess > rannum){ //if the player's guess is higher than the random number alert too high
alert("Too high!");
document.getElementById("guess").value='';
}
else if (guess < rannum){ //if the player's guess is lower than the random number alert too low
alert("Too low!");
document.getElementById("guess").value='';
}
}
EDIT: I added the restart functionality as well. By adding a restart button which is initially hidden display: none
<button id="restart" style="display:none">Restart</button>
It will get displayed when either the user wins or the Game gets over (max guesses reached).
document.getElementById("restart").style.display='block'; //making it visible
Then when the user clicks on restart, all the values reset, restart button disappears and the game begins again.
document.getElementById('restart').onclick = function (){
rannum = Math.floor((Math.random() * 10) + 1);
counter = 0;
guess = 0;
document.getElementById("checkBtn").disabled = false;
document.getElementById("guess").value='';
document.getElementById("restart").style.display='none';
}
You don't need to use loops here. You can just use a variable that tracks how many guesses are still left. You decrease the variable by one each time you compute the answer. If it gets to 0, the game is lost.
I also made some other improvements to your code, namely:
File index.html:
<!DOCTYPE html>
<html>
<head>
<title>Guess the number</title>
</head>
<body>
<form>
<input type="text" id="guess" />
<input type="submit" id="submitAnswer" value="Check answer" />
</form>
<div id="answer"></div>
<script src="game.js"></script>
</body>
</html>
File game.js:
(function () {
var guessesLeft, randomNumber, guessInput, submitButton, answerDisplay, maxGuesses;
maxGuesses = 3;
// Load all the element references from the DOM
// so that we don't need to do that every time we chek the answer
guessInput = document.getElementById("guess");
submitButton = document.getElementById("submitAnswer");
// Let's use a DIV element to display the answer.
// It's nicer than using alert().
answerDisplay = document.getElementById("answer");
answerDisplay.innerHTML = "Please make a guess!";
submitButton.addEventListener("click", function (event) {
event.stopPropagation();
event.preventDefault();
checkAnswer();
});
initGame();
function initGame () {
guessesLeft = maxGuesses;
randomNumber = Math.floor(Math.random() * 10 + 1);
guessInput.value = "";
}
function checkAnswer () {
if (guessInput.value == randomNumber) {
answerDisplay.innerHTML = "You win! " + randomNumber + " is correct. " +
"Please input your next guess to start again.";
initGame();
return;
}
else if (guessInput.value > randomNumber) {
answerDisplay.innerHTML = "Too high!";
}
else {
answerDisplay.innerHTML = "Too low!";
}
guessesLeft -= 1;
if (guessesLeft === 0) {
answerDisplay.innerHTML += " No guesses left - you lost!";
initGame();
}
}
}());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.