How should I embed external data files for run-time retrieval in ActionScript 3? Architecture help needed
I'm writing a Flash game where the game levels are saved in small plain-text files, which I want to embed in the swf file. My current solution has a d开发者_C百科istinct code smell in its repetition, and I'm certain that there is a better way. My code is basically:
In a LevelLoader class, embed all the levels
[Embed( source="levels/1.dat", mimeType="application/octet-stream" )]
protected var level1:Class;
[Embed( source="levels/2.dat", mimeType="application/octet-stream" )]
protected var level2:Class;
When the level needs to be loaded, read the string:
var bytes:ByteArray;
if ( levelNumber == 1 ) {
bytes = new level1();
} else if ( levelNumber == 2 ) {
bytes = new level2();
}
var levelStr:String = bytes.readMultiByte( bytes.bytesAvailable, bytes.endian );
prepareLevel( levelStr );
There are a couple of problems with this approach:
- I have to add a line for embedding each level. Optimally, all files in a folder would be automatically embedded.
- A level can't be "prepared" from a string. I'd like to be able to pass LevelLoader a level number or level name as a string.
- I think that all strings are stored in memory rather than on disk.
How could I program this "correctly"? Is ActionScript 3 capable of solving this problem?
You will need to embed each file individually unless you are not deciding to load the files on demand. Even if it is possible to tell the compiler to include certain non script files that are not referenced in code, you need to link these files to variables.
However, you may dynamize the access to your level files.
function startLevel(levelId : uint) : void {
var bytes : ByteArray = new (this["level" + levelId])();
...
prepareLevel(levelStr);
}
Of course, all your levels are stored in memory. To avoid it you could load the level data using URLLoader.
精彩评论