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
//! Goal definitions and progress evaluation.
//!
//! Provides the data structures that track player objectives along with
//! helpers for determining whether goal conditions are satisfied.
//!
//! `Goal`s are stateless -- goal completions are not marked or stored -- just
//! three conditions upon creation:
//!
//! - when it becomes active / potentially achievable
//! - when it is considered complete
//! - when it is failed (active but can never be completed)
//!
//! Goals are only evaluated if/when the player issues a "goals" command.
//! When they do, each defined goal's conditions are checked and it is assigned
//! a `GoalStatus`, which is then used to filter/style goals and their descriptions
//! for display.

use crate::{ItemId, RoomId};
use serde::de::{self, DeserializeOwned, Deserializer, EnumAccess, VariantAccess, Visitor};
use serde::{Deserialize, Serialize};
use std::fmt;
use variantly::Variantly;

use crate::{AmbleWorld, ItemHolder, player::Flag};

/// Groups that goals can be assigned to.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum GoalGroup {
    Required,
    Optional,
    StatusEffect,
}

/// Types of conditions that can activate or complete a goal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum GoalCondition {
    FlagComplete { flag: String },    // for checking if sequence-type flags are at end
    FlagInProgress { flag: String },  // check if a sequence flag not yet at end
    GoalComplete { goal_id: String }, // for activating a goal after another is done
    HasItem { item_id: ItemId },
    HasFlag { flag: String },
    MissingFlag { flag: String },
    ReachedRoom { room_id: RoomId },
}
impl GoalCondition {
    /// Returns true if the condition has been satisfied.
    pub fn satisfied(&self, world: &AmbleWorld) -> bool {
        // Helper closure to check if a flag is set by comparing flag values
        // This works because Flag::value() returns the current state representation
        // with sequence flags in the form <flag>#<step>.
        let flag_is_set = |flag_str: &str| world.player.flags.iter().any(|f| f.value() == *flag_str);

        match self {
            Self::HasItem { item_id } => world.player.contains_item(item_id.clone()),
            Self::HasFlag { flag } => flag_is_set(flag),
            Self::MissingFlag { flag } => !flag_is_set(flag),
            Self::ReachedRoom { room_id } => {
                if let Some(room) = world.rooms.get(room_id) {
                    room.visited
                } else {
                    false
                }
            },
            Self::GoalComplete { goal_id } => {
                if let Some(goal) = world.goals.iter().find(|g| g.id == *goal_id) {
                    goal.status(world) == GoalStatus::Complete
                } else {
                    false
                }
            },
            Self::FlagInProgress { flag } => world
                .player
                .flags
                .get(&Flag::Simple {
                    name: flag.into(),
                    turn_set: 0,
                })
                .is_some_and(|f| !f.is_complete()),
            Self::FlagComplete { flag } => {
                let target = Flag::simple(flag, world.turn_count);
                world.player.flags.get(&target).is_some_and(Flag::is_complete)
            },
        }
    }
}

/// Represents current state of the `Goal`
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Variantly)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum GoalStatus {
    Inactive,
    Active,
    Complete,
    Failed,
}

fn deserialize_maybe_value<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    T: DeserializeOwned,
    D: Deserializer<'de>,
{
    // Avoid serde's untagged backtracking here: tuple/newtype values (e.g. RoomId)
    // can fail to match reliably when we accept both bare values and Some(...)
    // wrappers from mixed historical encodings.
    let value = ron::Value::deserialize(deserializer)?;
    match value {
        ron::Value::Option(None) => Ok(None),
        ron::Value::Option(Some(inner)) => inner.into_rust::<T>().map(Some).map_err(de::Error::custom),
        other => other.into_rust::<T>().map(Some).map_err(de::Error::custom),
    }
}

#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
enum GoalGroupKind {
    Required,
    Optional,
    StatusEffect,
}

impl GoalGroupKind {
    fn from_str(value: &str) -> Option<Self> {
        let value = value.strip_prefix("r#").unwrap_or(value);
        match value {
            v if v.eq_ignore_ascii_case("required") => Some(Self::Required),
            v if v.eq_ignore_ascii_case("optional") => Some(Self::Optional),
            v if v.eq_ignore_ascii_case("status-effect") => Some(Self::StatusEffect),
            _ => None,
        }
    }
}

