If statement with || is not doing anything - javascript

some context,
I'm making a game wherein you have to guess a randomly generated number between 1 and 1 million. I'm trying to make it so that if the user inputs something that is not a number, above 1 million, or below zero, it will display an error warning. The last else if statement is supposed to do this, but is not doing so. I've tried several revisions, including individual else if statements for each forbidden case, but they aren't working.
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess >= 1000000 || userGuess =< 0 || userGuess == "") {
alert('input a valid number !')
}
}
</script

You have to write the last else if before you check if the userGuess is higher or lower than the randomNumber.
That's because when userGuess is below 0 or over 1.000.000 it will always be catched by the else ifs that check if the userGuess is lower or higher than randomNumber. Therefore the last else if will never be reached.
The correct order would be:
Check if the user guessed right.
Check if the input is wrong.
Check if the user guessed too high.
Check if the user guessed too low.
But you did:
Check if the user guessed right.
Check if the user guessed too high.
Check if the user guessed too low.
Check if the input is wrong.
Do the following:
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
alert('input a valid number !')
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
}
</script

There are a couple problems with your conditionals.
else if (userGuess > randomNumber)
{ ... }
This will handle all numbers, even those greater than 1,000,000.
else if (userGuess < randomNumber)
{ ... }
This will handle all numbers, even those less than 0.
Therefore, your last conditional will only ever catch a blank input (which would probably be better expressed as a cast to string or bool).
Also, as pointed out in the comments to your question, the correct less than or equal syntax is <=.

You do:
else if (userGuess >= 1000000 || userGuess =< 0 || userGuess == "") {
But it's like this:
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
<script type = "text/javascript">
var randomNumber = Math.floor(Math.random() * 1000000 + 1);
var count = 0;
var x = 1000000
console.log(randomNumber)
document.getElementById("submitguess").onclick = function(){
var userGuess = document.getElementById("guessField").value;
console.log(userGuess)
if(userGuess == randomNumber)
{
if (count < 10) {
document.getElementById('higherOrLower').innerHTML = '<div class="powerupstyling"><a class="facethebossstyling">YOU BEAT THE GAME. CONGRATS !</a></div>'
}
else if (count > 10) {
document.getElementById('higherOrLower').innerHTML = "<center>grats you got it in " + count + " tries. Unfortunately, you didn't quite beat the game. Aim for 10 tries or lower.</center>"
}
}
else if (userGuess > randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go lower</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess < randomNumber) {
count++;
document.getElementById('higherOrLower').innerHTML = '<br><div class="powerupstyling"><a class="gostyling">go higher</a></div>'
document.getElementById('countCounter').innerHTML = "<center>tries: " + count + "</center>";
}
else if (userGuess >= 1000000 || userGuess <= 0 || userGuess == "") {
alert('input a valid number !')
}
}
</script

Related

I want the user to guess a random number but every time I refresh the page a new random number generates

I need to create a random number that the user has to guess. When I refresh the page it appears the generate a new random number.
var userPrompt = prompt("Guess a number");
var ran = Math.floor(Math.random() * 10);
function ranNumGame(ran) {
if (userPrompt == ran) {
return "Congrats";
}
else if (ran < userPrompt) {
return "Lower";
}
else if (ran > userPrompt) {
return "Higher";
}
}
console.log(ranNumGame(ran));
var randomNumber = Math.floor(Math.random() * 10);
var userInput = prompt("Pick a number between 0 and 10");
while (userInput != randomNumber) {
alert("nope");
if (userInput < randomNumber) {
userInput = prompt("guess higher");
} else if (userInput > randomNumber) {
userInput = prompt("guess lower");
} else if (userInput == randomNumber) {
alert("congrats");
console.log("congrats");
}
}

My JavaScript console game is not working

This is my first time asking a question here, so pardon if it has an error/is less descriptive.
Actually, I am a beginner in JavaScript, and while making a console guess game, there is just nothing in the output window(it supports alert and prompt boxes). Here's the code:
function runGame() {
Boolean isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random(10) * 1);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Moved your while isPlaying to the inside while loop. A while loop with a function inside will just call that function over and over again.
Math.random(10) only changes the seed, it does not choose between 1-10.
function runGame() {
var isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random() * 10);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0 && isPlaying) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
runGame()

Parameter being set to undefined

