Quick and dirty internationalization and localization support in Cocos2d-x

The idea here was to use rapidjson which is part of the cocos2d-x distribution to easily load a set of strings and store references to corresponding fonts for different languages.

The language strings are stored in separate json/javascript files(shown below as one) and reloaded when required.

[js] {
“en”: {
“hello”: “Welcome to the wonderful world of cocoss 2D X “,
“help” : “Press space to change language”
},
“hi” : {
“hello”: “เค•เฅ‹เค•เฅ‹เคธ 2 เคกเฅ€ เคเค•เฅเคธ เค•เฅ€ เคถเคพเคจเคฆเคพเคฐ เคฆเฅเคจเคฟเคฏเคพ เคฎเฅ‡เค‚ เค†เคชเค•เคพ เคธเฅเคตเคพเค—เคค เคนเฅˆ”,
“help” : “เคญเคพเคทเคพ เคฌเคฆเคฒเคจเฅ‡ เค•เฅ‡ เคฒเคฟเค เคธเฅเคชเฅ‡เคธเคฌเคพเคฐ เคฆเคฌเคพเคเค‚”
},
“ml” : {
“hello”: “Cocoss 2D X เดจเตเดฑเต† เด…เดคเตเดญเตเดคเด•เดฐเดฎเดพเดฏ เดฒเต‡เดพเด•เดคเตเดคเดฟเดฒเต‡เด•เตเด•เต เดธเตเดตเดพเด—เดคเด‚”,
“help” : “เดญเดพเดท เดฎเดพเดฑเตเดฑเดพเตป เดธเตเดชเต†เดฏเตเดธเตเดฌเดพเตผ เด…เดฎเตผเดคเตเดคเตเด•”
}
}
[/js]

All one needs to do is to load the fonts using the loadUIFonts function and call the setUILanguage function. Which sets the language and also calls the loadStrings function, this loads the strings for the current language and stores it internally.

[cpp] void GameResources::loadStrings(std::string defaultLangauge) {

// json file containing strings for multiple languages
std::string filename = “ui/strings/” + defaultLangauge + “.json”;
std::string data = cocos2d::FileUtils::getInstance()->getStringFromFile(cocos2d::FileUtils::getInstance()->fullPathForFilename(filename));
gameStrings.Parse(data.c_str());

settingsUILanguage = defaultLangauge;

}
[/cpp]

The getUIString function retrieves the appropriate value for the key for the current set language.

[cpp] const rapidjson::Value& v = gameStrings[langauge.c_str()];
return v[key.c_str()].GetString();
[/cpp]

What would probably be interesting is to do something like what Drupal does, have a “t” function that uses the string in English as the key. That will have to wait for another post ๐Ÿ™‚ I’m sure there are many other ways of pulling this off, but this seems to work well for me for now, so I’ll stick with it till a new problem crops up.

You can fork it or download it here. This is how the project looks and works.

This post was inspired by a conversationย on #cocos2dx on chat.gamedev.in ย – Feel free to join like minded game developers and artsits for more such interesting conversations.