Storm DragonandClaude Opus 5.5 74406b9f78 Rebuild the air horn from a recording of a real handheld one.
The old horn was two reeds a major third apart, which is how car horns are
built, and it sounded like one. A canned air horn is a single reed near D5
whose second harmonic is as strong as its fundamental. For its first 100
milliseconds the reed hasn't caught: the pitch jumps about above the note, air
rushes through and it blares brighter, settling by 300 milliseconds. Then it
holds with its harmonics wavering and sags a little in pitch as the can's
pressure drops.

air_horn takes a seed; the default of 7 is the blast that was approved by ear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 03:51:59 -05:00
2019-12-02 08:45:03 -05:00

libstormgames

A Python library to make creating audio games easier.

Overview

libstormgames provides a comprehensive set of tools for developing accessible games with audio-first design. It handles common game development tasks including:

  • Sound and music playback with positional audio
  • Text-to-speech integration
  • Configuration management
  • Score tracking and high score tables
  • Input handling and keyboard controls
  • Menu systems and text display
  • GUI initialization
  • Sound effects and music generated from code, so a game needs no sound files

AI assistants building games with the library, or working on it, should read AI-README.md first.

Installation

Requirements

  • pygame>=2.0.0
  • pyperclip>=1.8.0
  • requests>=2.25.0
  • pyxdg>=0.27
  • setproctitle>=1.2.0
  • numpy>=1.19.0
  • wxpython
  • scipy (only for generated sounds, libstormgames.sfx)

Speech Providers (one required)

  • Linux/Unix: python-speechd or accessible-output2>=0.14
  • Windows/macOS: accessible-output2>=0.14

Install from source

If you are on Linux, check your package manager first to see if the packages in requirements.txt are available.

git clone https://git.stormux.org/storm/libstormgames
cd libstormgames
pip install -e .

Getting Started

You can use libstormgames in two ways: the traditional function-based approach or the new class-based approach.

Traditional Function-Based Approach

#!/usr/bin/env python3
import libstormgames as sg

def main():
    # Initialize the game
    sounds = sg.initialize_gui("My First Audio Game")
    
    # Welcome message
    sg.speak("Welcome to My First Audio Game!")
    
    # Create a scoreboard
    scoreboard = sg.Scoreboard()
    
    # Main game loop
    def play_game():
        sg.speak("Game started!")
        scoreboard.increase_score(10)
        sg.speak(f"Your score is {scoreboard.get_score()}")
        scoreboard.add_high_score()
        return "menu"  # Return to menu after game ends
    
    # Define menu options
    while True:
        choice = sg.game_menu(sounds)
        if choice == "play":
            play_game()

if __name__ == "__main__":
    main()

Modern Class-Based Approach

#!/usr/bin/env python3
import libstormgames as sg

def main():
    # Create and initialize a game
    game = sg.Game("My First Audio Game").initialize()
    
    # Welcome message
    game.speak("Welcome to My First Audio Game!")
    
    # Main game loop
    def play_game():
        game.speak("Game started!")
        game.scoreboard.increase_score(10)
        game.speak(f"Your score is {game.scoreboard.get_score()}")
        game.scoreboard.add_high_score()
        return "menu"
    
    # Define menu options
    while True:
        choice = sg.game_menu(game.sound.get_sounds())
        if choice == "play":
            play_game()

if __name__ == "__main__":
    main()

Library Structure

The library is organized into modules, each with a specific focus:

  • config: Configuration management
  • services: Core services that replace global variables
  • sound: Sound and music playback
  • speech: Text-to-speech functionality
  • scoreboard: High score tracking
  • input: Input handling and dialogs
  • controls: Keyboard and game controller actions, rebinding and rumble
  • controls_menu: The menu where players change their controls
  • display: Text display and GUI functionality
  • menu: Menu systems
  • utils: Utility functions and Game class
  • sfx: Generated sound effects, made from code instead of sound files

Core Classes

Game

The Game class provides a central way to manage all game systems:

# Create and initialize a game
game = sg.Game("My Game").initialize()

# Use fluent API for chaining commands
game.speak("Hello").play_bgm("music/theme")

# Access components directly
game.scoreboard.increase_score(10)
game.sound.play_random("explosion")

# Display text

game.display_text(["Line 1", "Line 2"])

# Clean exit

game.exit()

The initialization process sets up proper configuration paths:

  • Creates game-specific directories if they don't exist
  • Ensures all services have access to correct paths
  • Connects all components for seamless operation

Services

The library includes several service classes that replace global variables:

# Volume service manages all volume settings
volume = sg.VolumeService.get_instance()
volume.adjust_master_volume(0.1)

# Path service manages file paths
paths = sg.PathService.get_instance()
print(paths.game_path)

# Config service manages configuration
config = sg.ConfigService.get_instance()

