ItsArkanix
ItsArkanix

Reputation: 21

How to keep the value of a variable when the page is refreshed

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.

Upvotes: 2

Views: 231

Answers (1)

Amit Mondal
Amit Mondal

Reputation: 359

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:

Note: I am considering that you are storing the data(point1 and point2) in the localStorage

Upvotes: 1

Related Questions