Guess the number game: progressing the loop / alert + reset - javascript
I want to create a "Guess the numbers game" where you guess a random number within a certain amount of attempts.
I struggle with:
(Must have)
1. Progressing in the loop after the alert (which shows you if your guess was to high, too low, or not a number.
(Nice to have)
2. Resetting the game if you managed to guess the number or ran out of attempts. Resetting means to restore the original amount of guesses and zeroing your attempts. Maybe just a command that refreshes the page.
I'm - after years of break after my first attempts - new to coding.
Here is access to my project: https://glitch.com/~gravel-pyrite
I think this is the relevant loop/conditions engine where I mess up:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
document.getElementById("submit").onclick = function() {
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I expect that after the alerts, I can enter a new value, instead I get stuck in an "alerts loop".
EDIT: I've updated my code now. Reloading the page in after succeeding using up all tries works well.
One thing open:
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
won't only show after the first time the button was submitted.
This is the HTML:
<body>
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button onclick="resetGame()">Reset Game</button>
</body>
Adjusted your code
See fiddle example: https://jsfiddle.net/u0cmtg7j/1/
You don't need a loop, do everything in you submit event.
Also move your DOM manipulation code inside your submit event since you want to update the HTML every time your result changes.
Suggestions:
pack you DOM/HTML manipulation code in a function so that is nice and re-usable.
JS
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Prompt that asks user to guess a number between x / 10
//Check if number is correct
//If wrong, prompt them to guess again unti they run out of guesses
//If correct, tell them they won, the number of attempts and thank you
document.getElementById("submit").onclick = function() {
var attempts = document.getElementById("guessInput").value;
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter > maxTries) { //If running outs of attempts, break out of loop
alert("You used up your maximum tries.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
}
function resetGame() {
}
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
HTML
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button>Reset Game</button>
There is no need for you to loop within your onclick callback method. By looping you're going to keep checking the value in guessInput without letting the user change their guess, and so the same if block will always run until the player is out of guesses. Instead, you need the click method to control when and how many times the code within your function runs, as it will allow the user to change their guess:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
console.log(randomNumber);
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries.");
// resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
//resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
}
<input id="guessInput" type="number" />
<button id="submit">Guess</button>
This is my result. I'm sure things can be improved but all works functionally:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
//The code
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I saw your question yesterday, I prepared an answer for you but I found that you have deleted your question :) .
I use console.log(someVariable); before using it in my code so that I make sure it exists and not null or undefined
when I did this with your code I found that the variable 'random' existed when I declared it and assign it, but inside the event handler function it becomes 'undefined' because the function is asynchronous
the working code is the following with simplified logic
var rangeMin = 0;
var rangeMax = 10;
var remainingGuesses = 4;
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
var random;
var guessesMade = 0;//the user hasn't guessed anything yet os we'll declare and assign the variable as zero
document.getElementById("submit").onclick = function guess() {
//this is a new guess from the user, lets increase the counter of guesses made and decrease remaining guesses
guessesMade++;
remainingGuesses--;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
//lets assign the variable random a number
random = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
//lets get what the user guessed
var userGuess = document.getElementById("guessInput").value;
if (random == userGuess) {
alert("CONGRATULATIONS!!! GUESSES NEEDED: " + guessesMade);
//Resetting:
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//So the user didn't guess it right, there two scenarios:
//1- user already consumed his chances, we'll alert him about it and reset the game
//2- user still has guesses to make, we will test and advise him
if (remainingGuesses == 0) {
// scenario (1-)
alert("SORRY, YOUR RAN OUT OF GUESSES. LETS PLAY AGAIN!");
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//scenario (2-)
//we will check the value of his guess and advise him
if (random > userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS SMALLER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A HIGHER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else if (random < userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS HIGHER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A SMALLER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
}
}
}
Related
vars not holding proper value after localStorage.getItem('key')
My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help. The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code <!DOCTYPE html> <html> <head> <title></title> </head> <body bgcolor="black" > <font color="white" > <progress id="myProgress" value="10" max="10"></progress><br> <p id='demo5' ;></p> <button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img id="enemy1" src="Game_Images/smiley_1.png"></button> <button id="spriteTest" type="button" onclick="imageSwap2()"><img id="enemy2" src="Game_Images/smiley_1.png"></button><br> <button id="upgrade" type="button" onclick="upgradeClickDamage()"> </button> <button type="button" onclick="moreGold()">More Gold</button><br> <button type="button" onclick="saveGame()">Save Game</button> <button type="button" onclick="loadGame()">Load Game</button> <p id='demo' ;></p> <p id='demo2' ;></p> <p id='demo3' ;></p> <p id='demo4' ;></p> <script> var clickDamage = 1; var gold = 0; var stage = 1; var enemyNum = 1; var enemiesTotal = 10; var enemiesKilled = 0; var cost = 100; var enemyHPTotal = 10; var enemyHPCurrent = 10; document.getElementById("upgrade").innerHTML = "Upgrade click damage for:" + cost + " gold."; document.getElementById("demo").innerHTML = "Gold: " + gold; document.getElementById("demo2").innerHTML = "Stage: " + stage; document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:" + enemiesKilled + "/" + enemiesTotal; document.getElementById("demo4").innerHTML = "Click Damage:" + clickDamage; document.getElementById("demo5").innerHTML = "Enemy HP remaining:" + enemyHPCurrent + "/" + enemyHPTotal; function imageSwap() { var image = document.getElementById("enemy1"); if (image.src.match("Game_Images/smiley_1")){ image.src="Game_Images/smiley_2.png" } else if (image.src.match("Game_Images/smiley_2")){ image.src="Game_Images/smiley_3.png" } else { image.src="Game_Images/smiley_1.png" } } function imageSwap2(){ var image2 = document.getElementById("enemy2"); if(image2.src.match("Game_Images/smiley_1")){ setTimeout(image2.src="Game_Images/smiley_2.png", 300); } else if(image2.src.match("Game_Images/smiley_2")){ setTimeout(image2.src="Game_Images/smiley_3.png", 300); } else { setTimeout(image2.src="Game_Images/smiley_1.png", 300); } } function dealDamage() { document.getElementById("myProgress").value -= clickDamage; //If enemy is hit but does not die if(document.getElementById("myProgress").value >= 1){ enemyHPCurrent = document.getElementById("myProgress").value enemyHPTotal = document.getElementById("myProgress").max document.getElementById("demo5").innerHTML = "Enemy HP remaining:" + enemyHPCurrent + "/" + enemyHPTotal; } //If enemy is killed and there are remaining enemies in the current stage if (document.getElementById("myProgress").value == 0 && enemyNum < 10) { document.getElementById("myProgress").value = document.getElementById("myProgress").max; gold += (1 * stage); enemyHPTotal = document.getElementById("myProgress").value; enemyNum += 1; document.getElementById("demo").innerHTML = "Gold: " + gold; document.getElementById("demo2").innerHTML = "Stage: " + stage; enemiesKilled += 1; document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:" + enemiesKilled + "/" + enemiesTotal; document.getElementById("demo4").innerHTML = "Click Damage:" + clickDamage; enemyHPCurrent = enemyHPTotal; document.getElementById("demo5").innerHTML = "Enemy HP remaining:" + enemyHPCurrent + "/" + enemyHPTotal; } //If the enemy is killed and it is the last enemy of the current stage if (document.getElementById("myProgress").value == 0 && enemyNum == 10) { document.getElementById("myProgress").max += 1; document.getElementById("myProgress").value = document.getElementById("myProgress").max; gold += (1 * stage); enemyNum = 1; stage += 1; document.getElementById("demo").innerHTML = "Gold: " + gold; document.getElementById("demo2").innerHTML = "Stage: " + stage; enemiesKilled = 0; document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:" + enemiesKilled + "/" + enemiesTotal; document.getElementById("demo4").innerHTML = "Click Damage:" + clickDamage; enemyHPTotal = document.getElementById("myProgress").max; enemyHPCurrent = enemyHPTotal; document.getElementById("demo5").innerHTML = "Enemy HP remaining:" + enemyHPCurrent + "/" + enemyHPTotal; } } function upgradeClickDamage() { if (gold >= cost) { gold -= cost; clickDamage += 1; cost += 100; document.getElementById("messageBox").innerHTML = "Congratulations!!! You just upgraded your click damage." document.getElementById("upgrade").innerHTML = "Upgrade click damage for:" + cost + " gold."; document.getElementById("demo").innerHTML = "Gold: " + gold; document.getElementById("demo4").innerHTML = "Click Damage:" + clickDamage; } else if (gold < cost) { document.getElementById("messageBox").innerHTML = "You don't have enough gold for this upgrade." } } function moreGold() { gold += 100; document.getElementById("demo").innerHTML = "Gold: " + gold; } function saveGame(){ //save all vars localStorage.setItem('CLICKDAMAGE', clickDamage); localStorage.setItem('GOLD', gold); localStorage.setItem('STAGE', stage); localStorage.setItem('ENEMYNUM', enemyNum); localStorage.setItem('ENEMIESTOTAL', enemiesTotal); localStorage.setItem('ENEMIESKILLED', enemiesKilled); localStorage.setItem('COST', cost); localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal); localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent); } function loadGame(){ //load all vars clickDamage = localStorage.getItem('CLICKDAMAGE'); gold = localStorage.getItem('GOLD'); stage = localStorage.getItem('STAGE'); enemyNum = localStorage.getItem('ENEMYNUM'); enemiesTotal = localStorage.getItem('ENEMIESTOTAL'); enemiesKilled = localStorage.getItem('ENEMIESKILLED'); cost = localStorage.getItem('COST'); enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL'); enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT'); } </script> <div id="messageBox"></div> </font> </body> </html> I expected all variables to function properly after loading. gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.
(This will restate a bit of what you hypothesized in your question for the sake of completeness) If you look at the documentation for Storage.getItem(), it says: Return value A DOMString containing the value of the key. If the key does not exist, null is returned. This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console: localStorage.setItem("test", 1); > undefined localStorage.getItem("test"); > "1" When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +. +localStorage.getItem("test"); > 1
The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value. So you are trying to concatenate string and number "1" + 1 === "11". To prevent this behavior you need to manually convert values to stringified JSON: localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage)); And then parse it back: clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));
How can I save best guess (higher/lower)
for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47. What I mean by this is that I want it not go lower anymore Same thing with the higher guess I want it to save/lock my best guess to the closest 'use strict' var toGuess = Math.floor(Math.random() * (100 + 1)); console.log("To Guess: " + toGuess); var guess = undefined; var amount = 0; var bestHigher = 100; var bestLower = 0; var hint = document.getElementById('hint'); var numbers = document.getElementById('numbers'); var lower = document.getElementById('lower'); var higher = document.getElementById('higher'); function GuessDone() { var put = document.getElementById('number').value; guess = Number(put); console.log("Guess: " + guess); document.getElementById('form').reset(); amount = amount + 1; console.log("Guesses " + amount); var numberDif = Number(toGuess) - Number(put); var bestLower = Number(put) > toGuess; var bestHigher = Number(put) < toGuess; if (numberDif > bestLower) { bestLower = Number(put); console.log("Lower " + bestLower); } if (numberDif < bestHigher) { bestHigher = Number(put); console.log("Higher " + bestHigher); } if (guess > toGuess) { hint.innerHTML = "You need to guess lower"; higher.innerHTML = "Best guess above " + bestHigher; } else if (guess < toGuess) { hint.innerHTML = "You need to guess higher"; lower.innerHTML = "Best guess below " + bestLower; } else { hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount; var print = ""; var i; for (i = 0; i <= toGuess; i++) { print += i + "<br>"; } numbers.innerHTML = print; } return false; EDIT This is my html <form id="form"> <label for="number">Guess number between 0-100: </label> <input id="number" type="text" name="number"> <button type="submit">Guess</button> </form> <p id="lower"></p> <p id="higher"></p> <p id="hint"></p> <p id="numbers"></p> <script src="numbergame.js"></script> FIDDLE https://jsfiddle.net/d3761nbj/2/
How can I keep this loop going until balance is zero?
I am new to Javascript and have figured how to make the first line log to the console, however, how can I continue the loop and display the results as the balance gets lower until the balance is zero? I appreciate any help with this. Thanks in advance. function displayPayment() { var year = 0; var balance = 1500; var interest = 0.015; var minimum = 0.02; var payNum = 0; if (balance > 0) { var newPayNum = payNum + 1; var newYear = year + 1; var interestPaid = balance * interest; var newBalance = interestPaid + balance; var minPay = newBalance * minimum; var balanceOwe = newBalance - minPay; return (" " + newYear + " " + balanceOwe + " " + newPayNum + " " + interestPaid); } } console.log(" Year " + " Balance " + " PaymentNum " + " InterestPaid \n"); console.log(displayPayment());
You can use either the do while loop or just a while loop. However your balance does not change during the process, so the loop will never exit.
Replacing a conditional statement with a loop
I am trying to make a guessing game that generates a random number which the user guesses. This guessing game must use some kind of loop. Right now it is enclosed in a function that is called when the user clicks a button, and a boolean that limits the number of guesses the user can make. To my understanding, a loop runs without stopping until its conditions have been satisfied. If I were to have a loop in this situation, the final output would be the loop's last iteration. NumGuesses would have a value of 6 because that was when the loop stopped. How can I replace the conditional with a loop and still have it work? //Declare variables and constants var guessesLeft; //number of guesses the user has left var userGuess; //user's guess var highLimit = 1000; //high parameter var numGuesses = 1; //number of guesess the user has guessed var allowedGuesses = 6; //number of allowed guesses var NL = "\n"; //new line //function to be called when the user presses Submit Guess function guessingGame() { //random number that is generated var randNum = Math.floor(Math.random() * highLimit + 1); if (numGuesses <= allowedGuesses) { userGuess = prompt("Enter a number between 1 and " + highLimit + ": " , "") userGuess = parseInt(userGuess); guessesLeft = (allowedGuesses - numGuesses) + " guesses left."; //If userGuess is in the specified parameters //If userGuess is larger than 1 and smaller than the higher parameter if ((userGuess > 1) && (userGuess < highLimit)) { //If userGuess does not equal randNum if (userGuess !== randNum) { //If userGuess is too low if (userGuess < randNum) { //output document.numForm.gameResults.value = "You guessed too low! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft; } //If userGuess is too high else if (userGuess > randNum) { document.numForm.gameResults.value = "You guessed too high! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft; }//end if } else { //If userGuess is correct document.numForm.gameResults.value = "You guessed correctly!"; }//end if } else { document.numForm.gameResults.value = "Your guess was out of the specified parameters. Please try again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You currently have " + guessesLeft; //user may have entered their guess wrong numGuesses--; }//end if //add to number of guesses so the program stops when it reaches the allowed number numGuesses++; }//end outer if statement return false; }//end guessingGame()
It sounds like the problem statement expects you to block waiting for user input as opposed to triggering a function in response to a DOM event. Have a look at window.prompt Placing this in a loop would block the loop until the user responded.
Using prompt() as suggested by retrohacker and a do {} while () loop, the following code demonstrates this in action: var minNumber = 1; var maxNumber = 2; var guessesLeft = 3; var numberToBeGuessed = minNumber + (Math.random() * (maxNumber - minNumber + 1) | 0); var succeeded; var message = 'Make a guess'; do { if (prompt(message) == numberToBeGuessed) { alert('Correct, the number is ' + numberToBeGuessed); succeeded = true; } else { guessesLeft--; message = 'Try again, ' + guessesLeft + ' guess' + (guessesLeft > 1 ? 'es' : '') + ' left'; } } while (!succeeded && guessesLeft)
Adding up a current variable with the previous one
I have a problem here, basically I want my Dice game to display 3 lines. The first line says what number of the die I got The second line adds the number I got from the first die with the second die i rolled and so on.. (basically everytime i click the button). The third line would just count how many times I rolled the dice. My problem is that on my second line, im not sure how I can add up my current die roll with my previous one everytime I click the button. var count=0; function swap_pic() { var x = Math.floor(Math.random()*6)+1; var pic = document.getElementById("dice"); var xx = x+x; count++; document.getElementById("result").innerHTML = "You got " + x; document.getElementById("result").innerHTML += "<br>Your score is: " + xx; document.getElementById("result").innerHTML += "<br>Number of tries = " + count; if (count==5) { document.getElementById("result").innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; count = 0; document.getElementById('button').setAttribute("style","visibility:hidden"); } if (x==1) { pic.src = "images/die1.png"; } else if (x==2) { pic.src = "images/die2.png"; } else if (x==3) { pic.src = "images/die3.png"; } else if (x==4) { pic.src = "images/die4.png"; } else if (x==5) { pic.src = "images/die5.png"; } else if (x==6) { pic.src = "images/die6.png"; } } Problem is this line document.getElementById("result").innerHTML += "<br>Your score is: " + xx; Thank you for the help guys!
Several concatenation of innerHTML should be avoided, as well as repeated else if when possible. Try this: var count = 0; var sum = 0; function swap_pic() { var x = Math.floor(Math.random() * 6) + 1; var pic = document.getElementById("dice"); sum += x; count++; var html = "You got " + x; html += "<br>Your score is: " + sum; html += "<br>Number of tries = " + count; if (count == 5) { html += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; count = 0; document.getElementById('button').setAttribute("style", "visibility:hidden"); } document.getElementById("result").innerHTML = html; pic.src = "images/die" + x +".png"; }
Try this on for size //create these as global variables var totalScore; var rollCount; var lastRoll; var image; var text; var button; function reload(){ totalScore = 0; rollCount = 0; lastRoll = 0; image = document.getElementById('dice'); //store image element text = document.getElementById('result'); //store result element button = document.getElementById('button'); //store button element button.style.visibility = visible; //restore button visibility } function roll(){ lastRoll = Math.floor(Math.random()*6)+1; //generate random number rollCount++; //increase our roll counter totalScore+= lastRoll; //add new roll to score image.src = "images/die" +lastRoll+ ".png"; //update dice image text.innerHTML = "You got " // generate result string + lastRoll + "<br>Your score is: " + totalScore + "<br>Number of tries = " + rollCount; if(rollCount >= 5){ //end game parameter!! text.innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; //add game over text button.style.visibility = 'hidden';//hide button //reload(); //uncomment to reset game now? } } window.onload = reload; //set up on page load