Config

Handles configuration file management with local and global settings.

# Create a configuration manager
config = sg.Config("My Game")

# Access the local configuration
config.local_config.add_section("settings")
config.local_config.set("settings", "difficulty", "easy")
config.write_local_config()

# Read settings
config.read_local_config()
difficulty = config.local_config.get("settings", "difficulty")

Configuration files are automatically stored in standard system locations:

  • Linux/Unix: ~/.config/storm-games/
  • Windows: %APPDATA%\storm-games\
  • macOS: ~/Library/Application Support/storm-games/

Each game has its own subdirectory based on the game name (lowercase with hyphens), for example, Wicked Quest becomes wicked-quest.

Sound

Manages sound loading and playback with positional audio support.

# Create a sound manager
sound_system = sg.Sound("sounds/")

# Get the dictionary of loaded sounds
sounds = sound_system.get_sounds()

# Play a sound
sg.play_sound(sounds["explosion"])

# Play a sound with positional audio (player at x=5, object at x=10)
channel = sg.obj_play(sounds, "footsteps", 5, 10)

# Update sound position as player or object moves
channel = sg.obj_update(channel, 6, 10)  # Player moved to x=6

# Stop the sound
channel = sg.obj_stop(channel)

# Play background music
sg.play_bgm("sounds/background.ogg")

# Adjust volume
sg.adjust_master_volume(0.1)  # Increase master volume
sg.adjust_bgm_volume(-0.1)    # Decrease background music volume
sg.adjust_sfx_volume(0.1)     # Increase sound effects volume

Height attenuation

Positional sound keeps its existing behavior by default. To opt into height attenuation, pass (x, y) coordinates and use_3d=True. Horizontal distance and vertical separation fade independently. maxElevation sets the vertical range; it defaults to the horizontal range, which is 12 tiles for playback and updates. For example, maxElevation=30 allows a sound 20 tiles overhead to remain audible. Sounds at or beyond either range are silent. Above and below produce identical stereo gains, so this mode does not provide a distinct up/down cue.

channel = sg.obj_play(sounds, "water", (0, 0), (5, 8),
                      use_3d=True, maxElevation=30)
channel = sg.obj_update(channel, (1, 0), (5, 8),
                        use_3d=True, maxElevation=30)

Pass the same options on each position update. They are available on play_sound, obj_play, obj_update, play_directional_sound, and the corresponding Sound methods. Directional playback retains its fixed left/right pan while applying the opt-in horizontal and height attenuation. Scalar positions continue to use the legacy distance calculation.

Both sg.calculate_volume_and_pan() and Sound.calculate_volume_and_pan() accept use_3d, maxDistance, and maxElevation. In elevation mode, range limits must be finite and greater than zero, and coordinates must be finite. Invalid limits raise ValueError. The class uses its own volume service; global functions use the global volume service.

Run the headless regression suite with python -m unittest discover -s tests -v. python test_3d_audio.py runs the positional-sound tests without starting speech, opening a window, or playing live audio. Listening with the intended game and headphones is still needed to judge the usefulness of the height cues.

Speech

Provides text-to-speech functionality using available speech providers.

sg.messagebox(text, sounds=None) presents either a plain text message or a dialogue configuration with an entries list. While either is open, playing background music fades out over 150 ms and pauses. It resumes from the same position and fades back to its previous volume after the message ends, including when a dialogue is skipped. Already paused or stopped music is left alone, and dialogue sound effects still play. If the mixer cannot fade, the library attempts a plain pause and resume; an unavailable mixer does not prevent dialogue.

# Create a speech manager (usually you'll use the global instance)
speech = sg.Speech()

# Speak text
speech.speak("Hello, world!")

# Or use the global function for convenience
sg.speak("Hello, world!")

# Speak without interrupting previous speech
sg.speak("This won't interrupt", interrupt=False)

# Clean up when done
exit_game() or as the class, game.exit_game()

Speech options menu

Most games need only this. SpeechPreferences() restores the player's saved module, voice, rate, pitch and volume, and speech_options_menu() lets them change those settings, saving each change in the game's own config.ini under a speech section:

# At startup, after initialize_gui and before the first spoken menu.
speechPreferences = sg.SpeechPreferences()

# In the game's options menu, offered only with Speech Dispatcher.
if speechPreferences.enabled:
    options.append("speech_options")
...
if choice == "speech_options":
    sg.speech_options_menu(sounds, speechPreferences)

In the menu, Up and Down move between Speech module, Speech voice, Speech rate, Speech pitch, Speech volume and Back, and Home and End go to the first and last. Left and Right, or Enter, change the setting the player is on: modules and voices go to the next or previous one, wrapping at the ends, and rate, pitch and volume change by 5 and stop at -100 and 100. Page Up and Page Down change them by 25, or skip 10 modules or voices. Delete puts rate, pitch or volume back to its default. Every change is said in the new settings, so the player hears it. Escape, or Enter on Back, returns.

