I'm practicing my javascript coding by writing a color guessing game where there is a set array of colors and one will randomly be selected as the target color. The user will then be prompted to select a color. The selection goes through some criteria and if correct the background color of the page changes to match the correct color. Those are the basics of the game. I can't even get the alerts of the code to run. I have no idea of the problem. Thank you.
Here's the code I have.
<!doctype html>
<html>
<body onload="do_game()">
<script>
alert("ok");
var colors = ["coral", "olive", "khaki", "lime", "red", "maroon", "yellow", "green", "orchid"];
var alpha_colors = colors.sort();
return alpha_colors;
var finished = false;
var guesses = 0;
function do_game(){
alert("ok so far");
var num_colors = colors.length-1;
var target = colors[math.floor.random()*num_colors]
do{
var color_guess=prompt("I am thinking of these colors \n\n"+alpha_colors+"What color am I thinking of?");
guesses += 1;
finished=checkguess();
} while(finished=false);
}
function checkguess(){
if(colors.indexOf(color_guess)=-1) {
alert("Sorry. I don't recognize your color. \n\n Please try again. ");
return false;
}
if(color_guess<target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically lower than mine");
return false;
}
if(color_guess>target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically higher than mine");
return false;
}
alert("Congratulations! You have guessed the color! \n\n It took you "+guesses+"guesses to finish the game! \n\n You can see the color in the background");
return true;
}
style.background-color=target
</script>
</body>
</html>
You made some beginner mistakes.
After you use "return" you end everything in the current scope. So
when you return alpha_colors at line 4 your code after that line
will never run.
Thats not how you compare strings alphabetically.
math.floor.random() is not how you make a random number. Next time
try Math.floor(Math.random()*maxNumber);
When you compare two things use == or ===. Never "="! "=" in programming is different than "=" in Math. Use "=" when you want to set value to a variable and use "==" when you want to compare two things.
alert("ok");
var colors = ["black",
"green",
"yellow"
];
var alpha_colors = colors.sort();
var finished = false;
var guesses = 0;
var target = colors[Math.floor(Math.random() * alpha_colors.length)];
function do_game() {
alert("ok so far");
var color_guess = prompt("I am thinking of these colors \n\n" + alpha_colors + "What color am I thinking of?");
guesses += 1;
checkguess(color_guess);
}
function checkguess(color_guess) {
if (color_guess == "stop") {
return false;
}
if (colors.indexOf(color_guess) == -1) {
alert("Sorry. I don't recognize your color. \n\n Please try again");
do_game();
}
if (color_guess < target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically lower than mine");
do_game();
}
if (color_guess > target) {
alert("Sorry, your guess is not correct. \n\n Hint: your color is alphabetically higher than mine");
do_game();
}
if (colors.indexOf(color_guess) >= 0) {
alert("Congratulations! You have guessed the color! \n\n It took you " + guesses + "guesses to finish the game! \n\n You can see the color in the background");
}
document.body.style.backgroundColor = target;
}
<!doctype html>
<html>
<head>
</head>
<body onload="do_game()">
<script src="script.js"></script>
</body>
</html>
Line 4 of your script tag has a return statement:
return alpha_colors;
Return statements can only be inside of functions. Also, you are referencing the function "do_game" before you have actually defined it.
Related
Here we have a simple practice javascript game , it has a list of valid HTML colors, it picks a random color when the page is loaded , it asks you for guesses and gives you hints based on your input, when you enter the correct color , it changes the background color to the color of the answer.
when you enter the winning answer , you get an alert to tell you that you've won, for some reason the background color only changes after i press ok when the alert appears on the screen, even though the statement that changes the bg color precedes the alert.
My questions are:
(1) why is the BG color changing after i close the alert popup ?
(2)whats the correct way to make the BG color change before the alert appears on the screen?
function do_game() {
var colors = ["aqua", "beige", "deeppink" , "coral", "honeydew", "lime", "gainsboro","rebeccapurple","peru","tan"].sort();
var answer = colors[Math.floor((Math.random() * colors.length))];
var finished = 0;
var numberOfGuesses = 0;
var myBody=document.getElementsByTagName("body")[0];
console.log(answer);
while(!finished){
var input = prompt('I am thinking of one of these colors \n\n' + colors + '\n\n what color am i thinking of? ' );
if(input === null)
finished = 1;
else{
numberOfGuesses++;
checkGuess(input);
if(input === answer){
myBody.style.background=answer;
finished = 1;
alert('You are right! \n you took ' + numberOfGuesses + ' Guesses!');
}
}
}
function checkGuess(input){
if(colors.indexOf(input) === -1){
//does not recognize input
alert('I don’t recognize that color!');
}else if(input > answer){
//alphabetically higher
alert('Your input is alphabetically higher than mine!');
}else if(input < answer){
//alphabatially lower
alert('Your input is alphabetically lower than mine!');
}
}
}
The browser won't repaint the screen until the function which has updated the DOM has finished running.
alert is blocking, so prevents that function from continuing to run until you click OK.
Put the alert in another function and use setTimeout to call it in a non-blocking way.
document.body.style.background = "blue";
setTimeout(function() {
alert("Hello");
});
I'm a newbie teaching myself how to code using a course through udemy.com. I'm in the process of learning Javascript and as a project we're instructed to created a simple Javascript game. Basically you enter a number that you think the computer is thinking. So far when you enter the correct number and click submit, a box will appear that states "Yay! That's exactly how many fingers I'm holding up!" or if it is not correct it will state "Sorry that's not correct, my number was .."
The problem is I can't figure out how to add additional if statements. For example I'm trying to alert a message that states "oops you need to enter a number" when the user clicks the submit button without entering a number or letter in the box. And when they've guessed the correct number of 0, the alert message will state "That's right, I have no fingers up!"
Here is the code that allows me to do the two instructions I listed above correctly:
<p>How many fingers am I holding up?</p>
<input id="answer"/>
<button id="myButton"><strong>Submit</strong></button>
<script type="text/javascript">
document.getElementById("myButton").onclick=function() {
var x=Math.random();
x=6*x;
x=Math.floor(x); //use floor to get whole number
if (x==document.getElementById("answer").value) {
alert("Yay! That's exactly how many fingers I'm holding up!");
} else {
alert("Sorry that's not correct! My number was" + x );
}
}
</script>
What am I doing wrong here?
Thanks in advance!
Here's a revised script, the problem was with the .value property. Please work on your indentation.
Follow this link for full code JS fiddle
document.getElementById("myButton").onclick = function() {
var x = Math.random();
var y = document.getElementById("answer");
x = 6 * x;
x = Math.floor(x); //use floor to get whole number
if (y.value === "") {
alert("Oops, you need to enter a number!");
} else if (x == y.value) {
if (x == 0) {
alert("That's right, I have no fingers up!");
} else {
alert("Yay! That's exactly how many fingers I'm holding up!");
}
} else {
alert("Sorry that's not correct! My number was " + x);
}
}
var x = Math.random();
x = 6*x;
x = Math.floor(x); //use floor to get whole number
var y = document.getElementById("answer").value;
if(y == null){
alert("Please enter a number");
}else{
if (x == y) {
if(x == 0){
alert("Yay! I'm not holding any fingers up!");
}else{
alert("Yay! That's exactly how many fingers I'm holding up!");
}
} else {
alert("Sorry that's not correct! My number was" + x );
}
}
I'm trying to build a guessing game, where the computer automatically generates a number between 1-100 and the user has 5 chances to guess the number. Between guesses I want to clear the input field. There is a hint button that can tell the user "lower" or "higher" and there is a div that shows how many guesses are remaining. There is also a play again button.
I've built the html, css and some of the JS but I'm getting stuck with a for loop.
The JS/HTML is:
<input type="text" id="playersGuess" placeholder="Input Number 1-100" class="form-control input" >
<h3 id="status"></h3>
<button onclick='playersGuessSubmission()' type="button" id="playersGuess"class="btn btn-lg btn-info submit">Submit Your Guess</button>
var playersGuess,
winningNumber
// Generate the Winning Number
function generateWinningNumber(){
winningNumber = Math.floor(Math.random() * 100);
console.log(winningNumber);
}
generateWinningNumber();
// Fetch the Players Guess
function playersGuessSubmission(){
playersGuess = parseInt($('#playersGuess').val());
console.log(playersGuess);
lowerOrHigher();
}
// Determine if the next guess should be a lower or higher number
function lowerOrHigher(){
var guessesRemaining=5;
for(i=guessesRemaining; i>0; i-- ) {
if (playersGuess > winningNumber){
console.log('lower');
guessesRemaining -= 1;
// $('remaining span').html(guessesRemaining);
console.log(guessesRemaining);
// return;
// playersGuessSubmission()
} else if (playersGuess < winningNumber) {
console.log('higher');
guessesRemaining -= 1;
// $('remaining span').html(guessesRemaining);
console.log(guessesRemaining);
// return;
// playersGuessSubmission()
} else {
console.log('you win')
return;
}
}
}
Currently, the computer generates a random number, the user is able to guess, and then the user runs through the loop console.logging out remaining guesses down to 0 without allowing the user to input any other guesses. Adding the return line in each 'if' statement ends the loop and the remaining guesses never decreases and the user is able to input infinitely until they guess correctly. Adding the playersGuessSubmission() function to each 'if' statement results in an infinite loop.
I'm new to learning JS (and doing it on my own) so any guidance is truly appreciated! Thanks in advance.
See JSFiddle here: http://jsfiddle.net/njpatten/qo1d63da/1/ Feel free to change console.log to alerts or replace div text.
Instead of using a for loop I would recommend to use a global variable to keep track of remaining guesses and decrement it by 1 each time the user takes a guess and the remainingGuesses > 0.
Your way does not wait for user input but rather checks the same value 5 times in a row. Something like this should work:
var guessesRemaining = 5;
function lowerOrHigher(){
if (guessesRemaining > 0){
guessesRemaining--;
if (playersGuess > winningNumber){
console.log('lower');
// $('remaining span').html(guessesRemaining);
console.log(guessesRemaining);
} else if (playersGuess < winningNumber) {
console.log('higher');
// $('remaining span').html(guessesRemaining);
console.log(guessesRemaining);
} else {
console.log('you win')
return;
}
}
else {
console.log('You ran out of guesses');
}
}
Not exactly sure if this would solve your problem, but going through the issues one at a time:
1:
I think the player runs out of guesses, because you loop for the number of guess decreasing the number of guesses each time, so the loop continues until the guesses are zero basically.
2:
If you add the return statement, the user's guesses never goes down because each time the button is pressed you call the lowerOrHigher() function again and you are setting guesses equal to five in the function
3:
For this exact same reason you get an infinite loop for calling the playerGuessSubmission() function, because the playerGuessSubmission() function calls lowerOrHigher() which in turn sets user guesses to five, allowing the loop to run again, calling playerGuessSubmission again, etc, etc
What I would do, is create an onload function with your jquery setting the initial number of guesses to five when the page loads:
$( document ).ready(function() {
guessesRemaining = 5;
});
And then only reset guessesRemaining = 5 when you call the PlayAgain() function as indicated in your JSFiddle, which I assume will be an "onclick" of the Play Again button:
function playAgain(){
guessesRemaining = 5;
}
From there I would remove the for loop completely, so that the lowerOrHigher() is called on button click only, and decides each time the button is clicked whether or not he guessesRemaining -= 1, or to console.log("You Won").
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
</head>
<body>
<input type="text" id="playersGuess" placeholder="Input Number 1-100" class="form-control input" >
<h3 id="status"></h3>
<button onclick='playersGuessSubmission()' type="button" id="playersGuess"class="btn btn-lg btn-info submit">Submit Your Guess</button>
<script>
var playersGuess,
winningNumber
// Fetch the Players Guess
function playersGuessSubmission(){
winningNumber = Math.floor(Math.random() * 100);
console.log(winningNumber +"winning");
playersGuess = parseInt($('#playersGuess').val());
console.log(playersGuess+ "guess");
if(playersGuess <winningNumber)
{
console.log("guess higher");
}
else if(playersGuess >winningNumber)
{
console.log("guess lower");
}
else
{
console.log("correct");
}
$('#playersGuess').val('');
}
// Determine if the next guess should be a lower or higher number
function lowerOrHigher(){
}</script>
</body>
</html>
Here is my suggestion
I changed the IDs of the buttons, they must be different and not the same as other variable names
DEMO
/* **** Global Variables **** */
// try to elminate these global variables in your project, these are here just to start.
var playersGuess, winningNumber, guessesRemaining;
/* **** Guessing Game Functions **** */
// Generate the Winning Number
function generateWinningNumber() {
winningNumber = Math.floor(Math.random() * 100);
guessesRemaining=5;
console.log(winningNumber);
$('#remaining').html(guessesRemaining+" left");
}
// Fetch the Players Guess
function playersGuessSubmission() {
playersGuess = parseInt($('#playersGuess').val(),10);
console.log(playersGuess);
lowerOrHigher();
}
// Determine if the next guess should be a lower or higher number
function lowerOrHigher() {
guessesRemaining--;
if (guessesRemaining<=0) {
$('#remaining').html("You lose");
return;
}
if (playersGuess > winningNumber) {
console.log('lower');
console.log(guessesRemaining);
$('#remaining').html("too high "+guessesRemaining+" left");
} else if (playersGuess < winningNumber) {
console.log('higher');
$('#remaining').html("too low "+guessesRemaining+" left");
} else if (playersGuess == winningNumber) {
$('#remaining').html("you win "+guessesRemaining+" left");
guessesRemaining=0;
}
else {
$('#remaining').html(playersGuess + " is not valid, "+guessesRemaining+" left");
}
}
//continues to console.log false, een when the winning number is set to 24
// Check if the Player's Guess is the winning number
function checkGuess() {
// add code here
}
// Create a provide hint button that provides additional clues to the "Player"
function provideHint() {
// add code here
}
// Allow the "Player" to Play Again
function playAgain() {
// add code here
generateWinningNumber();
}
/* **** Event Listeners/Handlers **** */
$(function() {
generateWinningNumber();
$("#playersGuessBut").on("click",function(e) {
e.preventDefault();
playersGuessSubmission();
});
$("#playAgain").on("click",playAgain);
});
I'm new to learning JS (and doing it on my own) so any guidance is truly appreciated!
I suggest you to learn javascript using something like :
Codeschool they have good javascript learning path for newcomers and basic courses are free.
or Coursera
According this
Adding the return line in each 'if' statement ends the loop and the remaining guesses never decreases and the user is able to input infinitely until they guess correctly
You define number of guesses in beggining of function. So every time you enter in it will be asigned with initial value (5).
I get an error in the console when i try to run this code but i don't know why! It says this:
Uncaught ReferenceError: Invalid left-hand side in assignment and it point to line 31
That is, the line : if (colors.indexOf(String(guess_input))=-1){
Basically what I am trying to do is check if an inputted string is part of my predefined array that you can see in the code below. The end point is a guessing game where the user has to guess a color.
<!DOCTYPE >
<html>
<head>
<title>Welcome To The JS Guessing Game</title>
</head>
<body onload="do_game()">
<script>
//Initialize the variables that will be needed.
var target;
var target_index;
var guess_input;
var guesses=0;
var finished=false;
var guesses=0;
var colors = ["blue", "cyan", "gold", "green", "magenta", "orange", "red", "white", "yellow"];
function do_game(){
var random_number = (Math.random()*colors.length);
var random_number=Math.floor(random_number);
target=colors[random_number];
alert(target);
while (!finished){
guess_input=prompt("I am thinking of a color in the list below. Can you guess which color?"+"\n\n"+ colors.join() );
guesses++;
finished = check_guess(); //so finished in the function has to return true for this condition to be met.
}
}
function check_guess(){
if (colors.indexOf(String(guess_input))=-1){
alert("I'm sorry, I do not recognize that color! Try again.");
return true;
}
else if (guess_input > target){
alert("Your guess is alphabetically higher than the correct answer.");
return true;
}
else if (guess_input < target){
alert("Your guess is alphabetically lower than the correct answer. ");
return true;
}
else {
myBody=document.getElementsByTagName("body")[0];
myBody.style.background=target;
alert("You are right! You took "+guesses+" guesses!");
return false;
}
}
</script>
</body>
</html>
The result is the first alert window shows up telling me the color, then the prompt, but then after that, and regardless of input, the thing just stops :(
Help would be appreciated.
Cheers,
David
Change
if (colors.indexOf(String(guess_input))=-1){
to
f (colors.indexOf(String(guess_input))==-1){
Your script basically tries to assign the value -1 to something that is not a variable.
Here's a JSfiddle of a guessing game I'm making: http://jsfiddle.net/JMqxq/13/
So far everything is working great, but the part that displays the remaining guesses isn't working the way I want it to. It starts out at 3 and goes down by one each time you have an incorrect guess, which is what I want, but once you run out of guesses I want you to revert back to level one and have the remaining guesses go back to 3 since you are starting over. It successfully starts the game over, but the display of the count gets stuck at 0 (even though it's actually back to 3). I also want the displayed guesses remaining to go back up to 3 after you get a correct guess (while moving up a level), but it doesn't. Can anyone help me fix this? Here is the actual code in question:
HTML:
<p id="result">Guess a color.</p>
<p>Remaining guesses: <span id="guesses">3</span></p>
<h2>Level <span id="level">1</span></h2>
Javascript/JQuery:
function correct(){
document.getElementById("result").innerHTML = "You are correct! Guess another color.";
level++;
reset();
}
function incorrect(){
document.getElementById("result").innerHTML = "Sorry, you are incorrect.";
guesses--;
document.getElementById("guesses").innerHTML = guesses;
if (guesses == 0){
level = 1;
reset();
document.getElementById("result").innerHTML = "Guess a color";
}
}
function reset(){
$(".box").animate({"opacity": "1"}, "slow");
guesses = 3;
temp = Math.floor((Math.random()*6)+1);
document.getElementById("level").innerHTML = level;
}
function rand(){
temp = Math.floor((Math.random()*6)+1);
$("div.box").click(function() {
if (temp == $(this).data("id")) {
correct();
} else {
$(this).animate({"opacity": "0.25"}, "slow");
incorrect();
}
});
}
You need to add
document.getElementById("guesses").innerHTML = guesses;
into your reset function.