# Baba Yaga Game Engine Architecture ## Vision Create an integrated game development environment inspired by Pico-8, where Baba Yaga serves as the scripting language for creating 2D graphical games, text adventures, and visual novels. The system should be approachable for beginners while powerful enough for complex games. ## Core Design Principles 1. **Batteries Included**: Everything needed for game development in one package 2. **Immediate Feedback**: Live coding with instant visual results 3. **Constraint-Based Creativity**: Reasonable limits that encourage creative solutions 4. **Cross-Genre Support**: Unified API that works for graphics, text, and hybrid games 5. **Functional Game Logic**: Leverage Baba Yaga's functional nature for clean game state management ## System Architecture Overview ``` ┌─────────────────────────────────────────────────────────────┐ │ Baba Yaga Game Engine │ ├─────────────────────────────────────────────────────────────┤ │ Game Scripts (.baba files) │ ├─────────────────────────────────────────────────────────────┤ │ Game Runtime API │ │ ├── Graphics API ├── Audio API ├── Input API │ │ ├── Text/UI API ├── Storage API ├── Scene API │ ├─────────────────────────────────────────────────────────────┤ │ Core Engine Systems │ │ ├── Renderer ├── Audio System ├── Input Manager │ │ ├── Asset Loader ├── Save System ├── Scene Manager │ ├─────────────────────────────────────────────────────────────┤ │ Platform Layer (Web/Desktop/Mobile) │ └─────────────────────────────────────────────────────────────┘ ``` ## Game Runtime API Design ### Core Game Loop ```baba // Game entry point - called once at startup init : () -> GameState; // Main update loop - called every frame update : (state: GameState, input: Input, dt: Float) -> GameState; // Render function - called every frame after update draw : (state: GameState) -> Unit; ``` ### Graphics API (`gfx` namespace) **Display System:** ```baba // Display management gfx.width : Int; // Screen width (e.g., 320) gfx.height : Int; // Screen height (e.g., 240) gfx.clear : (color: Color) -> Unit; // Clear screen gfx.present : () -> Unit; // Present frame (auto-called) // Coordinate system: (0,0) at top-left, (width-1, height-1) at bottom-right ``` **Drawing Primitives:** ```baba // Basic shapes gfx.pixel : (x: Int, y: Int, color: Color) -> Unit; gfx.line : (x1: Int, y1: Int, x2: Int, y2: Int, color: Color) -> Unit; gfx.rect : (x: Int, y: Int, w: Int, h: Int, color: Color) -> Unit; gfx.rectFill : (x: Int, y: Int, w: Int, h: Int, color: Color) -> Unit; gfx.circle : (x: Int, y: Int, radius: Int, color: Color) -> Unit; gfx.circleFill : (x: Int, y: Int, radius: Int, color: Color) -> Unit; // Color system (16-color palette like Pico-8) gfx.colors : { black: 0, darkBlue: 1, darkPurple: 2, darkGreen: 3, brown: 4, darkGray: 5, lightGray: 6, white: 7, red: 8, orange: 9, yellow: 10, green: 11, blue: 12, indigo: 13, pink: 14, peach: 15 }; ``` **Sprite System:** ```baba // Sprite management gfx.sprite : (id: Int, x: Int, y: Int) -> Unit; gfx.spriteFlip : (id: Int, x: Int, y: Int, flipX: Bool, flipY: Bool) -> Unit; gfx.spriteScale : (id: Int, x: Int, y: Int, scale: Float) -> Unit; // Sprite sheet: 128x128 pixels, 8x8 sprites = 16x16 grid of sprites gfx.spriteSize : Int; // 8 pixels gfx.spriteSheet : {width: 128, height: 128, sprites: 256}; ``` **Text Rendering:** ```baba gfx.text : (text: String, x: Int, y: Int, color: Color) -> Unit; gfx.textCentered : (text: String, x: Int, y: Int, color: Color) -> Unit; gfx.textBox : (text: String, x: Int, y: Int, w: Int, h: Int, color: Color) -> Unit; gfx.font : {width: 4, height: 6}; // Fixed-width bitmap font ``` ### Audio API (`sfx` namespace) ```baba // Sound effects (64 slots) sfx.play : (id: Int) -> Unit; sfx.stop : (id: Int) -> Unit; sfx.volume : (id: Int, volume: Float) -> Unit; // 0.0 to 1.0 // Music (8 tracks) music.play : (track: Int) -> Unit; music.stop : () -> Unit; music.pause : () -> Unit; music.resume : () -> Unit; music.volume : (volume: Float) -> Unit; // Simple sound synthesis sfx.beep : (frequency: Float, duration: Float) -> Unit; sfx.noise : (duration: Float) -> Unit; ``` ### Input API (`input` namespace) ```baba // Button states (8 buttons like a gamepad) input.buttons : { up: 0, down: 1, left: 2, right: 3, a: 4, b: 5, start: 6, select: 7 }; // Input checking input.pressed : (button: Int) -> Bool; // Just pressed this frame input.held : (button: Int) -> Bool; // Held down input.released : (button: Int) -> Bool; // Just released this frame // Mouse/touch (for visual novels and UI) input.mouse : {x: Int, y: Int, pressed: Bool, held: Bool, released: Bool}; // Keyboard (for text adventures) input.key : (keyCode: String) -> Bool; input.textInput : () -> String; // Text entered this frame ``` ### Text/UI API (`ui` namespace) **For Text Adventures & Visual Novels:** ```baba // Text display system ui.textBuffer : [String]; // Scrolling text buffer ui.print : (text: String) -> Unit; ui.println : (text: String) -> Unit; ui.clear : () -> Unit; ui.scroll : (lines: Int) -> Unit; // Choice system for branching narratives ui.choice : (prompt: String, options: [String]) -> Result Int String; ui.input : (prompt: String) -> String; // Dialog system ui.dialog : { show: (speaker: String, text: String) -> Unit, hide: () -> Unit, isShowing: Bool }; // Menu system ui.menu : (title: String, options: [String], selected: Int) -> Int; ``` ### Storage API (`save` namespace) ```baba // Persistent storage (like cartridge data) save.set : (key: String, value: any) -> Unit; save.get : (key: String) -> Result any String; save.has : (key: String) -> Bool; save.remove : (key: String) -> Unit; save.clear : () -> Unit; // High scores, progress, settings save.highScore : (score: Int) -> Unit; save.getHighScore : () -> Int; save.checkpoint : (data: any) -> Unit; save.loadCheckpoint : () -> Result any String; ``` ### Scene API (`scene` namespace) ```baba // Scene management for complex games scene.current : String; scene.switch : (name: String) -> Unit; scene.push : (name: String) -> Unit; // For menus/overlays scene.pop : () -> Unit; // Scene registration scene.register : (name: String, init: () -> State, update: UpdateFn, draw: DrawFn) -> Unit; ``` ## Game Types and Patterns ### 2D Action/Platformer Games ```baba // Example: Simple platformer GameState : { player: {x: Float, y: Float, vx: Float, vy: Float}, enemies: [Enemy], level: Level, score: Int }; init : () -> GameState -> { player: {x: 160, y: 120, vx: 0, vy: 0}, enemies: [], level: loadLevel 1, score: 0 }; update : state input dt -> with ( // Handle input newVx : when (input.held input.buttons.left) is true then -100 _ then when (input.held input.buttons.right) is true then 100 _ then state.player.vx * 0.8; // Friction // Update player newPlayer : updatePlayer state.player newVx dt; // Update enemies newEnemies : map (enemy -> updateEnemy enemy dt) state.enemies; ) -> set state "player" newPlayer |> set "enemies" newEnemies; draw : state -> gfx.clear gfx.colors.darkBlue; drawLevel state.level; drawPlayer state.player; map drawEnemy state.enemies; gfx.text ("Score: " .. (str.concat "" state.score)) 4 4 gfx.colors.white; ``` ### Text Adventure Games ```baba // Example: Text adventure AdventureState : { currentRoom: String, inventory: [String], gameText: [String], gameOver: Bool }; init : () -> AdventureState -> { currentRoom: "start", inventory: [], gameText: ["Welcome to the Adventure!", "You are in a dark room."], gameOver: false }; update : state input dt -> when (input.textInput != "") is false then state true then processCommand state (input.textInput); draw : state -> gfx.clear gfx.colors.black; drawTextBuffer state.gameText; ui.print "> "; processCommand : state command -> when (text.words command) is ["go", direction] then movePlayer state direction ["take", item] then takeItem state item ["use", item] then useItem state item ["inventory"] then showInventory state _ then addText state "I don't understand that command."; ``` ### Visual Novel Games ```baba // Example: Visual novel NovelState : { currentScene: String, characterSprites: Table, background: String, textBox: {visible: Bool, speaker: String, text: String}, choices: [String], flags: Table // Story flags }; init : () -> NovelState -> { currentScene: "intro", characterSprites: {}, background: "room", textBox: {visible: false, speaker: "", text: ""}, choices: [], flags: {} }; update : state input dt -> when state.choices is [] then // Regular dialog when (input.pressed input.buttons.a) is true then advanceDialog state _ then state _ then // Choice selection when (input.pressed input.buttons.a) is true then selectChoice state _ then navigateChoices state input; draw : state -> drawBackground state.background; drawCharacterSprites state.characterSprites; when state.textBox.visible is true then drawTextBox state.textBox _ then {}; when (length state.choices > 0) is true then drawChoices state.choices _ then {}; ``` ## Asset Management ### File Structure ``` game/ ├── main.baba # Entry point ├── sprites.png # 128x128 sprite sheet ├── sounds/ # Audio files │ ├── sfx_001.wav │ └── music_001.wav ├── scenes/ # Scene scripts │ ├── intro.baba │ └── gameplay.baba └── data/ # Game data ├── levels.json └── dialog.json ``` ### Asset Loading ```baba // Automatic asset loading based on file structure assets.sprites : SpriteSheet; // sprites.png assets.sounds : [Sound]; // sounds/*.wav assets.music : [Music]; // sounds/music_*.wav assets.data : Table; // data/*.json parsed as tables ``` ## Development Tools Integration ### Live Coding - **Hot Reload**: Changes to .baba files reload game state - **REPL Integration**: Debug console accessible during gameplay - **State Inspector**: View and modify game state in real-time ### Built-in Editors - **Sprite Editor**: Pixel art editor for the 128x128 sprite sheet - **Sound Editor**: Simple sound effect generator and sequencer - **Map Editor**: Tile-based level editor for 2D games - **Dialog Editor**: Visual dialog tree editor for visual novels ### Export and Sharing - **Web Export**: Single HTML file with embedded assets - **Standalone Export**: Desktop executables - **Cartridge Format**: .baba-cart files containing code and assets - **Online Sharing**: Upload and share games on web platform ## Performance Constraints Following Pico-8's philosophy of creative constraints: ### Technical Limits - **Display**: 320x240 pixels (or 640x480 for high-DPI) - **Colors**: 16-color fixed palette - **Sprites**: 256 sprites, 8x8 pixels each - **Code Size**: ~32KB of Baba Yaga source code - **Audio**: 64 sound effects, 8 music tracks - **Save Data**: 1KB persistent storage ### Performance Targets - **60 FPS**: Smooth gameplay on modest hardware - **Low Latency**: <16ms input response time - **Fast Startup**: <2 seconds from launch to gameplay ## Example Game Templates ### Template 1: Arcade Game ```baba // Minimal arcade game template init : () -> {score: 0, gameOver: false}; update : state input dt -> when state.gameOver is true then when (input.pressed input.buttons.start) is true then init _ then state _ then updateGameplay state input dt; draw : state -> gfx.clear gfx.colors.black; when state.gameOver is true then drawGameOver state.score _ then drawGameplay state; ``` ### Template 2: Text Adventure ```baba // Text adventure template with room system rooms : { start: { description: "A dark room with exits north and east.", exits: {north: "hallway", east: "kitchen"}, items: ["flashlight"] } // ... more rooms }; processCommand : state command -> when (parseCommand command) is Move direction then moveToRoom state direction Take item then takeItem state item _ then unknownCommand state; ``` ### Template 3: Visual Novel ```baba // Visual novel template with scene system scenes : { intro: [ {type: "background", image: "school"}, {type: "character", name: "alice", position: "left"}, {type: "dialog", speaker: "Alice", text: "Hello there!"}, {type: "choice", options: ["Hello!", "Who are you?"]} ] // ... more scenes }; playScene : state sceneData -> reduce executeSceneAction state sceneData; ``` ## Integration with Existing Baba Yaga Features ### Leveraging Language Features - **Pattern Matching**: Perfect for game state transitions and input handling - **Immutability**: Clean game state management without side effects - **Result Type**: Robust error handling for asset loading and save/load - **Higher-Order Functions**: Flexible entity systems and behavior trees - **Debug Tools**: Built-in debugging for game development ### Extended Standard Library - **Game Math**: Vector operations, collision detection, easing functions - **Random Enhanced**: Seeded random for reproducible gameplay - **Collections**: Spatial data structures for game entities - **Validation**: Input validation for save data and user input ## Next Steps 1. **Prototype Core Systems**: Start with basic graphics and input 2. **Build Example Games**: Create reference implementations for each genre 3. **Developer Tools**: Integrated sprite and sound editors 4. **Community Platform**: Sharing and collaboration features 5. **Documentation**: Comprehensive tutorials and API reference This architecture provides a solid foundation for a Baba Yaga-powered game development environment that can handle everything from simple arcade games to complex visual novels, all while maintaining the functional programming principles that make Baba Yaga unique.