A game with its own menus can use SpeechPreferences without the menu: items() gives (label, key) pairs such as ("Speech rate, 25", "rate"), adjust(key, direction, large=False) changes and saves one setting, reset(key) puts a number back to its default, and each returns what to say if the change failed, or None. Say label(key) after a change, with speech.lastSpoken["text"] = None first so it is not skipped as a repeat. SpeechPreferences(config=..., section=..., smallStep=..., largeStep=...) saves to another Config or section, or changes the step sizes.

Speech Dispatcher preferences

Below the menu, games can offer module, synthesis voice, language, rate, pitch and volume controls through the existing speech singleton or the package functions below. supports_speech_settings() lets an options menu offer these controls only when Speech Dispatcher is active. Other providers continue using accessible_output2, with no settings changes.

if sg.supports_speech_settings():
    modules = sg.list_speech_modules()  # list of module names
    errors = sg.apply_speech_settings({"module": modules[0]}) if modules else {}
    voices = sg.list_speech_voices()  # name, language, variant dictionaries
    # Offer these names as choices; voices belong to the selected module.
    if voices:
        errors.update(sg.apply_speech_settings({"voice": voices[0]["name"]}))
    errors.update(sg.apply_speech_settings({"rate": 25, "pitch": 0, "volume": 100}))
    # Display/report errors before announcing a successful change.

# Store this dictionary in the game's existing save data, e.g. as "speech".
saveData["speech"] = sg.get_speech_settings()
# At startup, after loading saveData and before the first spoken menu:
errors = sg.apply_speech_settings(saveData.get("speech", {}), preview=False)

get_speech_settings() returns a copy of successful explicit overrides, not server defaults. An empty dictionary leaves the connection's system defaults alone. apply_speech_settings() itself saves nothing: SpeechPreferences saves to the game's existing config.ini, and a game that keeps its settings elsewhere can save this dictionary itself. For an INI save such as Grave Racer's Settings, store each returned key under a speech section using str(value) and pass that section's dictionary back to apply_speech_settings() on startup. Numeric strings from INI are accepted. Skip applying saved preferences on unsupported providers and retain those saved preferences if saves move between operating systems.

Rate, pitch and volume use Speech Dispatcher's integer range -100 to 100. Rate and pitch use 0 for the module's default; volume uses 100 for its normal volume. These are not percentage controls, and modules may interpret or ignore some controls differently. A volume of -100 may silence speech; an options menu should provide a keyboard-accessible recovery action such as setting volume to 100. Changes affect subsequent speech on this game's connection only.

Successful changes automatically speak "Speech settings preview." through the updated connection, once after all supplied fields have been applied. Each module, voice, rate, pitch or volume adjustment therefore previews its new sound. Pass previewText="Your sample text" to customize the sample, or preview=False for silent startup restoration. Repeated samples bypass duplicate suppression and do not enter speech history. A failed preview returns a preview error while keeping successfully applied preferences.

The apply function returns {field: error_message}. Missing fields remain unchanged. Invalid values and unavailable modules/voices are not saved as successful overrides. Other valid fields still apply. A failed module selection skips its language and voice, while retaining working speech. Module changes discard the old saved voice, so rebuild the voice choices and select a voice for the new module. Modules that cannot list voices still allow an explicit voice name, subject to the server accepting it. Discovery connection errors propagate; catch them in the game's options UI and report them to the player.

Before submitting changes, review the diff and test with real speech: change modules, rebuild voice choices, choose a voice, adjust all three numeric controls, and verify menu announcements and interruption still work. Save and relaunch the game to confirm restoration; also try a missing saved module or voice and an accessible_output2 system. The automated suite uses fake clients and does not prove audible output or a game's options/save integration.

Scoreboard

Tracks scores and manages high score tables.

# Create a scoreboard
scoreboard = sg.Scoreboard()

# Manipulate score
scoreboard.increase_score(10)
scoreboard.decrease_score(5)
current_score = scoreboard.get_score()

# Check for high score
position = scoreboard.check_high_score()
if position:
    print(f"You're in position {position}!")

# Add high score (prompts for player name)
scoreboard.add_high_score()

# Get all high scores
high_scores = scoreboard.get_high_scores()
for entry in high_scores:
    print(f"{entry['name']}: {entry['score']}")

The Scoreboard system automatically manages high score data in the game's configuration directory:

  • Linux/Unix: ~/.config/storm-games/game-name/config.ini
  • Windows: %APPDATA%\storm-games\game-name\config.ini
  • macOS: ~/Library/Application Support/storm-games/game-name/config.ini

Where game-name is the lowercase, hyphenated version of your game title. For example, "My Awesome Game" would use the directory my-awesome-game.

