JavaScript weird issue with else if statement - javascript

I'm making a game of Guess the Number, and I want to test if a variable guess is greater than a variable difficulty. difficulty has been taken from my HTML page, and it is not comparing correctly with guess.
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = document.getElementById("difficulty").value;
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = prompt("Enter your guess: ");
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
body {
font-family: sans-serif;
text-align: center;
animation: background 10s infinite;
}
h1 {
margin-top: 48px;
margin-bottom: 48px;
animation: heading 10s infinite;
}
button {
height: 48px;
width: 250px;
font-size: 24px;
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>
Read this: key info
This code works, but I want something to happen: When the guess is greater than difficulty, I want to print "Please enter a number between 1-" + difficulty. However, when I change this code:
else if (guess < 1) {
alert("Please enter a number between 1-" + difficulty);
}
into this:
else if (guess < 1 || guess > difficulty) {...}
(EDIT: the above code is to find out if the guess is greater than difficulty)
then what happens is that EVERY guess except 1, difficulty and anything more than difficulty is alerted by Please enter a number.
How should I fix this?

You're comparing strings not numbers. Convert your strings into numbers.
else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
Better way: Convert it directly after input and...
guess = parseInt(prompt("Enter your guess: "));
...get the difficulty value as number
var difficulty = parseInt(document.getElementById("difficulty").value);
//Initialize variables for player guess, guess counter and previous guesses
var guess = 0;
var guessCount = 0;
var previousGuesses = [];
function startGame() {
//Calculate difficulty
var difficulty = parseInt(document.getElementById("difficulty").value);
//Calculate secret number
var secretNumber = Math.floor((Math.random() * difficulty) + 1);
//Repeats while player has not guessed the secret number
while (guess != secretNumber) {
//Checks for Cancel button pressed
guess = parseInt(prompt("Enter your guess: "));
if (guess == null) {
return;
}
//Checks for empty string/no input
else if (guess == "") {
alert("Please enter a number");
}
//Checks if previously guessed
else if (previousGuesses.includes(guess)) {
alert("You have guessed this number before. Please try a different number.");
}
else if (guess < 1 || guess > difficulty) {
alert("Please enter a number between 1-" + difficulty);
}
//Checks if guess is higher than secretNumber
else if (guess > secretNumber) {
alert("Your guess is too high");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks if guess is lower than secretNumber
else if (guess < secretNumber) {
alert("Your guess is too low");
//Increments guess counter
guessCount++;
//Adds the previous guess to previousGuesses
previousGuesses.push(guess);
}
//Checks for correct guess
else if (guess == secretNumber) {
//Increments guess counter
guessCount++;
//Checks for correct grammar - guesses or guess
if (guessCount > 1) {
alert("Congratulations, you guessed the correct number in " + guessCount + " guesses!");
}
else {
alert("Congratulations, you guessed the correct number in " + guessCount + " guess!");
}
}
}
//Resets variables to play again
guess = 0;
guessCount = 0;
previousGuesses = [];
}
<h1>Guess the Number</h1>
<button onclick="startGame()">Start the Game</button>
<h2>Difficulty</h2>
<select id="difficulty">
<option value="10">Beginner</option>
<option value="50">Intermediate</option>
<option value="100">Hard</option>
</select>

change else if (guess < 1 || guess > parseInt(difficulty))
to else if (parseInt(guess) < 1 || parseInt(guess) > parseInt(difficulty))
or change the type at the input
guess = parseInt(prompt("Enter your guess: "));

You can also use the built-in Number function. See how I fixed your code below:
difficulty = Number(difficulty);
guess = Number(guess);
Try applying this after your variables are declared and it should work!

Change to this should help:
else if (guess < 1 || guess > parseInt(difficulty)) {

Related

JavaScript - begginner questions

I have some difficulties with my first number guessing "game" in JavaScript. Can someone have a look and guide me what I did wrong? Started with that language not that long ago..
Function is assigned to one button
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start !
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check(guess) {
window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
You designed your check function to have a guess passed to it but you are just calling it without doing so. So all your comparisons are against undefined.
You are also using window.prompt to get the actual guess. What you need to do is save the value returned from the prompt into a variable and then compare it. Check the snippet.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert(
"Guess number " + attemps + " is incorrect. The number is " + result + "."
);
}
if (attemps >= 3) {
window.alert(
"Sorry, you have run out of guesses! The number was " + hiddenNum
);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start
you need to assign the prompt
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value='guess'onClick="check()">Click to start!
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
You should store the value from window.prompt. In your code, you just use guess in the parameter of the function as the value of window.prompt which is incorrect.
Syntax for window.promp:
result = window.prompt(message, default);
Also, I have shorten your codes and store the duplicate item in a function to make it a little bit less messy.
function smallcheck() {
let again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again.toUpperCase() == "N") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
console.log(guess)
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
smallcheck()
} else {
attempts++;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attempts + " is incorrect. The number is " + result + ".");
}
if (attempts >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
smallcheck()
}
}
Noticed you never declared 'result'. So I made that variable into a ternary operator to shorten up your code a little more. Also, I added template literals :)
let hiddenNum = Math.floor(Math.random() * 10);
//console.log(hiddenNum);
hiddenNum = hiddenNum;
let attempts = 0;
const nextRound = function () {
let again = window.prompt('Would you like to try again? Enter Y or N.');
if (again.toUpperCase() === 'N') {
window.alert("Thank's for trying. Later nerd");
window.close();
} else {
window.alert('Try to guess the new number, nerd.');
window.location.reload();
}
};
function check() {
let guess = prompt('Please enter the number between 1 and 10');
console.log(guess);
if (hiddenNum === guess) {
alert('Congratulations! You guessed correctly !');
nextRound();
} else {
attempts++;
let result = hiddenNum < guess ? 'lower' : 'higher';
alert(`Guess number is ${attempts} is incorrect. The number is ${result}.`);
}
if (attempts >= 3) {
alert(`Sorry, you have run out of guesses! The number was ${hiddenNum}`);
nextRound();
}
}
<div>
<input
id="box"
class="btn"
style="
display: inline-block;
border-radius: 2em;
box-sizing: border-box;
color: white;
background-color: blueviolet;
cursor: pointer;
"
type="button"
value="Guess"
onClick="check()"
/>Click to start !
</div>

