1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
|
# 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.
|