Translated menu labels, instructions and credits, and Shift+F12 to English

game_menu takes optionLabels, a dictionary or a function giving what to
say for each of a game's own options, so a translated game no longer
hears its option names read out in English. A function is asked each
time, so labels follow a change of language. The option is still what
game_menu returns.

instructions() and credits() read files/instructions.<language>.txt and
files/credits.<language>.txt when there is one for the language being
spoken, falling back to the language without its region and then to
English, and read them as UTF-8. translated_file() and language_code()
do the same for a game's own files.

Shift+F12 in game_menu, instruction_menu and learn_sounds goes back to
English and says so in English. set_language_reset() lets a game switch
its own text and remember the choice at the same time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Storm DragonandClaude Opus 5.5 committed 2026-11-24 20:52:37 -05:00
1 parent e6505790c2
commit 8d354dbe1c
5 files changed
+245 -17

No files matched your search

+23 -1
View File
@@ -406,6 +406,14 @@ choice = sg.game_menu(sounds, None, "practice_mode", soundDescriptions=soundDesc
# learn_sounds can also be called directly
sg.learn_sounds(sounds, soundDescriptions)
# A game that translates its menu says what to speak for its own options.
# game_menu still returns the option, so the game's code doesn't change.
# A function is asked each time an option is spoken, so labels follow a
# change of language; a dictionary works too, as {"load_game": _("Load game")}.
labels = {"load_game": N_("Load game"), "language": N_("Language")}
choice = sg.game_menu(sounds, None, "load_game", "language",
optionLabels=lambda option: _(labels[option]))
```
@@ -605,7 +613,21 @@ The text the library speaks itself, such as the text box's "Submitted" and "Begi
sg.set_language("de")
```
Without a translation for that language, the library speaks English. Translations live in `locales/<language>/LC_MESSAGES/libstormgames.po`. `tools/update-translations.sh` extracts the text into `locales/libstormgames.pot` and compiles every translation, and `tools/update-translations.sh new de` starts one. It needs GNU gettext. A game bundled with PyInstaller must include the `locales` folder next to the library's code, as `libstormgames/locales`.
Without a translation for that language, the library speaks English.
`sg.instructions()` and `sg.credits()` read the file in the language being spoken when there is one, as `files/instructions.de.txt` beside `files/instructions.txt`, and fall back to the language without its region, so `de_AT` reads `instructions.de.txt`. Otherwise they read the English file. `sg.translated_file(path)` finds such a file for a game's own text files, and `sg.language_code()` says which language is being spoken: the one set, or else the system's.
Shift+F12 in `game_menu`, `instruction_menu` and `learn_sounds` goes back to English, for anyone stuck in a language they can't understand, and says "Language set to English." in English. By itself it switches only the library's text. A game with its own translations tells the library what to do instead, so it switches the game's text too and remembers the choice:
```python
def reset_to_english():
set_game_language("en") # the game's own translations, which also call sg.set_language("en")
save_language_choice("en")
sg.set_language_reset(reset_to_english)
```
Translations live in `locales/<language>/LC_MESSAGES/libstormgames.po`. `tools/update-translations.sh` extracts the text into `locales/libstormgames.pot` and compiles every translation, and `tools/update-translations.sh new de` starts one. It needs GNU gettext. A game bundled with PyInstaller must include the `locales` folder next to the library's code, as `libstormgames/locales`.
## Advanced Examples
+2 -2
View File
@@ -40,7 +40,7 @@ from .sound import (
)
# Translations of the library's own text
from .i18n import set_language
from .i18n import set_language, set_language_reset, language_code, translated_file
# Import Speech class and functions
from .speech import (messagebox, speak, Speech, speak_previous, speak_current, speak_next, set_text_display,
@@ -115,7 +115,7 @@ __all__ = [
'remove_speech_listener',
# Translations
'set_language',
'set_language', 'set_language_reset', 'language_code', 'translated_file',
# Scoreboard
'Scoreboard',
+59 -1
View File
@@ -13,6 +13,10 @@ that lets players choose a language calls set_language() with the same
code it uses for its own text, so the library and the game always speak
the same language.
Shift+F12 in the library's menus goes back to English, and says so in
English. A game passes set_language_reset() what to do then, so it can
switch its own text and remember the choice too.
Mark text with _() where it is spoken, ngettext() where it depends on a
number, and N_() for tables defined before the language is chosen, passed
through _() when spoken. Placeholders are always named, as in
@@ -23,8 +27,15 @@ import gettext
import os
domain = "libstormgames"
english = "en"
localeDirectory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "locales")
translation = gettext.NullTranslations()
# The language a game chose, or None while following the system.
currentLanguage = None
# What Shift+F12 in the menus calls to go back to English; None just switches the library.
languageResetHandler = None
# Said after Shift+F12, in English whatever the language was, so it is never translated.
languageResetMessage = "Language set to English."
def set_language(language=None, directory=None):
@@ -37,11 +48,58 @@ def set_language(language=None, directory=None):
directory (str): Where to find translations, for testing one that is
not part of the library yet. Defaults to the library's own locales.
"""
global translation
global translation, currentLanguage
currentLanguage = language
languages = [language] if language else None
translation = gettext.translation(domain, directory or localeDirectory, languages=languages, fallback=True)
def language_code():
"""The language being spoken: the one a game chose, else the system's, as "de" or "pt_BR"."""
if currentLanguage:
return currentLanguage
# The same settings gettext follows, in the same order.
for variable in ("LANGUAGE", "LC_ALL", "LC_MESSAGES", "LANG"):
value = os.environ.get(variable)
if value:
code = value.split(":")[0].split(".")[0].split("@")[0]
if code and code not in ("C", "POSIX"):
return code
return english
def translated_file(path):
"""A text file in the language being spoken, as <name>.<language><extension> beside it, such as
files/instructions.de.txt for files/instructions.txt, or path itself when there is none."""
stem, extension = os.path.splitext(path)
code = language_code()
for candidate in (code, code.split("_")[0]):
if candidate == english:
continue
translated = f"{stem}.{candidate}{extension}"
if os.path.isfile(translated):
return translated
return path
def set_language_reset(handler=None):
"""Choose what Shift+F12 in the library's menus does, the way back for anyone stuck in a
language they cannot understand. handler is called with no arguments, and should switch
the game and the library to English and remember that, as by calling set_language("en").
Without one, Shift+F12 switches only the library's own text to English."""
global languageResetHandler
languageResetHandler = handler
def reset_language():
"""Go back to English, as Shift+F12 does in the menus. Returns the English message to speak."""
if languageResetHandler:
languageResetHandler()
else:
set_language(english)
return languageResetMessage
def _(message):
return translation.gettext(message)
+50 -12
View File
@@ -24,10 +24,10 @@ from .sound import adjust_master_volume, adjust_bgm_volume, adjust_sfx_volume, p
from .display import display_text
from .scoreboard import Scoreboard
from .services import PathService, ConfigService
from .i18n import _, N_
from .i18n import _, N_, reset_language, translated_file
# What game_menu() says for its own items. A game's own items are spoken
# as they are given, with underscores read as spaces.
# as its optionLabels say, or as they are given with underscores read as spaces.
standardItemNames = {
"play": N_("play"),
"high_scores": N_("high scores"),
@@ -38,6 +38,26 @@ standardItemNames = {
"exit_game": N_("exit game"),
}
def is_language_reset(event):
"""Shift+F12, which in every menu goes back to English."""
return event.key == pygame.K_F12 and bool(pygame.key.get_mods() & pygame.KMOD_SHIFT)
def option_label(option, optionLabels=None):
"""What game_menu says for option: the library's name for its own items, else optionLabels' label for it,
else the option with underscores read as spaces."""
if option in standardItemNames:
return _(standardItemNames[option])
if callable(optionLabels):
label = optionLabels(option)
elif optionLabels:
label = optionLabels.get(option)
else:
label = None
return label if label else option.replace("_", " ")
def instruction_menu(sounds, instruction_text, *options):
"""Display a menu with an instruction announcement at the top.
@@ -73,7 +93,10 @@ def instruction_menu(sounds, instruction_text, *options):
event = pygame.event.wait()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if is_language_reset(event):
speech.speak(reset_language())
last_spoken = current_index
elif event.key == pygame.K_ESCAPE:
return None
elif event.key in [pygame.K_DOWN, pygame.K_s]:
moved = False
@@ -126,7 +149,7 @@ def instruction_menu(sounds, instruction_text, *options):
pygame.event.clear()
time.sleep(0.001)
def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None):
def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None, optionLabels=None):
"""Display and handle the main game menu with standard and custom options.
Standard menu structure:
@@ -155,6 +178,13 @@ def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None)
identifiers are used for actions and returned unchanged.
soundDescriptions (dict, optional): What each sound means, passed on to
learn_sounds. See learn_sounds for the format.
optionLabels (dict or function, optional): What to say for each custom
option, for a game that translates its menu: a dictionary from
option to label, or a function given the option that returns its
label. A function is asked each time the option is spoken, so its
labels follow a change of language. An option without a label is
spoken with underscores read as spaces. The option itself is
still what game_menu returns.
Returns:
str: Selected menu option or "exit" if user pressed escape
@@ -206,7 +236,7 @@ def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None)
while loop:
if currentIndex != lastSpoken:
option = allOptions[currentIndex]
speech.speak(_(standardItemNames[option]) if option in standardItemNames else option.replace("_", " "))
speech.speak(option_label(option, optionLabels))
lastSpoken = currentIndex
event = pygame.event.wait()
@@ -231,7 +261,10 @@ def game_menu(sounds, playCallback=None, *customOptions, soundDescriptions=None)
adjust_sfx_volume(-0.1)
# Regular menu navigation (no Alt required)
else:
if event.key == pygame.K_ESCAPE:
if is_language_reset(event):
speech.speak(reset_language())
lastSpoken = currentIndex
elif event.key == pygame.K_ESCAPE:
# Exit with fade if music is playing
exit_game(500 if pygame.mixer.music.get_busy() else 0)
elif event.key == pygame.K_HOME:
@@ -511,7 +544,9 @@ def learn_sounds(sounds, descriptions=None):
event = pygame.event.wait()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if is_language_reset(event):
speech.speak(reset_language())
elif event.key == pygame.K_ESCAPE:
returnToMenu = True
# Sound navigation
@@ -561,11 +596,13 @@ def learn_sounds(sounds, descriptions=None):
def instructions():
"""Display game instructions from file.
Reads and displays instructions from 'files/instructions.txt'.
Reads and displays instructions from 'files/instructions.txt', or from
its translation in the language being spoken, such as
'files/instructions.de.txt', when there is one.
If file is missing, displays an error message.
"""
try:
with open('files/instructions.txt', 'r') as f:
with open(translated_file('files/instructions.txt'), 'r', encoding='utf-8') as f:
info = f.readlines()
except:
info = [_("Instructions file is missing.")]
@@ -574,12 +611,13 @@ def instructions():
def credits():
"""Display game credits from file.
Reads and displays credits from 'files/credits.txt'.
Adds game name header before displaying.
Reads and displays credits from 'files/credits.txt', or from its
translation in the language being spoken, such as 'files/credits.de.txt',
when there is one. Adds game name header before displaying.
If file is missing, displays an error message.
"""
try:
with open('files/credits.txt', 'r') as f:
with open(translated_file('files/credits.txt'), 'r', encoding='utf-8') as f:
info = f.readlines()
pathService = PathService.get_instance()
+111 -1
View File
@@ -4,8 +4,10 @@ Run from the library root: python -m unittest discover -s tests -v
"""
import importlib.util
import os
from pathlib import Path
import sys
import tempfile
from types import ModuleType, SimpleNamespace
import unittest
from unittest.mock import Mock, patch
@@ -35,6 +37,8 @@ def load_menu():
menu = importlib.util.module_from_spec(spec)
with patch.dict(sys.modules, modules):
spec.loader.exec_module(menu)
# The real translations module, loaded alongside, so tests can see the language change.
menu.i18nModule = sys.modules[f"{packageName}.i18n"]
return menu
@@ -46,7 +50,7 @@ class MenuTestCase(unittest.TestCase):
menu.Scoreboard.has_high_scores.return_value = highScores
menu.pygame = Mock()
for name in dir(pygame):
if name.startswith("K_") or name in ["KEYDOWN", "QUIT", "KMOD_ALT"]:
if name.startswith("K_") or name in ["KEYDOWN", "QUIT", "KMOD_ALT", "KMOD_SHIFT"]:
setattr(menu.pygame, name, getattr(pygame, name))
menu.pygame.key.get_mods.return_value = 0
menu.pygame.mixer.music.get_busy.return_value = True
@@ -182,5 +186,111 @@ class LearnSoundsTests(MenuTestCase):
sounds["candy"].play.assert_not_called()
class TranslationTests(MenuTestCase):
resetMessage = "Language set to English."
def test_option_labels_from_a_dictionary_are_spoken_and_the_option_returned(self):
menu = self.make_menu([pygame.K_DOWN, pygame.K_DOWN, pygame.K_RETURN])
result = menu.game_menu({}, None, "load_game", optionLabels={"load_game": "Partie laden"})
self.assertEqual(result, "load_game")
self.assertEqual(self.spoken_labels(menu), ["play", "high scores", "Partie laden"])
def test_an_option_without_a_label_is_spoken_as_before(self):
menu = self.make_menu([pygame.K_DOWN, pygame.K_DOWN, pygame.K_DOWN, pygame.K_RETURN])
result = menu.game_menu({}, None, "load_game", "practice_mode", optionLabels={"load_game": "Partie laden"})
self.assertEqual(result, "practice_mode")
self.assertEqual(self.spoken_labels(menu)[-1], "practice mode")
def test_shift_f12_calls_the_games_reset_and_labels_follow_the_new_language(self):
keyCodes = [pygame.K_DOWN, pygame.K_DOWN, pygame.K_F12, pygame.K_UP, pygame.K_DOWN, pygame.K_RETURN]
menu = self.make_menu(keyCodes)
menu.pygame.key.get_mods.return_value = pygame.KMOD_SHIFT
state = {"language": "de"}
labels = {"de": "Partie laden", "en": "Load game"}
handler = Mock(side_effect=lambda: state.update(language="en"))
menu.i18nModule.set_language_reset(handler)
result = menu.game_menu({}, None, "load_game", optionLabels=lambda option: labels[state["language"]])
self.assertEqual(result, "load_game")
handler.assert_called_once_with()
self.assertEqual(self.spoken_labels(menu),
["play", "high scores", "Partie laden", self.resetMessage, "high scores", "Load game"])
def test_shift_f12_without_a_game_reset_switches_the_library_to_english(self):
menu = self.make_menu([pygame.K_F12, pygame.K_RETURN])
menu.pygame.key.get_mods.return_value = pygame.KMOD_SHIFT
menu.i18nModule.set_language("de")
self.assertEqual(menu.game_menu({}), "play")
self.assertEqual(menu.i18nModule.currentLanguage, "en")
self.assertIn(self.resetMessage, self.spoken_labels(menu))
def test_f12_without_shift_does_nothing(self):
menu = self.make_menu([pygame.K_F12, pygame.K_RETURN])
handler = Mock()
menu.i18nModule.set_language_reset(handler)
self.assertEqual(menu.game_menu({}), "play")
handler.assert_not_called()
self.assertEqual(self.spoken_labels(menu), ["play"])
def test_shift_f12_in_an_instruction_menu_neither_chooses_nor_leaves(self):
menu = self.make_menu([pygame.K_F12, pygame.K_DOWN, pygame.K_RETURN])
menu.pygame.key.get_mods.return_value = pygame.KMOD_SHIFT
self.assertEqual(menu.instruction_menu({}, "Wähle:", "Geschichte"), "Geschichte")
self.assertEqual(self.spoken_labels(menu), ["Wähle:", self.resetMessage, "Geschichte"])
def test_shift_f12_in_learn_sounds_keeps_the_menu_open(self):
menu = self.make_menu([pygame.K_F12, pygame.K_DOWN, pygame.K_ESCAPE])
menu.pygame.key.get_mods.return_value = pygame.KMOD_SHIFT
self.assertEqual(menu.learn_sounds({"candy": Mock(), "guts": Mock()}), "menu")
self.assertEqual(self.spoken_labels(menu), ["Root directory: candy, 1 of 2", self.resetMessage, "guts, 2 of 2"])
class TranslatedFileTests(unittest.TestCase):
def setUp(self):
self.menu = load_menu()
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
os.makedirs(os.path.join(folder.name, "files"))
for name, text in [("instructions.txt", "English guide"), ("instructions.de.txt", "Deutsche Anleitung"),
("credits.txt", "English credits"), ("credits.pt_BR.txt", "Créditos")]:
with open(os.path.join(folder.name, "files", name), "w", encoding="utf-8") as textFile:
textFile.write(text)
previousFolder = os.getcwd()
os.chdir(folder.name)
self.addCleanup(os.chdir, previousFolder)
self.menu.PathService.get_instance.return_value.gameName = "Game"
def shown_text(self):
return "".join(self.menu.display_text.call_args.args[0])
def test_instructions_in_the_chosen_language_or_its_base_language(self):
for language in ["de", "de_AT"]:
with self.subTest(language=language):
self.menu.i18nModule.set_language(language)
self.menu.instructions()
self.assertEqual(self.shown_text(), "Deutsche Anleitung")
def test_without_a_translation_the_english_file_is_read(self):
self.menu.i18nModule.set_language("fr")
self.menu.instructions()
self.assertEqual(self.shown_text(), "English guide")
self.menu.credits()
self.assertEqual(self.shown_text(), "Game\nEnglish credits")
def test_credits_follow_the_system_language_when_none_is_chosen(self):
self.menu.i18nModule.set_language(None)
with patch.dict(os.environ, {"LANG": "pt_BR.UTF-8"}, clear=True):
self.menu.credits()
self.assertEqual(self.shown_text(), "Game\nCréditos")
def test_system_language_codes_drop_encoding_and_ignore_c(self):
i18n = self.menu.i18nModule
i18n.set_language(None)
cases = [({"LANGUAGE": "pt_BR:pt", "LANG": "de_DE.UTF-8"}, "pt_BR"), ({"LC_ALL": "de_DE.UTF-8@euro"}, "de_DE"),
({"LANG": "C.UTF-8"}, "en"), ({}, "en")]
for environment, expected in cases:
with self.subTest(environment=environment), patch.dict(os.environ, environment, clear=True):
self.assertEqual(i18n.language_code(), expected)
if __name__ == "__main__":
unittest.main()