first commit
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* I18n.js
|
||||
* Internationalization module for Tank Adventure.
|
||||
* Auto-detects language from WeChat system info.
|
||||
* Supports {variable} placeholder interpolation.
|
||||
*/
|
||||
|
||||
const zhLang = require('./zh');
|
||||
const enLang = require('./en');
|
||||
|
||||
// ============================================================
|
||||
// Language Detection
|
||||
// ============================================================
|
||||
let _currentLang = 'en'; // default fallback
|
||||
|
||||
try {
|
||||
const sysInfo = wx.getSystemInfoSync();
|
||||
const lang = (sysInfo.language || '').toLowerCase();
|
||||
// zh_CN, zh_TW, zh_HK, etc.
|
||||
if (lang.startsWith('zh')) {
|
||||
_currentLang = 'zh';
|
||||
}
|
||||
} catch (e) {
|
||||
// Fallback to English if wx API is unavailable
|
||||
_currentLang = 'en';
|
||||
}
|
||||
|
||||
const _langPacks = {
|
||||
zh: zhLang,
|
||||
en: enLang,
|
||||
};
|
||||
|
||||
// ============================================================
|
||||
// Translation Function
|
||||
// ============================================================
|
||||
|
||||
/**
|
||||
* Get translated text by key.
|
||||
* Supports {variable} placeholder interpolation.
|
||||
*
|
||||
* @param {string} key - The translation key, e.g. 'menu.title'
|
||||
* @param {Object} [params] - Optional parameters for interpolation
|
||||
* @returns {string} The translated text
|
||||
*
|
||||
* @example
|
||||
* t('menu.title') // => '坦克探险' or 'Tank Adventure'
|
||||
* t('pvp.hp', { count: 3 }) // => '生命 x3' or 'HP x3'
|
||||
*/
|
||||
function t(key, params) {
|
||||
// Try current language first
|
||||
let text = _langPacks[_currentLang] && _langPacks[_currentLang][key];
|
||||
|
||||
// Fallback to English
|
||||
if (text === undefined && _currentLang !== 'en') {
|
||||
text = _langPacks.en[key];
|
||||
}
|
||||
|
||||
// Fallback to key itself
|
||||
if (text === undefined) {
|
||||
return key;
|
||||
}
|
||||
|
||||
// Interpolate {variable} placeholders
|
||||
if (params) {
|
||||
text = text.replace(/\{(\w+)\}/g, (match, name) => {
|
||||
return params[name] !== undefined ? String(params[name]) : match;
|
||||
});
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current language code.
|
||||
* @returns {string} 'zh' or 'en'
|
||||
*/
|
||||
function getLang() {
|
||||
return _currentLang;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the language manually (for testing or future settings).
|
||||
* @param {string} lang - 'zh' or 'en'
|
||||
*/
|
||||
function setLang(lang) {
|
||||
if (_langPacks[lang]) {
|
||||
_currentLang = lang;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { t, getLang, setLang };
|
||||
Reference in New Issue
Block a user