Incremental Game Error - javascript

I am making an incremental game but when I load the game it adds more decimals and counts up to "infinite".
I made a codepen so you can see the error for yourself
Try and click the picture a couple of times and press save and load.
Why are the number of quickscopes going up like that?
The Codepen
var faze = 0;
function fazeClick(number){
faze = faze + number;
document.getElementById('faze').innerHTML = faze;
}
var mntDew = 0;
function buyDew(){
var mntDewCost = Math.floor(10 * Math.pow(1.1,mntDew));
if(faze >= mntDewCost){
mntDew = mntDew +1;
faze = faze - mntDewCost;
document.getElementById('mntDew').innerHTML = mntDew;
document.getElementById('faze').innerHTML = faze;
};
var nextCost = Math.floor(10 * Math.pow(1.2,mntDew));
document.getElementById('mntDewCost').innerHTML = nextCost;
};
function save(){
localStorage.setItem('faze', JSON.stringify(faze));
localStorage.setItem('mntDew', JSON.stringify(mntDew));
//add more here
};
function load(){
if (localStorage.getItem('mntDew')){
faze = localStorage.getItem('faze');
};
if (localStorage.getItem('faze')){
faze = localStorage.getItem('faze');
};
//add more here
};
function deleteSave(){
localStorage.removeItem("save");
};
window.setInterval(function(){
fazeClick(mntDew);
}, 1000);
// <button type="button" onClick="buyDew()">Buy Mountain Dew</button> #buyCursor
//Mountain Dew: <span id="mntDew">0</span><br/> #cursors
//cost: <span id="mntDewCost">10</span> #cursorCost

