for loop getting skipped in javascript - 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.");

Related

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.

Hangman in javascript, when letter is wrong retuns always true

I have a game hangman. But I tried to make the logic, that if a user enters the wrong letter, then the user will get a message that he/she has to try again.
But now even if the user has chosen the correct letter, the user will get the message that he/she has to try it again.
This is the code:
<script>
var words = [
"ha",
"pe",
"jaa"
];
var word = words[Math.floor(Math.random() * words.length)];
var answareArray = [];
for (var i = 0; i < word.length; i++) {
answareArray[i] = "_";
}
var remainingLetters = word.length;
while (remainingLetters > 0) {
//gaming code
alert(answareArray.join(" "));
//Get a gues from the user:
var guess = prompt("Guess a letter, or click cancel to stop");
if (guess === null) {
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter");
} else {
for (var j = 0; j < word.length; j++) {
if (word[j] !== guess) {
debugger;
alert("try again");
}
if (word[j] === guess) {
if (answareArray[j] !== "_") {
alert("Letter already be guessed");
break;
} else {
answareArray[j] = guess;
remainingLetters--;
}
}
}
}
}
alert(answareArray.join(" "));
alert("Good Job the answare was: " + word);
</script>
And in this part:
if (word[j] !== guess) {
debugger;
alert("try again");
}
I try to return the message to the user.
So what do I have to correct?
You have to show the alert after you checked all the letters, you're currently showing it at each iteration.
You can do that by using a flag (a boolean variable).
Here is an example:
var goodGuess = false;
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
goodGuess = true;
if (answareArray[j] !== "_") {
alert("Letter already be guessed");
break;
} else {
answareArray[j] = guess;
remainingLetters--;
}
}
}
if(!goodGuess){
alert("try again");
}
What this does, is to first set the goodGuess variable to false, then go through all the letters and if the user's guess is equal to any of them, set goodGuess to true.
At the end of the loop (after all the letters were checked), if goodGuess is false, the alert is shown.

How to put timer in guessing game in Javascript?

I'm having a problem with my Javascript code that involves putting a timer in a Random guessing game. I must give the user 5 seconds to guess the number. The user can guess multiple times within the span of 5 seconds. If the time runs out, I must prompt the user if he wants to play again or exit. If yes I have to loop back to the game. My timer is not working. I would every much appreciate it if any of you guys can help. Thank you.
<script type="text/javascript">
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0
function timer (upper) {
var timeID = setInterval (getRandomNumber, 5000);
}
function getRandomNumber (upper) {
var number = Math.floor(Math.random()*upper) +1;
return number;
}
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
}else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
}else if(parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
</script>
As prompt freezes the internal timer (in Chrome, Opera and Safari), we can't set a timeout for the user's response. One way is to use html <input> instead of prompt. In this case setTimeout works as desired.
const input = document.getElementById("input");
const getRandomNumber = (upper) => Math.floor(Math.random() * upper) + 1;
const upper = 10;
let guessCounter = 0;
let randomNumber = getRandomNumber(upper);
let timer;
const play = () => {
if (timer) clearTimeout(timer);
input.value = "";
guessCounter++;
timer = setTimeout(() => {
if (confirm("Time is out. Play again?")) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
}
}, 5000);
}
document.getElementById("question").innerHTML = `I am thinking of a number between 1 and ${upper}. What is it?`;
document.getElementById("guess").addEventListener("click", () => {
let userGuess = parseInt(input.value);
if (userGuess > randomNumber) {
alert('Try again! Your number is too high');
play();
} else if (userGuess < randomNumber) {
alert('Try again! Your number is too low ');
play();
} else if (userGuess === randomNumber) {
if (confirm(`You have guessed the number! It took you: ${guessCounter} tries. Play again?`)) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
} else {
clearTimeout(timer);
}
}
});
play();
<div id="question"></div>
<input id="input" type="input">
<button id="guess">Guess</button>
I recommend moving your game into a function and naming it, e.g. "startGame". Then, when the game finishes it, you can implement your timer to relaunch the game.
function getRandomNumber(upper) {
var number = Math.floor(Math.random()*upper) + 1;
return number;
}
function startGame() {
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0;
var playAgain;
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
} else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
} else if (parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
if (confirm('Do you want to play again?')) {
setInterval(startGame, 5000); // Start a new game in 5 seconds
}
}
startGame();

Categories