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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! Item types and related helpers.
//!
//! Items represent objects the player can interact with. Some may act as
//! containers for other items. Functions here handle display logic and
//! movement between locations.

use crate::{
    ItemId, Location, NpcId, RoomId, View, ViewItem, WorldObject,
    scheduler::EventCondition,
    style::GameStyle,
    view::ContentLine,
    world::{AmbleWorld, item_is_listed, item_is_visible},
};

use anyhow::{Context, Result};
use colored::Colorize;

use crate::Id;
use log::info;
use serde::{Deserialize, Serialize};
use std::{
    collections::{HashMap, HashSet},
    fmt::Display,
};
use variantly::Variantly;

/// Anything in '`AmbleWorld`' that can be inspected or manipulated apart from NPCs.
///
/// Some 'Items' can also act as containers for other items, if '`container_state`' is 'Some(_)'.
/// `symbol` and `id` refer to the same string -- a holdover from a previous engine version where they differed.
///
/// `movability` specifies whether the `Item` can change location, and why not if it can't.
///
/// 'abilities' are special things you can do with this item (e.g. read, smash, ignite, clean)
///
/// '`interaction_requires`' maps a type of interaction (a thing that can be done to this item using another item) to an ability.
///     e.g. `ItemInteractionType::Burn` => `ItemAbility::Ignite`
///
/// Combined with an appropriate ActOnItem-based trigger, this would mean any `Item` with `ItemAbility::Ignite` can be
/// used to `Burn` this item -- and importantly _only_ items with that ability can be used to Burn it.
///
/// 'consumable' makes an item consumable if present, with number of uses and what to do when
/// all uses are expended defined in `ConsumableOpts`.
///
#[derive(Debug, Serialize, Deserialize, Default, Clone)]
pub struct Item {
    /// The stable id of this item.
    pub id: ItemId,
    /// The symbol used to refer to this item in world data.
    pub symbol: String,
    /// The display name of the item.
    pub name: String,
    /// A general description of the item.
    pub description: String,
    /// The current `Location` of the item.
    pub location: Location,
    /// Determines whether the item appears in listings or is discoverable.
    #[serde(default)]
    pub visibility: ItemVisibility,
    /// Optional condition gating visibility.
    #[serde(default)]
    pub visible_when: Option<EventCondition>,
    /// Alternate names that can match this item in parser searches.
    #[serde(default)]
    pub aliases: Vec<String>,
    /// Determines whether the item can be moved from its current location.
    pub movability: Movability,
    /// Some state (open, locked, etc) for the item as a container, or `None` if it is not a container.
    pub container_state: Option<ContainerState>,
    /// Set of ids of other items contained by this one.
    pub contents: HashSet<ItemId>,
    /// Set of capabilities [`ItemAbility`] for this item.
    pub abilities: HashSet<ItemAbility>,
    /// Relates interactions to abilities. (Ex: to perform the "burn" interaction targeting this item, the other item must have the "ignite" capability.)
    pub interaction_requires: HashMap<ItemInteractionType, ItemAbility>,
    /// Any legible detail text on the item. **Also used as the detail text for the "examine" command.**
    pub text: Option<String>,
    /// Some consumable parameters [`ConsumableOpts`], or None it the item isn't consumable.
    pub consumable: Option<ConsumableOpts>,
}

/// Determines whether an item is listed (shows in room and item contents listings),
/// scenery (available for some interaction but not specifically listed), or hidden
/// (currently completely hidden from view).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum ItemVisibility {
    #[default]
    Listed,
    Scenery,
    Hidden,
}

impl WorldObject for Item {
    fn id(&self) -> Id {
        self.id.to_string()
    }
    fn symbol(&self) -> &str {
        &self.symbol
    }
    fn name(&self) -> &str {
        &self.name
    }
    fn description(&self) -> &str {
        &self.description
    }
    fn location(&self) -> &Location {
        &self.location
    }
}

