How do I store total points after user input in Javascript? - javascript

I'm coding my first JavaScript create your own adventure game. I have an input field for the user to enter his actions, a button to submit the action and an output text field for the story. When the button is clicked it starts a function to calculate the effectiveness of the user action.
Each action has a certain amount of points (25, 50, 75). If the user reaches 100 points after a few tries, he wins. If he reaches over 100 he loses. As long as 100 points aren't met, the user may keep on trying different actions.
The problem is that the function needs to store the current total points in a global variable, but it doesn't do that. After every button click the check function checks if the 100 points are met and gives hints to the user. But right now, it just says "You did it!" which is what it says when you meet 100 total points. What am I doing wrong?
I'm a total beginner at JavaScript, so I hope my code isn't a complete mess. Any help and advice is welcome. :)
Here is my HTML code:
<form>
<fieldset>
<label>Enter your answer here:</label>
<input id="userInput" type="text" name="userInput">
<input id="submit" type="button" name="submit" value="Click!" onclick="userAction()">
<textarea id="txtOutput" type="text" readonly="readonly" name="txtOutput">
</textarea>
</fieldset>
And my Javascript code:
var userInput = document.getElementById("userInput");
var txtOutput = document.getElementById("txtOutput");
txtOutput.value = "(\This is just a test and not the actual game.\) \n\nChoose your method to convince the merchant: \n\nA. compliment him on his work \nB. bribe him with money \nC. initmidate him \nD. blackmail him";
var totalPoints = 0;
function add(points) {
totalPoints += points;
}
window.userAction = function() {
var input = userInput.value.toUpperCase();
var compliment = "A";
var bribe = "B";
var intimidate = "C";
var blackmail = "D";
if (input == compliment) {
add(25);
}
else if (input == bribe) {
add(25);
}
else if (input == intimidate) {
add(50);
}
else if (input == blackmail) {
add(75);
}
else {
txtOutput = "Method not found. Choose either A, B, C or D.";
}
check();
}
window.check = function() {
if (totalPoints <= 25) {
txtOutput.value = "You have his attention. Keep going.";
userAction();
}
else if (totalPoints <= 50) {
txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
userAction();
}
else if (totalPoints <= 75) {
txtOutput.value = "You almost convinced him. Be careful now!";
userAction();
}
else if (totalPoints = 100) {
txtOutput.value = "You did it!";
}
else if (totalPoints > 100) {
txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
else {
txtOutput.value = "input not found.";
}
}
The JSfiddle

Remove your calls to UserAction from within window.check
it is calling the same action multiple times and hence you get you did it on first click
change this
window.check = function() {
if (totalPoints <= 25) {
txtOutput.value = "You have his attention. Keep going.";
userAction();
}
else if (totalPoints <= 50) {
txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
userAction();
}
else if (totalPoints <= 75) {
txtOutput.value = "You almost convinced him. Be careful now!";
userAction();
}
else if (totalPoints == 100) {
txtOutput.value = "You did it!";
}
else if (totalPoints > 100) {
txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
else {
txtOutput.value = "input not found.";
}
to this
window.check = function() {
if (totalPoints <= 25) {
txtOutput.value = "You have his attention. Keep going.";
}
else if (totalPoints <= 50) {
txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
}
else if (totalPoints <= 75) {
txtOutput.value = "You almost convinced him. Be careful now!";
}
else if (totalPoints = 100) {
txtOutput.value = "You did it!";
}
else if (totalPoints > 100) {
txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
else {
txtOutput.value = "input not found.";
}
}
here is a fiddle https://jsfiddle.net/0mo7peoc/15/
also change this line
else if (totalPoints = 100) {
to this
else if (totalPoints == 100) {

So your problem is you are re-invoking userAction() & with your equality setting vs checking:
// Notice here you check `<=`
else if (totalPoints <= 75) {
txtOutput.value = "You almost convinced him. Be careful now!";
}
// Notice here you SET `=`, this should be `===`
// this will ALWAYS be true
else if (totalPoints = 100) {
txtOutput.value = "You did it!";
}
// Notice here you check `>`
else if (totalPoints > 100) {
txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
See: https://jsfiddle.net/0mo7peoc/7/

Here is a solution
https://jsfiddle.net/exa2k8vq/1/
You had 2 errors:
else if (totalPoints = 100) while you need ==
you called userAction() in your if, so player got point twice

Only wrong condition is totalPoints = 100 change it to totalPoints == 100. But the actual reason you are getting this behavior is your check method. In each of your condition, you are calling userAction method again and again. This is why you reach to the conclusion at once.
I have made the adjustment to your fiddle to fix this issue. See updated fiddle UPDATED FIDDLE
Update your check method to
window.check = function() {
if (totalPoints <= 25) {
txtOutput.value = "You have his attention. Keep going.";
}
else if (totalPoints <= 50) {
txtOutput.value = "It's working. Keep going. Don't push it too hard, though.";
}
else if (totalPoints <= 75) {
txtOutput.value = "You almost convinced him. Be careful now!";
}
else if (totalPoints == 100) {
txtOutput.value = "You did it!";
}
else if (totalPoints > 100) {
txtOutput.value = "You pushed it too hard. The merchant runs away!";
}
else {
txtOutput.value = "input not found.";
}
Note: I have removed calls to your userAction method from this method.

You simply mistyped equals operator, ==.
...
else if (totalPoints == 100) {
txtOutput.value = "You did it!";
}

Related

A button is saying that the browser is wrong, even though it isn’t

I was testing a new milestone on a button I made in a Code.org Web Lab when, all of a sudden, it starts saying the browser I’m using doesn’t support the code.
I tried removing the new code I added, nothing happened. I tried fixing code errors, nothing happened. I even tried restoring the previous format of the code by copying and pasting code from a previous question, nothing happened.
Here's the current javascript code, including the new milestone:
<script>
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "People have attempted but failed to help me <span id='recolor'>" + localStorage.clickcount + "</span> times.";
if (localStorage.clickcount >= 100) {
document.getElementById("recolor").style.color = "#bc5c18";
}
if (localStorage.clickcount >= 250) {
document.getElementById("recolor").style.color = "#c9c9c9";
}
if (localStorage.clickcount >= 500) {
document.getElementById("recolor").style.color = "#e5d860";
}
if (localStorage.clickcount >= 1000) {
document.getElementById("recolor").style.color = "#6af2eb";
}
if (localStorage.clickcount >= 5000) {
document.getElementById("recolor").style.color = "#42f456";
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support helping me.";
}
}
}
</script>
It stopped working only when I added the very last one.
Here's the code for the button that increases the counter:
<p><button onclick="clickCounter()" type="button"><b>HELP ME</b></button></p>
<div id="result"></div>
I expected it to output this result:
People have attempted and failed to help me x times
but the actual output it gives is:
Sorry, your browser doesn't support helping me.
This result doesn't change no matter what I try. What do I do?
you need to have else if
if (localStorage.clickcount <= 100) {
document.getElementById("recolor").style.color = "#bc5c18";
}
else if (localStorage.clickcount <= 250) {
document.getElementById("recolor").style.color = "#c9c9c9";
}
else if (localStorage.clickcount <= 500) {
document.getElementById("recolor").style.color = "#e5d860";
}
else if (localStorage.clickcount <= 1000) {
document.getElementById("recolor").style.color = "#6af2eb";
}
else if (localStorage.clickcount <= 5000) {
document.getElementById("recolor").style.color = "#42f456";
}
else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support helping me.";
}

How to loop my question? Javascript Number Guessing Game

New programmer here - I am trying to create a number guessing game.
If I guess too high, it tells me "Too high, guess again."
If I guess too low, it tells me "Too low, guess again."
If I guess correct it tells me correct.
But I can only guess 1 wrong answer in each direction.
I have searched and searched and tried almost everything (if/else/while)
I know this is probably a simple fix for experienced programmers.
Please help.
Thanks ---
var secretNumber = 53;
var guess = prompt('Guess a number');
if (guess == (53)) {
alert("Yes you got it! 53 is the right answer!")}
while (guess < (53)) {
var guess = prompt('Too Low, Guess again');
}
while (guess > (53)) {
var guess = prompt('Too High, Guess again');
}
Try this:
var secretNumber = 53;
var high = false;
var low = false;
var done = false;
var guess = prompt('Guess a number');
while (!done) {
if (guess === secretNumber) {
alert("Yes you got it! " + secretNumber + " is the right answer!");
done = true;
} else if (guess < secretNumber) {
if (low) {
alert('You have failed');
done = true;
} else {
low = true;
guess = prompt('Too Low, Guess again');
}
} else if (guess > secretNumber) {
if (high) {
alert('You have failed');
done = true;
} else {
high = true;
guess = prompt('Too High, Guess again');
}
}
}
It is not optimal but for this exercise should do.

random number doesn't change in loop

The random number doesn't change using while loop. When I want to play again, the randomnumber is still the same.
Here's the code:
randomnumber=Math.floor(Math.random()*10);
while(true){
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
You should repeat the generation of the random number when a next game is requested:
var randomnumber = Math.floor(Math.random()*10);
while (true) {
var yourguess = prompt("Please Enter A Number Between 1-10");
if (randomnumber == yourguess) {
alert("Good Job");
var answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
randomnumber = Math.floor(Math.random()*10); //<---
} else {
break;
}
} else {
alert("Not Matched "+ randomnumber);
}
}
Make sure to declare your variables (with var, let or const).
You need to generate that randomnumber inside the while loop:
while(true){
var randomnumber=Math.floor(Math.random()*10);
yourguess=prompt("Please Enter A Number Between 1-10");
if(randomnumber==yourguess){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N")
if(answer=="Y"){
}else{
break;
}
}else{
alert("Not Matched "+ randomnumber);
}
}
If you want a different random number each time the loop is executed, you need to generate the randomnumber inside the while loop.
while (true) {
let randomnumber = Math.floor(Math.random() * 10);
yourguess = prompt("Please Enter A Number
Between 1 - 10");
if (randomnumber == yourguess) {
alert("Good Job");
answer = prompt("Do You Want To Play More ? Y/N")
if (answer == "Y") {
} else {
break;
}
} else {
alert("Not Matched " + randomnumber);
}
}
You could make randomnumber a function and call it on loop start. In addition your code snippet was changed a bit in order not to get stuck in a loop of un-closing prompt windows, what was missing is a small part that checks what happens when user does not provide an answer or clicks the cancel button.
var randomnumber = function() { return Math.floor(Math.random()*10); }
while(true){
let number = randomnumber();
yourguess=prompt("Please Enter A Number Between 1-10");
if(!yourguess) {
break;
}
if(number===parseInt(yourguess)){
alert("Good Job");
answer=prompt("Do You Want To Play More ? Y/N");
if(!RegExp("y","gi").test(answer) || !answer){
break;
}
}else{
alert("Not Matched "+ number);
}
}

do while javascript - loop for guessing game

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title>Game</title>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<h1>GameSite</h1>
<p> This program will generate a random number. Please input your guess in the box!</p>
<button onclick="guessGame()">Press me to play a quick game!</button>
<script>
function guessGame(){
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
do {
guess = prompt("Keep guessing!");
if (number < guess) {
prompt("You've guessed too high!");
} else if (number > guess) {
prompt("You've guessed too low!");
} else document.write("Good Job!");
} while (guess != number);
}
</script>
</body>
</html>
I am having trouble with the loop. It loops fine but if I move the guess statement too after the if statement it goes back to that each time. If I put it outside the if statement then it seems to not actually allow me to guess a valid number. It's hard to explain :\
I would suggest just to use only one prompt and assign it to the variable.
function guessGame() {
var number = Math.random() * 11 | 0,
guess,
text = 'Guess a number:';
do {
guess = prompt(text);
if (number < guess) {
text = "You've guessed too high!";
} else if (number > guess) {
text = "You've guessed too low!";
}
} while (guess != number);
document.write("Good Job!");
}
guessGame();
Try this:
function guessGame(){
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
while (guess != number) {
if (number < guess) {
guess = prompt("You've guessed too high! Keep guessing!");
} else {
guess = prompt("You've guessed too low! Keep guessing!");
}
}
document.write("Good Job!");
}
The while loop will keep running until the correct number is guessed, and then it will terminate.
edit: sorry, mistakes from typing too fast
I'd recommend use alert when you don't need user's response
function guessGame(){
number = Math.floor(Math.random()*11);
var guess;
do {
guess = prompt("Guess a number: "); // you should handle string input here
if (number < guess) {
alert("You've guessed too high!");
alert("Keep guessing!");
} else if (number > guess) {
alert("You've guessed too low!");
alert("Keep guessing!");
}
} while (guess != number);
alert("Good Job!");
}
Trust me, I'm a programmer.
function guessGame() {
guess:
var number = Math.floor(Math.random() * 11);
document.write(number);
var guess;// = prompt("Guess a number: ");
var text = 'Guess a number:';
guess = prompt(text);
if (number == guess) {
document.write("Good Job!");
return true;
} else {
if (number < guess) {
text = "You've guessed too low!";
} else {
text = "You've guessed too high!";
}
goto guess;
}
}
guessGame();

Trying to learn and run a simple if-else-if script, but not getting results

This is the nested script I made and am trying to run:
var coin = Math.round(Math.random() * 2);
var character = Math.round(Math.random() * 2);
if (character == 1) {
//It's a kid
if (coin == 0) {
alert("where'd the coin go?");
} else if (coin == 1) {
alert("you got heads dude");
} else if (coin== 2) {
alert("you got tails dude");
}
} else {
//now it's a computer
if (coin ==0) {
alert("3RR0R C01N G0N3");
} else if (coin==1) {
alert("H34D5");
} else if (coin==2) {
alert("T41L5");
}
Sadly, nothing is showing up. Any suggestions?
edi-t updated with correct code formatting, sorry for the mistake
You are missing the last parenthesis:
var coin = Math.round(Math.random() * 2);
var character = Math.round(Math.random() * 2);
if (character == 1) {
//It's a kid
if (coin == 0) {
alert("where'd the coin go?");
} else if (coin == 1) {
alert("you got heads dude");
} else if (coin== 2) {
alert("you got tails dude");
}
} else {
//now it's a computer
if (coin ==0) {
alert("3RR0R C01N G0N3");
} else if (coin==1) {
alert("H34D5");
} else if (coin==2) {
alert("T41L5");
}
}
You should always check Console output of your browser when dealing with "mysterious" stuff like this!
Oh, and if you need a simple JS console for trying code snipets - use jsbin
Looks like you're missing a } to close the else statement.
EXAMPLE
Your biggest else is not closed.

Categories

Resources