Firebase Hosted JS Game Skipping Lines of Code - javascript

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

Related

Adding more If statements for a simple javascript game

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

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 style type

I would like to implement it in a way where when the user has visited my page for the first time.
They will have a pop up appearing like a forum message " Hi , you've just visited our forum "
So when the second time the same user visit , the pop up will disappear .
Here's my code I'm working on :
var beenherecookie = 'FE44been644';
var beenherebegin = document.cookie.indexOf(beenherecookie);
if (beenherebegin > -1){
//Want to implement the code of when user enter first time , "style="display:none;"
else{
function setTimeout("style="display:block;", 60000 * 10); ; //set to 1000 X number of desired delay seconds. So 2 minutes (120 seconds) is 120 X 1000 =
120000
WriteCookie("FE44been644","yes");}
Here's my HTML code for the style::
style="javascript:meh(the function of the style which changes)"
So here's the situation :
When the user visit the website for the first time,
The javascript function meh would be style="display:none"
If the user has entered the website previously
The javascript function meh would be style="display:block"
I need some favors thanks in advance
There are several ways you can implement the scenario..
declare your meh function
var meh = function(){}
if (beenherebegin > -1){
meh = function(){
document.getElementById('popupID').style.display='none';
}
}
else{
meh = function(){
document.getElementById('popupID').style.display='block';
}
}
EDIT
var isFirstTime = false;
var popupHandler = function(firstTime){
if(firstTime){
return "block";
}
else{
return "none";
}
}
if (beenherebegin > -1){
isFirstTime = false;
}
else{
isFirstTime = true;
}
document.getElementById('popupID').style.display= popupHandler(isFirstTime);
Hello,
Once you use the cookie profiling to identify if the user has visited before. You can use document.getElementById.show() and document.getElementById.hide() methods to achieve what you are trying to do. There would be a div element enclosing the popup code, so you can use that. Please tell me if this helps or not. Additionally you can also use jquery methods for show/hide.
Thank You

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.

Javascript loop to update image is returning broken image

I am new to javascript and am trying to create this loop to simulate some dice rolls. When I click roll none of the images are refreshed and it ends with the broken image shown. Can anyone see where my error is?
function roll(){
for(x=0;x<10;x++){
var die_num1 = Math.ceil(Math.random()*6);
for(y=0;y<20;y++){
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
}
}
body:
<input type ="button" value = "Roll" onclick="roll()" >
<img name="dice" id="dice" src="http://localhost/CodeIgniter_2.1.2/dice/die-1.gif" >
I used adocument.write to make sure that at least the final image existed in my folder and it does. I would expect to see the images cycling through as the loop progresses though. Again, I have no experience with javascript and have put this together based on how I thought it should look. Any help will be appreciated.enter code here
I wouldn't expect browser as an event-driven environment even to consider updating the screen before you return from you roll(). You need to get acquainted with setTimeout and handle it as a sequence of timer events.
Thanks for setting me in the right direction. I have reworked this to use setTimeout as Michael suggested and it is working great. Only needed 1/10 of a second per iteration, not much but made all the difference.
function roll2(){
var timer = setTimeout ("roll2();", 100);
i++;
if(i >= 15) clearTimeout(timer);
var die_num1 = Math.ceil(Math.random()*6);
var picturetype1 = Math.ceil(Math.random()*3);
if (picturetype1 == 1){prefix1 = "die-";}
if (picturetype1 == 2){prefix1 = "dicet-";}
if (picturetype1 == 3){prefix1 = "dices-";}
if (i <=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/' + prefix1 + die_num1 + '.gif';
}
if (i >=15) {
document.getElementById("dice").src='http://localhost/CodeIgniter_2.1.2/dice/die-' + die_num1 + '.gif';
i=0;
}
}

Categories

Resources