how to implement javascript localStorage - javascript

I want to implement localStorage for one of my values in my Achievements class. So basically what this class does is take player data from backend database and if a player clears certain tasks an achievement gets unlocked. For now I have just 1 achievement defined as follows
Achievements:{ 1:{name:'First_Achievement',status:1} },
The status field acts like a flag for my achievements. If status is 1 then achievement is still locked and if it goes 0 the achievement gets unlocked.
This is a skeleton code for when my achievement gets unlocked. This block of code is checked in my game every 10 seconds to see if a certain task is cleared to unlock an achievement
checkAchievements:function(){
this.probsSolved = this.getTeamProbSolved();
if( this.Achievements[1].status == 1 && this.probsSolved.length >=3)
this.triggerAchievement(1); // spawns achievement 1 on screen
this.Achievements[1].status = 0;
},
So this works fine when I run the game. The "this.Achievements[1].status" is set to 0 until I start my game again the next time. It sets the "this.Achievements[1].status" back to 1 and the if loop runs again as status is set back to 1 which I don't want because its obvious I want my achievement to be spawned or displayed just once and not every time I run the game.
So how do go about an implement localStorage here? I suppose I need to store my "Achievements.status" field in the localStorage so that the if loop runs just once and not everytime. Or is there any other way I can implement this?
I tried the following
localStorage.setItem(this.Achievements[1].status,0);
but it does not work
any help would be appreciated! Thanks!

First, I'd recommend reading the documentation on localStorage at MDN - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage. Next, let's look at your call:
localStorage.setItem(this.Achievements[1].status,0);
This says: I want you to store a value, 0, and retrieve it by the key that is the value of this.achievements[1].status.
That seems to be booleans for you. So you basically did:
localStorage.setItem(true, 0)
The localStorage API expects a string for the keyname, so it will get the string value of true which is, true. So it probably did work for you, but you used a key that probably isn't what you want. You need to think of a key name scheme that makes sense for you.

Related

How can I add permanent data into an variable

I'm working on a project that plays a game of rock paper scissors
the game works fine but i want to add something into it. a pointing system where it will add 1 each time a player win but i can't seem to make this work i've been trying to find workarounds for almost 2 day now but i can't seem to find any solution. The thing is the code works but after i log the function that adds 1 to a variable but after that it returns to it's original value which is 0.
const one = 1
function addone(test){
test += 1
}
addone(one)
console.log(one)
This print the original value like the function did not do anything to it. im so confused.
I see two problems in your code:
one is a const variable. That means that you can't modify its initial value.
test is a local variable inside your function, that means function won't modify the values of the variable that you pass as parameter (one).
There is an operator(++) that add a unit, I highly recommend you to use it instead of make a function:
var one = 1
one++;
console.log(one)
If you want to use a function you have to do like this:
var one = 1
function addone(test){
return test+1;
}
one = addone(one);
console.log(one)
In terms to store permanent data into a javascript variable, that's not possible. Variable are stored in RAM, that means that when you stop the program, al data of your program are wiped. Permanent store are made in database and other complex data structures.
If you want to play multiple games, you should consider to allow the players to play more games before the program finish.
thank you very much i never think that i could get more dumb so i cant manipulate it because it's just a copy of that variable that im inputing as parameter? so it means that the function did not touch the variable at all. I wish i could go back to my mother's womb.
and the const it's just a typo very sorry for this.
i did not know this website is very active i thought i would wait days just to get a response thank you very much and have a nice day

how to refresh php div every few seconds

