Parameter being set to undefined - javascript

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

Related

sea battle game / prevent typing the same thing twice

such a problem is that if I enter the same number 3 times and it counts for me as a win, but I need to prohibit it so that I cannot enter the same number a second time, can you tell me how to do this?
let randomLocation = Math.floor(Math.random() * 6)
let location1 = randomLocation
let location2 = location1 + 1
let location3 = location2 + 1
let guess
let hits = 0
let guesses = 0
let isSunk = false
while (isSunk == false) {
guess = prompt('Enter the coordonation: ')
let secondTime = guess
if (guess < 0 || guess > 6) {
alert('Your number is incorrect')
} else {
guesses++
if (guess == location1 || guess == location2 || guess == location3) {
alert('SHOT')
hits++
if (hits == 3) {
isSunk = true
alert('The ship was wrecked')
}
} else {
alert('you missed')
}
}
}
let stats = 'You wrecked from ' + guesses + ' attempts ' + ' which means you have statistics ' + (3 / guesses)
console.log(stats)
Here's one way to check to see if the user has entered the same thing before. Use a Set.
let answers = new Set();
while(true) {
let input = prompt('Enter something')
if (input == null) break;
if (answers.has(input)) {
alert('You already entered that.');
} else {
alert('That is new!')
answers.add(input); // Remember this input for later.
}
}

can not display the dialog when load both file .js or .html?

I am having trouble with this problem. When I coded this very simple javascript code from head first javasript book, they said to me that I must saved it as the name battle.js and run it, but after that, they said to me that I must run it as the name battle.html. Here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = promt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3/guesses);
alert(stats);
As they described, it must appear a dialog and we can enter something into that, but when I ran it, nothing appeared.
I just a newbie with javascript, could you please give me some ideas ? Thank you very much.
Your code has typing mistake. replace promt to prompt
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);

Javascript battleship game - prompt not responding

I'm trying to follow along with my javascript book "headfirst javascript programming"....
the assignment is to make a simplified battleship game. It was working until I added more code... Now the prompt is not showing. Im sure im doing something wrong with the curly brackets. I just want the prompt "Ready, aim, fire! (enter a number from 0-6):" to appear when launching the browser and for it to respond to numerical inputs.
Can anyone quickly tell me why im screwing up? thank you! here is my simple code --->>>
//declare variables
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
//loop
while (isSunk == false) {
//get
guess = prompt("Ready, aim, fire! (enter a number from 0-6):");
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
//add
guesses = guesses + 1;
//if
if (guess == location1 || guess == location2 || guess == location 3) {
alet("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + "guesses to sink the battleship, " +
"which means your shooting accuracry was " + (3/guesses);
alert(stats);
Your lines
if (guess == location1 || guess == location2 || guess == location 3) {
and
alet("HIT!");
have errors, a extra space in location3 variable name and missing r from alert, they should be
if (guess == location1 || guess == location2 || guess == location3) {
and
alert("HIT!");

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.

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