amble_engine 0.67.0

Data-first interactive fiction engine and REPL for worlds authored in the Amble DSL.
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
//! Data structures representing the game world.
//!
//! This module defines [`AmbleWorld`] and related types used at runtime to
//! track the current state of the adventure.

use crate::item::{ContainerState, ItemVisibility};
use crate::loader::scoring::ScoringConfig;
use crate::npc::Npc;
use crate::spinners::{CoreSpinnerType, SpinnerType, TextPool};
use crate::trigger::Trigger;
use crate::{AMBLE_VERSION, ItemId, NpcId, RoomId};
use crate::{Goal, Item, Player, Room, Scheduler};

use anyhow::{Context, Result, anyhow};
use log::info;
use serde::{Deserialize, Serialize};

use crate::Id;
use std::collections::{HashMap, HashSet};
use variantly::Variantly;

/// Kinds of places where a `WorldObject` may be located.
/// Because Rooms *are* the locations, their location is always `Nowhere`
/// Unspawned/despawned items and NPCs are also located `Nowhere`
#[derive(Debug, Default, Clone, Serialize, Deserialize, Variantly, PartialEq, Eq)]
pub enum Location {
    Item(ItemId),
    Inventory,
    #[default]
    Nowhere,
    Npc(NpcId),
    Room(RoomId),
}

impl Location {
    /// Return the room id if this `Location` is [`Location::Room`].
    ///
    /// # Errors
    ///
    /// Returns an error if the location is not a room.
    pub fn room_id(&self) -> Result<RoomId> {
        self.room_ref()
            .cloned()
            .ok_or_else(|| anyhow!("location is not a room"))
    }
}

/// Common API shared by rooms, items, NPCs, and the player.
///
/// Note: There is a duplication here. `id()` and `symbol()` effectively return different
/// views of the same string. It is a throwback to when the engine read TOML and assigned
/// UUIDs to entities. The DSL symbol strings now *are* the Ids,
pub trait WorldObject {
    /// Stable id assigned to the object.
    fn id(&self) -> Id;
    /// Symbol used in world data to refer to the object.
    fn symbol(&self) -> &str;
    /// Display-friendly name.
    fn name(&self) -> &str;
    /// Long-form description shown to players.
    fn description(&self) -> &str;
    /// Current location of the object within the world.
    fn location(&self) -> &Location;
}

/// Complete state of the running game.
///
/// `AmbleWorld` contains every room, item, NPC and trigger currently active, as
/// well as the player character. It is created during loading and then mutated
/// throughout gameplay.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AmbleWorld {
    /// Rooms or areas that define the game world
    pub rooms: HashMap<RoomId, Room>,
    /// Inanimate objects
    pub items: HashMap<ItemId, Item>,
    /// Actions that fire in response to events or changes in world state
    pub triggers: Vec<Trigger>,
    /// The player character
    pub player: Player,
    /// History of the player's path since the beginning of the game (Room IDs)
    #[serde(default)]
    pub player_path: Vec<RoomId>,
    /// Text / phrase randomizers for ambient events, status effects, and non-repetitive engine messages.
    pub spinners: HashMap<SpinnerType, TextPool>,
    /// Non-playable characters
    pub npcs: HashMap<NpcId, Npc>,
    /// The maximum achieveable score in the game
    pub max_score: usize,
    /// Goals or achievements to guide player progress
    pub goals: Vec<Goal>,
    /// Configuration for final scoring report when player quits the game
    pub scoring: ScoringConfig,
    /// Game title displayed at startup.
    pub game_title: String,
    /// Stable slug identifying the world content.
    #[serde(default)]
    pub world_slug: String,
    /// World author or studio name.
    #[serde(default)]
    pub world_author: String,
    /// World content version string.
    #[serde(default)]
    pub world_version: String,
    /// Short description used in launchers or choosers.
    #[serde(default)]
    pub world_blurb: String,
    /// Introductory text displayed after the title.
    pub intro_text: String,
    /// The Amble engine version for the current build
    pub version: String,
    /// Number of turns taken so far
    pub turn_count: usize,
    /// The Event Scheduler -- schedules conditional events for future game turns
    pub scheduler: Scheduler,
}
impl AmbleWorld {
    /// Create a new empty world with a default player.
    pub fn new_empty() -> AmbleWorld {
        let world = Self {
            rooms: HashMap::new(),
            npcs: HashMap::new(),
            items: HashMap::new(),
            triggers: Vec::new(),
            player: Player::default(),
            player_path: Vec::new(),
            spinners: HashMap::new(),
            max_score: 0,
            goals: Vec::new(),
            scoring: ScoringConfig::default(),
            game_title: String::new(),
            world_slug: String::new(),
            world_author: String::new(),
            world_version: String::new(),
            world_blurb: String::new(),
            intro_text: String::new(),
            version: AMBLE_VERSION.to_string(),
            turn_count: 0,
            scheduler: Scheduler::default(),
        };
        info!("new, empty 'AmbleWorld' created");
        world
    }