impl<'de> Deserialize<'de> for GoalGroupKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct KindVisitor;

        impl<'de> Visitor<'de> for KindVisitor {
            type Value = GoalGroupKind;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("goal group identifier")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                GoalGroupKind::from_str(value)
                    .ok_or_else(|| de::Error::unknown_variant(value, &["required", "optional", "status-effect"]))
            }

            fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(value)
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
            where
                A: EnumAccess<'de>,
            {
                let (variant, access) = data.variant::<String>()?;
                access.unit_variant()?;
                self.visit_str(&variant)
            }
        }

        deserializer.deserialize_any(KindVisitor)
    }
}

#[derive(Deserialize)]
struct GoalGroupRepr {
    #[serde(rename = "type")]
    kind: GoalGroupKind,
}

impl<'de> Deserialize<'de> for GoalGroup {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = GoalGroupRepr::deserialize(deserializer)?;
        Ok(match repr.kind {
            GoalGroupKind::Required => GoalGroup::Required,
            GoalGroupKind::Optional => GoalGroup::Optional,
            GoalGroupKind::StatusEffect => GoalGroup::StatusEffect,
        })
    }
}

#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum GoalConditionKind {
    FlagComplete,
    FlagInProgress,
    GoalComplete,
    HasItem,
    HasFlag,
    MissingFlag,
    ReachedRoom,
}

impl GoalConditionKind {
    fn from_str(value: &str) -> Option<Self> {
        match value {
            v if v.eq_ignore_ascii_case("flagComplete") => Some(Self::FlagComplete),
            v if v.eq_ignore_ascii_case("flagInProgress") => Some(Self::FlagInProgress),
            v if v.eq_ignore_ascii_case("goalComplete") => Some(Self::GoalComplete),
            v if v.eq_ignore_ascii_case("hasItem") => Some(Self::HasItem),
            v if v.eq_ignore_ascii_case("hasFlag") => Some(Self::HasFlag),
            v if v.eq_ignore_ascii_case("missingFlag") => Some(Self::MissingFlag),
            v if v.eq_ignore_ascii_case("reachedRoom") => Some(Self::ReachedRoom),
            _ => None,
        }
    }
}

impl<'de> Deserialize<'de> for GoalConditionKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct KindVisitor;

        impl<'de> Visitor<'de> for KindVisitor {
            type Value = GoalConditionKind;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("goal condition identifier")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                GoalConditionKind::from_str(value).ok_or_else(|| {
                    de::Error::unknown_variant(
                        value,
                        &[
                            "flagComplete",
                            "flagInProgress",
                            "goalComplete",
                            "hasItem",
                            "hasFlag",
                            "missingFlag",
                            "reachedRoom",
                        ],
                    )
                })
            }

            fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(value)
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
            where
                A: EnumAccess<'de>,
            {
                let (variant, access) = data.variant::<String>()?;
                access.unit_variant()?;
                self.visit_str(&variant)
            }
        }

        deserializer.deserialize_any(KindVisitor)
    }
}

#[derive(Deserialize)]
struct GoalConditionRepr {
    #[serde(rename = "type")]
    kind: GoalConditionKind,
    #[serde(default, deserialize_with = "deserialize_maybe_value")]
    flag: Option<String>,
    #[serde(default, deserialize_with = "deserialize_maybe_value")]
    goal_id: Option<String>,
    #[serde(default, deserialize_with = "deserialize_maybe_value")]
    item_id: Option<ItemId>,
    #[serde(default, deserialize_with = "deserialize_maybe_value")]
    room_id: Option<RoomId>,
}