impl ItemHolder for Item {
    fn add_item(&mut self, item_id: ItemId) {
        // ensure this is a container and disallow placing an item inside itself
        if self.container_state.is_some() && self.id.ne(&item_id) {
            self.contents.insert(item_id);
        }
    }
    fn remove_item(&mut self, item_id: ItemId) {
        if self.container_state.is_some() {
            self.contents.remove(&item_id);
        }
    }
    fn contains_item(&self, item_id: ItemId) -> bool {
        self.contents.contains(&item_id)
    }
}

impl Item {
    /// Returns true if item is consumable and has been consumed.
    pub fn is_consumed(&self) -> bool {
        match &self.consumable {
            Some(opts) => opts.uses_left == 0,
            None => false,
        }
    }

    /// Returns true if item's contents can be accessed directly.
    pub fn is_accessible(&self) -> bool {
        self.container_state
            .is_some_and(|cs| cs.is_open() || cs.is_transparent_open())
    }

    /// Returns true if the item is a container and its contents are visible even when closed or locked.
    pub fn is_transparent(&self) -> bool {
        self.container_state
            .is_some_and(|cs| cs.is_transparent_closed() || cs.is_transparent_locked() || cs.is_transparent_open())
    }
    /// Set location to a `Room` by id.
    pub fn set_location_room(&mut self, room_id: RoomId) {
        self.location = Location::Room(room_id);
    }
    /// Set location to inside another container `Item` by id.
    pub fn set_location_item(&mut self, container_id: ItemId) {
        self.location = Location::Item(container_id);
    }
    /// Set location to player inventory
    pub fn set_location_inventory(&mut self) {
        // once a restricted item has been obtained, it must be unrestricted (or else the player wouldn't
        // be able to pick it up again after dropping it)
        // if given back to an NPC or "locked in" to a receiver item,
        // it can be optionally re-restricted using a trigger action
        if matches!(self.movability, Movability::Restricted { .. }) {
            self.movability = Movability::Free;
        }
        self.location = Location::Inventory;
    }
    /// Set location to NPC inventory by id.
    pub fn set_location_npc(&mut self, npc_id: NpcId) {
        self.location = Location::Npc(npc_id);
    }
    /// Show item description (and any contents if a container and open).
    pub fn show(&self, world: &AmbleWorld, view: &mut View) {
        // push general desccription to View
        view.push(ViewItem::ItemDescription {
            name: self.name.clone(),
            description: self.description.clone(),
        });

        // push any consumable status to View
        if let Some(opts) = &self.consumable {
            let consuming_abilities: Vec<_> = opts.consume_on.iter().map(ItemAbility::to_string).collect();
            let uses = consuming_abilities.join(" or ").underline();
            view.push(ViewItem::ItemConsumableStatus(format!(
                "You can {uses} {} more time{}.",
                opts.uses_left.to_string().yellow(),
                if opts.uses_left == 1 { "" } else { "s" }
            )));
        }

        // handle container / contained item display
        if self.container_state.is_some() {
            if self.is_accessible() || self.is_transparent() {
                self.show_contents(world, view);
                if self.is_transparent() {
                    self.show_transparency_note(view);
                }
            } else {
                self.show_contents_obscured(view);
            }
        }
    }

    fn show_contents_obscured(&self, view: &mut View) {
        let action = if self.container_state.is_some_and(|cs| cs.is_locked()) {
            "unlock".bold().red()
        } else {
            "open".bold().green()
        };
        view.push(ViewItem::ActionFailure(format!(
            "You must {action} it to see what's inside."
        )));
    }

    fn show_transparency_note(&self, view: &mut View) {
        let action = if self
            .container_state
            .is_some_and(|cs| cs.is_locked() || cs.is_transparent_locked())
        {
            "unlock".bold().red()
        } else {
            "open".bold().green()
        };
        view.push(ViewItem::ActionFailure(format!(
            "You can see inside, but you must {action} it to access the contents."
        )));
    }

    fn show_contents(&self, world: &AmbleWorld, view: &mut View) {
        let visible_contents: Vec<_> = self
            .contents
            .iter()
            .filter(|id| item_is_visible(world, id) && item_is_listed(world, id))
            .filter_map(|id| world.items.get(id))
            .collect();
        if !visible_contents.is_empty() {
            view.push(ViewItem::ItemContents(
                visible_contents
                    .into_iter()
                    .map(|i| ContentLine {
                        item_name: i.name.clone(),
                        restricted: matches!(i.movability, Movability::Restricted { .. }),
                    })
                    .collect(),
            ));
        }
    }

