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” : “ഭാഷ മാറ്റാൻ സ്പെയ്സ്ബാർ അമർത്തുക”

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));

settingsUILanguage = defaultLangauge;


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();

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.