impl<'de> Deserialize<'de> for GoalCondition {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = GoalConditionRepr::deserialize(deserializer)?;
        Ok(match repr.kind {
            GoalConditionKind::FlagComplete => GoalCondition::FlagComplete {
                flag: repr.flag.ok_or_else(|| de::Error::missing_field("flag"))?,
            },
            GoalConditionKind::FlagInProgress => GoalCondition::FlagInProgress {
                flag: repr.flag.ok_or_else(|| de::Error::missing_field("flag"))?,
            },
            GoalConditionKind::GoalComplete => GoalCondition::GoalComplete {
                goal_id: repr.goal_id.ok_or_else(|| de::Error::missing_field("goal_id"))?,
            },
            GoalConditionKind::HasItem => GoalCondition::HasItem {
                item_id: repr.item_id.ok_or_else(|| de::Error::missing_field("item_id"))?,
            },
            GoalConditionKind::HasFlag => GoalCondition::HasFlag {
                flag: repr.flag.ok_or_else(|| de::Error::missing_field("flag"))?,
            },
            GoalConditionKind::MissingFlag => GoalCondition::MissingFlag {
                flag: repr.flag.ok_or_else(|| de::Error::missing_field("flag"))?,
            },
            GoalConditionKind::ReachedRoom => GoalCondition::ReachedRoom {
                room_id: repr.room_id.ok_or_else(|| de::Error::missing_field("room_id"))?,
            },
        })
    }
}

#[derive(Debug, Copy, Clone, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
enum GoalStatusKind {
    Inactive,
    Active,
    Complete,
    Failed,
}

impl GoalStatusKind {
    fn from_str(value: &str) -> Option<Self> {
        match value {
            v if v.eq_ignore_ascii_case("inactive") => Some(Self::Inactive),
            v if v.eq_ignore_ascii_case("active") => Some(Self::Active),
            v if v.eq_ignore_ascii_case("complete") => Some(Self::Complete),
            v if v.eq_ignore_ascii_case("failed") => Some(Self::Failed),
            _ => None,
        }
    }
}

impl<'de> Deserialize<'de> for GoalStatusKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct KindVisitor;

        impl<'de> Visitor<'de> for KindVisitor {
            type Value = GoalStatusKind;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("goal status identifier")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                GoalStatusKind::from_str(value)
                    .ok_or_else(|| de::Error::unknown_variant(value, &["inactive", "active", "complete", "failed"]))
            }

            fn visit_borrowed_str<E>(self, value: &'de str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(value)
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                self.visit_str(&value)
            }

            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
            where
                A: EnumAccess<'de>,
            {
                let (variant, access) = data.variant::<String>()?;
                access.unit_variant()?;
                self.visit_str(&variant)
            }
        }

        deserializer.deserialize_any(KindVisitor)
    }
}

#[derive(Deserialize)]
struct GoalStatusRepr {
    #[serde(rename = "type")]
    kind: GoalStatusKind,
}

impl<'de> Deserialize<'de> for GoalStatus {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let repr = GoalStatusRepr::deserialize(deserializer)?;
        Ok(match repr.kind {
            GoalStatusKind::Inactive => GoalStatus::Inactive,
            GoalStatusKind::Active => GoalStatus::Active,
            GoalStatusKind::Complete => GoalStatus::Complete,
            GoalStatusKind::Failed => GoalStatus::Failed,
        })
    }
}

