I'm new to HTML and Javascript, and to learn it I am making an incremental game (similar to CookieClicker or CivClicker).
I'm trying to save and load progress, and I can save it just fine, but when I load it, it loads all the variables correctly, but when I click on a button to increment a variable, it does some weird stuff, it's hard to explain, I'll post the code so you can look at it some more.
JSFiddle Here
function loadProgress() {
if (typeof (Storage) !== "undefined") {
progress = localStorage.progress;
speed = localStorage.speed;
quality = localStorage.quality;
isDone = localStorage.isDone;
totalMoney = localStorage.totalMoney;
speedCost = localStorage.speedCost;
gamesSold = localStorage.gamesSold;
autoclick = localStorage.autoclick;
autoclickCost = localStorage.autoclickCost;
currentBugs = localStorage.currentBugs;
refreshDisplay();
} else {
console.log("LocalStore not appliable.")
}
}
Press 'Design' until you get to 100% then click 'Sell your game'. Then just press Save Progress then Load progress and click design and sell game again, you will see the numbers increase very oddly and that isn't expected at all.
'ShowMeTheMoney' will show you the variables in the console so you can verify that the variables were stored correctly.
I have no idea why this is happening, so if someone could help that would be awesome.
Local storage aka Web Storage, stores values as strings, so you need to convert/cast to numbers when you retrieve the values, otherwise the variables will remain as strings, and you'll see concatenation instead of the value being incremented. For example 1 + 1 becomes 11 not 2.
Updated working fiddle
There are many ways of converting to a number, one way is the + method:
progress = +localStorage.progress;
speed = +localStorage.speed;
quality = +localStorage.quality;
Related
I'm currently doing a school project where I have to remake a "Pong" type game. I've just started coding, but everything has gone smooth so far. But, I got stuck on this scoring thing. I basically want to keep the value of the variables when the page is refreshed. Some of my code is in french, hence the french words. "Point" is basically the score ( two players so two different scores ). "Fin" is when a player scores. Also, try not judging my code, it's one of the first things I'm doing :P.
Since I'm a complete noob in the coding world, I've tried multiple ways to keep retain the value of the variable when the page refreshes. I've tried cookies and local storage.
var point1=0
var point2=0
if(balle.x+balle.w>=canvas.width){
gameOver=true
player1=true
point1++
}
if(balle.x-balle.w<=0){
gameOver=true
player2=true
point2++
}
function fin1(){
c.font="100px Impact"
c.drawImage(sas,0,0)
c.fillText("Sasuke scores!",200,100)
}
function fin2(){
c.font="100px Impact"
c.drawImage(ita,200,0)
c.fillText("Itachi scores!",200,100)
}
function restart(){
if(gameOver==true){
setTimeout("window.location.reload(false)",2000);}
}
My restart function works, but it just resets the value of the "point1" and "point2" variables everytime the page reloads.
Ahh, I see what's happening here at least what I can understand through your query is:
You are setting data to the local storage but on reset the file runs again and sets the value of point1 and point2 to 0. Basically you are not getting that item from local storage. So what's the solution you ask: write an If condition, If the data is present in local storage then use it, if not then initialize to 0 something like this.
var point1 = localStorage.getItem('point1') ? localStorage.getItem('point1') : 0;
var point2 = localStorage.getItem('point2') ? localStorage.getItem('point2') : 0;
You can get more insight on localStorage from:
MDN localStorage
web-storage
Note: I am considering that you are storing the data(point1 and point2) in the localStorage
So I'm building a clicker game on CodePen and I ran into a problem while coding my save/load functions. It seems as if my save function may not me working, but I'm not sure why.Here are the functions:
function savegame(){
localStorage.clicks = Number(document.getElementById('clicks').innerHTML);
localStorage.cps = document.getElementById('cps').innerHTML;
localStorage.clickPower =
Number(document.getElementById('clickpower').innerHTML);
localStorage.onecpow = Number(document.getElementById('1clickpowe').innerHTML);
localStorage.onecps = Number(document.getElementById('1cps').innerHTML);
localStorage.fivecps = Number(document.getElementById('5cps').innerHTML);
localStorage.fivecpow = Number(document.getElementById('5clickpower').innerHTML);
localStorage.tencps = document.getElementById('10cps').innerHTML;}
function loadgame(){document.getElementById('1clickpower').innerHTML = localStorage.getItem("onecpow");
document.getElementById('clicks').innerHTML = localStorage.getItem("clicks");
document.getElementById('cps').innerHTML = localStorage.getItem('cps');
document.getElementById('clickpower').innerHTML = localStorage.getItem('clickpower');
document.getElementById('5clickpower').innerHTML = localStorage.getItem('fivecpow');
document.getElementById('5cps').innerHTML = localStorage.getItem('fivecps');
document.getElementById('1cps').innerHTML = localStorage.getItem('onecps');
document.getElementById('10cps').innerHTML = localStorage.getItem('tencps');}
I forgot to clarify what I'm expecting the code to do. What this should do is save the players progress and upgrades, instead upon loading the saved data the players data is not loaded and returns many blank spaces where saved data should have been loaded.
Instead of doing localStorage.onecpow = "someValue" try
storage.setItem(onecpow, "someValue");
You can check the Storage docs here for more info
You are using 'localStorage' wrong. Have a look at this:
// writing to localStorage
localStorage.setItem('myId', value);
// reading from localStorage
var whatever = localStorage.getItem('myId');
// remove an item from localStorage
localStorage.removeItem('myId');
EDIT:
The problem is that you're mixing up 2 different approaches. You have to decide which one to use. Either the object-driven or the key-driven.
My example above is the key-driven approach. You should also be able to use the object-driven approach like this:
// writing to localStorage
localStorage.myObject = value;
// reading from localStorage
var whatever = localStorage.myObject;
Choose your style, but don't mix them. ;o)
I found a solution, though it's kind of strange how it works.
I added capital letters to the localStorage attributes and used localStorage.setItem and localStorage.getItem. Don't know why it works but it does.
I've made an event in Google Tag Manager, which triggers when a specific page is loaded.
The Event label is the value of my user defined variable SearchCounter with type: Custom JavaScript.
In 'SearchCounter' I have the following JS:
function(){
var counter;
if(localStorage.getItem("count_search") === null || localStorage.getItem("count_search") === 'undefined'){
localStorage.setItem("count_search", "1");
return localStorage.getItem("count_search");
}
else{
counter = parseInt(localStorage.getItem("count_search"));
counter = counter + 1;
localStorage.setItem("count_search", counter);
return localStorage.getItem("count_search");
}
return localStorage.getItem("count_search");
}
When I don't have the item in my local storage already, it still give's me 7 instead of 1. Then I'll press F5: count_search = 17, And again f5: 27. A CTRL-F5 gives me 37.
It should be 1, 2, 3, 4, 5 etcetera.
I hope someone can help me to implement a counter-alike function in Google Tag Manager, so I can send the amount of searches to GA, when a goal has been achieved. So, When someone clicks a specific button a would like to get the value of count_search, to send it to GA within an event.
Thanks very much.
First of all this metric is given by google analytics by default so i don't see why ur trying to store it somewhere else. If you dont want the avg that google uses you can just store a custom dimension at 'Session' level with the sessionID and those in a custom report open Sessions by pageviews. Here is info about it.
On the other hand, if you insist doing it your way i think even if this works it isn't the best approach you would get a much better result storing the counter in a custom dimension at 'Session' level. (It ll overwrite the value each time for a given session and you ll end up with the last one send)
Hope it helps.
What you need to do is changing the name of the parameter saved in the localStorage. I don't know why, but count_search does not work. I tested your setup and encountered the same weird effect where the count_search item is summing up to astronomical numbers. Using a different name like thisIsMyPageViewCounter works just fine though! Probably count_search is accessed by another object in the document or window and you managed to get a value out of it by chance.
If you want to add the page view count to an event, I do not see any other way than creating both a Custom HTML Tag to set the counter and a Custom JS Variable to return the count.
This is the Custom HTML Script to be added to each page view:
<script>
(function() {
if(localStorage.getItem("thisIsMyPageViewCounter") === null || localStorage.getItem("thisIsMyPageViewCounter") === 'undefined') {
localStorage.setItem("thisIsMyPageViewCounter", 1);
} else {
var counter = 0;
counter = parseInt(localStorage.getItem("thisIsMyPageViewCounter"));
counter = counter + 1;
localStorage.setItem("thisIsMyPageViewCounter", counter);
}
})();
</script>
This is the Custom JS Variable to be added as a value to the event:
function() {
pageviewCounter = parseInt(localStorage.getItem("thisIsMyPageViewCounter"));
return pageviewCounter;
}
I hope this helps!
I'm trying to make a code which lets me show how much a certain part of my website has been views.
My problem is, when I fresh refresh, it goes back to zero, instead of 2. I hope you can help me out. I want the code to run forever, or as long as I want it to, and it will just add a 1 to what it has been, even if it was yesterday. Here's the sample of the code.
<script type="text/javascript">
var bannerViews = 0;
function addViews (){
bannerViews = bannerViews + 1;
}
addViews();
</script>
<p>This banner has been viewed <script type="text/javascript">document.write(bannerViews);</script> timesĀ </p>
Hope you can help me out.
It is because every time you refresh your page, your code reinitializes. In-order to persist the data, you need to store it somewhere. Either in a cookie or a localstorage.
If you go ahead with the localstorage, here's how you do it.
var bannerViewCount = localStorage.getItem('bannerViews');
if(!bannerViewCount) {
bannerViewCount = 0;
}
function addViews() {
localStorage.setItem('bannerViews', ++bannerViewCount);
document.body.innerHTML = 'Banner view count is :' + bannerViewCount;
}
addViews();
Demo (click on Run on the top bar multiple times and see it incrementing)
Here, what am doing is first, fetching the banners view count. If I don't get it, I initialize it with zero.
Later, I on addViews() call, I increment the bannerViewCount by one and store it to the localStorage. That's it.
Note that the data is stored in your local storage, so if you are expecting that the count should be visible to other users too, you need to store it in a database or a text file and later parse it.
If you want to store it on the cloud, so that you can share the count across the visitors, you can do something like this.
function addViews() {
$.get('//jsonbin.io/b/5974382ca489d40388582791/latest', function(data) {
var bannerViewCount = data.bannerviews;
$.ajax({
url: '//jsonbin.io/b/update/5974382ca489d40388582791',
type: 'post',
dataType: 'json',
data: {
snippet: JSON.stringify({
bannerviews: ++data.bannerviews
})
},
success: function(fetch) {
var data = fetch.data;
document.body.innerHTML = 'Banner view count is : ' + JSON.parse(data).bannerviews;
}
});
});
}
addViews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on "Run Code Snippet" button and see the counter incrementing. Go to any other browser and the count will persist as expected. Note that the data stored here can be manipulated as there is no authentication in place. So avoid it if you want the count to be precise and legit.
It goes back to 0 because the variable bannerViews is reinitialised to 0 on every page load.
You will need to store this variable in a JSON file/DB and fetch/update the value there.
Every time you refresh the page the code is going to be reset and variables are included.
To solve this you have to either use a web server and have the variable saved there or find a way to save the variable to the filesystem and load it
back.
The reason the counter is reset constantly is because you're declaring the variable during runtime. There is no persistence to the variable so every time the website is loaded, the variable starts against from 0. Each browser client would keep track of the variable separately so even if you were able to get the variable to persist on your local browser, you would not be able to keep track of the page views from other browsers. The solution to this problem is to keep track of the page views from a centralized server.
You can use a free service such as http://www.webestools.com/pages-views-counter-free-number-pages-views-statistics.html to create the counter that would persist between page views and different clients.
What you need to do is to get the initial value 0 , store in on the server , database or file.
change line var bannerViews = 0; to something like;
var bannerViews = getValueFromServer();
and every after re assigning it, you store it back to the external storage;
For now everytime you refersh the page .
the code var bannerViews = 0; will run and hence bannerViews will alwayz be re assigned to 0
Trying to play a sound via javascript and want to change it dynamically using sessionstorage
The following is a simplified version that plays sound/s in android/FF Linux/Win when u click the "sprite me button" - I've included other buttons for the example to set and retrieve session values in HTML5.
http://globability.org/webapp/asprite20111124_8.html
The wiki below has Android phone specs where it works: (Samsung Galaxy SII) in case you're interested
http://globability.org/wiki/doku.php?id=current_working_specs_p-tab / also see http://globability.org/wiki/doku.php?id=mobile_pointing_tablet to get a proper idea about what it is that I am working on.
What I need is to have the "play soundsprite" javascript that you can see below in the following section load from sessionstorage and insert values loaded from sessionstorage inserted into an array.
I am not looking for any changes is how the sound is played back - just need to make a dynamically built array work from within the particular javascript.
The code below is based on the soundsprite idea from www.phpied.com/audio-sprites/ by Stoyan Stefanov - made to reduce the http calls needed for playing sounds... Also stabilizes the sound quality, less choppy sound etc.
Antway here goes: YOU ONLY NEED TO LOOK AT PSEUDOCODE SECTION - The rest is functioning
<script>
var thing = 'the thing';
function shut() {
if (typeof thing.pause !== 'undefined') {
thing.pause();
}
}
function log(what) {
document.getElementById('log').innerHTML += what + "<br>";
}
var spriteme = function(){
var sprites = {
// id: [start, length]
'blank':[0.1, 0.5], //This the first sprite, it has to be the first defined and is
called first, it is a blank piece of sound in the combined sound file and needed as of
now.
'success':[13, 2,5],
/* I would like to be able to set the parameters i.e. sound bite to play dynamically -
here a pseudocode example using session storage in preparation for getting the sound
parameters from a database
'wordgen'[null,null];
//this array should be dynamically built from values read from the two session storage keys not sure you need the new thing in HTML5
sessionStorage.globabilitykey1;
sessionStorage.globabilitykey2;
strkey1=globabilitykey1
strkey2=globabilitykey2
var gkey1=parsefloat(strkey1)
var gkey2=parsefloat(strkey2)
'wordgen':[gkey1,gkey2]
and then the idea is to replace the array success in the script with the "generated"
array 'wordgen' to allow dynamic seting of sound to play back */
//the following are sound bites from the collection of soundsprites the site plays from
'word1': [0.5, 2,36], //one
'word2': [3.1, 3.0], //two
'word3': [7.0, 1.82], //three
'word4': [10.03, 2], //four ?
},
song = ['blank', 'success'],
//here you're setting the playback sequence (this is where I would like to replace 'success' with 'wordgen'
current = 0,
id = song[current],
start = 0,
end = sprites[id][1],
int;
thing = document.getElementById('sprite');
thing.play();
log('file: ' + thing.currentSrc);
log(id + ': start: ' + sprites[id].join(', length: '));
// change
int = setInterval(function() {
if (thing.currentTime > end) {
thing.pause();
if (current === song.length - 1) {
clearInterval(int);
return;
}
current++;
id = song[current];
start = sprites[id][0];
end = start + sprites[id][1]
thing.currentTime = start;
thing.play();
log(id + ': start: ' + sprites[id].join(', length: '));
}
}, 10);
};
</script>
Any ideas on how to dynamically create the 'wordgen' array within the javascript based on the values is sessionstorage ?
The whole code/working example can be seen here: http://globability.org/webapp/asprite20111124_8.html
I know the page is one ugly mess... but this is an alpha prototype :)
Argh... it was sooooo simple, I was this close to solving it myself, however a kind freelancer at freelancer.com who has perviously helped me getting one of my ideas to work did it again this time...
And without further ado:
'wordgen':eval("["+sessionStorage.globabilitykey1+","+sessionStorage.globabilitykey2+"]"),
That was what I needed - I had been trying to do the same but without the " eval " in front and the paranthesis around the arguments....
Oh and don't forget to set the value by clicking the button before you try or there will be no sound coming out of your speakers ;)
Here's a link to the working page if you care to try and if you want to see the code in it's "entirity": http://globability.org/webapp/asprite20111201_2.html - Thanks to those of you voting the question up!!!