简体   繁体   中英

Scores using Filestream (AS3 - Air for Android)

I've started a little board game for android and i've been researching ways to permanently save scores. Everytime the user wins a game against the "AI", he/she gains a point (which can be used to unlock special pawns and boardgames). I tries with SharedObject but apparently they can be erased if user delete game data (or something). So I went with Filestream. I read a few posts online about it and thought I understood, but since it's not working for me, I guess I didn't :).

var wonGames:int; //variable I want to save

function writeObject():void { //First function to create/write in the file
    var score1:Object = new Object();
    score1.value =  wonGames; //value of object = variable value
    trace(score1.value);

    var file:File = File.applicationStorageDirectory.resolvePath("score1.file");
    var fileStream:FileStream = new FileStream(); 
    fileStream.open(file, FileMode.WRITE);
    fileStream.writeObject(score1);
    fileStream.close();
};


function readObject():void { //second function to read the file and modify the variable.

    var file:File = File.applicationStorageDirectory.resolvePath("score1.file");
    if (!file.exists) {
        return;
    }
    var fileStream:FileStream = new FileStream();
    fileStream.open(file, FileMode.READ);
    var score1:Object = fileStream.readObject(); 
    wonGames=score1.value;//update the variable
    fileStream.close();
};

btn26.addEventListener(MouseEvent.CLICK, fnBtn26);
function fnBtn26(e: Event): void { //third function, where the winning happens
    if (winP1.currentFrame==1){ //game won
        winP1.nextFrame(); //victory screen
        readObject(); //get old value for score 1
        wonGames=wonGames+1; //update it
        trace("WonGames= "+ wonGames);
        writeObject(); //write it in file
    }
};

wonGames is updated, but when I close the app and restart it, it is back to 0. If you guys know what's wrong (or have another way to achieve my goal), I'm all ears. Thank you.

Probably “value” from wonGames=score1.value; not exists and FP evaluate it to undefined and trying to assign it to int (wonGames) return 0; In WriteObject try:

  fileStream.writeInt(score1);

and readObject try:

  wonGames =  fileStream.readInt(); 

// wonGames=score1.value;//update the variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM