I am working on a computer science project, I need to make a Wheel of Fortune game - basically, get a random word, show blank spaces, and have the player(s) guess the letters to form the word. Right now, I've got the parts where the word is chosen, hidden (switching the letters for blank spaces), and shown. Now, I am on the part of enable player turns to start guessing the letters. I have set up a button to call a function which calls other functions (each turn is broken down into multiple parts, such as asking for a guess, checking what type of guess it is, and checking if that guess is in the word). For some reason, this bigger function is, when calling them, only calling the first function, and spamming that single function. Why is it not going down the list of functions and calling each in order?
Here is the code that relates to that part:
function player1() {
console.log("Player 1 is going.");
nowGoing = 1;
player1Elements.style.display = "block";
alert(player1Name + " it is your turn. What do you guess?");
prompt();
checkGuessType();
checkGuess();
}
function prompt() {
console.log("Prompting");
var playerGuess;
playerGuess = prompt("What letter would you like to guess?");
checkGuessType(playerGuess);
}
function checkGuessType(playerGuess) {
console.log("Checking");
if (playerGuess.length > 1) {
console.log(player1Name + " guessed a word.");
} else if (playerGuess == "a" || playerGuess == "e" || playerGuess == "i" || playerGuess == "o" || playerGuess == "u") {
console.log(player1Name + " guessed a vowel.");
} else {
console.log(player1Name + " guessed a consonant.");
}
}
All that appears in the console (the console.logs are exactly for this purpose) are 6000 lines saying "Prompting", not "Prompting" and "Checking". If there is any more code I should show, please let me know!
If anyone could help me out, that would be great!
Edit: I tried changing the code to the following (basically changing to a global variable), but it still didn't work. I'm not sure why, as the same thing happens.
function player1() {
console.log("Player 1 is going.");
nowGoing = 1;
player1Elements.style.display = "block";
alert(playerName1 + " it is your turn. What do you guess?");
prompt();
checkGuessType();
checkGuess();
}
function prompt() {
// console.log("Prompting");
playerGuess = prompt("What letter would you like to guess?");
}
function checkGuessType() {
console.log("Checking");
if (playerGuess.length > 1) {
console.log(playerName1 + " guessed a word.");
} else if (playerGuess == "a" || playerGuess == "e" || playerGuess == "i" || playerGuess == "o" || playerGuess == "u") {
console.log(playerName1 + " guessed a vowel.");
} else {
console.log(playerName1 + " guessed a consonant.");
}
}
The reason that "Prompting" is appearing over and over is that you provide playerGuess as the argument for checkGuessType in prompt but playerGuess is just another call to prompt so it starts recursing. However, prompt never returns any value under any condition, so the recursion will never resolve to a value causing the stack of function calls to collapse and execute the call to checkGuessType, so you never see a repetition of the console.log in checkGuessType.
EDIT
After your edit I just wanted to point at what I think the problem is directly:
function prompt() {
// console.log("Prompting");
playerGuess = prompt("What letter would you like to guess?");
}
Within the scope of your function, prompt just refers to the function itself. This is causing a recursion. That recursive stack will never end because nothing returns from prompt, thus eventually causing a stack overflow error. If you don't mean to be starting a recursive stack, you need to rename your prompt function to something other than what the built in prompt function is called.
Related
I am a begginer to javascript. I was writing some code for my program in which mainly it's loop. It's about you enter your age and it says you should drive or not a simple program but , I wanted to make it repeating itself until the user didn't enters n or N. I wrote a if statement with break and another else - if statement with continue. When i press n it stops but , when I type y it dosen't continue. Plz try to help me Here is the code below:
while(true){
let age = prompt("Enter your age")
if (age>18){
console.log("You can drive")
}
else if (age<0){
console.log("Invalid age")
}
else if (age>100){
console.log("Invalid age")
}
else if (age==18){
console.log("Come to our office")
}
else{
console.log("You cannot drive")
}
let choice = prompt("Type y or Y to run again type n or N to exit")
if(choice == "n" || "N"){
continue
}
if (choice == "y" || "Y")
break
}
Your if conditions are strange, you say if(choice == "n" || "N"), which means, in words "go in the next block if the variabe choice is 'n' or if 'N'". I'm guessing saying if("N") gets interpreted as true, since it's not null.
You should write, explicitly, if(choice === "n" || choice === "N").
Also, as phuzi said in the comments, continue makes the code restart the loop with the next iteration, while break makes the code go out of the loop. It seems you have them backwards
This is the first app I have ever written. I have seen a million random number-generating games here, javascript and otherwise, but none had the problems I'm having. I apologize for my ignorance, but when I know what I'm doing wrong, this will go a long way toward my understanding of javascript and coding in general. I'm just playing in the browser console as of now.
I've done this with a for loop, but I wanted to try another option and use a decrement counter. I've tried using the if/else stuff from the inner function inside the while loop. The code looks right to me.
const guessingGame = (tries) => {
const answer = Math.floor(Math.random() * 11)
let guess = null
let status = "playing"
function makeGuess() {
if (guess === answer) {
status = "won"
} else if (tries === 0) {
status = "lost"
} else {
tries--
if (tries === 1) {
console.log(tries + ' guess left')
} else {
console.log(tries + ' guesses left')
}
}
}
while (status === "playing") {
if (!guess) {
guess = prompt('Guess a number between 1 and 10')
makeGuess()
} else if (guess > answer) {
guess = prompt('Lower')
makeGuess()
} else if (guess < answer) {
guess = prompt('Higher')
makeGuess()
} else {
break
}
}
console.log("Game Over. You " + status + "! The answer was " + answer + ".")
}
This game should invoke/launch with one argument, the number of tries allowed. If I correctly guess the answer, the console log at the end should include status = "won". But when I win, it includes status = "playing".
When I guess wrong "tries" number of times, I should lose. But when I see "0 guesses left" in the console, the game gives one more guess, and I can take it, effectively making tries -1, I think. When I make one additional wrong guess, status correctly changes to "lost" and the final console message is correct.
You checked tries === 0 before tries--, that's why you get 0 guesses left. You should decrement before checking.
The guess is actually a string not a number, so guess === answer never true. The next iteration after you guessed correctly, it falls into else{break} with the status still playing. You either want Number(guess) === answer or just guess == answer.
By Math.floor(Math.random() * 11) you are actually generating 0-10. You want Math.floor(Math.random() * 10) + 1 for 1-10. Just remember Math.floor(Math.random() * n) gives you n possible outcomes, which happens to be an integer in the range [0,n). Then do whatever calculation you want to map it to your desire output value.
const guessingGame = (tries) => {
const answer = Math.floor(Math.random() * 10) + 1
let guess = null
let status = "playing"
function makeGuess() {
tries--;
if (guess === answer) {
status = "won"
} else if (tries === 0) {
status = "lost"
} else {
if (tries === 1) {
console.log(tries + ' guess left')
} else {
console.log(tries + ' guesses left')
}
}
}
while (status === "playing") {
if (!guess) {
guess = Number(prompt('Guess a number between 1 and 10'))
makeGuess()
} else if (guess > answer) {
guess = Number(prompt('Lower'))
makeGuess()
} else if (guess < answer) {
guess = Number(prompt('Higher'))
makeGuess()
} else {
break
}
}
console.log("Game Over. You " + status + "! The answer was " + answer + ".")
}
guessingGame(5);
The result of prompt is a string; thus, guess is a string. The result of Math.floor is a number, so answer is a number.
> and < are coercing operators: if one of the operands is a number, the other is converted into the number, as well. This means guess < answer and guess > answer work as you hope it does.
However, you've apparently heard people say "never use ==, always use ===" and taken it to heart. The reason for the saying is == is also a coercing operator, and as a consequence sometimes things that don't look equal end up being equal. However, here you actually needed to use the coercing ==, because 1 == '1' (even though 1 and '1' are different types), but the strict 1 === '1' ends up being false!
Thus, you first check if guess is strictly equal to answer. Since their types are different, it is impossible, so you move on. You check if guess is above the answer, then you check whether it is below the answer, both of those return false as well. The only remaining option is to break from the loop - and "winner" never gets printed.
Beside this, your biggest problem is actually logic. The placement of different tests and actions is somewhat questionable. For example, one would expect that testing whether guess is equal to the answer would be right next to the test to see if it is bigger or smaller. The test for tries would be most at home right at the while loop; but you have an infinite loop, and an independent test for tries. You enter the first guess with a unique prompt, but it is inside an infinite loop, despite the fact it can only ever happen once. You have a function called makeGuess, but the function does two or three different things, none of which is actually making a guess.
Rather than start working on code right away, then fixing problems as they pop up, try to imagine first what the flow would be. How would a human do it? Then write code.
Here's the basic idea for the same game:
answer = imagineAnswer()
guess = askForFirstGuess()
status = "lost"
while (--tries) {
if (guess > answer) {
guess = askForHigherGuess()
} else if (guess < answer) {
guess = askForLowerGuess()
} else {
status = "won"
break
}
}
reportGameEnd(status)
I am currently new to JavaScript and am learning in school! There is an assignment that I am doing by creating a game but the alert keeps popping up with the wrong one. Every time it alerts as "You found a match!" for every card, however this is not supposed to happen. I have been trying to figure this out for the last hour. Thanks
var cards = ["queen", "king", "queen", "king"];
var cardsInPlay = [];
var cardOne = cards[0];
cardsInPlay.push(cardOne);
console.log("User flipped " + cardOne);
var cardTwo = cards[1];
cardsInPlay.push(cardTwo);
console.log("User flipped " + cardTwo);
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
alert("You found a match!");
} else {
alert("Sorry, try again");
}
You have a simple syntax error.
if (cardsInPlay.length === 2){
cardsInPlay[0] === cardsInPlay[1];
By putting your second conditional inside the bracket {, you've made it ineffective. Try this:
if (cardsInPly.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
The condition always goes inside the parenthesis ( ). If it's outside of it, it won't work.
Typing cardsInPlay[0] === cardsInPlay[1]; when they aren't equal is effectively like typing false;. It's technically valid, but doesn't do anything.
I think you ment to put the condition like below:
if (cardsInPlay.length === 2 && cardsInPlay[0] === cardsInPlay[1]) {
alert("You found a match!");
}
I'm a student creating a 3-guess game with JavaScript. My game doesn't work properly, I believe Math.random is generating a new number at every stage of the game. I would be most grateful if somebody helps me define a single number for the variable randomNumber.
Here's the JavaScript:
function game()
{
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt ("Guess what number I'm thinking of? (It's between 0 & 10)");
if (userGuess === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess2 = prompt ("Dohhh! You got it wrong. You have 2 more chances.");
}
if (userGuess2 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
var userGuess3 = prompt ("Dohhh! You got it wrong. You have 1 more chance.");
}
if (userGuess3 === randomNumber)
{
alert ("Good Guess, you must be psychic!");
}
else
{
alert ("Bad luck. The number was: " + randomNumber);
}
}
prompt returns a string. You are using the strict equality operator, ===, to compare strings with numbers. They will never be equal.
Use the abstract equality operator, ==, or convert the strings to numbers before comparing with the strict equality operator.
Also, your function should probably return after a correct guess, rather than prompting for more guesses.
Here's a suggestion for a cleaned-up version of your code:
function playGame(guesses)
{
// By default, give the player 3 guesses.
guesses = guesses || 3;
var randomNumber = Math.floor(Math.random()*11);
var userGuess = prompt("Guess what number I'm thinking of? (It's between 0 & 10)");
// Repeat the following logic whenever the user guesses incorrectly.
while (userGuess !== randomNumber.toString())
{
--guesses;
if (guesses === 0)
{
alert("Bad luck. The number was: " + randomNumber);
return false;
}
userGuess = prompt("Dohhh! You got it wrong. You have " + guesses + " more chance(s).");
}
alert("Good Guess, you must be psychic!");
return true;
}
Notice that it's now more flexible (you can give the user a configurable number of guesses) while also reducing code duplication: instead of repeating the same block of logic (with small differences), there is really just one bit of logic that can be repeated as many times as you like.
I have some JavaScript code that creates a different message depending on various factors in the response object from an Ajax request. For example
if (response.correct_guess === true){
message = "your guess was correct
}
If the user wins the game, the 'won' key is set to 'won'
won: "won"
and I'm therefore hoping to set the message like this
else if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
However, this 'else if' isn't getting triggered
I also tried "==" (i.e. two equal signs instead of three). Can you explain what I'm doing wrong?
What your code means:
if (response.correct_guess === true){
message = "your guess was correct
}else if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
}
If the guess is correct, message = "your guess was correct, and that's it. If the guess was not correct, AND if the user won, message = "You finished with" + response.seconds + "left on the clock."
You forget that if control enters the first if, it will never reach the second else if. In an if-elseif chain, the first if/elseif block control enters is the only one it will enter . I don't think you want that. You probably want:
if (response.correct_guess === true){
message = "your guess was correct
}
if(response.won === "won") {
message = "You finished with" + response.seconds + "left on the clock."
}