I am working on a school project which is based on the game Wheel of Fortune. Currently, I am working on having the computer differentiate between a consonant and vowel, and adding to the player's balance if they correctly guess a letter. As of now, I have encountered two problems.
First, when checking if a letter is a vowel, it correctly says which is which, and also checks if a vowel CAN be guessed (player needs to have at least a certain amount of money). If they can, it will deduct the necessary amount and move on normally. If not, however, it should disregard the guess and have the player guess again. This works until the player guesses a different letter. What happens is the second guess that the player tries is checked, but the first guess, the vowel which they could not afford, is also checked.
Here is what it looks like:
The word is CANADA
Basically, the player guessed A at first, but when asked to guess another letter (because they did not have enough money), they guessed C. When updating, the computer updated both for letter A and letter C, which I do not want.
Second, I am trying to have the player's balance update if they correctly guess a letter. For this, I have a separate function setup to update a balance based on the type of guess, but somewhere, the variable becomes undefined. This is the related code that I have for that part:
I am using parameters to do this, what is going wrong?
function spinWheel() {
spinAmount();
ask();
}
function spinAmount() {
var luck = randomNum(0, rewards.length);
var multiplier = rewards[luck];
if (multiplier == undefined) {
spinAmount();
} else {
alert("You spun $" + multiplier);
return multiplier;
}
updateBalance(multiplier);
}
function ask() {
console.log("Prompting");
var guess = prompt("What letter would you like to guess?");
var playerGuess = guess.toUpperCase();
console.log(playerName1 + " guessed " + playerGuess);
checkGuessType(playerGuess);
}
function checkGuessType(checkMe) {
console.log("Checking type...");
if (checkMe.length > 1) {
console.log(playerName1 + " guessed a word.");
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 < 100) {
console.log(playerName1 + " tried to guess a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("You do not have enough money to buy a vowel. Guess a different letter.");
ask();
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 > 100) {
console.log(playerName1 + " guessed a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("Since you guessed a vowel, you do not get any money added to your account. Instead, $100 was deducted.");
isVowel = true;
} else if (checkMe !== "") {
console.log(playerName1 + " guessed a consonant.");
} else if (checkMe == "") {
console.log(playerName1 + " did not guess.");
alert("Please guess a letter or word.")
ask();
}
checkForGuess(checkMe);
}
function checkForGuess(amIThere) {
console.log("Checking if letter is present...");
for (x = 0; x < magicyMagic.length; x++) {
if (amIThere == magicyMagic.charAt(x)) {
console.log("Ding ding ding!");
lettersMatched = lettersMatched + 1;
isCorrect = true;
output[x] = amIThere;
if (isVowel == false) {
updateBalance();
} else if (isVowel == true && nowGoing == 1) {
balance1 = balance1 - 100;
} else if (isVowel == true && nowGoing == 2) {
balance2 = balance2 - 100;
}
lettersMatched = 0;
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}
if (isCorrect == false && amIThere !== "") {
console.log("Player did not guess correctly...");
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "There are no " + amIThere + "'s in the word.";
lettersMatched = 0;
document.getElementById("lastMessage").innerHTML = "Player 2 (" + playerName2 + ") will now go.";
}
hasBeenGuessed.push(amIThere);
console.log(hasBeenGuessed[0] + " has been added to the list. Players cannot guess this letter again.");
}
function updateBalance(totalMoneySpun) {
alert(totalMoneySpun)
if (nowGoing == 1) {
balance1 = balance1 + (lettersMatched * totalMoneySpun);
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}

Simple Guessing Game Program in Javascript

Trying to create a very simple number guessing game as a first project. I want the player to have 5 guesses before they lose.
I'm having difficulty troubleshooting the bugs or coding mistakes.
var num = Math.floor((Math.random(1,10) * 10) +1);
console.log(num); //To check
var counter = 5;
while(counter > 0){
function guess(){
counter = counter-1
var guess = prompt("You've got " + counter + " tries to guess the number.");
if (num == guess){
alert("That's the number!");
}else if (guess != (int){
alert("That's not a number...");
}else{
alert("Nice try");
}
}
}
alert("You lost.");
Working fiddle: http://jsfiddle.net/0skh4t4r/
var num = Math.floor((Math.random(1, 10) * 10) + 1);
console.log(num); //To check
var counter = 5;
function guess() {
var x = prompt("You've got " + counter + " tries to guess the number.");
if (!x) return; // cancel the game
counter--;
if (num === parseInt(x)) {
alert("That's the number!");
return;
} else if (isNaN(x)) {
alert("That's not a number...");
} else {
alert("Nice try");
}
if(counter === 0) {
alert("You lost");
} else {
guess(); // next try
}
}
guess();

How do I end javascript program mid program

I need some help ending my program. Is there a command to end it halfway through? In this short guess the number game i made everything goes fine unless the first person wins because it has to complete the loop even after the game has ended
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Use break; to break the while loop like this:
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Or you can define the process as a function when someone win the game return a value and it will end :
function game() {
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
}
game();
I think you are looking for continue
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
continue;
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
The break statement, which was briefly introduced with the switch
statement, is used to exit a loop early, breaking out of the enclosing
curly braces.
To handle all such situations, JavaScript provides break and continue
statements. These statements are used to immediately come out of any
loop or to start the next iteration of any loop respectively.
Example
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Information courtesy of TutorialsPoint.com
By changing a bit your logic:
Store Player names into an Array, change turn using 0,1,0,1... numbers,
Use only one prompt!! The current player is defined by players[turnNumber]
var rnd = Math.round( Math.random() * 5), // 0 - 5
res = -1, // Result
pl = [], // ["Ethan", "Roko"]
t = 0; // turn: 0,1,0,1... (0 = 1st player)
for(var i=0; i<2; i++) pl[i] = prompt("Player"+ (i+1) +", please enter your name:");
while (res !== rnd) {
res = parseInt( prompt( pl[t] + ", take a Guess (0-5)"), 10);
alert( res===rnd ? (res +" is correct! "+ pl[t] +" has won!") : (res<rnd? "Higher" : "Lower"));
t = ++t % 2; // increment turn and reset to 0 if === 2 Results in: 1,0,1,0...
}

Categories

Resources