showing total scores with localStorage - Javascript - javascript

I'd like to display scores and total scores in a basic clicking game. Every time the user clicks, the scores add 1 , and totalscores adds the total and the 1 generated in scores.
Every time the user starts the game the total score is showing and then it just keeps adding the numbers showed in scores
I think this works in the first round -> the scores are the same as total scores in the board and when i click start the totalScores are showing instead of going back to 0.
But when i start clicking the element the total scores don't add what I have stored they just follow along the number of scores.
How can I store the total and just add the score ?
the click function
score++;
scoreBoard.textContent = score;
localStorage.setItem("totalscore", score);
total.textContent = "total " + localStorage.getItem("totalscore");
the start function
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");

If I am right in assuiming that this is your Javascript code:
click = () => {
score++;
scoreBoard.textContent = score;
localStorage.setItem("totalscore", score);
total.textContent = "total " + localStorage.getItem("totalscore");
}
start = () => {
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");
}
Then you should do the following:
click = () => {
score++;
scoreBoard.textContent = score;
localStorage.totalscore = score;
total.textContent = "total " + localStorage.totalscore;
}
start = () => {
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.totalscore;
}

localStorage set the items as string
Use Number(localStorage.getItem('totalScore')) to convert string to number

the click function
score++;
scoreBoard.textContent = score;
var currentTotalScore = new Number(localStorage.getItem("totalScore") || 0);
localStorage.setItem("totalscore", currentTotalScore + score);
total.textContent = "total " + localStorage.getItem("totalscore");
the start function
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");

Related

Guess the number game: progressing the loop / alert + reset

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;
}
}
}
}

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'));

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

HTML javascript movie and dinner

I'm receiving NotANumber for my total from movieTotal, as well as im not getting the correct value of adding pricePerTicket + pricePerDinner. Can someone help me figure out what im doing wrong?
<script type="text/javascript">
<!--
var ticket, earlyBirdTicket, WeekDinner, weekendDinner, numberOfTickets, TotalDue;
var numberOfTickets, pricePerTicket, pricePerDinner, costOfDandT, totalAmountOwed;
var totalDandT, yes, week, movieTotal;
var ticket = 5;
var nightTicket = 10;
var weekDinner = 8;
var weekendDinner = 12;
var yes = ticket;
var week = weekDinner;
var movieTotal = totalDandT * numberOfTickets;
totalDandT = pricePerDinner + pricePerTicket;
numberOfTickets = prompt ("How many tickets?");
pricePerTicket = prompt ("Is this earlybird? yes/no ");
pricePerDinner = prompt ("weekend or weekday? week/weekend ");
pricePerTicket = parseInt(pricePerTicket);
pricePerDinner = parseInt(pricePerDinner);
movieTotal = parseInt (movieTotal);
if (pricePerTicket = yes)
{
pricePerTicket = ticket;
}
else
{
pricePerTicket = nightTicket;
}
if (pricePerDinner = week)
{
pricePerDinner = weekDinner;
}
else
{
pricePerDinner = weekendDinner;
}
document.write ("<br>Number of tickets sold : " + numberOfTickets);
document.write ("<br>Cost per ticket tonight : $" + pricePerTicket);
document.write ("<br>Cost per dinner tonight : $" + pricePerDinner);
document.write ("<br>Cost of dinner and ticket : $" + pricePerTicket + pricePerDinner);
document.write ("<br> Your total today is $" + movieTotal);
// -->
</script>
You have not initialized the variables. You should do it before using them.
Uninitialized variables are equals to undefined so yes.undefined plus undefined is not a number.

Categories

Resources