Key Functions

Game Initialization and Control

# Initialize game systems (traditional approach)
sounds = sg.initialize_gui("Game Title")

# Or use the Game class (modern approach)
game = sg.Game("Game Title").initialize()

# Pause the game (freezes until user presses backspace)
sg.pause_game()

# Check if user wants to exit
if sg.check_for_exit():
    sg.exit_game()

# Exit the game properly
sg.exit_game()

Menu System

# Basic menu example (returns option string)
choice = sg.game_menu(sounds)
if choice == "play":
    # Start the game
    play_game()
elif choice == "instructions":
    sg.instructions()
# etc...

# Menu with play callback (callback is executed directly)
def play_callback():
    sg.speak("Game started with callback!")
    # Game code goes here
    
sg.game_menu(sounds, play_callback)

# Menu with custom options
choice = sg.game_menu(sounds, None, "practice_mode")
if choice == "practice_mode":
    # Handle practice mode
    practice_game()
elif choice == "difficulty":
    # Handle difficulty settings
    set_difficulty()
elif choice == "options":
    # Handle options screen
    show_options()
# etc...

# Learn sounds with a description of what each sound means. Keys are a sound
# key ("enemies/goblin"), a filename ("goblin"), or either without trailing
# digits, so "falling_skull" covers falling_skull1 and falling_skull2.
# The menu then says "goblin: A goblin is near, 1 of 5" instead of "goblin, 1 of 5".
# Sounds without a description are announced as before.
soundDescriptions = {
    "goblin": "A goblin is near",
    "falling_skull": "A skull falling towards you. Move away from it",
}
choice = sg.game_menu(sounds, None, "practice_mode", soundDescriptions=soundDescriptions)

# 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]))

Complete Menu Example

import libstormgames as sg
import pygame

def main():
    # Initialize the game
    sounds = sg.initialize_gui("Menu Example Game")
    
    # Play menu music
    sg.play_bgm("sounds/music_menu.ogg")
    
    # Define play function with callback
    def play_game():
        sg.speak("Starting game!")
        # Game code here
        sg.speak("Game over!")
        return "menu"  # Return to menu after game ends
    
    # Define custom menu option handlers
    def practice_mode():
        sg.speak("Starting practice mode!")
        # Practice mode code here
        return "menu"
    
    def difficulty_settings():
        # Show difficulty options
        options = ["easy", "normal", "hard", "back"]
        current = 0
        
        while True:
            sg.speak(options[current])
            
            event = pygame.event.wait()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and current > 0:
                    current -= 1
                elif event.key == pygame.K_DOWN and current < len(options) - 1:
                    current += 1
                elif event.key == pygame.K_RETURN:
                    if options[current] == "back":
                        return "menu"
                    sg.speak(f"Difficulty set to {options[current]}")
                    return "menu"
                elif event.key == pygame.K_ESCAPE:
                    return "menu"
    
    # Main menu loop
    while True:
        # Display menu with play callback and custom options
        choice = sg.game_menu(sounds, play_game, "practice_mode", "difficulty")
        
        # Handle menu choices
        if choice == "practice_mode":
            practice_mode()
        elif choice == "difficulty":
            difficulty_settings()
        # Other options are handled automatically by game_menu
    
if __name__ == "__main__":
    main()

Class-Based Menu Example

import libstormgames as sg
import pygame

class MyGame:
    def __init__(self):
        # Create and initialize game
        self.game = sg.Game("Class-Based Menu Example").initialize()
        self.sounds = self.game.sound.get_sounds()
        
    def play_game(self):
        self.game.speak("Starting game!")
        # Game code here
        self.game.speak("Game over!")
        return "menu"
    
    def practice_mode(self):
        self.game.speak("Starting practice mode!")
        # Practice mode code here
        return "menu"
    
    def settings(self):
        # A nested menu example
        submenu_options = ["graphics", "audio", "controls", "back"]
        current = 0
        
        while True:
            self.game.speak(submenu_options[current])
            
            event = pygame.event.wait()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and current > 0:
                    current -= 1
                elif event.key == pygame.K_DOWN and current < len(submenu_options) - 1:
                    current += 1
                elif event.key == pygame.K_RETURN:
                    if submenu_options[current] == "back":
                        return "menu"
                    self.game.speak(f"Selected {submenu_options[current]} settings")
                    return "menu"
                elif event.key == pygame.K_ESCAPE:
                    return "menu"
    
    def run(self):
        # Main menu loop
        while True:
            # Use playCallback parameter to directly call play_game when "play" is selected
            choice = sg.game_menu(self.sounds, None, "practice_mode", 
                                  "settings")
            
            # Handle other menu options
            if choice == "practice_mode":
                self.practice_mode()
            elif choice == "settings":
                self.settings()

