JS while loop doesnt stop at true - javascript

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.

Related

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

Use While Loop With setTimeout

I have making a text-based space rpg game. In the battle system, the player and AI take turns firing at each other. I can't figure out how to make the system loop with a while loop without making the browser crash via infinite loop. Here is my code:
function battle(enemy) {
var battleOver = false;
console.log(enemy.name + " appears!");
//problem loop here.
while(battleOver === false){
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
var ibumped = i + 1;
console.log("Press " + ibumped + " to fire the " + userWeapons[i].name + ".");
}
var weaponChosen;
setTimeout(function() {
var weaponChoice = prompt("Which weapon do you choose?");
switch (weaponChoice) {
case 1:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
break;
case 2:
weaponChosen = userWeapons[1];
console.log(userWeapons[1].name + " chosen.");
break;
default:
weaponChosen = userWeapons[0];
console.log(userWeapons[0].name + " chosen.");
};
}, 1000);
setTimeout(function() {
if (enemy.shields > 0 && weaponChosen.ignoreShield === false) {
enemy.shields = enemy.shields - weaponChosen.damage;
weaponChosen.fire(enemy);
if (enemy.shields < 0) {
enemy.health = enemy.health + enemy.shields;
console.log("Enemy shields destroyed and enemy took " + -1 * enemy.shields + " damage!")
} else {
console.log("Enemy shields have been reduced to " + enemy.shields + ".");
}
} else {
enemy.health = enemy.health - weaponChosen.damage;
weaponChosen.fire(enemy);
console.log("Enemy takes " + weaponChosen.damage + " damage!");
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
}
}, 3000);
setTimeout(function() {
if (enemy.health > 0 && battleOver === false) {
if (enemy.weapons != null) {
console.log(enemy.weapons.name + " fired at you.");
health = health - enemy.weapons.damage;
console.log("You have " + health + " health left.");
if (health <= 0) {
console.log("Game over... You were destroyed");
battleOver = true;
}
} else {
console.log("The enemy did nothing...");
}
};
}, 5000);
}
}
All help is appreciated!
Things start getting very tricky when you use setTimeout. Most games will have a "main game loop" that runs 60 times a second.
Try using a main game loop and cooldowns.
Here's an example of how you could restructure the program.
var timeForOneFrame = 1000/60 // 60 Frames per second
var enemy;
var battleOver;
function initGame() {
/*
Initialize the enemy etc.
*/
}
function gameLoop() {
battle(enemy);
}
function battle(enemy) {
/*
Do all the battle stuff, this function is called 60 times a second-
there's no need for setTimeout!
*/
// If you want an enemy to only be able to attack every 2 seconds, give them
// a cooldown...
if (enemy.cooldown <= 0) {
// Attack!
enemy.cooldown += 2000
} else {
enemy.cooldown -= timeForOneFrame
}
if (enemy.health <= 0 && battleOver === false) {
console.log("Enemy destroyed!");
battleOver = true;
clearInterval(gameLoopInterval)
}
}
initGame();
var gameLoopInterval = setInterval(gameLoop, timeForOneFrame);
A while loop blocks the whole page until it ends, and as your loop never exits its infinite. You may replace it with a high speed interval:
const loop = setInterval( function(){
if( battleOver ) return clearInterval(loop);
console.log("This enemy has " + enemy.health + " health.");
for (var i = 0; i < userWeapons.length; i++) {
console.log("Press " + (i + 1) + " to fire the " + userWeapons[i].name + ".");
}
},10);
I would take that loop out and use a recursive call on the end of the interactions.
Let's say:
function battle(enemy) {
//All your code here
if (HeroAlive) {
battle(enemy);
}
}

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