How do I end javascript program mid program - javascript

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...
}

Related

If statement with || is not doing anything

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

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;
}
}

JS while loop doesnt stop at true

When you run this script it shows the HP for both of the pokemon when you press 1 and click enter it subtracts your attack hit points to the enemies hit points. When you or the ememy hits 0 or less than 0 hit points it is supposed to stop and just show who won in the console log. Instead it takes an extra hit to for it to show the message.
So if you are at -10 hp it takes one more hit.
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
if (!firstFight) {
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
}
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
}
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
Are there any ways I can make this code more efficient?
you can simply add another if condition to check whether life of the player is still greater then '0' or less then '0' in the same turn like this.
in this way you don't have to go for next turn to check for the players life plus it rids off the extra conditional statements...
if (fightOptions == 1) {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
}
if (!firstFight){
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
}
}
}
The problem is, the points are getting subtracted after you check if they are equal to or below zero. Here is a way you can check before:
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
wildPokemon[0].hp -= pokeBox[0].attack.hp;
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
console.log(wildPokemon[0].hp);
}
pokeBox[0].hp -= wildPokemon[0].attack.hp;
if (!firstFight && pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
console.log(pokeBox[0].hp);
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
While loops stops when the condition is false, in you case, you set it to not false, it is not stopping because you did not explicitly determine it. There are 2 ways you can do.
1st:
while(!firstFight == false)
2nd:
var firstFight = true;
while(firstFight)
then set the firstFight to false inside your if else statements.

Infinite Loop in JavaScript - While Loop

Does anyone know why this may be causing an infinite loop. I just can't see why!
I feel the issue may be with my while loop under play to five.
The while loop should be stopping at 5 and when the player or computer reaches this the game should stop.
This is Rock, Paper, Scissors. The result of each game is either player win, computer win or draw.
The game should end once either player reaches 5 wins.
The problem is the game is not ending as intended!
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.");
return prompt("Please choose either 'rock', 'paper', or 'scissors'");
}
function getPlayerMove() {
return getInput();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
}
else if (randomNumber < 0.66) {
return "paper";
}
else {
return "scissors";
}
}
function getComputerMove() {
return randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
// A big limitation of this game is the user is only allowed to choose once! To allow more choices you'd need to design the program differently
function playToFive() {
var playerWins = 0;
var computerWins = 0;
var playerMove = getPlayerMove();
while ((playerWins <= 5) || (computerWins <= 5)) {
var computerMove = getComputerMove();
var winner = getWinner(getPlayerMove, getComputerMove);
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "player") {
playerWins += 1;
}
else if (winner === "computer") {
computerWins += 1;
}
if ((playerWins = 5) || (computerWins = 5)) {
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
playToFive ();
Problem is this line
var winner = getWinner(getPlayerMove, getComputerMove);
you are passing the function reference to the getWinner() method
var winner = getWinner(playerMove , computerMove );
Which means that you need to get moves again later, so change your method to (multiple issues fixed in your code)
function playToFive()
{
var playerWins = 0;
var computerWins = 0;
while ((playerWins <= 5) && (computerWins <= 5)) //this line has && instead of ||
{
var computerMove = getComputerMove();
var playerMove = getPlayerMove(); //this line is now inside while loop
var winner = getWinner( playerMove , computerMove );
console.log('The player has chosen ' + playerMove + '. The computer has chosen ' + computerMove);
if (winner === "Player") { //P caps
playerWins += 1;
}
else if (winner === "Computer") { //C caps
computerWins += 1;
}
if ((playerWins == 5) || (computerWins == 5)) { //= is replaced by ==
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
else {
console.log("The " + winner + ' takes the round. It is now ' + playerWins + ' to ' + computerWins);
}
}
}
In order for this if to run accordingly:
if ((playerWins = 5) || (computerWins = 5)) {}
You'll need to use the == operator, because just one = is used for value assignation.
if ((playerWins == 5) || (computerWins == 5)) {}
Firstly in the while loop you need to change it too a && statement otherwise if the computer is 8 and the player is 3 the loop will continue until both players are >5.
I Think first you should understand the difference between (==) and (===) here.
Use This Code (Conditional Code not assignment)
if ((playerWins == 5) || (computerWins == 5)) { //use logical Operator not assignment Oprtr.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Instead of ##
if ((playerWins = 5) || (computerWins = 5)) { // Error Code.
console.log("The game is over! " + "The " + winner + " has taken out the game!");
console.log("The final score was. " + playerWins + " to " + computerWins);
}
Problem is this line
you are passing the function reference to the getWinner() method
use this
var winner = getWinner(playerMove , computerMove );
instead of
var winner = getWinner(getPlayerMove, getComputerMove);
For This Function...
function getWinner(playerMove,computerMove) {
var winner;
if (playerMove === 'rock' && computerMove === 'scissors') {
winner = 'Player';
}
else if (playerMove === 'scissors' && computerMove === 'paper') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'rock') {
winner='Player';
}
else if (playerMove === 'paper' && computerMove === 'scissors') {
winner='Computer';
}
else if (playerMove === 'rock' && computerMove === 'paper') {
winner='Computer';
}
else if (playerMove === 'scissors' && computerMove === 'rock') {
winner = 'Computer';
}
else {
winner = "tie";
}
return winner;
}
Every time this method set tie as winner.
But you should know the difference between (==) equalto and (===) equal value and equal type here
Thanks guys. There were quite a few issues.
Cheers guys. Definitely needed && rather than ||. The || was resulting in the game continuing even
Also var winner = getWinner(getPlayerMove, getComputerMove) was required. This was causing an infinite loop.

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

Categories

Resources