I recently developed a Flash Game that I translated to German and English. You can have a look at it here: http://www.bioaschi.ch/?lang=en#/game. You can change the language on the fly in the settings menu.
To translate the game, I used the following approach:
I have a custom written Config class that is basically just a registry of key => value pairs. The config class can read from an XML file and also dispatches events when a value changes.
For the game I created 2 different config files. One is the main
config, and then one file containing the translations (called lang
). Them main
config contains a key that specifies the language, eg. lang = en. In game I listen for change events on that key. Whenever that happens, I read/apply the values from the appropriate language.
Here's a small snippet of code that shows how the language is switched in game:
Somewhere in the "Settings" panel code:
Config.getConfig('main').setValue('lang', 'de'); // or 'en'
Then anywhere else where text needs to be localized:
// this is in the construtor or some init method
...
var cfg:Config = Config.getConfig('main');
cfg.addEventListener(ConfigEvent.CONFIG_CHANGE, onConfigChange);
updateText(cfg.getValue('lang', 'en') + '.');
}
private function updateText(langns:String) : void {
var langCfg:Config = Config.getConfig('lang');
this.title.htmlText = langCfg.getValue(langns + "credits.TITLE", "<title>");
this.text.htmlText = langCfg.getValue(langns + "credits.TEXT", "<text>");
_btnClose.label = langCfg.getValue(langns + 'highscore.CLOSE', 'X');
}
private function onConfigChange(evt:ConfigEvent) : void {
if(evt.key == 'lang'){
updateText(evt.value + ".");
}
}
You can have a look at the file that is being loaded by the game here: http://www.bioaschi.ch/game/language.xml
To substitute parts of the text with variables (eg. your score is %d
transforms to your score is 10000
), I suggest you use the excellent Polygonal Datastructures Library. It contains a AS3 implementation of Sprintf.
Instead of having all translations in one file, you could also easily have one single file per language.
For the sake of completeness, here are some code listings:
Wow, this kinda turned out to be a long post, I'm sorry. The approach I took is rather simplistic and doesn't cover the more complicated topics of internationalization, like date formats, number or currency formatting etc. For simple translations it works just fine though.