    /// Returns a random string from the selected spinner type, or a supplied default.
    pub fn spin_spinner(&self, spin_type: &SpinnerType, default: &'static str) -> String {
        self.spinners
            .get(spin_type)
            .map(TextPool::draw)
            .unwrap_or_else(|| default.to_string())
    }

    /// Convenience method to spin a core spinner type.
    pub fn spin_core(&self, core_type: CoreSpinnerType, default: &'static str) -> String {
        self.spin_spinner(&SpinnerType::Core(core_type), default)
    }

    /// Convenience method to spin a custom spinner by key.
    pub fn spin_custom(&self, key: &str, default: &'static str) -> String {
        self.spin_spinner(&SpinnerType::Custom(key.to_string()), default)
    }

    pub fn player_room_id(&self) -> RoomId {
        self.player
            .location
            .clone()
            .expect_room("player should always be in a Room")
    }

    /// Obtain a reference to the room the player occupies.
    /// # Errors
    /// - if player isn't in a Room or the Room's id is not found
    pub fn player_room_ref(&self) -> Result<&Room> {
        match &self.player.location {
            Location::Room(room_id) => self
                .rooms
                .get(room_id)
                .ok_or_else(|| anyhow!("player's room id ({room_id}) not found in world")),
            _ => Err(anyhow!("player not in a room - located at {:?}", self.player.location)),
        }
    }

    /// Obtain a mutable reference to the room the player occupies.
    /// # Errors
    /// - if player is not in a room or room's id is not found
    pub fn player_room_mut(&mut self) -> Result<&mut Room> {
        match &self.player.location {
            Location::Room(room_id) => self
                .rooms
                .get_mut(room_id)
                .ok_or_else(|| anyhow!("player's room id ({room_id}) not found in world")),
            _ => Err(anyhow!("player not in a room - located at {:?}", self.player.location)),
        }
    }

    /// Get a mutable reference to an item by id, if present.
    pub fn get_item_mut(&mut self, item_id: &ItemId) -> Option<&mut Item> {
        self.items.get_mut(item_id)
    }
}

/// Collect all item ids visible within a `Room` according to a predicate.
///
/// Items stored directly in the room are always included. Contents of containers are only
/// traversed if the supplied `should_include_contents` function returns `true` for the
/// container item (typically when it either is open or transparent).
fn collect_room_items(
    world: &AmbleWorld,
    room_id: &RoomId,
    // Predicate determining whether an item's contents should be collected
    should_include_contents: impl Fn(&Item) -> bool,
    // Predicate determining whether an item itself should be included
    should_include_item: impl Fn(&Item) -> bool,
) -> Result<HashSet<ItemId>> {
    let current_room = world
        .rooms
        .get(room_id)
        .with_context(|| format!("{room_id} room id not found"))?;
    let room_items = &current_room.contents;
    let mut visible_room_items = HashSet::new();
    let mut contained_items = HashSet::new();
    for item_id in room_items {
        if let Some(item) = world.items.get(item_id) {
            if !should_include_item(item) {
                continue;
            }
            visible_room_items.insert(item_id.clone());
            if should_include_contents(item) {
                for contained_id in &item.contents {
                    if let Some(contained_item) = world.items.get(contained_id)
                        && should_include_item(contained_item)
                    {
                        contained_items.insert(contained_id.clone());
                    }
                }
            }
        }
    }
    Ok(visible_room_items.union(&contained_items).cloned().collect())
}