How to stop execution of a JavaScript program

So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();

Guess a number game using HTML and javascript

Hello I have a simple script:
var play = true;
var correct = false;
var number = 0;
var guess = 0;
while (play) {
// random number between 1 and 10.
number = Math.floor(Math.random() * 10 - 1);
if (number == 0) number = 1;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}
When I get the number right and prompted to "Do you want another game?" and enter "yes", the program redisplays and stuck at "Do you want another game?".
You need to reset the state of correct on every play loop:
let play = true;
while (play) {
let number = Math.floor(Math.random() * 10 + 1);
let guess = 0;
let correct = false;
while (!correct) {
guess = window.prompt("What is the number?");
if (guess < number) {
alert("Guess higher ;)");
} else if (guess > number) {
alert("Guess lower ;)");
} else if (guess == number) {
correct = true;
alert("You got it!");
}
}
if (window.prompt("Do you want another game?", "yes") != "yes") {
play = false;
}
}

Hit register for a 1d Battleship game. Using array to record previous user inputs, then cross-checking them with current input

I am a novice programmer. I have started teaching myself JavaScript. I made a rudimentary battleship game. Problem is that if the user enters the same location(if it's a hit) 3 times the battleship sinks. To avoid that I added an array "userchoices" to record user inputs and then cross-check by iterating through a for-loop. the for loop, in turn, contains an If statement that should alert the user if they have already fired at the location before. Problem is that the if statement gets executed each time.
Please review the code below and suggest corrections. Thank you.
var randomloc = Math.floor(Math.random() * 5);
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
var guess;
var userchoices = [];
var hits = 0;
var guesses = 0;
var issunk = false;
function battleship() {
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if (guess == null)
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been
incremented.")
}
else{
guesses++;
userchoices[guesses] = guess;
console.log("users choices = " + userchoices);
}
/* for(var i = 0; i <= guesses; i++)
{
if(userchoices[guesses] = guess)
console.log("you have already fired at this location");
} */
if (guess == location1 || guess == location2 || guess == location3){
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3){
issunk = true;
alert("Enemy battleship sunk")
}
}
else{
alert("You Missed");
}
}
if (issunk){var stats = "you took " + guesses + " guesses to sink the battleship. You accuracy was " + (3/guesses);alert(stats);}
else{alert("You Failed!"); issunk = false;}
}
This is the part that is causing an error
for(var i = 0; i<=guesses; i++)
{
if (userchoices[guesses] = guess){
console.log("you have fired at this location already");
}}
The if statement should execute only when the user enters a grid number that he already has fire upon, no matter hit or miss.
You are accessing the array by the wrong index. Try userchoices[i] instead of userchoices[guesses]. Also equality comparison is performed using 2 equal signs ==:
for(var i = 0; i<=guesses; i++)
{
if (userchoices[i] == guess){
console.log("you have fired at this location already");
}
}
This can also be expressed as:
if (userchoices.includes(guess)){
console.log("you have fired at this location already");
}
Also guesses should be incremented after adding the first value:
else{
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
EDIT
There is a logic error here as you are checking the array for the element after inserting it into the array, perform the check in the else statement before inserting the element. Combining all of the above:
else if (userchoices.includes(guess)){
console.log("you have fired at this location already");
} else {
userchoices[guesses] = guess;
guesses++;
console.log("users choices = " + userchoices);
}
After much-needed help from Avin Kavish and bit of tinkering of my own, I can now present an answer to my own question for future viewers.
Edit: More like my final program
function battleship()
{
var guess; //Stores user's guess
var userchoices = []; //records user's guess until ship is sunk or user chickens out
var issunk = false; //status of ship
var hits = 0; //number of hits
var guesses = 0; //number of guesses
var randomloc = Math.floor(Math.random() * 5); //Random Number Generator
var location1 = randomloc;
var location2 = location1 + 1;
var location3 = location2 + 1;
while(issunk == false)
{
guess = prompt("Ready,Aim,Fire! (Enter a number 0-6):");
console.log("users input = " + guess);
if(guess == null) // If users presses 'OK' without entering anything or the 'Cancel' this would break the loop.
break;
if (guess < 0 || guess > 6){
alert("Please enter a valid cell number. No of guesses has been incremented.");
guesses++; //Gotta punish the player.
}
else if (userchoices.includes(guess) == false) /*instead of doing what i did yo u
can change this line to "else if (userchoices.includes(guess)) and then put the
following oprations in its else clause. */
{
guesses++;
userchoices[guesses] = guess;
console.log("User choices = " + userchoices);
if (guess == location1 || guess == location2 || guess == location3)
{
alert("Enemy Battleship HIT");
hits = hits + 1;
if (hits == 3)
{
issunk = true;
alert("Enemy battleship sunk");
}
}
else
{
alert("You Missed");
}
}
else
{
alert("you have already fired at this location.")
}
if (issunk) //writing issunk == true is overkill
{
var stats = "you took " + guesses + " guesses to sink the battleship. You
accuracy was " + (3/guesses);
alert(stats);
}
}
if(guess == null && issunk == false)
console.log("You failed"); //Humiliate the user for chickening out.
userchoices = []; //Empties the array so user can start over again without relaoding the page
issunk = false; //sets issunk to false for a new game
var randomloc = Math.floor(Math.random() * 5); //creates new random numbers for ship coordinates
}
2D 7X7 version coming soon. Will post here.

for loop getting skipped in javascript

I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");

Categories