I've making a game where you should sell your product.
But for some reason my function to substract that amount from the produced product, is not working, i can for some reason produce unlimited money. I've tried to check in the console what the value is after substrackting, but it is unchanged.
var x = document.getElementById.bind(document);
x('sell').onclick = function() {
if (dipped_cookie < 1) {
return false;
} else {
dipped_cookie -= sell;
console.log(dipped_cookie);
bank += sell;
}
Hope you can help. Thanks in advance
If dipped_cookie, sell and bank aren't global variables, they are not defined. And when you try to add some javascript variable which is not defined, the value become NaN
Related
I am making a simple reaction time game for a final project.
We are using javascript to power the functions in the game, most of my code is in working order, but I have an if conditional statement that's giving me trouble.
Here's the code
function fireTime() {
setTimeout(ShotsFired, time);
function ShotsFired() {
fire.style.visibility = "visible";
createdTime = Date.now();
console.log(createdTime);
EnemyTime = Math.floor((Math.random() * 1000) + 400);
setTimeout(EnemyShoot, EnemyTime)
function EnemyShoot() {
console.log(EnemyTime);
gameplay();
}
function gameplay() {
reactionTime = -(createdTime - clickedTime);
var EnemyTime;
console.log(reactionTime);
if (reactionTime < EnemyTime) {
alert("Wow you beat him! Congrats!");
fire.style.visibility = "hidden";
clickedTime = 0;
createdTime = 0;
reactionTime = 0;
scavnumber++;
BGnumber++;
DesertBG.src = "images/Desert" + BGnumber + ".png";
scav.src = "images/scav" + scavnumber + ".png";
fireTime();
} else {
EndScreen.style.visibility = "visible";
}
}
This is not the entire code, just the function that should progress the game to the next level.
For whatever reason, even though reactionTime is less than EnemyTime, the EndScreen becomes visible.
Anyone know what could cause this?
Use floating point for your enemy time maths, i.e. 400.0 , else you are getting 0/1 seconds and not using milliseconds, and it is useing Math integer. Specifically cast your enemyTime as a float number, for the moment, if you print it it's probably an integer. its a MAJOR js coding detail that you will cost you hours of bughunting in the future if you think that 101/50 = 2.05, it isn't it equals 2, so divide by 50.0 and same with all second/ms tasks.
Use EnemyTime as a global variable for all scripts, at the moment, the code things you have a different function called EnemyTime in all scripts, the latter one has no value.
Use print to see when your else conditions work, specify a print in both an print the enemyTime value.
That's how you are supposed to resolve the issue, by printing the variables that are confusing.
EDIT I originally posted this with my version of the J.S but it's so far off no one can even help so i'm starting over. Here is the pseudocode i have done that needs to be translated into a Javascript program. Any help is appreciated!
I am a beginning programmer i understand this code will have multiple errors, that's why i am here. Array's and loops have given me much trouble while trying to learn them and especially with formatting them in JavaScript. The things i know are incorrect or still need i commented out i still need them, i also know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated.
Module main()
//Declare local variables
Declare endProgram = “no”
While endProgram == “no”
Declare Real notGreenCost[12]
Declare Real goneGreenCost[12]
Declare Real savings[12]
Declare String months[12] = “January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”
//function calls
getNotGreen(notGreenCost, months)
getGoneGreen(goneGreenCost, months)
energySaved(notGreenCost, goneGreenCosts, savings)
displayInfo(notGreenCost, goneGreenCosts, savings, months)
Display “Do you want to end the program? Yes or no”
Input endProgram
End While
End Module
Module getNotGreen(Real notGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module getGoneGreen(Real goneGreenCost[], String months[])
Set counter = 0
While counter < 12
Display “Enter GONE GREEN energy costs for”, months[counter]
Input goneGreenCosts[counter]
Set counter = counter + 1
End While
End Module
Module energySaved(Real notGreenCost[], Real goneGreenCost[], Real savings[])
Set counter = 0
While counter < 12
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo(Real notGreenCost[], Real goneGreenCost[], Real savings[], String months[])
Set counter = 0
While counter < 12
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
A few notes:
Currently the program creates a few variables and functions that
don't seem to interact
Most of the edits below are not optimal - there are parts that
could be done by much simpler means (i.e. counter++) - But thats
for you to learn =P
I made quite a few assumptions of what you wanted the program to
do, they might be wrong, they might be right
var notGreenCost = []; //Array lengths don't need to be specified
var goneGreenCost = [];
var savings = [];
var months = ["January", "Feburary", "March", "April", "May", "June"];
//A boolean value (true | false) would suit this better as opposed to "yes"/ "no"
var endProgram = false;
var option = 0;
/* You dont need main functions in javascript
* migrated everything to be global :/
* Delete:
function main(){
// Move this (made it global): var endProgram = "no";
}
*/
// I don't think this is meant to be initMonths..
// Maybe something like getOptions?
function /*initMonths*/getOptions(){
while (endProgram == false){ //lowercase while
//Because prompt would block everything else until it gets input
//we probably want to move the prompt to be after the alerts
alert("options:"); //Clarity
alert("1 to enter data");
alert("2 to display data");
alert("3 to write data to a file");
alert("4 to read data from a file");
//Alter global "option" to take the value of the prompt
option = prompt("What would you like to do? Type:");
//} //I assume you want the rest of the code in this while loop - otherwise it will loop forever
// Delete this bracket (its unmatched): {
// Delete return statement as it will stop the function return option;
// Delete this bracket (its unmatched): }
//Create a variable to take the value of prompt (this should be outside the while loop) but it seem clearer for explanation purposes to be here
var toEnd;
toEnd = prompt("Do you want to end the program (enter yes or no)");
// Javascript uses != for "not equal to" and && for "AND"
while (toEnd != "no" && toEnd != "yes") {
toEnd = prompt("Please enter a value of yes or no");
}
//I think you want to assign the value of toEnd to endProgram
// Note the the below is not the only/best way to do it
if(toEnd == "no") {
endProgram = false;
} else if(toEnd == "yes") {
endProgram = true;
}
// While use brackets not End s
// End While
// End While
}//End while loop here
}
Javascript in a browser cannot alter files - writeToFile, readFromFile have all been removed
I believe you want months to be global, if it is then initMonths is unnecessary
getNotGreen:
function getNotGreen(){
//You don't need to specify types in Javascript
/*Integer*/ var counter = 0
while (counter < 6){ //lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
notGreenCost.push(prompt("Enter NOT GREEN energy costs for" + months[counter]))
//Returning here makes the rest of the function redundant
//}
//return notGreenCost[counter];
//}
//Javascript does not use Set
// Note that below is not the only/best way to do it
/*Set*/ counter = counter + 1
} //End the while loop here
}
getGoneGreen:
function getGoneGreen(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
//I'm assuming you want to combine the values of "Enter NOT GREEN energy costs for" and months[counter] - This is done by using the + sign
//Im also assuming you want to read the value into notGreenCost
//.push adds a value to a array
goneGreenCost.push(prompt("Enter GONE GREEN energy costs for" + months[counter]));
//See above (getNotGreen)
//}
//return goneGreenCost[counter];
/*Set*/ counter = counter + 1;
}//End while loop here
}
energySaved:
function energySaved(){
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
savings[counter] = notGreenCost[counter] - goneGreenCost[counter]
counter = counter + 1;
}
} //I assume you want to end energySaved here?
displayInfo:
function displayInfo(){
//Alert produced individual boxes, i assume you want the following in a single window?
// "\n" is a line break
alert("SAVINGS NOT GREEN GONE GREEN MONTH\n"+
"_________________________________________________\n");
//Counter should probably be local (not global) - use var
var counter = 0;
while (counter < 6){//lowercase while
alert( "$" + savings[counter] + "$" + notGreenCost[counter] + "$" + goneGreenCost[counter] + "" + months[counter]);
counter = counter + 1;
}
} //I assume you want to end displayInfo here?
so i was programming a javascript program, and for some reason, i got an error saying: ReferenceError: treasureHunter not defined
I searched all over the internet for this info, but although this has been answered many times, their answers don't fit specifically to the problem in the code.
Here's the code:
// Sets a global variable for loot. Global variables exist outside functions or conditional statements. Local variables exist within those things.
global loot = 0;
// alert(loot);
// Creates a function called treasureHunter(). We don't put anything in the parenthesis, but we will later for other functions.
function treasureHunter() {
//Creates a local variable inside treasureHunter called treasureSuccess equal to Math.random(). Math.random is bult into JavaScript, and creates a random number between 0 and 1, e.g. .456 or .99. We use this to create excitement in an otherwise dull and boring existence.
var treasureSuccess = Math.random();
//Here we create a local variable called closedChest equal to the image that we want to pull down from the interwebs when we fail at getting loot.
var closedChest = "<img src='https://s-media-cache-ak0.pinimg.com/736x/eb/c7/84/ebc784ae55857b1470767c4747eb0715.jpg' length='285px' width='285px'>";
//Here we create a local variable called openChest equal to the image that we want to call up when we succeed - YES!
var openChest = "<img src='https://slm-assets1.secondlife.com/assets/1545906/lightbox/e6cfd0355756301c0f6f6d666e75c3de.jpg?1277247329' length='285px' width='285px'>";
var dragon = "<img src='http://orig06.deviantart.net/dd94/f/2012/112/c/b/cb9da88db9660edea4746e95df8fa4ed-d4x7orn.jpg' length='285px' width='285px'>";
//Here we create a conditional statement that asks if the variable treasureSuccess is greater than 5. This is called a boolean operation, it can be answered yes or no. This will of course be random, since treasureSuccess is equal to Math.random() - see above.
if (treasureSuccess > .5) {
//Here we tell the conditional statement what to do if it evaluates true, in other words, if Math.random() happens to be greater than .5. This will change the element using treasureChest, our DIV above in our HTML to the openChest variable, which is set to the image of an open chest. Go figure :)
if (treasureSuccess > .9) {
//dragon time!!
document.getElementById("TreasureChest").innerHTML = dragon;
//dragon image
loot = 0;
//loot reset
document.getElementById("Loot").innerHTML = "You lost all your gold!";
}
}
else {
document.getElementById("TreasureChest").innerHTML = openChest;
//This adds 100 to the global variable loot, each time we are successful, or each time treasureSuccess is greater than .5
loot = loot + 100;
//This tells the loot ID selector to update, so we can see how much gold we've got. THis uses the updated value for loot, which is why it is written below the loot = loot +100 line.
document.getElementById("Loot").innerHTML = "You've got" + " " + loot + " " + " gold";
//waits 500 milliseconds
setTimeout(treasureHunter,500);
document.getElementById("TreasureChest").innerHTML = closedChest;
//reputs the picture
}
//this is the end of the conditional statement
//This tells the statement what to do if the conditional statement evaluates to false, or if treasureSuccess is less than .5. You get a chest slammed shut in your face son.
else document.getElementById("TreasureChest").innerHTML = closedChest;
}
//this is the end of the function
I call it like this:
<div onclick="treasureHunter()" align="center" id="TreasureChest">
<img src="https://s-media-cache-ak0.pinimg.com/736x/eb/c7/84/ebc784ae55857b1470767c4747eb0715.jpg" length="285px" width="285px">
Any help is appreciated!
There are some syntax errors, so treasureHunter() wasn't defined.
global in global loot = 0; doesn't seem valid. Change it to var or something.
else in else document.getElementById("TreasureChest").innerHTML = closedChest; is invalid since there are no corresponding if. Remove it or fix the code properly.
Hello everyone and thanks for any help in advance,
I have some functions already in place, first one adds 1% of the total money amount once every second. the second is onclick there is $100 added to the total original amount. The third is to minus $200 plus 10% of the 200 from the total amount, so every time it is clicked the minus amount goes up.
These functions are working on my local machine but I am unable to get them to work in a JSFIDDLE.
I want to disable the minus button once the total amount is less than the minus amount, and also enable it again once there is enough money in the total amount to use.
Here is my JS so far
setInterval(function () {
var moneyTotal = document.getElementById('money-total').innerHTML;
var perSec = (1 / 100) * moneyTotal;
var moneyNewTotal = (+moneyTotal) + (+perSec);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
document.getElementById('per-second').innerHTML = (perSec.toFixed(2));
}, 1000);
function add() {
var addAmount = 100;
var moneyTotal = document.getElementById('money-total').innerHTML;
var addTotal = (+addAmount) + (+moneyTotal);
document.getElementById('money-total').innerHTML = (addTotal.toFixed(2));
}
function minus() {
var cost = document.getElementById('cost').innerHTML;
var money = document.getElementById('money-total').innerHTML;
if (money > cost) {
var moneyNewTotal = (+money) - (+cost);
var newCost = (10 / 100) * cost;
var costTotal = (+newCost) + (+cost);
document.getElementById('cost').innerHTML = Math.ceil(costTotal);
document.getElementById('money-total').innerHTML = (moneyNewTotal.toFixed(2));
} else {
alert("Not enough money");
}
}
Any help would be greatly appreciated!
First, the Fiddle isn't working because you have it set to load your javascript onLoad which is wrapping your functions in a different scope and so they aren't available on the window. Changing it to load the javascript No wrap - in <head> (or <body>) will help it work.
Then you need to have something that is checking for the value and enabling disabling the minus button.
function checkTotal() {
var moneyTotal = +document.getElementById('money-total').innerHTML;
var cost = +document.getElementById('cost').innerHTML;
if (cost > moneyTotal) {
document.getElementById('minus').setAttribute('disabled', 'disabled');
} else {
document.getElementById('minus').removeAttribute('disabled');
}
}
Then you would need to call this at the end of the add, minus, and even the function you have defined in setInterval so that as money gets added it checks. This code only adds the disabled attribute to the button, so any styling would need to be handled either by the code or through CSS and setting/removing class names or something similar.
There are perhaps different ways to do this through data binding or using an event model as part of a framework, but those are a more substantial topic that can't really be covered in this answer.
Working on an assignment for my Intro Programming class, I created a function and got everything working with a little help from some guys on here (thanks a ton btw) and now I have a new issue. I have two variables that I declare and prompted for a value before starting my function and causing it to prompt for a new value if it doesn't pass. But now when I return them it doesn't change the variable outside of the code.
// 1 Declare Variables
var numTrees;
var counter = 0;
var answer = "no";
function treeFunction(answer, counter, numTrees) {
while (answer == "no" && counter < 3)
{
if (numTrees < 5 || numTrees > 10)
{
alert("That is an incorrect value.\nThe sample size should be less than 5 or greater than 10.\nPlease try again.");
answer = "no";
numTrees = prompt("Please reenter the amount of trees in your sample.");
alert("You have entered: " + numTrees)
counter + 1;
}
else
{
answer = "yes";
}
}
if (answer == "no") {
alert("You have entered an incorrect number too many times.\nThe Program will now end.");
window.open('', '_self', '');
window.close();
} else if (answer == "yes") {
return numTrees;
}
}
// 2 Prompt the Instructor for the number of Trees
numTrees = prompt("How many trees are in your sample?");
alert("You have entered: " + numTrees);
treeFunction(answer, counter, numTrees)
document.write(numTrees);
document.write("<br/>")
document.write("<br/> <br/>" + "End of Program.");
EDIT: I have change what I'm doing, I no longer need to return both variables, only numTrees. howver the document.write for some reason show the original value, not the value it was changed to in the function even after return.
answer, counter, numTrees are global, however when you pass them into a function as arguments;
function treeFunction(answer, counter, numTrees) {
you get a set of new local variables which happen to have the same name as the globals, and therefore hide them.
To use the globals, dont pass them
function treeFunction() {
answer = ....
(You also want counter += 1 to actually increment the variable)
A function can return only one value. So,
return numTrees;
return answer;
the second statement will not get executed.
Since, variables are declared outside the function, they are global. So, you dont need to return it. ie, it will have modified value after the function completes execution.
instead of calling return twice (which will not work anyway), you can return an Array.
return [numTrees, answer];
So now we can catch that by assigning the return value and access it:
var ret = treeFunction(answer, counter, numTrees);
// ret[0] is "numTrees"
// ret[1] is "answer"