The responsible of your 'bug' is the following instructions:
window.setInterval(function(){
fazeClick(mntDew);
}, 1000);
Your counter start to increment because the onclick of 'Buy Mountain Dew' button increment the value of `mntDew var', before of that the set interval call fazeClick(0);
I am really sorry, but I'm not able to understand what you want to achieve

Related

Attempting to make a repeat function in java that will repeat a function 'x' times and will then proceed to load another function after 'x' times

I'm working on trying to create a random image generator that will show a random image in Javascript. I've been able to make it show a random image via the Javascript math and using random variables. But sadly I'm still yet to be eligible to make my code repeat itself.
I know its probably very simplistic but as you know, we all start from somewhere. I've tried my best to compact my code and I have looked at other stackoverflow recourses but im still in no luck.
A quick overview of what happens, you are meant to be able to press a button and then, a selected random image is replaced by the current one.
What I want: to be able to press a button and then it will proceed to cycle through the random images 'x' times.
My code:
function imgRandom() {
var myImages1 = new Array();
myImages1[1] = "images/Random/Icon1.png";
myImages1[2] = "images/Random/Icon2.png";
myImages1[3] = "images/Random/Icon3.png";
myImages1[4] = "images/Random/Icon4.png";
myImages1[5] = "images/Random/Icon5.png";
myImages1[6] = "images/Random/Icon6.png";
myImages1[7] = "images/Random/Icon7.png";
myImages1[8] = "images/Random/Icon8.png";
myImages1[9] = "images/Random/Icon9.png";
myImages1[10] = "images/Random/Icon10.png";
myImages1[11] = "images/Random/Icon11.png";
myImages1[12] = "images/Random/Icon12.png";
myImages1[13] = "images/Random/Icon13.png";
myImages1[14] = "images/Random/Icon14.png";
myImages1[15] = "images/Random/Icon15.png";
myImages1[16] = "images/Random/Icon16.png";
myImages1[17] = "images/Random/Icon17.png";
myImages1[18] = "images/Random/Icon18.png";
myImages1[19] = "images/Random/Icon19.png";
myImages1[20] = "images/Random/Icon20.png";
myImages1[21] = "images/Random/Icon21.png";
myImages1[22] = "images/Random/Icon22.png";
myImages1[23] = "images/Random/Icon23.png";
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
<center>
<p>
<img id="gen-img" class="character-image" src="images/QuestionMark.png" style="width:180px;height:310px;">
</p>
<p>
<input type="button" class="button" value="Choose" onclick="setTimeout(imgRandom, 3000);" />
</p>
</center>
I hope this isn't too confusing, i'll be active for a long time if you're able to help! Thanks,
David.
I refactored your code a bit with an possible approach Here's the fiddle: https://jsfiddle.net/mrlew/d2py2jvb/
I commented with some explanations.
/* some flags you can set */
var timesTocycle = 10;
var totalImagesToCreate = 23;
var timeBetweenCycle = 3000;
/* global variables */
var allMyImages = [];
var timesCycled = 0;
/*
function to create your images path.
Called once when you load your page.
*/
function createMyImages(total) {
for (var i=0; i<total;i++) {
var imageNumber = i+1;
var path = getImagePath(imageNumber);
allMyImages.push(path);
}
}
/* separated your path getter */
function getImagePath(imageNumber) {
return "images/Random/Icon" + imageNumber + ".png";
}
/* this is the function called when you press the button and when one cycle ends */
function triggerRandomImage() {
if (timesCycled >= timesTocycle) return;
setTimeout(displayRandomImage, timeBetweenCycle);
}
/* random integer javascript function */
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/* function called on setTimeout */
function displayRandomImage() {
var rnd = getRandomInt(0,allMyImages.length-1);
var imageToDisplayPath = allMyImages[rnd];
document.getElementById("gen-img").src = imageToDisplayPath;
timesCycled++;
triggerRandomImage();
/* debug info */
document.getElementById('info').innerText = "(showing: " + imageToDisplayPath + ", cycle: " + timesCycled + ", max: " + timesTocycle + ")";
}
/* call this function to populate the allMyImages array */
createMyImages(totalImagesToCreate);
I believe what you want is for loop. Let me demonstrate with your code:
var count = 10; //number of times to run the for loop
for (i = 0; i < count; i++){
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
The above code would run the randomizing bit 10 times (= 10 images). Now, I have not tested it yet, but I believe that the images would flash by really quickly. Also, unrelated to the question you may want to read about Javascript arrays.

How to make this function do this in an interval

I'm trying to get the first function, to run repeatedly. Like it does in the second function. Where should I take a look?
(function printLetterByLetter() {
var i = 0;
var destination = "comment";
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
var typewriter = function () {
document.getElementById(destination).innerHTML += message.charAt(i);
i++;
if (i > message.length) {
clearInterval(typespeed);
}
}
var speed = 60;
var typespeed = setInterval(typewriter, speed)
}());
(function printLetterByLetter() {
var destination = "comment";
var frequency = 1000;
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
}, frequency)
}());
So what i'm trying to do is to make one function/module that types out a random comment at a set speed(first function). And after a set time the comment will disappear and a new comment will be typed out(second function). And like the second function this will go on.
So far I haven't made it work myself so I thought: let's see if anyone can help me on stackoverflow.
If anyone can give a tip on where to take a look, that is also most welcome.
You could set and alter the function parameters outside of the function then access them inside. Caveat is that you can't put var in front when setting them. Not putting var in front makes it accessible outside of the current scope.
destination = "comment";
frequency = 6000;
(function printLetterByLetter() {
//now you have access to destination and frequency as they are defined before the function is called
var RandomComment = [
"Did you choose that outfit?"
, "I like trains."];
var RandomCommentTimer = setInterval(function () {
var message = RandomComment[Math.floor(Math.random() * RandomComment.length)];
document.getElementById(destination).innerHTML = message;
}, frequency)
}());

How to properly use document.getElementById()?

Maybe I am not understanding this right or I am just writing something wrong. I am making an incremental game and am trying to figure out total dps which then I can change how gold is generated
This is the line of HTML I am trying to use the function with.
Total DPS:<span id="dps">0</span>
This is the javascript
function dps(){
dps = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = dps;
};
function damageClick(number){
damage = damage + number;
document.getElementById("damage").innerHTML = damage;
gold =gold +1;
document.getElementById("gold").innerHTML = gold;
xp = damage * 2;
document.getElementById("xp").innerHTML = xp;
};
var aadmg = 0;
function buyAA(){
var aaCost = Math.floor(10 * Math.pow(1.1,aadmg));
if(gold >= aaCost){
aadmg = aadmg + 1;
gold = gold - aaCost;
document.getElementById("aadmg").innerHTML = aadmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(10 * Math.pow(1.1,aadmg));
document.getElementById('aaCost').innerHTML = nextCost;
};
function buyDagger(){
var daggerCost = Math.floor(300 * Math.pow(1.1,daggerdmg));
if(gold >= daggerCost){
daggerdmg = daggerdmg + 5;
gold = gold - daggerCost;
document.getElementById("daggerdmg").innerHTML = daggerdmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(300 * Math.pow(1.1,daggerdmg));
document.getElementById('daggerCost').innerHTML = nextCost;
};
var sworddmg = 0;
function buySword(){
var swordCost = Math.floor(500 * Math.pow(1.1,sworddmg));
if(gold >= swordCost){
sworddmg = sworddmg + 7;
gold = gold - swordCost;
document.getElementById("sworddmg").innerHTML = sworddmg;
document.getElementById("gold").innerHTML = gold;
};
var nextCost = Math.floor(500 * Math.pow(1.1,sworddmg));
document.getElementById('swordCost').innerHTML = nextCost;
};
My thought was that I have function dps used in the html and then it should equal aadmg + daggerdmg + sworddmg. I am getting the element dps with the document.getElementByID("dps").innerHTML = dps;. I have also tried adding getElement for all the dmg's as well. I am confused on how to obtain those numbers from the HTML and then add them together and display them.
You have a suicide function. When you have called the dps function once, it will have replaced itself with the value that you calculate. The next time that you try to call it, the dps identifier doesn't point to the function any more, so the code will crash.
Use a different variable in the function (and make it local by using the var keyword):
function dps(){
var x = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = x;
};
(It would work just to make it local, but there is no good reason to use a local variable by the same name as the function.)
I think you're missunderstanding how functions are called in javascript. They are not called just because they have the same name/id as an html-element.
You would need something that triggers your calculations. A button for example.
A button could trigger your function like so:
<button id="myButton">clickme to calulate</button>
<script>
document.getElementById('myButton').addEventListener("click", function(){
dps();
});
</script>
Then your function dps() would have to look like that:
function dps(){
var x = aadmg + daggerdmg + sworddmg;
document.getElementById("dps").innerHTML = x;
};
But you should refactor your code to have an object that saves and serves all the data you need, instead of having plain global variables.

Javascript for loop doesn't work (adding numbers to a total)

I am using Jasmine for JS testing, and unfortunately I can't get the following test to pass.
it('should know the total game score', function() {
frame1 = new Frame;
frame2 = new Frame;
game = new Game;
frame1.score(3, 4);
frame2.score(5, 5);
expect(game.totalScore()).toEqual(17)
});
The error message I get is as follows: Error: Expected 0 to equal 17.
The code is as follows:
function Game() {
this.scorecard = []
};
Game.prototype.add = function(frame) {
this.scorecard.push(frame)
};
// Why is this not working!!???
Game.prototype.totalScore = function() {
total = 0;
for(i = 0; i < this.scorecard.length; i++)
{
total +=this.scorecard[i].rollOne + this.scorecard[i].rollTwo;
}
return total;
};
function Frame() {};
Frame.prototype.score = function(first_roll, second_roll) {
this.rollOne = first_roll;
this.rollTwo = second_roll;
return this
};
Frame.prototype.isStrike = function() {
return (this.rollOne === 10);
};
Frame.prototype.isSpare = function() {
return (this.rollOne + this.rollTwo === 10) && (this.rollOne !== 10)
};
Adding the numbers together manually seems to work e.g. total = game.scorecard[0].rollOne + this.scorecard[0].rollTwo , but the for loop (even though it looks correct) doesn't seem to work. Any help would be greatly appreciated :)
I am not pretty sure, but it seems that you are not calling the "Add" method, so no data is added to the scorecard.
You have to add the Frames to your game i guess
it('should know the total game score', function () {
frame1 = new Frame;
frame2 = new Frame;
game = new Game;
// those lines are missing
game.add(frame1);
game.add(frame2);
frame1.score(3, 4);
frame2.score(5, 5);
expect(17).toEqual(game.totalScore())
});
otherwise, the scorecard-array is empty and the total score is therefore equal to 0.
missing (so no data is added to the scorecard.)
game.Add(frame1);
game.Add(frame2);

JS mini-game in grid, browser frozen after first replication

I'm trying to create a small game that replicate neighbors cells in a grid. I use a web worker that draw replicate cells every seconds. I'm able to replicate the first second. If my initial cell is row3col3, the new replicated cells will be :
row3col2, row3col4
row2col3, row4col3
The problem is, after the first second (and the replication), the game freezes, and i'm not able to do something. Can't click on cells, etc.
EDIT : After few seconds, it go to '00:02' but Chrome crashed "Aw, Snap! Something went wrong...' [RELOAD]
EDIT 2 : After looking on the memory used, It appears I have an memory overflow, 16000 Mb ! My method is bad, so.
I know my code is not really optimised, and I think that is the problem. Unfortunatly, i'm not able to do more efficient code, so I ask some help to you guys, to give me some ways to explore.
Here the code :
var lastClicked;
var cellTab = Array();
var replicant = Array();
var newReplicant = Array();
var count = 5;
var rows = 20;
var cols = 20;
var randomRow = Math.floor((Math.random() * rows));
var randomCol = Math.floor((Math.random() * cols));
var grid = clickableGrid(rows, cols,randomRow,randomCol,cellTab, function(el,row,col,i){
console.log("You clicked on element:",el);
console.log("You clicked on row:",row);
console.log("You clicked on col:",col);
console.log("You clicked on item #:",i);
$(el).addClass('clicked');
lastClicked = el;
});
document.getElementById("game").appendChild(grid);
function clickableGrid( rows, cols, randomRow, randomCol, cellTab, callback ){
var i=0;
var grid = document.createElement('table');
grid.className = 'grid';
for (var r=0;r<rows;++r){
var tr = grid.appendChild(document.createElement('tr'));
for (var c=0;c<cols;++c){
var cell = tr.appendChild(document.createElement('td'));
$(cell).addClass('row'+r+'col'+c);
if(randomCol == c && randomRow == r)
{
storeCoordinate(r, c, replicant);
$(cell).css('background', '#000000');
}
storeCoordinate(r, c, cellTab);
cell.addEventListener('click',(function(el,r,c,i){
return function(){
callback(el,r,c,i);
}
})(cell,r,c,i),false);
}
}
return grid;
}
function storeCoordinate(xVal, yVal, array)
{
array.push({x: xVal, y: yVal});
}
function replicate(replicant)
{
for (var i = 0; i < replicant.length; i++) {
console.log(replicant);
var supRowX = replicant[i].x-1;
var supRowY = replicant[i].y;
storeCoordinate(supRowX, supRowY, newReplicant);
var subRowX = replicant[i].x+1;
var subRowY = replicant[i].y;
storeCoordinate(subRowX, subRowY, newReplicant);
var supColsX = replicant[i].x;
var supColsY = replicant[i].y-1;
storeCoordinate(supColsX, supColsY, newReplicant);
var subColsX = replicant[i].x;
var subColsY = replicant[i].y+1;
storeCoordinate(subColsX, subColsY, newReplicant);
}
}
function drawReplicant(replicant, cellTab)
{
for (var i = 0; i < replicant.length; i++) {
if($.inArray(replicant[i], cellTab))
{
$('.row'+replicant[i].x+'col'+replicant[i].y).css('background', '#000000');
}
}
}
var w = null; // initialize variable
// function to start the timer
function startTimer()
{
// First check whether Web Workers are supported
if (typeof(Worker)!=="undefined"){
// Check whether Web Worker has been created. If not, create a new Web Worker based on the Javascript file simple-timer.js
if (w==null){
w = new Worker("w.countdown.js");
}
// Update timer div with output from Web Worker
w.onmessage = function (event) {
document.getElementById("timer").innerHTML = event.data;
console.log(event.data);
replicate(replicant);
replicant = newReplicant;
drawReplicant(replicant, cellTab);
};
} else {
// Web workers are not supported by your browser
document.getElementById("timer").innerHTML = "Sorry, your browser does not support Web Workers ...";
}
}
// function to stop the timer
function stopTimer()
{
w.terminate();
timerStart = true;
w = null;
}
startTimer();
And here, the web worker :
var timerStart = true;
function myTimer(d0)
{
// get current time
var d=(new Date()).valueOf();
// calculate time difference between now and initial time
var diff = d-d0;
// calculate number of minutes
var minutes = Math.floor(diff/1000/60);
// calculate number of seconds
var seconds = Math.floor(diff/1000)-minutes*60;
var myVar = null;
// if number of minutes less than 10, add a leading "0"
minutes = minutes.toString();
if (minutes.length == 1){
minutes = "0"+minutes;
}
// if number of seconds less than 10, add a leading "0"
seconds = seconds.toString();
if (seconds.length == 1){
seconds = "0"+seconds;
}
// return output to Web Worker
postMessage(minutes+":"+seconds);
}
if (timerStart){
// get current time
var d0=(new Date()).valueOf();
// repeat myTimer(d0) every 100 ms
myVar=setInterval(function(){myTimer(d0)},1000);
// timer should not start anymore since it has been started
timerStart = false;
}
Maybe it's because I use jQuery ?

Categories

Resources