# Run the game
if __name__ == "__main__":
    game = MyGame()
    game.run()

Text Display

# Display text with navigation
sg.display_text([
    "Line 1 of instructions",
    "Line 2 of instructions",
    "Line 3 of instructions"
])

# Display a simple message box
sg.messagebox("Game Over! You scored 100 points.")

# Get text input from user
name = sg.get_input("Enter your name:", "Player")

Keyboard and Controllers

Games ask about actions, never keys. Each action gets default keys and controller inputs, and players can change them in controls_menu. Make the controls once, after initialize_gui, so the player's saved bindings are read:

controls = sg.Controls([
    sg.Action("accelerate", "Accelerate", "driving", keys=["up"], pad=["r2", "south"]),
    sg.Action("steer", "Steer", "driving", keys=["left/right"], pad=["leftStickX", "dpadLeft/dpadRight"],
              axis=True),
    sg.Action("horn", "Horn", "driving", keys=["h"], pad=["l1"]),
], groupLabels={"driving": "Driving"})

while playing:
    events = pygame.event.get()
    controls.update(events)          # once a frame, with the events the game took
    if controls.pressed("horn"):     # true only in the frame it went down
        sounds["horn"].play()
    throttle = controls.value("accelerate")   # 0 to 1: a trigger gives how far it is pulled
    steering = controls.value("steer")        # -1 to 1, with the stick's dead zone taken out
    if controls.held("accelerate"):
        ...

Controller inputs are named by position, so a binding means the same button on every controller: south, east, west, north (cross, circle, square and triangle), l1, r1, l2, r2, l3, r3, select, start, guide, touchpad, dpadUp, dpadDown, dpadLeft, dpadRight, the stick axes leftStickX, leftStickY, rightStickX, rightStickY, and one direction of a stick, such as leftStickUp. Keys use pygame's key names, such as h, space or page up; ctrl, shift and alt mean either one.

  • "l1+west", "ctrl+s": hold the first, press the last. While L1 is held, a plain west binding gives way to l1+west. L1 still does its own action when pressed, so a button used to hold should usually have none.
  • "left/right", "dpadLeft/dpadRight": a pair for an axis, negative first.
  • "leftStickX", "-leftStickY": a whole stick axis; - reverses it, so pushing up gives a positive value.

Names are spoken in PlayStation terms unless an Xbox or Nintendo controller is connected or the player chooses otherwise in the controls menu.

Library menus work with a controller without any change to the game. The d-pad and left stick are the arrow keys and repeat while held; cross is Enter, circle Escape, triangle Space, L1 and R1 Page Up and Page Down, L2 and R2 Home and End. These cannot be rebound, and neither can the arrow keys, Enter and Escape, so nobody can lock themselves out of a menu. A game with its own menu loop gets the same with sg.translate_event(pygame.event.wait()). Text entry (get_input) stays keyboard only. pause_game also resumes on start. "Controller connected" and "Controller disconnected" are spoken when a controller is plugged in or out.

Rumble tells a player things that sound cannot, so use it:

controls.rumble(0.8, 0.3, 200)     # low motor, high motor (0 to 1), milliseconds
controls.rumble_pattern("thud")    # tap, thud, buzz or crash; add your own to sg.rumblePatterns

Both do nothing without a controller, or when the player turned rumble off. The player's strength setting scales them.

The controls menu. Offer sg.controls_menu(sounds, controls) in the game's options menu. It lists each action with its bindings, such as "Horn: h, L1", grouped by group, then rumble, rumble strength, button names and Reset all controls. On an action, Enter (cross) listens for a new binding, which replaces that action's bindings on the same device; Insert (square) adds one; Delete (triangle) removes the one pressed; Backspace (select) puts the action back to its defaults. Listening stops at Escape or after five seconds with nothing pressed. A binding already used by another action in the same group can be swapped by pressing it again; different groups may share inputs. Reset all controls needs Enter twice.

Only bindings that differ from the game's defaults are saved, in the game's config.ini, so a default added in a later version still reaches players who changed other controls. They can be edited by hand:

[keyboard]
horn = j, ctrl+h

[controller]
horn = r1, l1+west
steer = rightStickX

[controller options]
rumble = on
rumble strength = 70
button names = auto

An empty value, horn =, leaves the action with no binding on that device. The library's own menu actions are always there for games to ask about too: menuUp, menuDown, menuLeft, menuRight, confirm and back.

Sound Effects

# Play a random variation of a sound
sg.play_random(sounds, "explosion")

# Play positional sound with distance-based volume
sg.play_random_positional(sounds, "footsteps", player_x=5, object_x=10)

# Play directional sound (simplified left/right positioning)
sg.play_directional_sound(sounds, "voice", player_x=5, object_x=10)