pub(crate) fn item_is_visible_item(item: &Item, world: &AmbleWorld) -> bool {
    item.visible_when.as_ref().is_none_or(|cond| cond.eval(world))
}

/// Returns true if the item passes its visibility condition (if any).
pub fn item_is_visible(world: &AmbleWorld, item_id: &ItemId) -> bool {
    world
        .items
        .get(item_id)
        .is_some_and(|item| item_is_visible_item(item, world))
}

/// Returns true if the item should be listed in automatic room/container listings.
pub fn item_is_listed(world: &AmbleWorld, item_id: &ItemId) -> bool {
    world
        .items
        .get(item_id)
        .is_some_and(|item| item.visibility == ItemVisibility::Listed)
}

/// Constructs a set of all potentially take-able / viewable item ids in a room.
/// Non-portable or restricted items not filtered here -- player discovers
/// that on their own. The scope includes items in room, and items in open containers.
/// Items in closed or locked containers and NPCs are excluded.
///
/// # Errors
/// - if supplied `room_id` is invalid
pub fn nearby_reachable_items(world: &AmbleWorld, room_id: &RoomId) -> Result<HashSet<ItemId>> {
    collect_room_items(
        world,
        room_id,
        |item| item.container_state == Some(ContainerState::Open),
        |item| item_is_visible_item(item, world),
    )
}

/// Get all items that are visible in the room, including those in transparent containers.
///
/// # Errors
/// - if supplied `room_id` is invalid
pub fn nearby_visible_items(world: &AmbleWorld, room_id: &RoomId) -> Result<HashSet<ItemId>> {
    collect_room_items(
        world,
        room_id,
        |item| item.container_state == Some(ContainerState::Open) || item.is_transparent(),
        |item| item_is_visible_item(item, world),
    )
}