    /// Determine what ability is required for certain interactions with this item.
    ///
    /// In `<verb> <target> with <tool>` commands, this returns whatever ability the `<tool>` must have
    /// in order to successfully `<verb>` the `<target>` (this item).
    ///
    /// Example -- if this item is `candle`, then:
    ///
    /// `candle.requires_capability_for(ItemInteractionType::Burn)`
    /// might return `Some(ItemAbility::Ignite)`.
    pub fn requires_capability_for(&self, inter: ItemInteractionType) -> Option<ItemAbility> {
        self.interaction_requires.get(&inter).cloned()
    }

    /// Returns the reason the item can't be accessed (as a container), if any
    pub fn access_denied_reason(&self) -> Option<String> {
        match self.container_state {
            Some(ContainerState::Open | ContainerState::TransparentOpen) => None,
            Some(ContainerState::Closed) => {
                let reason = format!("The {} is {}.", self.name().item_style(), "closed".bold());
                Some(reason)
            },
            Some(ContainerState::Locked) => {
                let reason = format!("The {} is {}.", self.name().item_style(), "locked".bold());
                Some(reason)
            },
            Some(ContainerState::TransparentClosed) => {
                let reason = format!(
                    "The {} is {}. You can see inside but can't access the contents.",
                    self.name().item_style(),
                    "closed".bold()
                );
                Some(reason)
            },
            Some(ContainerState::TransparentLocked) => {
                let reason = format!(
                    "The {} is {}. You can see inside but can't access the contents.",
                    self.name().item_style(),
                    "locked".bold()
                );
                Some(reason)
            },
            None => {
                let reason = format!("The {} isn't a container.", self.name().item_style());
                Some(reason)
            },
        }
    }

    /// Returns the reason an item can't be taken into inventory, if any
    pub fn take_denied_reason(&self) -> Option<String> {
        match &self.movability {
            Movability::Fixed { reason } | Movability::Restricted { reason } => Some(reason.clone()),
            Movability::Free => None,
        }
    }
}

/// Consumes one use of the item with the specified ability.
///
/// # Arguments
/// * `world` - Mutable reference to the game world
/// * `item_id` - id of the item to consume
/// * `ability` - The ability that triggered the consumption (e.g. `ItemAbility::Ignite`)
///
/// # Returns
/// * `Ok(Some(uses_left))` - Item was consumable and consumed, returns remaining uses
/// * `Ok(None)` - Item is not consumable or ability doesn't trigger consumption
/// * `Err(_)` - Item lookup failed
///
/// # Errors
/// * Returns error if the item id is not found in world.items
/// * Context will include the item id that failed lookup
pub fn consume(world: &mut AmbleWorld, item_id: &ItemId, ability: &ItemAbility) -> Result<Option<usize>> {
    let item = world
        .items
        .get_mut(item_id)
        .with_context(|| format!("failed lookup trying to consume() item '{item_id}'"))?;

    let item_id = item.id.clone();
    let item_sym = item.symbol.clone();

    // if consumable, decrement and set to # of remaining uses
    // if not consumable, return early with None
    let (uses_left, when_consumed) = if let Some(opts) = &mut item.consumable {
        // decrement uses_left if right ability was used
        if opts.consume_on.contains(ability) && opts.uses_left > 0 {
            opts.uses_left -= 1;
        }
        (opts.uses_left, opts.when_consumed.clone())
    } else {
        return Ok(None);
    };

    // if uses_left is now zero, handle the consumption, current options are just to despawn,
    // or to despawn and replace with another item either in inventory or the current room
    if uses_left == 0 {
        // release the mutable borrow on the item before performing actions that
        // require another mutable borrow of the world
        let _ = item;

        match when_consumed {
            ConsumeType::ReplaceInventory { replacement } => {
                crate::trigger::despawn_item(world, &item_id)?;
                crate::trigger::spawn_item_in_inventory(world, &replacement)?;
            },
            ConsumeType::ReplaceCurrentRoom { replacement } => {
                crate::trigger::despawn_item(world, &item_id)?;
                crate::trigger::spawn_item_in_current_room(world, &replacement)?;
            },
            ConsumeType::Despawn => crate::trigger::despawn_item(world, &item_id)?,
        }
    }
    info!("used ({ability}) ability of consumable item '{item_sym}': {uses_left} uses left");
    Ok(Some(uses_left))
}