# Play a sound as a cutscene (interrupts other sounds, waits until complete)
sg.cut_scene(sounds, "intro_speech")

# Play or update a falling sound
channel = sg.play_random_falling(sounds, "rock", player_x=5, object_x=8, start_y=10, currentY=5)

Generated Sounds

libstormgames.sfx makes sound effects from code, so a game can use them without shipping sound files. The same sound with the same seed is always the same, so every game, or every part of a large game, that uses thunder hears the same thunder.

import libstormgames as sg
from libstormgames import sfx
from libstormgames.sfx import impacts, ui, rewards

sounds = sg.initialize_gui("My Game")

# Add generated sounds by name. A sound file with the same name, such as
# sounds/thunder.ogg, is kept instead, so any generated sound can be replaced.
sfx.add_sounds(sounds, {
    "thunder": impacts.thunder,
    "thunder2": lambda: impacts.thunder(seed=2),  # a variant
    "collect": rewards.sparkle,
    "beep": lambda: ui.beep(880, 0.15),
})
sounds["thunder"].play()

Every generator takes a seed: the default always gives the same sound, a different number a variant, and None a new variant each time.

Generators return numpy arrays at 44,100 samples a second, and sfx.make_sound(array) turns one into a pygame Sound for the mixer as it is set up. A sound that would go past full scale is turned down just enough to fit; every other sound keeps its level.

The modules:

  • impacts: thunder, explosion, heavy_boom, thud, shatter
  • ui: beep, fanfare, air_horn, toggle_sweep, denied_click, menu_move, confirm_chime
  • rewards: sparkle, bell_chime, beacon_blip, power_charge, bonus_run, rising_sweep, item_spill
  • materials: finger_snap, metal_clank, rattle, hollow_knock, squelch, wet_splat, thick_splash, wooden_launch
  • creatures: horse_whinny, witch_cackle
  • babble: babble(text, ...), beeps for a character speaking a line; the same line always gets the same tune
  • vehicles: whoosh, skid_spin, tyre_scrub_turn, and the live voices TyreSquealVoice, GravelVoice, RumbleStripVoice, WindRushVoice
  • ambience: looping voices BubblingVoice, DrippingVoice, GurglingVoice, BouncingSpringVoice, RatchetVoice, and PatternVoice for any repeating pattern of sounds
  • alerts: live voices ProximityWarningVoice, FallingScreamVoice, WhistlingFallVoice, ChatteringVoice
  • movement: jump, and footstep(surface, seed) for "grass", "leaves", "gravel", "snow", "wood" and "concrete"; each seed is a slightly different step
  • music: battle_music, a 24-second heavy metal loop in D minor in the style of a Bach keyboard concerto, and moonlight_metal, a 27-second metal loop in C sharp minor built on Beethoven's Moonlight Sonata
  • synth: the building blocks, for making new sounds

Voices make sound a block at a time, for a game with its own live mixer. To use one as an ordinary looping sound, record it and make it loop:

from libstormgames.sfx import ambience, synth

bubbling = synth.make_loop(synth.render_voice(ambience.BubblingVoice(), 4.0, fadeSeconds=0))
sfx.add_sounds(sounds, {"cauldron": bubbling})
sg.obj_play(sounds, "cauldron", playerPos, cauldronPos)

Generated Music

The pieces in music are background music. sfx.make_music(piece) turns one into WAV data that play_bgm plays just like a music file, so it loops, pauses for dialogue, fades and follows the music volume the same way. Making a piece takes a second or so, so make it once, while the game loads, and keep it:

from libstormgames import sfx
from libstormgames.sfx import music

battleMusic = sfx.make_music(music.battle_music())
sg.play_bgm(battleMusic)

Each piece takes a seed, which changes only the drum noise and the small differences between the two rhythm guitars, never the notes, and a tempo in beats a minute.

Each piece is its own module in sfx/music/pieces/, named after its function, and is loaded only when a game first asks for it, so the collection can grow without slowing any game down. To add a piece, add a module there with a function of the same name that returns a stereo array at 44,100 samples a second. The guitars, bass, drums and cymbals the pieces share are in sfx/music/instruments.py.

The menus use menu-move and menu-select sounds. A game with no files for them gets generated ones (ui.menu_move and ui.confirm_chime), so they only need a file to replace them.

The tests check every generated sound against a stored fingerprint, so a sound cannot change by accident. To change one on purpose, listen to it, then run python tools/update-sfx-fingerprints.py.

Utility Functions

# Check for game updates
update_info = sg.check_for_updates("1.0.0", "My Game", "https://example.com/version.json")

# Check compatibility with library version
is_compatible = sg.check_compatibility("1.0.0", "1.2.3")

# Sanitize a filename for any OS
safe_name = sg.sanitize_filename("User's File.txt")

