1

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 distinct 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?

Andy
  • 95
  • 1
  • 7

1 Answers1

0

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.

Kaken Bok
  • 3,395
  • 1
  • 19
  • 21
  • You also may cheet a bit using a ZIP of your levels: http://stackoverflow.com/questions/1053546/howto-embed-images-in-actionscript-3-flex-3-the-right-way/1055867#1055867 – Kaken Bok Jul 30 '11 at 12:30
  • Thanks, this solves half the problem. Is there a way to embed into a hash or other key-value store, so that I didn't need a variable for each level? – Andy Jul 30 '11 at 12:47
  • Definitely no. Here is another approach apart from using the ZIP one: http://stackoverflow.com/questions/3908929/how-to-embed-a-lot-of-images-using-actionscript-3 – Kaken Bok Jul 30 '11 at 12:52