Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save gameplay in localStorage

Tags:

javascript

I have this code:

Storage.prototype.setObj = function(key, obj) {
    return this.setItem(key, JSON.stringify(obj))
}
Storage.prototype.getObj = function(key) {
    return JSON.parse(this.getItem(key))
}
function onReady() {
    if (localStorage["piecesArray"]) {
        piecesArray = new Array();
        piecesArray.length = 0; 
        piecesArray = localStorage.getObj("piecesArray");
    } else {
        piecesArray = new Array();
    }
    can = document.getElementById('myCanvas');
    ctx = can.getContext('2d');         
    img = new Image();
    img.onload = onImage1Load;
    img.src = "http://www.niagaraparks.com/images/wallpaper/niagarafalls_640x480.jpg";
}

And I want to save the game state in localStorage, and after refreshing the page I want to refresh the game state.

What am I doing wrong?

like image 536
Piszu Avatar asked Jan 25 '26 21:01

Piszu


1 Answers

So, there's two problems I noticed in your fiddle.

First, you have a function you're calling that isn't defined, so you're not running the setObj function.

if (drawHighlight) highlightRect(drawX, drawY);
// liczymy kliknięcia
clickCounter(); // This function doesn't exist
localStorage.setObj("piecesArray", piecesArray);

I added in a dummy clickCounter function for you that doesn't do anything.

Additionally, you were loading up the piecesArray from local storage, but then just overwriting it anyway. Once your image loads, you need to check to see if you already have a piecesArray. I did that like this:

function onImage1Load() {
    var r;
    if (piecesArray.length === 0) {
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < 3; j++) {
                r = new Rectangle(i * blockSize, j * blockSize, i * blockSize + blockSize, j * blockSize + blockSize);
                piecesArray.push(r);
            }
        }

        scrambleArray(piecesArray, 30);
    }
    drawImage();

}

Working Fiddle

like image 64
Colin DeClue Avatar answered Jan 28 '26 11:01

Colin DeClue