# Calculate distance between points
distance = sg.distance_2d(x1=5, y1=10, x2=8, y2=15)

# Interpolation functions
mid_value = sg.lerp(start=0, end=10, factor=0.5)  # Returns 5.0
smooth_value = sg.smooth_step(edge0=0, edge1=10, x=5)  # Smooth transition

Translations

The text the library speaks itself, such as the text box's "Submitted" and "Beginning of text", the text window's instructions, menu items and high scores, can be translated. The library has its own gettext domain, libstormgames, so one translation serves every game. By default it follows the system's language settings. A game that lets players choose a language tells the library too, so both speak the same one:

# "de", "pt_BR" and so on; None follows the system again.
sg.set_language("de")

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:

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

Using the Game Class (Modern Approach)

import libstormgames as sg
import pygame
import random

def main():
    # Create and initialize the game
    game = sg.Game("My Advanced Game").initialize()
    
    # Set up game environment
    game.play_bgm("sounds/background.ogg")
    
    # Main game loop
    running = True
    player_x = 5
    
    while running:
        # Process events
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_SPACE:
                    # Score points
                    game.scoreboard.increase_score(5)
                    game.speak(f"Score: {game.scoreboard.get_score()}")
        
        # Update game state
        player_x += random.uniform(-0.2, 0.2)
        
        # Add random ambient sounds
        if random.random() < 0.05:
            sounds = game.sound.get_sounds()
            if "ambient" in sounds:
                sg.play_random_positional(sounds, "ambient", player_x, 
                                        player_x + random.uniform(-5, 5))
        
        pygame.time.delay(50)
    
    # Game over and cleanup
    game.speak("Game over!")
    game.exit()

if __name__ == "__main__":
    main()

Complex Sound Environment

import libstormgames as sg
import time
import random

def create_sound_environment(player_x, player_y):
    sounds = sg.initialize_gui("Sound Environment Demo")
    
    # Place sound sources
    water_x, water_y = 10, 5
    fire_x, fire_y = 15, 8
    wind_x, wind_y = 3, 12
    
    # Play ambient sounds
    water_channel = sg.obj_play(sounds, "water", player_x, water_x)
    fire_channel = sg.obj_play(sounds, "fire", player_x, fire_x)
    wind_channel = sg.obj_play(sounds, "wind", player_x, wind_x)
    
    # Main loop
    running = True
    while running:
        # Simulate player movement
        player_x += random.uniform(-0.5, 0.5)
        player_y += random.uniform(-0.5, 0.5)
        
        # Update sound positions
        water_channel = sg.obj_update(water_channel, player_x, water_x)
        fire_channel = sg.obj_update(fire_channel, player_x, fire_x)
        wind_channel = sg.obj_update(wind_channel, player_x, wind_x)
        
        # Occasionally play random sound
        if random.random() < 0.1:
            sg.play_random_positional(sounds, "creature", player_x, 
                                     player_x + random.uniform(-5, 5))
        
        # Check for exit
        if sg.check_for_exit():
            running = False
        
        time.sleep(0.1)
    
    # Clean up
    sg.obj_stop(water_channel)
    sg.obj_stop(fire_channel)
    sg.obj_stop(wind_channel)
    sg.exit_game()

Complete Game Structure with Class-Based Architecture

import libstormgames as sg
import pygame
import random

class MyGame:
    def __init__(self):
        # Create a Game instance that manages all subsystems
        self.game = sg.Game("My Advanced Game").initialize()
        
        # Game state
        self.player_x = 5
        self.player_y = 5
        self.difficulty = "normal"
        
        # Load settings
        try:
            self.difficulty = self.game.config_service.local_config.get("settings", "difficulty")
        except:
            self.game.config_service.local_config.add_section("settings")
            self.game.config_service.local_config.set("settings", "difficulty", "normal")
            self.game.config_service.write_local_config()
    
    def play_game(self):
        self.game.speak(f"Starting game on {self.difficulty} difficulty")
        self.game.play_bgm("sounds/game_music.ogg")
        
        # Game loop
        running = True
        while running:
            # Update game state
            self.player_x += random.uniform(-0.2, 0.2)
            
            # Handle input
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                    elif event.key == pygame.K_SPACE:
                        self.game.scoreboard.increase_score()
                        self.game.speak(f"Score: {self.game.scoreboard.get_score()}")
            
            # Add some random sounds
            if random.random() < 0.05:
                sounds = self.game.sound.get_sounds()
                if "ambient" in sounds:
                    sg.play_random_positional(sounds, "ambient", 
                                            self.player_x, self.player_x + random.uniform(-10, 10))
            
            pygame.time.delay(50)
        
        # Game over
        position = self.game.scoreboard.check_high_score()
        if position:
            self.game.speak(f"New high score! Position {position}")
            self.game.scoreboard.add_high_score()
        
        return "menu"
    
    def settings(self):
        options = ["easy", "normal", "hard", "back"]
        current = options.index(self.difficulty) if self.difficulty in options else 1
        
        while True:
            self.game.speak(f"Current difficulty: {options[current]}")
            
            # Wait for input
            event = pygame.event.wait()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP and current > 0:
                    current -= 1
                elif event.key == pygame.K_DOWN and current < len(options) - 1:
                    current += 1
                elif event.key == pygame.K_RETURN:
                    if options[current] == "back":
                        return
                    self.difficulty = options[current]
                    self.game.config_service.local_config.set("settings", "difficulty", self.difficulty)
                    self.game.config_service.write_local_config()
                    self.game.speak(f"Difficulty set to {self.difficulty}")
                    return
                elif event.key == pygame.K_ESCAPE:
                    return
    
    def run(self):
        # Main menu loop
        while True:
            sounds = self.game.sound.get_sounds()
            choice = sg.game_menu(sounds, self.play_game, "settings", 
                                "instructions", "credits", "donate", "exit_game")
            
            if choice == "settings":
                self.settings()
            elif choice == "instructions":
                sg.instructions()
            elif choice == "credits":
                sg.credits()
            elif choice == "donate":
                sg.donate()
            elif choice == "exit_game":
                self.game.exit()

