Adding more If statements for a simple javascript game - javascript

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

Related

Firebase Hosted JS Game Skipping Lines of Code

I made a little game with HTML/JS/CSS to learn more javascript that I have hosted as a firebase web app right now. I was playing it after deploying and watching the console in Google chrome and realized that my game is passing over big important sections of code. I can link to the game if anyone wants to see these "skips" in action. My two big problems are that the tile sometimes returns true for an enemy but does not trigger a fight and sometimes the game does not check if the player should be alive. This doesn't happen every time, just some of the time. I can also share anything else from the project that would be helpful. This is really the first time I've used JS outside of simple tags for a webpage so try not to judge it too harshly. Thanks in advance!
The pieces in question that are being skipped are:
//decide if a tile has an enemy
function hasEnemy(){
let roll = Math.random();
console.log(roll);
if(roll > .6666){
return true;
}else{
return false;
}
}
//there is one gameView.onXClick for each cardinal direction.
//button functions
gameView.onNorthClick = function(){
console.log("north");
oPos = thePlayer.pos;
if ((thePlayer.pos - 5) < 0){
null;
}else{
thePlayer.pos -= 5;
gameView.updateLoc(oPos, thePlayer.pos);
if(thePlayer.pos == 12){
gameView.updateNar("You are home");
gameView.homeMenu();
}else{
gameView.updateNar("You travel North");
console.log(hasEnemy());
if(hasEnemy()){
fightEnemy();
}else{
this.updateNar("Nothing around...");
}
}
}
}
and a very important piece of the game:
//player hits
gameView.onHitClick = function(){
console.log("You Hit");
thePlayer.hp = thePlayer.hp - curEnemy.atk;
curEnemy.hp = curEnemy.hp - thePlayer.atk;
gameView.updateFight(thePlayer.hp, thePlayer.atk, thePlayer.def, curEnemy.hp, curEnemy.atk, curEnemy.def);
this.updateNar("You hit for " + thePlayer.atk);
if(enemyLive(curEnemy.hp) == false){
this.updateNar("You beat the enemy");
thePlayer.kc += 1;
thePlayer.exp += curEnemy.expw;
thePlayer.gold += curEnemy.gold;
gameView.mapScene();
gameView.moveMenu();
gameView.updateLoc(oPos, thePlayer.pos);
}else if(playerLive(thePlayer.hp) == false) {
gameView.loseScene(thePlayer.kc, thePlayer.gold);
gameView.loseMenu();
}
}
//check if the player is alive
function playerLive(php){
if(php <= 0){
return false;
}else{
return true;
}
}

javascript alert and halting execution

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

Debugging an XP bar

I've been working awhile on making this code, but I can't seem to make it work like I want it to. I wanted a prompt to come up, ask for how long you've worked on a topic, then give the correct width on the progress bar.
Edit: widthGenerator creates the popup, but I can't seem to have the variable width in widthGenerator() transfer to Move() as Move's width.
Here is my code:
<body class="w3-container">
<div class="w3-progress-container w3-round-xlarge">
<div id="myBar" class="w3-progressbar w3-round-xlarge" style="width:1%"></div>
</div>
<button class="w3-btn" onclick="move()">Click Me</button>
<script>
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here");
if (isNaN(question) == false) {
var width = (question * 2.33463);
break;
} else if (isNaN(question) == true) {
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here");
break;
};
}
function move() {
var elem = document.getElementById("myBar");
var id = setInterval(frame, 1);
var width = widthGenerator()
function frame() {
if (width >= widthGenerator()) {
clearInterval(id);
} else {
width += 0.1;
elem.style.width = width + '%';
}
}
}
</script>
You need a return statement in your widthGenerator() function:
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here");
if (!isNaN(Number(question))) {
var width = (question * 2.33463);
} else {
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here");
}
return width;
}
I didn't want to tinker too much with your code but note that it is possible the user will never enter a number based on how widthGenerator() is written.
This code makes sure, that the user is asked for a valid number, till he gives it. It is also a bit cleaner. And I removed the break as it is not a valid syntax, if you are not inside of an switch.
You may want to remove the timeout in your code, as it will be proccesed after asking for width anyway. And clearing imeout from within of it win't do anything. Lastly I removed function frame, reason 1 beeing, that it was created for every call of move(), but secondly and mostly, it is unecesery as you can use an anonymous function for this type of job.
function widthGenerator() {
var question = prompt("Enter number of hours worked:", "Enter here")
while(isNaN(question)){
question = prompt("That is not a number; Enter the number of hours worked:", "Enter here")
// this will make it loop, till the user gives a valid number
}
return (question * 2.33463)
}
function move() {
var elem = document.getElementById("myBar")
var width = widthGenerator()
// You don't really need the timeout, since you can make the if anyway.
var id = setInterval(function(){
// this is anonymous function, it is used if you need to pass a callback to
if (width >= widthGenerator()) {
// Clearing this timeout won't do anything as you allready did cleared it by calling it
clearInterval(id)
} else {
width += 0.1
elem.style.width = width + '%'
}
}, 1)
}
Feel free to ask any questions.

Number Guessing Game Program Build with JavaScript

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

Javascript/JQuery guessing game

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.

Categories

Resources