Reputation:
I finished a quizgame tutorial in JavaScript but I would like to enchance it now by adding a highscore to it.
The highscore will contain usernames and their score. I do not wish to save the data to a database but instead an external file. The reason is because I want to be able to play even if you are offline.
Here is the code that appears when you have finished the quiz and it calculates your score:
function _(x){
return document.getElementById(x);
}
function thequestion(){
pingvin = _("pingvin");
if(pos >= questions.length){
pingvin.innerHTML = "<h2>You achieved "+correct+" of "+questions.length+" questions correct</h2>";
_("pingvin_status").innerHTML = "Your Quest Has Come To An End";
pos = 0;
correct = 0;
return false;
}
I guess that when you have finished the quest an input field and a submitt button should appear. When clicked the values of the score and the input field get stored inside a txt-file. This is what I need help with and I would appreciate if anyone could take some time and help me out.
Upvotes: 0
Views: 1709
Reputation: 5116
I suggest you use localStorage. You can't save a file directly, with Javascript, with a few exceptions, like Chrome's Storage API.
Here are the basics of reading and writing data with localStorage. You want to make an array of scores, convert the array into JSON, and then when you're reading data, you parse the JSON that you saved, and somehow display the scores you saved.
if(localStorage){ // make sure the browser supports localStorage
// WRITING DATA
// sample array of scores
var scores = [{"Player 1" : 1000}, {"Player 2":900}, {"Player 3": 800}];
// save the data under the key "scores"
localStorage.setItem("scores", JSON.stringify(scores));
// READING DATA
// if localStorage contains something under the key "scores"
if(localStorage.getItem("scores") != null)
{
// read the data saved in localStorage
var data = localStorage.getItem("scores");
// turn the data from JSON into an array.
var scores = JSON.parse(data);
}
}
Upvotes: 3