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);
}
Related
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
Sounds complicated, but bear with me. I want to make a simple game in PHP/JS/Jquery. The data is being retrieved from the database in JSON. It is an array of questions, hints, answers & the correct answer.
I want to present all the questions on a single php page, one by one. The user can click any button, when he/she clicks the right answer, a green checkmark is shown & the score is updated. The next question is shown and so on. If the user runs out of time before attempting all 4 buttons, a red cross is shown, the score stays the same. The next question is shown.
Now, I can loop through the questions, but I cannot wait on user input, since JS is async, so I have to add callbacks. I can't think of a way to code it up in a way that makes verification easy without compromising the correct answer.
Here is some barebones code that gets the data from the db, and uses regular loops, no callbacks. How do I tweak this to get it to do what I want?
// Global variables
var QNAData = null;
var currentQuestionIndex = null;
$(document).ready(function(){
// Get question & answer data from the db
function reqListener () {
QNAData = jQuery.parseJSON(this.responseText);
StartGame(QNAData);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "GetNewGameData.php", true);
oReq.send();
}); // end document.ready
function StartGame(QNAData)
{
// Loop through the questions
for (stageIndex=0; stageIndex < QNAData.length; stageIndex++) {
currentQuestionIndex = stageIndex;
// Populate the Question and Answer text containers
$("#QuestionTextContainer").html(QNAData[stageIndex]['QuestionText']);
$('#QuestionShortHintContainer').text(QNAData[stageIndex]['QuestionHintShort']);
$('#QuestionLongHintContainer').text(QNAData[stageIndex]['QuestionHintLong']);
$("#Answer1TextContainer").html(QNAData[stageIndex]['AllAnswersText'][0]);
$("#Answer2TextContainer").html(QNAData[stageIndex]['AllAnswersText'][1]);
$("#Answer3TextContainer").html(QNAData[stageIndex]['AllAnswersText'][2]);
$("#Answer4TextContainer").html(QNAData[stageIndex]['AllAnswersText'][3]);
// Set up the countdown timer after the answers have been displayed
$('#countdown-container').hide().fadeIn().ClassyCountdown();
}
First of all, using only one question and changing text and answers is very troublesome. I would recommend building HTML for all questions, and only show the current one (control via JS). Your life will be much easier having to just control visibility and not constantly updating text and values around. This will also help you in not changing values and text while user is clicking on answer, since the HTML is different.
Second, there's no way around callbacks in JS. Accept it. You'll need click handlers, change handlers, timeout handlers, ajax handler, all callbacks.
As for the user timeout problem, here's how I'd do it:
You want to use setTimeout. On the function for its callback, make it the function that displays the timeout cross.
The return value of it is a handler, which you can store in a variable.
In case the user press button to check answer for example, or to move to other questions, you can use clearTimeout and pass the stored timeout, so it won't run.
Then create a new one for the new question being displayed.
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
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.
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