How to loop my question? Javascript Number Guessing Game - javascript

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.

Related

Javascript won't display message

I'm trying to create a simple program where a user needs to pick a maximum number, then try to guess a number between 1 and that maximum number. When they enter their guess, I need to validate the input, and offer a choice of feedback: different messages if it's (1) not a number, (2) a number not within the range, (3) the correct guess, (4) too high, but within range, and (5) too low, but within range.
function do_guess(prompt) {
let valid_input = false;
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
while (!valid_input) {
input = window.prompt(prompt);
guess = Number(input);
if (isNaN(guess)) {
message.innerHTML = "That is not a number!";
} else if (guess < 1 || guess > val) {
// val = max_num - "I wasn't sure how to code this."
message.innerHTML = "That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
} else {
message.innerHTML = "No, try a higher number.";
}
}
}
do_guess("Number from 1 to 10")
Guess <input id="guess" value="" />
<div id="message"></div>
Based on your requirements, I'm loading the max_val from the input box and calling the do_guess function with a new button.
function do_guess(prompt) {
let valid_input = false;
let max_val = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
let output = '';
let num = Math.floor((Math.random() * max_val) + 1);
prompt = prompt + max_val;
while (!valid_input) {
input = window.prompt(prompt + output);
let guess = Number(input);
if (isNaN(guess)) {
output = " That is not a number!";
} else if (guess < 1|| guess > max_val) {
output = " That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
output = " No, try a lower number.";
} else {
output = " No, try a higher number.";
}
}
}
Max Guess <input id="guess" value="" />
<div id="message"></div>
<button onClick="javascript:do_guess('Number from 1 to ')">
Guess
</button>

How do I store total points after user input in 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!";
}

JS code guessing game color NOT WORKING

I am a neophyte JS, I'm making a game where the user has to guess a randomly generated color.
I noticed that the code I tried to write results in errors, that is, when I go to enter a color in the prompt, even if it is wrong always says the right thing. I have something wrong in check_guess function where I wrote the conditions.
Another mistake I detected when the game ends, should be out in the background the color that guessed it, nor should you.
Can you help me figure out where I'm wrong?
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors:\n\n" +
colors_message + "\n\n What is the color am I thinking of?");
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess();
}
}
function check_guess() {
if (guess_input == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_input > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_input < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = target;
return true;
}
}
</script>
Referring to your code revisions I got the required data. There were few glitches that were found like:
You were checking guess_input with target, where guess_input holds a string value of the user input and target holds an integer value of the correct answer. None of the conditions will ever be satisfied in this case, and thus the last else part will be executed always. That is, alert("Congratulations! You ha..);
myBody.style.background = target; will set the background
property to an integer (index of answer in colors array). You need
to set it like myBody.style.background = colors[target];
Below is the working code:
var colors = ["antiquewhite", "blueviolet", "crimson", "deepskyblue", "forestgreen", "gold", "lawngreen", "magenta", "palegreen", "skyblue"];
var colors_message = colors.join(", ");
var target;
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
var ask_again = false;
function do_game() {
var target_index = Math.random() * colors.length;
var target_index_integer = Math.floor(target_index);
target = target_index_integer;
var answer = String(colors[target]).toLowerCase();
//Alert correct answer for testing purposes
alert("The correct answer is: " + answer);
guess_input_text = prompt("I am thinking of one of these colors:\n\n" + colors_message + "\n\n What is the color am I thinking of?");
while (!finished) {
if(ask_again){
guess_input_text = prompt("What is the color I was thinking of?");
}
guess_input = guess_input_text.toLowerCase();
guesses += 1;
finished = check_guess(colors.indexOf(guess_input));
}
}
function check_guess(guess_index) {
ask_again = true;
if (guess_index == -1) {
alert("Sorry, I don't recognize your color. \n\n Please try again.");
return false;
} else if (guess_index > target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically higher than mine.\n\nPlease try again.");
return false;
} else if (guess_index < target) {
alert("Sorry, your guess is not correct!\n\nHint: Your color is alphabetically lower than mine.\n\nPlease try again.");
return false;
} else {
ask_again = true;
alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game!\n\nYou can see the colour in the background.");
var myBody = document.getElementsByTagName("body")[0];
myBody.style.background = colors[target];
return true;
}
}
<body onload="do_game()"></body>

Can't save the value of JavaScript prompt() function

I'm new to JavaScript and I'm building a very basic battleship program, but I've noticed that the prompt() function doesn't seem to bring up a dialog box if I try to save it's value to a variable. Here's my code:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk == false){
guess = prompt("Ready, aim, fire! Enter a number 0-6");
if (guess < 0 || > 6){
alert("PLease enter a valid cell number!");
}
else{
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
else{
alert("Miss!");
}
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Now, the reason that I think my prompt not appearing when I load the browser is due to the fact that I'm trying to set the value of the prompt to the variable guess is because the following code executes without issue:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk == false){
prompt("Ready, aim, fire! Enter a number 0-6");
isSunk = true;
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Can someone help me understand what the issue with my code is please? Thanks in advance :)
You are using prompt() correctly.
The problem is in the line below :
if (guess < 0 || > 6) {
should be
if (guess < 0 || guess > 6){
This error was stopping the JS before prompt() was called.
In the future, you should use the browser console to debug your code. You would have seen this error.
If you use Firefox, you can open it with Ctrl+Shift+K. With Chrome it's Ctrl+Shift+J.
When you will have resolved this issue, you will see that the rest of the code has no syntax error but is not doing exactly the right thing (for example I can hit the same location several times). Logic errors are not as easy to fix (you have no debugger to help you). So... good luck !
Well, don't worry in your case it won't be hard to fix.
+1 to the above comment.
Furthermore Kiyana, when you run your code, you'll notice that as long as the user's input is not <0 or >6, the alert("Hit!") and the alert("Miss!") are both appearing.
This has to do with the ordering of your code:
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
else{
alert("Miss!");
}
}
Here is the order in which you want the above code to appear.
Pseudo Code:
If user's guess is 3, 4, or 5 (location1, location2, or location3), then we want to alert a "Hit"
Then, add 1 counter to the hit variable (hit = hit + 1)
ELSE - then we want to alert a "Miss."
After this guess is evaluated, we want to check to see if the hit counter has reached 3.
a) If it hasn't, then we loop back through all the code.
b) If it has, then we want to make isSunk equal to true (to stop the loop) and alert a "You sank my battleship!"
The code should look like this:
var location1 = 3;
var location2 = 4;
var location3 = 5;
var hits = 0;
var guesses = 0;
var guess;
var isSunk = false;
while (isSunk === false){
guess = prompt("Ready, aim, fire! Enter a number 0-6");
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number!");
} else{
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3){
alert("Hit!");
hits = hits + 1;
}else{
alert("Miss!");
}
if (hits == 3){
isSunk = true;
alert("You sank my battleship!");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting accuracy was " + (3/guesses);
alert(stats);
Hope this helps!

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

Categories

Resources