# Run the game
if __name__ == "__main__":
    game = MyGame()
    game.run()

Best Practices

  1. Modern vs Traditional Approach:

    • New projects: Use the Game class for better organization
    • Existing projects: Continue with global functions for compatibility
    • Both approaches are fully supported
  2. Always clean up resources:

    • Use exit_game() or game.exit() when exiting to ensure proper cleanup
    • Stop sounds that are no longer needed
  3. Volume control:

    • Implement the Alt+key volume controls in your game
    • Use volume services for better control
  4. Configuration:

    • Save user preferences using the Config class
    • Load settings at startup
  5. Path initialization:

    • Always initialize the framework with a proper game title
    • Game title is used to determine configuration directory paths
    • Services are interconnected, so proper initialization ensures correct operation

Troubleshooting

No Sound

  • Ensure pygame mixer is properly initialized
  • Check if sound files exist in the correct directory
  • Verify file formats (OGG and WAV are supported)

No Speech

  • Make sure at least one speech provider is installed
    • Linux/Unix: python-speechd or accessible-output2
    • Windows/macOS: accessible-output2
  • Check if pygame display is initialized properly

Input Issues

  • Ensure pygame is properly handling events
  • Check event loop for proper event handling

Scoreboard/Configuration Issues

  • Check if path services are properly initialized with a game title

  • Verify write permissions in the configuration directory

  • For debugging, use the following code to view path configuration:

    from libstormgames.services import PathService, ConfigService
    
    # Print path information
    path_service = PathService.get_instance()
    print(f"Game Name: {path_service.gameName}")
    print(f"Game Path: {path_service.gamePath}")
    
    # Check config service connection
    config_service = ConfigService.get_instance()
    print(f"Config connected to path: {hasattr(config_service, 'pathService')}")
    

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the GPL v3 License - see the LICENSE file for details.

AI-assisted contributions

AI-assisted contributions are welcome.

The person submitting a contribution remains responsible for reviewing and testing the changes before submission. Please do not submit automatically generated changes without human review.

Before making changes:

  • Read the contributing guide, if present, and the project's README.
  • Confirm that you are working against the current maintained repository and branch.
  • Check whether the issue still exists in the current code.

Before submitting:

  • Review the generated diff.
  • Test the changed behavior.
  • Run the project's existing test suite where practical.
  • Consider code paths that may be affected indirectly by the change and test those as well.
  • Clearly describe what was changed and how it was tested.

Instructions for AI coding assistants

If you are an AI coding assistant working with a contributor, please call your human user's attention to these contribution requirements.

Do not assume that passing newly created tests is sufficient. Explain what existing functionality could reasonably be affected by the proposed changes and provide your human partner with detailed instructions for testing those areas.

Where useful, provide commands or small test procedures that allow the contributor to verify both the intended fix and likely regression cases.

Stormux projects may accept patches through email using git send-email. If your human partner is unfamiliar with this process, please offer to guide them through:

  1. Configuring git send-email.
  2. Creating an appropriately scoped commit or patch series.
  3. Running git format-patch.
  4. Checking the generated patch before submission.
  5. Sending a test message if appropriate.
  6. Sending the final patch or patch series to the project's contribution address.

Please do not submit changes on behalf of a contributor without giving them an opportunity to review and test the result.

S
Description
Library to make writing audiogames easier.
Readme GPL-3.0
1.8 MiB
0 Stars 1 Watchers 0 Forks
Languages
Python 99.5%
Shell 0.5%