Don't know what's wrong with my IF statement (JAVASCRIPT) - javascript

I am trying to make a number guessing game where the user gets 3 chances to guess a number between 1 to 10 and after the third try if they don't manage to guess the number correctly, they'll lose and the number input becomes disabled.
So my variable "tryNum" is meant to be the number of guesses the user gets which I set to be 3. And I then wrote my if statement whereby every time the user guesses the number incorrectly, the value of tryNum decreases by 1. And based on my code, by the time the user guesses 3 incorrect numbers, the input should become disabled and an error message should be displayed. However, when I run my code, it takes 4 incorrect guesses instead of 3 for my code to execute.
I am not sure why this is. Any help would be greatly appreciated.
Here is my code:
let min = 1,
max = 10,
winningNum = 3;
tryNum = 3;
function btnClciked(){
guessedNum = parseInt(userInput.value);
if (tryNum > 0){
let status;
if (isNaN(guessedNum) || guessedNum < min || guessedNum > max ){
if(document.querySelector(".error-display")){
status = false;
} else {
status = true;
}
isNaN(guessedNum) ? createDivElement("You havn't entered any number!", status, "#eb992d","black", true) : createDivElement(`You must guess a number between ${min} and ${max}`, status, "#eb992d", "black", true);
}
else if (guessedNum === winningNum){
status = true;
userInput.disabled = true;
userInput.style.borderColor = "green";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Congratulations! You guessed the winning number: ${winningNum} Correctly!`, status, "green", "white");
}
else {
status = true;
userInput.style.borderColor = "red";
userInput.value = "";
tryNum -= 1;
createDivElement(`${guessedNum} isn't the winning number! You have ${tryNum} more guesses left!`, status, "red", "white");
}
} else {
userInput.disabled = true;
status = true;
userInput.style.borderColor = "red";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Game Over! The winning number was ${winningNum}.`, status, "red", "white");
}
}

When the user guesses it wrong, you should check if tryNum is equal to 0, in which case you should show that it is Game Over.
function btnClciked(){
guessedNum = parseInt(userInput.value);
if (tryNum > 0){
let status;
if (isNaN(guessedNum) || guessedNum < min || guessedNum > max ){
if(document.querySelector(".error-display")){
status = false;
} else {
status = true;
}
isNaN(guessedNum) ? createDivElement("You havn't entered any number!", status, "#eb992d","black", true) : createDivElement(`You must guess a number between ${min} and ${max}`, status, "#eb992d", "black", true);
}
else if (guessedNum === winningNum){
status = true;
userInput.disabled = true;
userInput.style.borderColor = "green";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Congratulations! You guessed the winning number: ${winningNum} Correctly!`, status, "green", "white");
}
else {
status = true;
userInput.style.borderColor = "red";
userInput.value = "";
tryNum -= 1;
if(tryNum != 0){
createDivElement(`${guessedNum} isn't the winning number! You have ${tryNum} more guesses left!`, status, "red", "white");
} else {
userInput.disabled = true;
status = true;
userInput.style.borderColor = "red";
submitBtn.value = "Play Again!";
submitBtn.className += "play-again";
createDivElement(`Game Over! The winning number was ${winningNum}.`, status, "red", "white");
}
}
}
}

Basically when you don't guess the number the third time the value of tryNum is 0 but you have to make another guess in order to trigger the first if statement and enter in the final else block.
The simplest solution is to put the final else block into an if statement below tryNum-=1 to check if the variable is 0

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

Set minimum required length of a text input field using javascript?

I want to be able to perform validation based on how many characters were entered by the user - I want there to be a minimum of 7 characters. (The maximum value is set using an HTML attribute) - I have tried the following:
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (val >= 3 || val == 0) {
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
else if (v3.value.length === 7){
v3.style.borderColor = "green";
flag3 = true;
}
}
The above works to an extent. The input fields border colour will only show green if 7 characters are inputted. However, if i delete characters from that point onwards, the border remains green. Any help on the matter is appreciated.
I'm not entirely sure about what you want; is this close to what you are looking for?
You probably did this and didn't include it in your snippet, but we need this to run each time the form is edited. We add an event listener to the input.
const input = document.getElementById('npo-registration-number');
input.addEventListener('input', () => {
// set the border to red if the value is < 7 characters
if (input.value.length < 7) {
input.style.borderColor = 'red';
return;
}
// otherwise, set it to green
input.style.borderColor = 'green';
});
This fixes an issue: you do not set the color of the border to red unless the value of the form is an empty string. Rather, we want the border to be red whenever the input length goes below seven.
It's because of your condition
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
When you start deleting characters in input, your input is not becoming red again because It's red only when there are no characters and it change to green after 7 characters inputed.
You need to capture the input event so js can evaluate and update.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
const ev3 = document.getElementById("npo-registration-number");
let flag3 = true;
ev3.addEventListener('input', (e) => {
const val = e.target.value;
if (val.length === 7){
ev3.style.borderColor = "green";
flag3 = true;
}
else {
ev3.style.borderColor = "red";
flag3 = true;
}
});
input {
outline: 0;
border: 1px solid;
}
<input id="npo-registration-number" type='text'>
You can just use button that will run this function for it, like send or post buttons(many sites use this method).
function click(){
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (val >= 3 || val == 0) {
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
}
else if (v3.value.length === 7){
v3.style.borderColor = "green";
flag3 = true;
}
}
}
Try this please
v3 = document.getElementById("npo-registration-number");
flag3 = true;
if (v3.value == "") {
v3.style.borderColor = "red";
flag3 = false;
} else {
if (v3.value.length < 7){
v3.style.borderColor = "red";
flag3 = false;
}
else {
v3.style.borderColor = "green";
flag3 = true;
}
}

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