nemu 0.1.0

An interactive story engine for creating text-based adventure games
Documentation
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use crate::story::loader::Story;
use crate::engine::{room::Room, parser::{parse_command, Command}};
use crossterm::{
    execute,
    terminal::{Clear, ClearType},
    style::{Print, SetForegroundColor, ResetColor, Color},
};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
use std::io::{self, Write};

#[derive(Debug, Serialize, Deserialize)]
struct SavedGame {
    current_room: String,
    inventory: HashSet<String>,
}

pub struct Game {
    story: Story,
    current_room: String,
    inventory: HashSet<String>,
}

#[derive(Debug)]
pub enum GameError {
    InvalidRoom,
    ItemNotFound,
    RoomNotFound,
}

impl std::fmt::Display for GameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            GameError::InvalidRoom => write!(f, "Invalid room"),
            GameError::ItemNotFound => write!(f, "Item not found"),
            GameError::RoomNotFound => write!(f, "Room not found"),
        }
    }
}

impl std::error::Error for GameError {}

impl Game {
    pub fn new(story: Story) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            current_room: story.story.start_room.clone(),
            story,
            inventory: HashSet::new(),
        })
    }
    
    pub async fn run(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        self.clear_screen()?;
        println!("=========================================");
        println!("    Welcome to: {}", self.story.story.title);
        println!("=========================================");
        
        // Show initial room
        self.show_room()?;
        
        loop {
            print!("> ");
            io::stdout().flush()?;
            
            let mut input = String::new();
            io::stdin().read_line(&mut input)?;
            
            let command = input.trim().to_lowercase();
            
            if command == "quit" || command == "exit" || command == "q" {
                println!("Thanks for playing! :D");
                break;
            }
            
            match self.process_command(&command).await {
                Ok(output) => {
                    if !output.is_empty() {
                        println!("{}", output);
                    }
                }
                Err(e) => println!("Error: {}", e),
            }
            
            // Show room description again after certain commands
            if matches!(parse_command(&command), Command::Go(_) | Command::North | Command::South | Command::East | Command::West) {
                self.show_room()?;
            }
        }
        
        Ok(())
    }
    
    async fn process_command(&mut self, input: &str) -> Result<String, GameError> {
        match parse_command(&command) {
                Command::Look => self.look(),
                Command::Go(direction) => self.go(&direction),
                Command::North => self.go("north"),
                Command::South => self.go("south"),
                Command::East => self.go("east"),
                Command::West => self.go("west"),
                Command::Take(item) => self.take(&item),
                Command::Drop(item) => self.drop(&item),
                Command::Inventory => self.show_inventory(),
                Command::Save(filename) => self.save(&filename),
                Command::Load(filename) => self.load(&filename),
                Command::ListSaves => Ok(self.list_saves()),
                Command::Help => Ok(self.help()),
                Command::Unknown => Ok("I don't understand that command. Type 'help' for available commands. :0".to_string()),
            }
    }
    
    fn look(&self) -> Result<String, GameError> {
        let room = self.get_current_room()?;
        let mut output = String::new();
        
        output.push_str(&format!("\n{}", room.title));
        output.push_str(&format!("\n{}", room.description));
        
        if !room.items.is_empty() {
            output.push_str("\n\nYou see: ");
            for (i, item_id) in room.items.iter().enumerate() {
                if let Some(item) = self.story.items.get(item_id) {
                    if i > 0 { output.push_str(", "); }
                    output.push_str(&item.name);
                }
            }
        }
        
        if !room.exits.is_empty() {
            output.push_str("\n\nExits: ");
            let exit_names: Vec<String> = room.exits.keys().cloned().collect();
            output.push_str(&exit_names.join(", "));
        }
        
        Ok(output)
    }
    
    fn go(&mut self, direction: &str) -> Result<String, GameError> {
        let current_room = self.get_current_room()?;
        
        if let Some(next_room_id) = current_room.exits.get(direction) {
            if self.story.rooms.contains_key(next_room_id) {
                self.current_room = next_room_id.clone();
                Ok(format!("You go {}.", direction))
            } else {
                Err(GameError::RoomNotFound)
            }
        } else {
            Ok(format!("You can't go {} from here.", direction))
        }
    }
    
    fn take(&mut self, item_name: &str) -> Result<String, GameError> {
        // Find the item by partial name match
        let mut found_item_id = None;
        {
            let current_room = self.get_current_room()?;
            for item_id in &current_room.items {
                if let Some(item) = self.story.items.get(item_id) {
                    if item.name.to_lowercase().contains(&item_name.to_lowercase()) {
                        found_item_id = Some(item_id.clone());
                        break;
                    }
                }
            }
        }
        
        if let Some(item_id) = found_item_id {
            // We need to remove the item from the room and add to inventory
            if let Some(room) = self.story.rooms.get_mut(&self.current_room) {
                room.items.retain(|id| id != &item_id);
            }
            self.inventory.insert(item_id.clone());
            
            if let Some(item) = self.story.items.get(&item_id) {
                Ok(format!("You take the {}.", item.name))
            } else {
                Ok("You take the item.".to_string())
            }
        } else {
            Err(GameError::ItemNotFound)
        }
    }
    
    fn drop(&mut self, item_name: &str) -> Result<String, GameError> {
        // Find the item in inventory by partial name match
        let mut found_item_id = None;
        for item_id in &self.inventory {
            if let Some(item) = self.story.items.get(item_id) {
                if item.name.to_lowercase().contains(&item_name.to_lowercase()) {
                    found_item_id = Some(item_id.clone());
                    break;
                }
            }
        }
        
        if let Some(item_id) = found_item_id {
            self.inventory.remove(&item_id);
            if let Some(room) = self.story.rooms.get_mut(&self.current_room) {
                room.items.push(item_id.clone());
            }
            
            if let Some(item) = self.story.items.get(&item_id) {
                Ok(format!("You drop the {}.", item.name))
            } else {
                Ok("You drop the item.".to_string())
            }
        } else {
            Err(GameError::ItemNotFound)
        }
    }
    
    fn show_inventory(&self) -> Result<String, GameError> {
        if self.inventory.is_empty() {
            Ok("Your inventory is empty. :0".to_string())
        } else {
            let mut output = "You are carrying:\n".to_string();
            for item_id in &self.inventory {
                if let Some(item) = self.story.items.get(item_id) {
                    output.push_str(&format!("- {}\n", item.name));
                }
            }
            // Remove the trailing newline
            if output.ends_with('\n') {
                output.pop();
            }
            Ok(output)
        }
    }
    
    fn help(&self) -> String {
        "Available commands:
- look: Look around the current room
- go [direction]: Move in a direction (north, south, east, west)
- n/s/e/w: Short forms for directions
- take [item]: Pick up an item
- drop [item]: Drop an item
- inventory: Check your inventory
- save [filename]: Save the current game
- load [filename]: Load a saved game
- help: Show this help
- quit: Exit the game

Example: 'go north' or 'take key' :D".to_string()
    }
    
    fn save(&self, filename: &str) -> Result<String, GameError> {
        let save_data = SavedGame {
            current_room: self.current_room.clone(),
            inventory: self.inventory.clone(),
        };
        
        let json = serde_json::to_string(&save_data).map_err(|_| GameError::InvalidRoom)?;
        fs::write(filename, json).map_err(|_| GameError::InvalidRoom)?;
        
        Ok(format!("Game saved to {}", filename))
    }
    
    fn load(&mut self, filename: &str) -> Result<String, GameError> {
        let json = fs::read_to_string(filename).map_err(|_| GameError::InvalidRoom)?;
        let save_data: SavedGame = serde_json::from_str(&json).map_err(|_| GameError::InvalidRoom)?;
        
        self.current_room = save_data.current_room;
        self.inventory = save_data.inventory;
        
        Ok(format!("Game loaded from {}", filename))
    }
    
    fn get_save_files(&self) -> Vec<String> {\n        let mut saves = Vec::new();\n        if let Ok(entries) = fs::read_dir(\".\") {\n            for entry in entries {\n                if let Ok(entry) = entry {\n                    let path = entry.path();\n                    if path.extension().map_or(false, |ext| ext == \"save\") {\n                        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {\n                            saves.push(name.to_string());\n                        }\n                    }\n                }\n            }\n        }\n        saves\n    }\n    \n    fn list_saves(&self) -> String {\n        let saves = self.get_save_files();\n        if saves.is_empty() {\n            \"No save files found. :0\".to_string()\n        } else {\n            let mut output = \"Available saves:\\n\".to_string();\n            for save in saves {\n                output.push_str(&format!(\"- {}\\n\", save));\n            }\n            // Remove the trailing newline\n            if output.ends_with('\\n') {\n                output.pop();\n            }\n            output\n        }\n    }
    
    fn show_room(&self) -> Result<(), Box<dyn std::error::Error>> {
        let room = self.get_current_room()?;
        
        execute!(
            io::stdout(),
            SetForegroundColor(Color::Cyan),
            Print(format!("{}\n", room.title)),
            ResetColor
        )?;
        
        execute!(
            io::stdout(),
            Print(format!("{}\n", room.description)),
        )?;
        
        Ok(())
    }
    
    fn get_current_room(&self) -> Result<&Room, GameError> {
        self.story.rooms.get(&self.current_room).ok_or(GameError::InvalidRoom)
    }
    
    fn clear_screen(&self) -> Result<(), Box<dyn std::error::Error>> {
        execute!(io::stdout(), Clear(ClearType::All))?;
        Ok(())
    }
}// Basic game loop implemented
// Inventory system - take/drop items :D
// Save system with json files
// Better error messages

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn test_game_creation() {
        // Create a minimal story for testing
        let mut rooms = HashMap::new();
        rooms.insert(
            "test_room".to_string(), 
            Room {
                title: "Test Room".to_string(),
                description: "A test room".to_string(),
                exits: HashMap::new(),
                items: vec!["test_item".to_string()],
            }
        );

        let mut items = HashMap::new();
        items.insert(
            "test_item".to_string(),
            Item {
                name: "Test Item".to_string(),
                description: "A test item".to_string(),
            }
        );

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "test_room".to_string(),
            },
            rooms,
            items,
        };

        let game = Game::new(story);
        assert!(game.is_ok());
    }

    #[test]
    fn test_take_item() {
        // Create a story with an item in a room
        let mut rooms = HashMap::new();
        let mut exits = HashMap::new();
        exits.insert("north".to_string(), "other_room".to_string());
        rooms.insert(
            "start".to_string(), 
            Room {
                title: "Start Room".to_string(),
                description: "A starting room".to_string(),
                exits,
                items: vec!["key".to_string()],
            }
        );
        rooms.insert(
            "other_room".to_string(), 
            Room {
                title: "Other Room".to_string(),
                description: "Another room".to_string(),
                exits: HashMap::new(),
                items: vec![],
            }
        );

        let mut items = HashMap::new();
        items.insert(
            "key".to_string(),
            Item {
                name: "Brass Key".to_string(),
                description: "An old brass key".to_string(),
            }
        );

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "start".to_string(),
            },
            rooms,
            items,
        };

        let mut game = Game::new(story).unwrap();
        
        // Test taking an item that exists
        let result = game.take("key");
        assert!(result.is_ok());
        assert!(result.unwrap().contains("take the"));
        
        // Verify the item is now in inventory
        assert!(game.inventory.contains("key"));
        
        // Verify the item is no longer in the room
        let room = game.story.rooms.get("start").unwrap();
        assert!(!room.items.contains(&"key".to_string()));
    }

    #[test]
    fn test_drop_item() {
        // Create a story for testing
        let mut rooms = HashMap::new();
        rooms.insert(
            "start".to_string(), 
            Room {
                title: "Start Room".to_string(),
                description: "A starting room".to_string(),
                exits: HashMap::new(),
                items: vec![],
            }
        );

        let mut items = HashMap::new();
        items.insert(
            "key".to_string(),
            Item {
                name: "Brass Key".to_string(),
                description: "An old brass key".to_string(),
            }
        );

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "start".to_string(),
            },
            rooms,
            items,
        };

        let mut game = Game::new(story).unwrap();
        
        // Add an item directly to inventory for testing drop
        game.inventory.insert("key".to_string());
        
        // Test dropping an item that exists in inventory
        let result = game.drop("key");
        assert!(result.is_ok());
        assert!(result.unwrap().contains("drop the"));
        
        // Verify the item is no longer in inventory
        assert!(!game.inventory.contains("key"));
        
        // Verify the item is now in the room
        let room = game.story.rooms.get("start").unwrap();
        assert!(room.items.contains(&"key".to_string()));
    }

    #[test]
    fn test_go_command() {
        // Create a story with connected rooms
        let mut rooms = HashMap::new();
        let mut exits = HashMap::new();
        exits.insert("north".to_string(), "north_room".to_string());
        rooms.insert(
            "start".to_string(), 
            Room {
                title: "Start Room".to_string(),
                description: "A starting room".to_string(),
                exits,
                items: vec![],
            }
        );
        
        rooms.insert(
            "north_room".to_string(), 
            Room {
                title: "North Room".to_string(),
                description: "A room to the north".to_string(),
                exits: HashMap::new(),
                items: vec![],
            }
        );

        let items = HashMap::new();

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "start".to_string(),
            },
            rooms,
            items,
        };

        let mut game = Game::new(story).unwrap();
        
        // Test moving to a connected room
        let result = game.go("north");
        assert!(result.is_ok());
        assert!(result.unwrap().contains("go north"));
        
        // Verify the current room has changed
        assert_eq!(game.current_room, "north_room");
    }

    #[test]
    fn test_look_command() {
        let mut rooms = HashMap::new();
        let mut exits = HashMap::new();
        exits.insert("north".to_string(), "other_room".to_string());
        rooms.insert(
            "start".to_string(), 
            Room {
                title = "Start Room".to_string(),
                description = "A starting room with exits north".to_string(),
                exits,
                items: vec!["key".to_string()],
            }
        );

        let mut items = HashMap::new();
        items.insert(
            "key".to_string(),
            Item {
                name: "Brass Key".to_string(),
                description: "An old brass key".to_string(),
            }
        );

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "start".to_string(),
            },
            rooms,
            items,
        };

        let game = Game::new(story).unwrap();
        
        // Test looking at the current room
        let result = game.look();
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Start Room"));
        assert!(output.contains("A starting room with exits north"));
        assert!(output.contains("key")); // Should show the item in the room
        assert!(output.contains("north")); // Should show the exit
    }

    #[test]
    fn test_show_inventory() {
        let mut rooms = HashMap::new();
        rooms.insert(
            "start".to_string(), 
            Room {
                title: "Start Room".to_string(),
                description: "A starting room".to_string(),
                exits: HashMap::new(),
                items: vec![],
            }
        );

        let mut items = HashMap::new();
        items.insert(
            "key".to_string(),
            Item {
                name: "Brass Key".to_string(),
                description: "An old brass key".to_string(),
            }
        );

        let story = Story {
            story: StoryInfo {
                title: "Test Story".to_string(),
                start_room: "start".to_string(),
            },
            rooms,
            items,
        };

        let mut game = Game::new(story).unwrap();
        
        // Test empty inventory
        let result = game.show_inventory();
        assert!(result.is_ok());
        assert!(result.unwrap().contains("empty"));
        
        // Add an item to inventory
        game.inventory.insert("key".to_string());
        
        // Test non-empty inventory
        let result = game.show_inventory();
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Brass Key"));
    }
}