/// Determine whether a tool item satisfies requirements for an interaction on a target item.
pub fn interaction_requirement_met(interaction: ItemInteractionType, target: &Item, tool: &Item) -> bool {
    if let Some(requirement) = target.interaction_requires.get(&interaction) {
        tool.abilities.contains(requirement)
    } else {
        true
    }
}

/// Modes of using ingestible items.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IngestMode {
    Eat,
    Drink,
    Inhale,
}
impl Display for IngestMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            IngestMode::Eat => write!(f, "eat"),
            IngestMode::Drink => write!(f, "drink"),
            IngestMode::Inhale => write!(f, "inhale"),
        }
    }
}

/// Methods common to things that can hold items.
pub trait ItemHolder {
    /// Insert an item into the holder's contents.
    fn add_item(&mut self, item_id: ItemId);
    /// Remove an item from the holder's contents.
    fn remove_item(&mut self, item_id: ItemId);
    /// Return `true` when the holder already contains the given item.
    fn contains_item(&self, item_id: ItemId) -> bool;
}

/// Things an item can do.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub enum ItemAbility {
    Attach,
    Clean,
    Cut,
    CutWood,
    Drink,
    Eat,
    Extinguish,
    Ignite,
    Inhale,
    Insulate,
    Magnify,
    Pluck,
    Pry,
    Read,
    Repair,
    Sharpen,
    Smash,
    TurnOn,
    TurnOff,
    Unlock(Option<ItemId>),
    Use,
}
impl Display for ItemAbility {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Attach => write!(f, "attach"),
            Self::Clean => write!(f, "clean"),
            Self::Cut => write!(f, "cut"),
            Self::CutWood => write!(f, "cut wood"),
            Self::Drink => write!(f, "drink"),
            Self::Eat => write!(f, "eat"),
            Self::Extinguish => write!(f, "extinguish"),
            Self::Ignite => write!(f, "ignite"),
            Self::Inhale => write!(f, "inhale"),
            Self::Insulate => write!(f, "insulate"),
            Self::Magnify => write!(f, "magnify"),
            Self::Read => write!(f, "read"),
            Self::Repair => write!(f, "repair"),
            Self::Sharpen => write!(f, "sharpen"),
            Self::TurnOn => write!(f, "turn on"),
            Self::TurnOff => write!(f, "turn off"),
            Self::Unlock(_) => write!(f, "unlock"),
            Self::Use => write!(f, "use"),
            Self::Pluck => write!(f, "pluck"),
            Self::Pry => write!(f, "pry"),
            Self::Smash => write!(f, "smash"),
        }
    }
}

/// Things you can do to an item, but only with certain other items.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Hash)]
#[serde(rename_all = "camelCase")]
pub enum ItemInteractionType {
    Attach,
    Break,
    Burn,
    Extinguish,
    Clean,
    Cover,
    Cut,
    Detach,
    Handle,
    Move,
    Open,
    Repair,
    Sharpen,
    Turn,
    Unlock,
}

impl Display for ItemInteractionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Attach => write!(f, "attach"),
            Self::Detach => write!(f, "detach"),
            Self::Break => write!(f, "break"),
            Self::Burn => write!(f, "burn"),
            Self::Extinguish => write!(f, "extinguish"),
            Self::Clean => write!(f, "clean"),
            Self::Cover => write!(f, "cover"),
            Self::Cut => write!(f, "cut"),
            Self::Handle => write!(f, "handle"),
            Self::Move => write!(f, "move"),
            Self::Open => write!(f, "open"),
            Self::Repair => write!(f, "repair"),
            Self::Sharpen => write!(f, "sharpen"),
            Self::Turn => write!(f, "turn"),
            Self::Unlock => write!(f, "unlock"),
        }
    }
}