/// Get a list of IDs of all items in the room that are containers.
///
/// # Errors
/// - if supplied `room_id` is invalid
pub fn nearby_vessel_items(world: &AmbleWorld, room_id: &RoomId) -> Result<HashSet<ItemId>> {
    let current_room = world
        .rooms
        .get(room_id)
        .with_context(|| format!("{room_id} room id not found"))?;
    let room_items = &current_room.contents;
    let mut contained_items = HashSet::new();
    for item_id in room_items {
        if let Some(item) = world.items.get(item_id) {
            contained_items.extend(item.contents.iter().cloned());
        }
    }
    let all_local_items: HashSet<_> = room_items.union(&contained_items).cloned().collect();
    let mut vessels = HashSet::new();
    for item_id in all_local_items {
        if let Some(item) = world.items.get(&item_id)
            && item.container_state.is_some()
            && item_is_visible_item(item, world)
        {
            vessels.insert(item_id);
        }
    }
    Ok(vessels)
}

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

    use crate::{
        health::HealthState,
        item::{ContainerState, Item, Movability},
        npc::{Npc, NpcState},
        player::Player,
        room::Room,
        spinners::{SpinnerType, TextPool},
    };
    use std::collections::{HashMap, HashSet};

    fn create_test_item(id: &ItemId, location: Location) -> Item {
        Item {
            id: id.clone(),
            symbol: format!("item_{id}"),
            name: format!("Item {id}"),
            description: "A test item".into(),
            location,
            visibility: crate::item::ItemVisibility::Listed,
            visible_when: None,
            aliases: Vec::new(),
            movability: Movability::Free,
            container_state: None,
            contents: HashSet::new(),
            abilities: HashSet::new(),
            interaction_requires: HashMap::new(),
            text: None,
            consumable: None,
        }
    }

    fn create_test_room(id: &RoomId) -> Room {
        Room {
            id: id.clone(),
            symbol: format!("room_{id}"),
            name: format!("Room {id}"),
            base_description: "A test room".into(),
            overlays: vec![],
            scenery: Vec::new(),
            scenery_default: None,
            location: Location::Nowhere,
            visited: false,
            exits: HashMap::new(),
            contents: HashSet::new(),
            npcs: HashSet::new(),
        }
    }

    #[allow(dead_code)]
    fn create_test_npc(id: &NpcId, location: Location) -> Npc {
        Npc {
            id: id.clone(),
            symbol: format!("npc_{id}"),
            name: format!("NPC {id}"),
            description: "A test NPC".into(),
            location,
            inventory: HashSet::new(),
            dialogue: HashMap::new(),
            state: NpcState::Normal,
            movement: None,
            health: HealthState::new(),
        }
    }

    #[test]
    fn location_variants_work() {
        let item_id: ItemId = crate::idgen::new_id().into();
        let room_id = crate::idgen::new_room_id();
        let npc_id: NpcId = crate::idgen::new_id().into();

        assert_eq!(Location::Item(item_id.clone()), Location::Item(item_id.clone()));
        assert_eq!(Location::Room(room_id.clone()), Location::Room(room_id.clone()));
        assert_eq!(Location::Npc(npc_id.clone()), Location::Npc(npc_id.clone()));
        assert_eq!(Location::Inventory, Location::Inventory);
        assert_eq!(Location::Nowhere, Location::Nowhere);

        assert_ne!(Location::Inventory, Location::Nowhere);
        assert_ne!(Location::Room(room_id.clone()), Location::Item(item_id.clone()));
    }

    #[test]
    fn location_default_is_nowhere() {
        assert_eq!(Location::default(), Location::Nowhere);
    }

    #[test]
    fn location_is_nowhere_works() {
        assert!(Location::Nowhere.is_nowhere());
        assert!(!Location::Inventory.is_nowhere());
        assert!(!Location::Room(crate::idgen::new_room_id()).is_nowhere());
    }

    #[test]
    fn location_is_not_nowhere_works() {
        assert!(!Location::Nowhere.is_not_nowhere());
        assert!(Location::Inventory.is_not_nowhere());
        assert!(Location::Room(crate::idgen::new_room_id()).is_not_nowhere());
    }

    #[test]
    fn location_room_id_works() {
        let room_id = crate::idgen::new_id();
        let location = Location::Room(RoomId::new(&room_id));
        assert_eq!(location.room_id().unwrap(), room_id);
    }

    #[test]
    fn location_room_id_errors_on_non_room() {
        assert!(Location::Inventory.room_id().is_err());
    }

    #[test]
    fn location_room_ref_works() {
        let room_id = crate::idgen::new_id();
        let location = Location::Room(RoomId::new(&room_id));
        assert_eq!(location.room_ref(), Some(&RoomId::new(&room_id)));

        assert_eq!(Location::Inventory.room_ref(), None);
        assert_eq!(Location::Nowhere.room_ref(), None);
    }

    #[test]
    fn amble_world_new_empty_creates_valid_world() {
        let world = AmbleWorld::new_empty();

        assert!(world.rooms.is_empty());
        assert!(world.items.is_empty());
        assert!(world.triggers.is_empty());
        assert!(world.npcs.is_empty());
        assert!(world.goals.is_empty());
        assert!(world.spinners.is_empty());
        assert_eq!(world.max_score, 0);
        assert_eq!(world.version, crate::AMBLE_VERSION);
        assert_eq!(world.player.name, "The Candidate");
    }

    #[test]
    fn amble_world_spin_spinner_returns_result_or_default() {
        let mut world = AmbleWorld::new_empty();

        // Test with no spinner
        let result = world.spin_spinner(&SpinnerType::Core(CoreSpinnerType::Movement), "default");
        assert_eq!(result, "default");

        // Test with spinner
        let spinner = TextPool::new(["custom result".to_string()]).unwrap();
        world
            .spinners
            .insert(SpinnerType::Core(CoreSpinnerType::Movement), spinner);

        let result = world.spin_spinner(&SpinnerType::Core(CoreSpinnerType::Movement), "default");
        assert_eq!(result, "custom result");
    }

    #[test]
    fn amble_world_spin_core_convenience() {
        let world = AmbleWorld::new_empty();

        // Test core convenience method
        let result = world.spin_core(CoreSpinnerType::Movement, "default");
        assert_eq!(result, "default");
    }

    #[test]
    fn amble_world_spin_custom_convenience() {
        let mut world = AmbleWorld::new_empty();

        // Test custom convenience method
        let result = world.spin_custom("testSpinner", "default");
        assert_eq!(result, "default");

        // Add a custom spinner and test
        let spinner = TextPool::new(["custom result".to_string()]).unwrap();
        world
            .spinners
            .insert(SpinnerType::Custom("testSpinner".to_string()), spinner);

        let result = world.spin_custom("testSpinner", "default");
        assert_eq!(result, "custom result");
    }

    #[test]
    fn amble_world_player_room_ref_works() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let room = create_test_room(&RoomId::new(&room_id));
        world.rooms.insert(RoomId::new(&room_id), room);
        world.player.location = Location::Room(RoomId::new(&room_id));

        let room_ref = world.player_room_ref().unwrap();
        assert_eq!(room_ref.id, room_id);
    }

    #[test]
    fn amble_world_player_room_ref_errors_when_not_in_room() {
        let world = AmbleWorld::new_empty();
        // Player defaults to Room location but room doesn't exist
        assert!(world.player_room_ref().is_err());
    }

    #[test]
    fn amble_world_player_room_ref_errors_when_player_in_inventory() {
        let mut world = AmbleWorld::new_empty();
        world.player.location = Location::Inventory;
        assert!(world.player_room_ref().is_err());
    }

    #[test]
    fn amble_world_player_room_mut_works() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let room = create_test_room(&RoomId::new(&room_id));
        world.rooms.insert(RoomId::new(&room_id), room);
        world.player.location = Location::Room(RoomId::new(&room_id));

        let room_mut = world.player_room_mut().unwrap();
        room_mut.visited = true;
        assert!(world.rooms.get(&RoomId::new(&room_id)).unwrap().visited);
    }

    #[test]
    fn amble_world_player_room_mut_errors_when_not_in_room() {
        let mut world = AmbleWorld::new_empty();
        world.player.location = Location::Inventory;
        assert!(world.player_room_mut().is_err());
    }

    #[test]
    fn amble_world_get_item_mut_works() {
        let item_id = ItemId::from("test_item");
        let mut world = AmbleWorld::new_empty();
        let item = create_test_item(&item_id, Location::Nowhere);
        world.items.insert(item_id.clone(), item);

        let item_mut = world.get_item_mut(&ItemId::from("test_item")).unwrap();
        item_mut.movability = Movability::Restricted {
            reason: "restricted".into(),
        };
        assert!(matches!(
            world.items.get(&ItemId::from("test_item")).unwrap().movability,
            Movability::Restricted { .. }
        ));
    }

    #[test]
    fn amble_world_get_item_mut_returns_none_for_nonexistent() {
        let mut world = AmbleWorld::new_empty();
        assert!(world.get_item_mut(&ItemId::from("test")).is_none());
    }

    #[test]
    fn nearby_reachable_items_includes_room_items() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let mut room = create_test_room(&RoomId::new(&room_id));

        let item_id: ItemId = crate::idgen::new_id().into();
        let item = create_test_item(&item_id, Location::Room(RoomId::new(&room_id)));
        room.contents.insert(item_id.clone());

        world.rooms.insert(RoomId::new(&room_id), room);
        world.items.insert(item_id.clone(), item);

        let reachable = nearby_reachable_items(&world, &room_id.into()).unwrap();
        assert!(reachable.contains(&item_id));
    }

    #[test]
    fn nearby_reachable_items_includes_open_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let mut room = create_test_room(&RoomId::new(&room_id));

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(RoomId::new(&room_id)));
        container.container_state = Some(ContainerState::Open);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());

        world.rooms.insert(RoomId::new(&room_id), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let reachable = nearby_reachable_items(&world, &RoomId::new(&room_id)).unwrap();
        assert!(reachable.contains(&container_id));
        assert!(reachable.contains(&item_in_container_id));
    }

    #[test]
    fn nearby_reachable_items_excludes_closed_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let mut room = create_test_room(&RoomId::new(&room_id));

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(RoomId::new(&room_id)));
        container.container_state = Some(ContainerState::Closed);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());

        world.rooms.insert(RoomId::new(&room_id), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let reachable = nearby_reachable_items(&world, &RoomId::new(&room_id)).unwrap();
        assert!(reachable.contains(&container_id));
        assert!(!reachable.contains(&item_in_container_id));
    }

    #[test]
    fn nearby_reachable_items_excludes_locked_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let mut room = create_test_room(&RoomId::new(&room_id));

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(RoomId::new(&room_id)));
        container.container_state = Some(ContainerState::Locked);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());

        world.rooms.insert(RoomId::new(&room_id), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let reachable = nearby_reachable_items(&world, &RoomId::new(&room_id)).unwrap();
        assert!(reachable.contains(&container_id));
        assert!(!reachable.contains(&item_in_container_id));
    }

    #[test]
    fn nearby_reachable_items_errors_for_invalid_room() {
        let world = AmbleWorld::new_empty();
        let result = nearby_reachable_items(&world, &"fleefawrtwerse".into());
        assert!(result.is_err());
    }

    #[test]
    fn nearby_reachable_items_handles_empty_room() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_id();
        let room = create_test_room(&RoomId::new(&room_id));
        world.rooms.insert(RoomId::new(&room_id), room);

        let reachable = nearby_reachable_items(&world, &RoomId::new(&room_id)).unwrap();
        assert!(reachable.is_empty());
    }

    #[test]
    fn nearby_reachable_items_handles_non_container_items() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_room_id();
        let mut room = create_test_room(&RoomId::new(&room_id));

        let item_id: ItemId = crate::idgen::new_id().into();
        let item = create_test_item(&item_id, Location::Room(room_id.clone()));
        room.contents.insert(item_id.clone());

        world.rooms.insert(room_id.clone(), room);
        world.items.insert(item_id.clone(), item);

        let reachable = nearby_reachable_items(&world, &room_id).unwrap();
        assert_eq!(reachable.len(), 1);
        assert!(reachable.contains(&item_id));
    }

    #[test]
    fn nearby_visible_items_includes_transparent_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_room_id();
        let mut room = create_test_room(&room_id);

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(room_id.clone()));
        container.container_state = Some(ContainerState::TransparentClosed);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());
        world.rooms.insert(room_id.clone(), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let visible = nearby_visible_items(&world, &room_id).unwrap();
        assert_eq!(visible.len(), 2);
        assert!(visible.contains(&container_id));
        assert!(visible.contains(&item_in_container_id));
    }

    #[test]
    fn nearby_visible_items_includes_transparent_locked_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_room_id();
        let mut room = create_test_room(&room_id);

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(room_id.clone()));
        container.container_state = Some(ContainerState::TransparentLocked);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());
        world.rooms.insert(room_id.clone(), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let visible = nearby_visible_items(&world, &room_id).unwrap();
        assert_eq!(visible.len(), 2);
        assert!(visible.contains(&container_id));
        assert!(visible.contains(&item_in_container_id));
    }

    #[test]
    fn nearby_visible_items_excludes_regular_locked_container_contents() {
        let mut world = AmbleWorld::new_empty();
        let room_id = crate::idgen::new_room_id();
        let mut room = create_test_room(&room_id);

        let container_id: ItemId = crate::idgen::new_id().into();
        let mut container = create_test_item(&container_id, Location::Room(room_id.clone()));
        container.container_state = Some(ContainerState::Locked);

        let item_in_container_id: ItemId = crate::idgen::new_id().into();
        let item_in_container = create_test_item(&item_in_container_id, Location::Item(container_id.clone()));
        container.contents.insert(item_in_container_id.clone());

        room.contents.insert(container_id.clone());
        world.rooms.insert(room_id.clone(), room);
        world.items.insert(container_id.clone(), container);
        world.items.insert(item_in_container_id.clone(), item_in_container);

        let visible = nearby_visible_items(&world, &room_id).unwrap();
        assert_eq!(visible.len(), 1);
        assert!(visible.contains(&container_id));
        assert!(!visible.contains(&item_in_container_id));
    }

    #[test]
    fn world_object_trait_implemented_for_player() {
        let player = Player::default();
        assert!(!player.id().is_empty());
        assert_eq!(player.symbol(), "the_candidate");
        assert_eq!(player.name(), "The Candidate");
        assert_eq!(player.description(), "default");
        assert_eq!(player.location(), &Location::default());
    }

    #[test]
    fn amble_world_serialization_includes_version() {
        let world = AmbleWorld::new_empty();
        assert_eq!(world.version, crate::AMBLE_VERSION);
    }
}