/// A goal for the player to achieve.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Goal {
    pub id: String,
    pub name: String,
    pub description: String,
    pub group: GoalGroup,
    pub activate_when: Option<GoalCondition>, // None = always active / visible
    pub finished_when: GoalCondition,
    pub failed_when: Option<GoalCondition>,
}
impl Goal {
    /// Determines and returns the current '`GoalStatus`' for this goal.
    pub fn status(&self, world: &AmbleWorld) -> GoalStatus {
        if let Some(fail_condition) = &self.failed_when
            && fail_condition.satisfied(world)
        {
            return GoalStatus::Failed;
        }

        if let Some(start_condition) = &self.activate_when {
            if start_condition.satisfied(world) {
                if self.finished_when.satisfied(world) {
                    GoalStatus::Complete
                } else {
                    GoalStatus::Active
                }
            } else {
                GoalStatus::Inactive
            }
        } else if self.finished_when.satisfied(world) {
            GoalStatus::Complete
        } else {
            GoalStatus::Active
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        item::{Item, Movability},
        player::Flag,
        room::Room,
        world::{AmbleWorld, Location},
    };
    use std::collections::{HashMap, HashSet};

    fn create_test_world() -> AmbleWorld {
        let mut world = AmbleWorld::new_empty();

        // Add test room
        let room_id = crate::idgen::new_room_id();
        let mut room = Room {
            id: room_id.clone(),
            symbol: "test_room".into(),
            name: "Test Room".into(),
            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(),
        };
        room.visited = true;
        world.rooms.insert(room_id.clone(), room);

        // Add test item
        let item_id: ItemId = crate::idgen::new_id().into();
        let item = Item {
            id: item_id.clone(),
            symbol: "test_item".into(),
            name: "Test Item".into(),
            description: "A test item".into(),
            location: Location::Inventory,
            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,
        };
        world.items.insert(item_id.clone(), item);
        world.player.inventory.insert(item_id.clone());

        // Add test flags
        world.player.flags.insert(Flag::simple("test_flag", world.turn_count));
        world
            .player
            .flags
            .insert(Flag::sequence("test_seq", Some(2), world.turn_count));

        world
    }

    #[test]
    fn goal_condition_flag_complete_works() {
        let mut world = create_test_world();

        // Add completed sequence flag
        let mut seq_flag = Flag::sequence("completed_seq", Some(2), world.turn_count);
        seq_flag.advance(); // step 1
        seq_flag.advance(); // step 2 (complete)
        world.player.flags.insert(seq_flag);

        let condition = GoalCondition::FlagComplete {
            flag: "completed_seq".into(),
        };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::FlagComplete {
            flag: "nonexistent".into(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_flag_in_progress_works() {
        let mut world = create_test_world();

        // Advance the test sequence flag
        world.player.advance_flag("test_seq");

        let condition = GoalCondition::FlagInProgress {
            flag: "test_seq".into(),
        };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::FlagInProgress {
            flag: "nonexistent".into(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_goal_complete_works() {
        let world = create_test_world();

        // Create a completed goal
        let completed_goal = Goal {
            id: "completed_goal".into(),
            name: "Completed Goal".into(),
            description: "A completed goal".into(),
            group: GoalGroup::Required,
            activate_when: None,
            finished_when: GoalCondition::HasFlag {
                flag: "test_flag".into(),
            },
            failed_when: None,
        };

        // Create a goal that depends on the completed goal
        let dependent_goal = Goal {
            id: "dependent_goal".into(),
            name: "Dependent Goal".into(),
            description: "A goal that depends on another".into(),
            group: GoalGroup::Optional,
            activate_when: Some(GoalCondition::GoalComplete {
                goal_id: "completed_goal".into(),
            }),
            finished_when: GoalCondition::HasFlag {
                flag: "nonexistent".into(),
            },
            failed_when: None,
        };

        // Test with completed goal in world
        let mut world_with_goals = world.clone();
        world_with_goals.goals.push(completed_goal);
        world_with_goals.goals.push(dependent_goal);

        let condition = GoalCondition::GoalComplete {
            goal_id: "completed_goal".into(),
        };
        assert!(condition.satisfied(&world_with_goals));

        let condition = GoalCondition::GoalComplete {
            goal_id: "nonexistent".into(),
        };
        assert!(!condition.satisfied(&world_with_goals));
    }

    #[test]
    fn goal_condition_has_item_works() {
        let world = create_test_world();
        let item_id = world.player.inventory.iter().next().cloned().unwrap();

        let condition = GoalCondition::HasItem { item_id };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::HasItem {
            item_id: crate::idgen::new_id().into(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_has_flag_works() {
        let world = create_test_world();

        let condition = GoalCondition::HasFlag {
            flag: "test_flag".into(),
        };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::HasFlag {
            flag: "nonexistent".into(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_missing_flag_works() {
        let world = create_test_world();

        let condition = GoalCondition::MissingFlag {
            flag: "nonexistent".into(),
        };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::MissingFlag {
            flag: "test_flag".into(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_reached_room_works() {
        let world = create_test_world();
        let room_id = world.rooms.keys().next().cloned().unwrap();

        let condition = GoalCondition::ReachedRoom { room_id };
        assert!(condition.satisfied(&world));

        let condition = GoalCondition::ReachedRoom {
            room_id: crate::idgen::new_room_id(),
        };
        assert!(!condition.satisfied(&world));
    }

    #[test]
    fn goal_condition_reached_room_deserializes_room_id_newtype() {
        let raw = r#"(type:"reachedRoom",room_id:("test-room"))"#;
        let condition: GoalCondition = ron::from_str(raw).expect("goal condition should deserialize");
        assert_eq!(
            condition,
            GoalCondition::ReachedRoom {
                room_id: "test-room".into()
            }
        );
    }

    #[test]
    fn goal_status_inactive_when_activation_condition_not_met() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: Some(GoalCondition::HasFlag {
                flag: "nonexistent".into(),
            }),
            finished_when: GoalCondition::HasFlag {
                flag: "test_flag".into(),
            },
            failed_when: None,
        };

        assert_eq!(goal.status(&world), GoalStatus::Inactive);
    }

    #[test]
    fn goal_status_active_when_conditions_met_but_not_finished() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: Some(GoalCondition::HasFlag {
                flag: "test_flag".into(),
            }),
            finished_when: GoalCondition::HasFlag {
                flag: "nonexistent".into(),
            },
            failed_when: None,
        };

        assert_eq!(goal.status(&world), GoalStatus::Active);
    }

    #[test]
    fn goal_status_complete_when_finished_condition_met() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: Some(GoalCondition::HasFlag {
                flag: "test_flag".into(),
            }),
            finished_when: GoalCondition::HasFlag {
                flag: "test_flag".into(),
            },
            failed_when: None,
        };

        assert_eq!(goal.status(&world), GoalStatus::Complete);
    }

    #[test]
    fn goal_status_failed_when_failure_condition_met() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: None,
            finished_when: GoalCondition::HasFlag {
                flag: "nonexistent".into(),
            },
            failed_when: Some(GoalCondition::HasFlag {
                flag: "test_flag".into(),
            }),
        };

        assert_eq!(goal.status(&world), GoalStatus::Failed);
    }

    #[test]
    fn goal_status_active_when_no_activation_condition_and_not_finished() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: None,
            finished_when: GoalCondition::HasFlag {
                flag: "nonexistent".into(),
            },
            failed_when: None,
        };

        assert_eq!(goal.status(&world), GoalStatus::Active);
    }

    #[test]
    fn goal_status_complete_when_no_activation_condition_and_finished() {
        let world = create_test_world();

        let goal = Goal {
            id: "test_goal".into(),
            name: "Test Goal".into(),
            description: "A test goal".into(),
            group: GoalGroup::Required,
            activate_when: None,
            finished_when: GoalCondition::HasFlag {
                flag: "test_flag".into(),
            },
            failed_when: None,
        };

        assert_eq!(goal.status(&world), GoalStatus::Complete);
    }

    #[test]
    fn goal_groups_are_properly_defined() {
        // Test that goal groups serialize/deserialize correctly
        let required = GoalGroup::Required;
        let optional = GoalGroup::Optional;
        let status_effect = GoalGroup::StatusEffect;

        assert_eq!(format!("{required:?}"), "Required");
        assert_eq!(format!("{optional:?}"), "Optional");
        assert_eq!(format!("{status_effect:?}"), "StatusEffect");
    }

    #[test]
    fn goal_status_variants_work() {
        // Test that goal status variants are properly defined
        assert_eq!(GoalStatus::Inactive, GoalStatus::Inactive);
        assert_eq!(GoalStatus::Active, GoalStatus::Active);
        assert_eq!(GoalStatus::Complete, GoalStatus::Complete);
        assert_eq!(GoalStatus::Failed, GoalStatus::Failed);

        assert_ne!(GoalStatus::Inactive, GoalStatus::Active);
        assert_ne!(GoalStatus::Complete, GoalStatus::Failed);
    }
}