/// All of the valid states a container can be in.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Variantly)]
#[serde(rename_all = "camelCase")]
pub enum ContainerState {
    Open,
    Closed,
    Locked,
    TransparentOpen,
    TransparentClosed,
    TransparentLocked,
}

/// Possible movability states for an `Item`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum Movability {
    Fixed {
        reason: String,
    },
    Restricted {
        reason: String,
    },
    #[default]
    Free,
}

/// Extra options / data for consumable items are represented here.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConsumableOpts {
    pub uses_left: usize,
    pub consume_on: HashSet<ItemAbility>,
    pub when_consumed: ConsumeType,
}

/// Types of things that can happen when an item has been consumed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConsumeType {
    Despawn,
    ReplaceInventory { replacement: ItemId },   // put replacement in inventory
    ReplaceCurrentRoom { replacement: ItemId }, // put replacement in current room
}

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

    use crate::world::{AmbleWorld, Location};
    use std::collections::{HashMap, HashSet};

    fn create_test_item(id: ItemId) -> Item {
        Item {
            id,
            symbol: "test_item".into(),
            name: "Test Item".into(),
            description: "A test item".into(),
            location: Location::Nowhere,
            visibility: 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_world() -> AmbleWorld {
        let mut world = AmbleWorld::new_empty();

        let item_id: ItemId = crate::idgen::new_id().into();
        let item = create_test_item(item_id.clone());
        world.items.insert(item_id.clone(), item);

        world
    }

    #[test]
    fn item_is_consumed_returns_false_for_non_consumable() {
        let item = create_test_item(crate::idgen::new_id().into());
        assert!(!item.is_consumed());
    }

    #[test]
    fn item_is_consumed_returns_false_for_unconsumed_consumable() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.consumable = Some(ConsumableOpts {
            uses_left: 3,
            consume_on: HashSet::new(),
            when_consumed: ConsumeType::Despawn,
        });
        assert!(!item.is_consumed());
    }

    #[test]
    fn item_is_consumed_returns_true_for_consumed_consumable() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.consumable = Some(ConsumableOpts {
            uses_left: 0,
            consume_on: HashSet::new(),
            when_consumed: ConsumeType::Despawn,
        });
        assert!(item.is_consumed());
    }

    #[test]
    fn item_is_accessible_returns_false_for_non_container() {
        let item = create_test_item(crate::idgen::new_id().into());
        assert!(!item.is_accessible());
    }

    #[test]
    fn item_is_accessible_returns_true_for_open_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Open);
        assert!(item.is_accessible());
    }

    #[test]
    fn item_is_accessible_returns_false_for_closed_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Closed);
        assert!(!item.is_accessible());
    }

    #[test]
    fn item_is_accessible_returns_false_for_locked_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Locked);
        assert!(!item.is_accessible());
    }

    #[test]
    fn item_is_accessible_returns_false_for_transparent_closed_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::TransparentClosed);
        assert!(!item.is_accessible());
    }

    #[test]
    fn item_is_accessible_returns_false_for_transparent_locked_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::TransparentLocked);
        assert!(!item.is_accessible());
    }

    #[test]
    fn item_is_transparent_returns_true_for_transparent_containers() {
        let mut item = create_test_item(crate::idgen::new_id().into());

        item.container_state = Some(ContainerState::TransparentClosed);
        assert!(item.is_transparent());

        item.container_state = Some(ContainerState::TransparentLocked);
        assert!(item.is_transparent());

        item.container_state = Some(ContainerState::Closed);
        assert!(!item.is_transparent());

        item.container_state = Some(ContainerState::Locked);
        assert!(!item.is_transparent());

        item.container_state = Some(ContainerState::Open);
        assert!(!item.is_transparent());

        item.container_state = None;
        assert!(!item.is_transparent());
    }

    #[test]
    fn set_location_room_updates_location() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        let room_id = crate::idgen::new_room_id();
        item.set_location_room(room_id.clone());
        assert_eq!(item.location, Location::Room(room_id));
    }

    #[test]
    fn set_location_item_updates_location() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        let container_id: ItemId = crate::idgen::new_id().into();
        item.set_location_item(container_id.clone());
        assert_eq!(item.location, Location::Item(container_id));
    }

    #[test]
    fn set_location_inventory_updates_location_and_unrestricts() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.movability = Movability::Restricted {
            reason: "You haven't earned it yet.".to_string(),
        };
        item.set_location_inventory();
        assert_eq!(item.location, Location::Inventory);
        assert!(matches!(item.movability, Movability::Free));
    }

    #[test]
    fn set_location_inventory_preserves_fixed_movability() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.movability = Movability::Fixed {
            reason: "Bolted down.".to_string(),
        };
        item.set_location_inventory();
        assert_eq!(item.location, Location::Inventory);
        assert!(matches!(item.movability, Movability::Fixed { .. }));
    }

    #[test]
    fn set_location_npc_updates_location() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        let npc_id: NpcId = crate::idgen::new_id().into();
        item.set_location_npc(npc_id.clone());
        assert_eq!(item.location, Location::Npc(npc_id));
    }

    #[test]
    fn requires_capability_for_returns_none_for_no_requirement() {
        let item = create_test_item(crate::idgen::new_id().into());
        assert_eq!(item.requires_capability_for(ItemInteractionType::Break), None);
    }

    #[test]
    fn requires_capability_for_returns_ability_when_required() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.interaction_requires
            .insert(ItemInteractionType::Break, ItemAbility::Smash);
        assert_eq!(
            item.requires_capability_for(ItemInteractionType::Break),
            Some(ItemAbility::Smash)
        );
    }

    #[test]
    fn access_denied_reason_returns_none_for_open_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Open);
        assert_eq!(item.access_denied_reason(), None);
    }

    #[test]
    fn access_denied_reason_returns_reason_for_closed_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Closed);
        let reason = item.access_denied_reason().unwrap();
        assert!(reason.contains("closed"));
    }

    #[test]
    fn access_denied_reason_returns_reason_for_locked_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Locked);
        let reason = item.access_denied_reason().unwrap();
        assert!(reason.contains("locked"));
    }

    #[test]
    fn access_denied_reason_returns_reason_for_transparent_closed_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::TransparentClosed);
        let reason = item.access_denied_reason().unwrap();
        assert!(reason.contains("closed"));
        assert!(reason.contains("see inside"));
    }

    #[test]
    fn access_denied_reason_returns_reason_for_transparent_locked_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::TransparentLocked);
        let reason = item.access_denied_reason().unwrap();
        assert!(reason.contains("locked"));
        assert!(reason.contains("see inside"));
    }

    #[test]
    fn access_denied_reason_returns_reason_for_non_container() {
        let item = create_test_item(crate::idgen::new_id().into());
        let reason = item.access_denied_reason().unwrap();
        assert!(reason.contains("isn't a container"));
    }

    #[test]
    fn take_denied_reason_returns_none_for_movable() {
        let item = create_test_item(crate::idgen::new_id().into());
        assert_eq!(item.take_denied_reason(), None);
    }

    #[test]
    fn take_denied_reason_returns_reason_for_fixed() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.movability = Movability::Fixed {
            reason: "The item isn't portable.".to_string(),
        };
        let reason = item.take_denied_reason().unwrap();
        assert!(reason.contains("isn't portable"));
    }

    #[test]
    fn take_denied_reason_returns_reason_for_restricted() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.movability = Movability::Restricted {
            reason: "You can't take that yet.".to_string(),
        };
        let reason = item.take_denied_reason().unwrap();
        assert!(reason.contains("can't take"));
    }

    #[test]
    fn item_holder_add_item_works() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Open);
        let item_to_add: ItemId = crate::idgen::new_id().into();

        item.add_item(item_to_add.clone());
        assert!(item.contents.contains(&item_to_add));
    }

    #[test]
    fn item_holder_add_item_ignores_self_reference() {
        let item_id: ItemId = crate::idgen::new_id().into();
        let mut item = create_test_item(item_id.clone());
        item.container_state = Some(ContainerState::Open);

        item.add_item(item_id.clone());
        assert!(!item.contents.contains(&item_id));
    }

    #[test]
    fn item_holder_add_item_ignores_non_container() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        let item_to_add: ItemId = crate::idgen::new_id().into();

        item.add_item(item_to_add.clone());
        assert!(!item.contents.contains(&item_to_add));
    }

    #[test]
    fn item_holder_remove_item_works() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        item.container_state = Some(ContainerState::Open);
        let item_to_remove: ItemId = crate::idgen::new_id().into();
        item.contents.insert(item_to_remove.clone());

        item.remove_item(item_to_remove.clone());
        assert!(!item.contents.contains(&item_to_remove));
    }

    #[test]
    fn item_holder_contains_item_works() {
        let mut item = create_test_item(crate::idgen::new_id().into());
        let contained_item: ItemId = crate::idgen::new_id().into();
        item.contents.insert(contained_item.clone());

        assert!(item.contains_item(contained_item));
        assert!(!item.contains_item(crate::idgen::new_id().into()));
    }

    #[test]
    fn consume_returns_none_for_non_consumable() {
        let mut world = create_test_world();
        let item_id = world.items.keys().next().unwrap().clone();

        let result = consume(&mut world, &item_id, &ItemAbility::Use).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn consume_decrements_uses_for_correct_ability() {
        let mut world = create_test_world();
        let item_id = world.items.keys().next().unwrap().clone();

        let mut consume_on = HashSet::new();
        consume_on.insert(ItemAbility::Ignite);

        world.items.get_mut(&item_id).unwrap().consumable = Some(ConsumableOpts {
            uses_left: 3,
            consume_on,
            when_consumed: ConsumeType::Despawn,
        });

        let result = consume(&mut world, &item_id, &ItemAbility::Ignite).unwrap();
        assert_eq!(result, Some(2));
        assert_eq!(world.items[&item_id].consumable.as_ref().unwrap().uses_left, 2);
    }

    #[test]
    fn consume_does_not_decrement_for_wrong_ability() {
        let mut world = create_test_world();
        let item_id = world.items.keys().next().unwrap().clone();

        let mut consume_on = HashSet::new();
        consume_on.insert(ItemAbility::Ignite);

        world.items.get_mut(&item_id).unwrap().consumable = Some(ConsumableOpts {
            uses_left: 3,
            consume_on,
            when_consumed: ConsumeType::Despawn,
        });

        let result = consume(&mut world, &item_id, &ItemAbility::Use).unwrap();
        assert_eq!(result, Some(3));
        assert_eq!(world.items[&item_id].consumable.as_ref().unwrap().uses_left, 3);
    }

    #[test]
    fn container_state_is_open_works() {
        assert!(ContainerState::Open.is_open());
        assert!(!ContainerState::Closed.is_open());
        assert!(!ContainerState::Locked.is_open());
    }

    #[test]
    fn item_ability_display_works() {
        assert_eq!(format!("{}", ItemAbility::Attach), "attach");
        assert_eq!(format!("{}", ItemAbility::Clean), "clean");
        assert_eq!(format!("{}", ItemAbility::CutWood), "cut wood");
        assert_eq!(format!("{}", ItemAbility::Extinguish), "extinguish");
        assert_eq!(format!("{}", ItemAbility::TurnOn), "turn on");
        assert_eq!(format!("{}", ItemAbility::TurnOff), "turn off");
        assert_eq!(format!("{}", ItemAbility::Unlock(None)), "unlock");
    }

    #[test]
    fn item_interaction_type_display_works() {
        assert_eq!(format!("{}", ItemInteractionType::Attach), "attach");
        assert_eq!(format!("{}", ItemInteractionType::Break), "break");
        assert_eq!(format!("{}", ItemInteractionType::Burn), "burn");
        assert_eq!(format!("{}", ItemInteractionType::Extinguish), "extinguish");
        assert_eq!(format!("{}", ItemInteractionType::Clean), "clean");
        assert_eq!(format!("{}", ItemInteractionType::Cover), "cover");
    }

    #[test]
    fn world_object_trait_works() {
        let item = create_test_item(crate::idgen::new_id().into());
        assert_eq!(item.id(), item.id.to_string());
        assert_eq!(item.symbol(), "test_item");
        assert_eq!(item.name(), "Test Item");
        assert_eq!(item.description(), "A test item");
        assert_eq!(item.location(), &Location::Nowhere);
    }
}