So I'm basically trying to implement an online trading card game in php and (maybe minimal) javascript, and so far I have a GUI set up in php, a database with the required tables (so far) to hold the decks, fields, and other various data. I've got it to the point where i have a function that initializes the fields for both players and populates their fields and hands with cards from their deck. I also got it to the point where a player on another computer or device can take the room number of the game and join the game so the see the exact initialized field.
my next objective was to be able to set up the turn logic, and allow the screen to update for one player while the other is making plays during their turn. My problem is I'm not sure what the minimum viable solution will be for this, because I have long intricate functions that display the current field based off of values that come from a field table. So my ideal logic is set up like this:
//find game form
//host game form
//if host is set (post){
//call insert field function (a long function that creates a table for the current game being played and initializes the field and hand with random cards from the deck table)
//link game to host for future field printing
// populate host function (a function that prints a table of every card on the field with the most up to date variables to represent each spot)
}
//if find is set (post){
//call insert field function
//link game to host for future field printing
//a button form to start the game which begins by calling heads or tails
// populate find function (same as host but for find player side)
}
//if start game is set (post){
// do game logic such as coin flip which will be notified to opponent in a message field in the game table upon the refresh
}
I was wrapping the populate host function in a refreshable div like this:
print "<div><meta http-equiv='refresh' content='5' />"; //host populate just disapears
populatehost($roomnumber); //populates self and opponents in hosts perspsective
print "</div>";
so that the function would be called every 5 seconds or so, but this just causes the field to disappear after 5 seconds. So...
Why is it disappearing?
How can i get it to refresh the page and just display one instance of the field using the populate field function?
Is this approach viable? if not, what's the easiest approach I could take and how?
I also tried a solution where the function was called every 5 seconds and gotten rid of, but i'm not sure if I was doing it right, the PHP manual didn't explain it very clearly, and after lots of trial and error i think i crashed my server. It was something like this:
//loop
ob_start();
populatehost($_SESSION['gamenumber']);
sleep(5);
ob_end_clean();
I kept playing around with that logic but it either printed infinitely, didn't print at all, or crashed my server. I'm afraid to play around even more for fear of crashing the server again. Maybe someone can explain the correct way to do it or why it is not viable if it isn't?
I'm sorry if these are dumb questions, I've spent days and days researching approaches to this problem, I wasn't sure if I could implement it using javascript or ajax along with my field printing function, I tried some and they weren't working, and I'm not sure if it's because my approach is viable or not.
You can take javascript or Ajax help for div you can assign id to the div and call id in javascript:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
check this fiddle:
http://jsfiddle.net/arunpjohny/asTBL/
Thanks

JavaScript: Accessing Variables from Other Files and Changing their Properties

So I am making a hacking type game coded with HTML and JavaScript, and I made a Store.html file for my store to purchase upgrades for your hacking system. I have several variables that I want to view and change from a different file than the one that I originally have it inside of.
Variable 1
var tutorialDone = false
Variable 2
var jobBoolean
Variable 3
var bitCoins = 30
var currentBit = bitCoins
I want this to be false because when the tutorial mission is finished, then I want to change the jobBoolean variable to "true" because when the tutorial mission is completed, then I want a new list of missions/jobs to show up on thee screen. The first mission is a seperate page. At the end of the mission when it is completed, then "tutorialDone" I want to be equal to "true", so that when I am back at the homepage, I can change the jobBoolean to true. Because the "tutorialDone" variable is dependent on the "jobBoolean" variable. When "tutorialDone" equals "true" so does "jobBoolean". I don't know how to make "tutorialDone" change along with the "jobBoolean".
I have for the third variable, there is two. That is because they are similar. I have a function inside the "Store.html" document that when an item is purchased, it grabs a variable which in this case is "currentBit". "currentBit" is equal to "bitCoins" because I thought that if I made a new variable, "currentBit", then set it equal to "bitCoins", it would connect with "bitCoins" from a seperate file. This was my only "solution" I could think of, but it doesn't work.
Also, as a bonus answer for you guys, how can I make an "if" statement in JavaScript, and then have it check if the variable I give it is equal to something, and if it is, run some code. Because whenever I try it, the function the if statement is in, it will run through the if part of the statement no matter if the statement is true or false.
Sorry if this question doesn't make much sense. This is just the first big problem I have encountered with JavaScript, that I couldn't fix myself.

Workaround for not being able to save booleans with HTML5 Web Storage

I'm currently making a Mario-esque game with Javascript, or more precisely, CraftyJS.
I've looked here as reference,
and understand how to save values inputed by the user.
But what I want to accomplish is to save certain booleans(is that what they are called?) automatically, or when the player presses a save button or something.
For example, I have a dungeon called dungeon1, and I create a variable to represent whether or not the dungeon has been completed.
It's var dungeon1 = false; by default.
But when the player completes dungeon1, it changes to var dungeon1 = true;,
resulting in new additions to the world map, such as a portal to dungeon2(this is working fine).
What I want to save is this var dungeon1 = true; statement, so that when the user opens the game again, the dungeons completed will be loaded and the corresponding unlocks will be shown correctly. How would I do so?
Is there a way to say, make a save management file called save.js, then store booleans such as the one above once they become true?
You would just store the string version of the boolean that you want.
So store "true" and "false", and instead of checking just like if(variable) you'd have to check in the form of if(variable === "true"). Its a little derpy but you can see how it doesn't really add more complexity to your code.
If that type of if checking just offends your sensibilities, then in the code where you "get" it from the localStorage you could then recast it to a boolean.
var bool = (localStorage.getItem("myItem") === "true")
PS. you can setItem with booleans... it will just cast them to strings :D because most things it calls toString() on to store them if they aren't already strings.
So you can do:
enter code herelocalStorage.setItem("myItem", true)

Javascript table on the fly

I've got some issues with javascript. Which causes some problems.
I'm using DevExpress MVC GridView, ASP.Net MVC 3 and javascript.
This my problem:
I've got a gridview, with for example customers.
I want them to select the customers, and show them in a table generated by javascript so we dont get all those refreshes. And they can then add other information so that they can be saved again to another table, but thats not really important.
I perform some calculations before generating the table row from the selected customer. Another problem is, the devexpress gridview has an event that calls on each selection change instead of a nice ~100 ms wait so that the user can multiselect quick without triggering method 3/4 times.
Im keeping track of my own table through an array. And the GridView from DevExpress got his own events that can give me the right information, so no need to worry about that.
So I got a method receiveSelectionFields(Values){ //do something } where I receive that information from the gridview on every selection.
Then I check my array to see if they added or removed a selection, and which.
Then I call addtablerow(customer) or removetablerow(customer). Which removes the customer from my table and then from my array.
Because I make some heavy calculations in between, there is a ~60ms delay before the calculation is done (on mine computer). So if the users makes 2 selections in 60 ms. My array will have the wrong value (not being modified by the first call that adds/removes a customer) and my javascript will cause an error e.g. the table row is not deleted. I check on length of my own array and on the length of the received array to see if something has been added or removed.
So what did I try?
Making my method a recursive method, that when the problem occurs it waites 60 ms and then redo the method. But this isn't working properly.
I tried adding a global variable busy, which is true when the method is still busy. And false when it ends. But my browser just quits when doing that. This was the code:
while (true) {
setTimeout(function () {
if (busy === false) {
break;
}
}, 50);
}
But I got the feeling it just endlessly loops.
And these are all workarounds, there must be a nice way to solve this. Any thoughts?
In short:
I want a way to let the functions go off in synch. even if their being called asynch. by the user so that my array doesn't mess up.
Found the answer why my problem exists:
Since javascript is a synch. language (1 thread). the functions should've triggered at the right time. The problem is the callback from DevExpress Gridview for MVC Extensions. It makes a callback to the server, which responds in for example ~150ms with the selected field values. This will give an error if you quickly trigger the devexpress function twice. The second trigger has a window to return FASTER then the first trigger. Which would mean my coding of the table get ruined since I check if something has been added or removed. So when the first trigger (which returns after the second trigger) and my table gets updated. It shows the table prior to my last selection. Thus missing 1 row or has 1 more row then it should've.
So I got to make a function that retrieves all the events, and then place them in an order ~200 ms after each order. To make sure there is enough time for the callback to retrieve. Though this is ofcourse still not reliable, I think I will just change the requirements on this.
Your while loop condition is true, therefore the loop will just continue endlessly. You may want to try the following:
var int = setInterval(function () {
if(busy === false) {
clearInterval(int);
}
}, 50);
Try this instead of looping through the setTimeout over and over. If I had to guess, the break is breaking the if statement but not the while loop causing your browser to get stuck in an endless loop. With the above code, you can set an interval at which to run the code. In this instance, the code runs every 50ms. Once the condition inside the if statement is true, the setInterval is cleared causing the browser to continue executing its normal functionality.
Hope this helps.

Categories

Resources