How to make a table out of the value of my counter? - javascript

I'm making a whack a mole game and I want to make a local high-score table for it. Currently I have a counter that counts the number of successful clicks on the moles. After each session(when the window is closed/stop button is clicked) I would like the value of the counter to get saved in a high score table. It needs to be sorted by score of course. Ex:When the top score is 10 and someone gets 11 the 10 goes to number 2 and the 11 takes 1st. The table only needs to be on the local machine, input for names would be great but not needed. I need an example of this, I've tried fooling around with HTML5 databases to no avail. My counter div is
<div id='counter' data-counter='0'>0</div>
and an example of how the counter goes up one on click of a mole
if ($(this).data("state") == "up") {
var counter = $("#counter");
counter.data("counter", counter.data("counter") + 1);
counter.text(counter.data("counter"));
}
I'm just starting web programming so I need it to be as noob friendly as possible. :P If you need clarification on the question, just comment.
Thanks!

If you want to store in the local machine, you could use cookies. You can save any string with cookies.
An easy way to use cookies with jquery is by using the jquery cookie plugin:
http://plugins.jquery.com/project/Cookie
You could store a serialization of your score object, for example if you have it in an array you could do:
$.cookie("scores", JSON.stringify(scoresArray));
To retrieve it, just do:
scoresArray = JSON.parse($.cookie("scores"));
JSON functions will work in modern browsers. More information on JSON can be found on http://json.org
Hope this helps. Cheers

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

Local Storage not stored after page refresh

I'm having a really hard time understanding what I did wrong in my code in order to have a value saved in local storage.
I have a pretty big code project so I'll try to summarize what the program is tryin to do overall.
I am pulling news articles from the news API and displaying the articles; each article (depending on the publication it came from) pushes a different numeric value into an array allSource2.
I then take the sum of this array to arrive to a "score" (variable is called sum)
I basically want that score to be locally stored, so that it is available even after a page refresh.
I think something wrong might be happening because of where I put the localStorage function. Currently I put it under the click event that also pushes the numeric value in the array (when you click the article title).
I am super confused at where else it could be, so that it truly updates the sum every time that sum changes.
Also, it does work to store it (I checked localStorage on the console, after a refresh it still works, but after refreshing and then clicking on another article, it resets to whatever the value of this article is)
I didn't put the entire code, as it's insanely long. everything else is working fine, it's just that.
Also, the all of this is contained within one big function
I define let sum =0; at the beginning of the code.
Then, this is the click event.
document.getElementsByClassName('article-rating')[i]
.addEventListener('click', function(event) {
sum = allSource2.reduce((tempSum, val) => tempSum + val);
console.log("article score is now" + " " + sum);
var lastname = localStorage.getItem("overallsum");
localStorage.setItem("overallsum", sum);
});
I also tried to put the var lastname = localStorage.getItem("overallsum"); at the beginning of the code, when the first function but no luck.
Thanks a lot for your help!
and apologies for any formatting issues, I'm super new to this.
Each time you click the event the overallsum is getting set and that is the problem. If the overallsum is a one time store to the local storage then you can check if the value of overallsum is null, and if so store the value for the first time.
Example:
if (localStorage.getItem("overallsum") === null) {
localStorage.setItem("overallsum", sum);
}
Otherwise, if the overallsum is something, then for every individual article you could 2D array and then set the value with the same conditional check.

Save highscore in localstorage (Javascript snake game)

So the problem I'm having is rather simple and yet I can't seem to get it to work within all the functions.
I simply want the highscore to be saved in the localstorage and automatically updated when the game is over.
I'm thankful for any specific solutions! Thanks!
Bonus question: The game should work on android (cordova) - hence the button controls. However, there seems to be a short delay when tapping a button. This is not the case when using the keyboard. How can I solve this?
You can just use window.localStorage object.
window.localStorage.setItem('highscore', JSON.stringify({userName: 'test', score: 100500}));
var score = window.localStorage.getItem('highscore')
if(score){
var scoreObj = JSON.parse(score);
console.log(scoreObj.score);
}

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

how to implement javascript localStorage

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.

Categories

Resources