Question

I am trying to make this game in Flash / AS3 which goes on as long as the player doesn't lose. The longer the player goes for, the higher his/her score is.

I also need to save the high score, so I decided to save this using a text file. I open the file with mode UPDATE so that if the file doesn't exist it is created and I can read/write. But obviously, when the file is first created it is empty so when I try to read the data in the file it returns error #2030. It then doesn't execute any of the code that involves the file stream. Also even if there is a number in the file, I can't read it because the program doesn't know how many digits the high score is going to be. This is the code that I am using:

var file:File = File.documentsDirectory;
file = file.resolvePath("hscore.txt");
var fileStream:FileStream = new FileStream();
fileStream.openAsync(file, FileMode.UPDATE);
var buffer:Number = fileStream.readInt();
if (buffer > 0){
    if (score > buffer){
        buffer = score;
        fileStream.writeInt(buffer);
    }
    else{
        highScore.text = String(buffer);
    }
}
else{
    fileStream.writeInt(score);
    highScore.text = String(score);
}
fileStream.close();

I have tried using readUTF/writeUTF and readUTFBytes/writeUTFBytes instead of readInt/writeInt, but with readUTF/writeUTF it just gives me the same error and with readUTFBytes/writeUTFBytes the program would need to know how many digits the high score is. If anyone knows how to get around a 2030 error or knows how to read a file without reaching the end or knows how to see how many digits there are in the file please let me know.

I could have added a line to the file telling the program how many digits there are but when the file is new the file stream would reach the end of the file while trying to read the number of digits. I am also open to other methods of storing the high score and reading it later. Thanks in advance for any help.

P.S. I am trying to do this with Adobe AIR for Android

Was it helpful?

Solution

Answering my own question based on help from comments:

  1. Open and close the file without making any changes so that if file doesn't exist the file is created.
  2. Check the file size, 1 byte = 1 digit (stored in UTF-8).
  3. Read appropriate number of bytes, make changes as needed, etc. ]
  4. Error 2030 avoided! :D

Thanks to @Vesper and @Craig

*****Edit*****
Realised you don't need to close the file in the first step...

*****Edit2*****
Not UTF-8, ASCII

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top