1use std::collections::{BTreeMap, VecDeque};
2use std::sync::{Arc, Once, OnceLock};
3
4use forge_carddb::CardDatabase;
5use forge_foundation::sealed_product::card_cosmetics::CardCosmetics;
6use forge_foundation::ZoneType;
7use serde::{Deserialize, Serialize};
8
9use crate::agent::GameEntity;
10use crate::card::card_damage_map::CardDamageMap;
11use crate::card::card_zone_table::CardZoneTable;
12use crate::card::Card;
13use crate::card::CounterType;
14use crate::ids::{CardId, PlayerId};
15use crate::phase::ExtraTurn;
16use crate::phase::TurnState;
17use crate::player::PlayerState;
18use crate::spellability::MagicStack;
19use crate::zone::{CostPaymentStack, Zone, ZoneKey, ZoneStore};
20
21pub struct TypeRegistry;
30
31static CREATURE_TYPES: OnceLock<Vec<String>> = OnceLock::new();
32
33impl TypeRegistry {
34 pub fn load(type_lists_content: &str) {
44 let _ = CREATURE_TYPES.set(Self::parse_creature_types(type_lists_content));
45 }
46
47 pub fn creature_types() -> &'static [String] {
52 CREATURE_TYPES.get().expect(
53 "TypeRegistry: creature types not loaded. \
54 Call TypeRegistry::load() with the contents of TypeLists.txt before starting a game.",
55 )
56 }
57
58 pub fn is_creature_type(creature_type: &str) -> bool {
63 CREATURE_TYPES.get().is_some_and(|types| {
64 types
65 .iter()
66 .any(|ty| ty.eq_ignore_ascii_case(creature_type))
67 })
68 }
69
70 fn parse_creature_types(content: &str) -> Vec<String> {
71 let mut in_creature_section = false;
72 let mut types = Vec::new();
73 for line in content.lines() {
74 let line = line.trim();
75 if line.is_empty() || line.starts_with('#') {
76 continue;
77 }
78 if line.starts_with('[') && line.ends_with(']') {
79 in_creature_section = &line[1..line.len() - 1] == "CreatureTypes";
80 continue;
81 }
82 if in_creature_section {
83 let singular = line.split(':').next().unwrap_or(line);
85 if !singular.is_empty() {
86 types.push(singular.to_string());
87 }
88 }
89 }
90 types
91 }
92}
93
94static CARD_DATABASE: OnceLock<Arc<CardDatabase>> = OnceLock::new();
95static CARD_DATABASE_PARSED: Once = Once::new();
96
97pub struct CardDatabaseRegistry;
98
99impl CardDatabaseRegistry {
100 pub fn load(database: Arc<CardDatabase>) {
101 let _ = CARD_DATABASE.set(database);
102 }
103
104 pub fn get() -> Option<&'static CardDatabase> {
105 CARD_DATABASE.get().map(Arc::as_ref)
106 }
107
108 pub fn all() -> Option<&'static CardDatabase> {
109 let database = Self::get()?;
110 CARD_DATABASE_PARSED.call_once(|| {
111 database.force_parse_all();
112 });
113 Some(database)
114 }
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
118pub struct TokenCosmeticBinding {
119 pub foil: bool,
120 pub cosmetics: Option<CardCosmetics>,
121}
122
123#[derive(Debug, Clone, Serialize, Deserialize)]
126pub struct GameState {
127 pub cards: Vec<Card>,
129 pub players: Vec<PlayerState>,
130 #[serde(default)]
131 pub token_cosmetics: BTreeMap<PlayerId, BTreeMap<String, TokenCosmeticBinding>>,
132
133 #[serde(skip)]
135 zones: ZoneStore,
136
137 pub stack: MagicStack,
139
140 #[serde(skip)]
143 pub cost_payment_stack: CostPaymentStack,
144
145 pub is_night: bool,
147 pub day_night_started: bool,
148
149 pub turn: TurnState,
151
152 pub player_order: Vec<PlayerId>,
154
155 pub game_over: bool,
157 pub winner: Option<PlayerId>,
158
159 #[serde(skip)]
162 pub extra_turns: VecDeque<ExtraTurn>,
163
164 pub prevent_all_combat_damage: bool,
167
168 pub monarch: Option<PlayerId>,
170
171 pub initiative_holder: Option<PlayerId>,
173
174 pub end_turn_requested: bool,
176
177 pub end_combat_requested: bool,
179
180 pub extra_combat_phases: u32,
182
183 next_card_id: u32,
185
186 next_zone_timestamp: u64,
191 next_effect_timestamp: i64,
194 #[serde(skip)]
197 pub pending_damage_map: Option<CardDamageMap>,
198 #[serde(skip)]
200 pub pending_prevent_map: Option<CardDamageMap>,
201 #[serde(skip)]
204 pub pending_change_zone_table: Option<CardZoneTable>,
205
206 #[serde(skip)]
211 pub synced_token_scripts: std::collections::BTreeSet<String>,
212
213 #[serde(skip)]
217 pub last_state_battlefield: Vec<crate::lki::CardSnapshot>,
218
219 #[serde(skip)]
225 pub pre_sba_battlefield: Vec<CardId>,
226
227 #[serde(skip)]
230 pub last_sacrificed_card: Option<CardId>,
231 #[serde(skip)]
232 pub counter_added_this_turn: BTreeMap<(GameEntity, Option<u64>, CounterType), i32>,
233}
234
235impl GameState {
236 pub fn new(player_names: &[&str], starting_life: i32) -> Self {
237 let mut players = Vec::new();
238 let mut player_order = Vec::new();
239
240 for (i, name) in player_names.iter().enumerate() {
241 let pid = PlayerId(i as u32);
242 players.push(PlayerState::new(pid, name.to_string(), starting_life));
243 player_order.push(pid);
244 }
245
246 let zones = ZoneStore::new(&player_order);
247
248 GameState {
249 cards: Vec::new(),
250 players,
251 token_cosmetics: BTreeMap::new(),
252 zones,
253 stack: MagicStack::new(),
254 cost_payment_stack: CostPaymentStack::new(),
255 is_night: false,
256 day_night_started: false,
257 turn: TurnState::new(player_order[0], player_order.len() as u32),
258 player_order,
259 game_over: false,
260 winner: None,
261 extra_turns: VecDeque::new(),
262 prevent_all_combat_damage: false,
263 monarch: None,
264 initiative_holder: None,
265 end_turn_requested: false,
266 end_combat_requested: false,
267 extra_combat_phases: 0,
268 next_card_id: 0,
269 next_zone_timestamp: 0,
270 next_effect_timestamp: 1,
271 pending_damage_map: None,
272 pending_prevent_map: None,
273 pending_change_zone_table: None,
274 synced_token_scripts: std::collections::BTreeSet::new(),
275 last_state_battlefield: Vec::new(),
276 pre_sba_battlefield: Vec::new(),
277 last_sacrificed_card: None,
278 counter_added_this_turn: BTreeMap::new(),
279 }
280 }
281
282 pub fn create_card(&mut self, mut card: Card) -> CardId {
284 if card.is_token {
285 let binding = card.get_s_var("TokenScript").and_then(|script| {
286 let overrides = self.token_cosmetics.get(&card.owner)?;
287 overrides.get(script).or_else(|| {
288 overrides
289 .iter()
290 .find(|(key, _)| key.eq_ignore_ascii_case(script))
291 .map(|(_, binding)| binding)
292 })
293 });
294 card.cosmetics = binding.and_then(|binding| binding.cosmetics.clone());
295 if let Some(binding) = binding {
296 card.paper_foil = binding.foil;
297 }
298 }
299 let id = CardId(self.next_card_id);
300 self.next_card_id += 1;
301 card.id = id;
302 let bound_host = card.clone();
303 for trigger in &mut card.triggers {
304 trigger.bind_host_card_id(bound_host.id);
305 }
306 for static_ability in &mut card.static_abilities {
307 static_ability.base.set_host_card_id(bound_host.id);
308 }
309 for replacement_effect in &mut card.replacement_effects {
310 replacement_effect.base.set_host_card_id(bound_host.id);
311 }
312 self.cards.push(card);
313 id
314 }
315
316 pub fn card(&self, id: CardId) -> &Card {
319 &self.cards[id.index()]
320 }
321
322 pub fn card_mut(&mut self, id: CardId) -> &mut Card {
323 &mut self.cards[id.index()]
324 }
325
326 pub fn player(&self, id: PlayerId) -> &PlayerState {
327 &self.players[id.index()]
328 }
329
330 pub fn player_mut(&mut self, id: PlayerId) -> &mut PlayerState {
331 &mut self.players[id.index()]
332 }
333
334 pub fn zone(&self, zone_type: ZoneType, owner: PlayerId) -> &Zone {
335 self.zones.get(zone_type, owner).expect("Zone not found")
336 }
337
338 pub fn zone_mut(&mut self, zone_type: ZoneType, owner: PlayerId) -> &mut Zone {
339 self.zones
340 .get_mut(zone_type, owner)
341 .expect("Zone not found")
342 }
343
344 pub fn zone_store_snapshot(&self) -> ZoneStore {
345 self.zones.clone()
346 }
347
348 pub fn replace_zone_store(&mut self, zones: ZoneStore) {
349 self.zones = zones;
350 }
351
352 pub fn iter_zones(&self) -> impl Iterator<Item = (ZoneKey, &Zone)> {
353 self.zones.iter()
354 }
355
356 pub fn cards_in_all_zones(&self, zone_type: ZoneType) -> impl Iterator<Item = CardId> + '_ {
357 self.iter_zones()
358 .filter(move |(key, _)| key.zone_type == zone_type)
359 .flat_map(|(_, zone)| zone.cards.iter().copied())
360 }
361
362 pub fn card_zone_location(&self, card: CardId) -> Option<ZoneKey> {
363 self.zones.card_location(card)
364 }
365
366 pub fn card_zone(&self, card: CardId) -> Option<ZoneType> {
367 self.card_zone_location(card)
368 .map(|location| location.zone_type)
369 }
370
371 pub fn card_current_zone(&self, card: CardId) -> ZoneType {
372 self.card_zone(card).unwrap_or_else(|| self.card(card).zone)
373 }
374
375 pub fn card_is_in_zone(&self, card: CardId, zone: ZoneType) -> bool {
376 self.card_current_zone(card) == zone
377 }
378
379 pub fn card_zone_owner(&self, card: CardId) -> Option<PlayerId> {
380 self.card_zone_location(card).map(|location| location.owner)
381 }
382
383 pub fn card_zone_location_matches_card(&self, card: CardId) -> bool {
384 let card_ref = self.card(card);
385 match self.card_zone_location(card) {
386 Some(location) => {
387 location.zone_type == card_ref.zone && location.owner == card_ref.controller
388 }
389 None => card_ref.zone == ZoneType::None,
390 }
391 }
392
393 pub fn reset_zone_turn_tracking(&mut self) {
394 for zone in self.zones.values_mut() {
395 zone.reset_cards_added_this_turn();
396 }
397 }
398
399 pub fn reset_card_turn_tracking(&mut self) {
400 self.counter_added_this_turn.clear();
401 for card in &mut self.cards {
402 card.reset_activations_per_turn();
403 card.reset_ability_resolved_this_turn();
404 }
405 }
406
407 pub fn counter_added_this_turn(
408 &self,
409 entity: GameEntity,
410 counter_type: Option<&CounterType>,
411 ) -> i32 {
412 self.counter_added_this_turn
413 .iter()
414 .filter(|((entry_entity, timestamp, entry_type), _)| {
415 *entry_entity == entity
416 && *timestamp == self.counter_entity_timestamp(entity)
417 && counter_type.is_none_or(|ct| ct == entry_type)
418 })
419 .map(|(_, amount)| *amount)
420 .sum()
421 }
422
423 pub fn record_counter_added(
424 &mut self,
425 entity: GameEntity,
426 counter_type: &CounterType,
427 amount: i32,
428 ) {
429 *self
430 .counter_added_this_turn
431 .entry((
432 entity,
433 self.counter_entity_timestamp(entity),
434 counter_type.clone(),
435 ))
436 .or_default() += amount;
437 }
438
439 fn counter_entity_timestamp(&self, entity: GameEntity) -> Option<u64> {
440 match entity {
441 GameEntity::Card(card) => Some(self.card(card).zone_timestamp),
442 GameEntity::Player(_) => None,
443 }
444 }
445
446 pub(crate) fn remove_card_from_zone(
447 &mut self,
448 zone_type: ZoneType,
449 owner: PlayerId,
450 card: CardId,
451 ) -> bool {
452 if std::env::var("FORGE_ZONE_TRACE").is_ok()
453 && self.cards[card.index()].card_name == "Mind Stone"
454 {
455 eprintln!(
456 "[zone-rust] T{} remove {:?} {} from {:?} owner={:?}",
457 self.turn.turn_number,
458 card,
459 self.cards[card.index()].card_name,
460 zone_type,
461 owner
462 );
463 }
464 self.zones.remove_card(zone_type, owner, card)
465 }
466
467 pub(crate) fn add_card_to_zone(&mut self, zone_type: ZoneType, owner: PlayerId, card: CardId) {
468 if std::env::var("FORGE_ZONE_TRACE").is_ok()
469 && self.cards[card.index()].card_name == "Mind Stone"
470 {
471 eprintln!(
472 "[zone-rust] T{} add {:?} {} -> {:?} owner={:?}",
473 self.turn.turn_number,
474 card,
475 self.cards[card.index()].card_name,
476 zone_type,
477 owner
478 );
479 }
480 self.zones.add_card_to_top(zone_type, owner, card);
481 }
482
483 pub(crate) fn add_card_to_zone_bottom(
484 &mut self,
485 zone_type: ZoneType,
486 owner: PlayerId,
487 card: CardId,
488 ) {
489 self.zones.add_card_to_bottom(zone_type, owner, card);
490 }
491
492 pub fn take_top_card_from_zone(
493 &mut self,
494 zone_type: ZoneType,
495 owner: PlayerId,
496 ) -> Option<CardId> {
497 self.zones.take_top_card(zone_type, owner)
498 }
499
500 pub fn take_top_cards_from_zone(
501 &mut self,
502 zone_type: ZoneType,
503 owner: PlayerId,
504 count: usize,
505 ) -> Vec<CardId> {
506 let mut cards = Vec::with_capacity(count);
507 for _ in 0..count {
508 let Some(card) = self.take_top_card_from_zone(zone_type, owner) else {
509 break;
510 };
511 cards.push(card);
512 }
513 cards.reverse();
514 cards
515 }
516
517 pub fn reorder_card_in_zone(
518 &mut self,
519 zone_type: ZoneType,
520 owner: PlayerId,
521 card: CardId,
522 index: usize,
523 ) {
524 self.zones.reorder_card(zone_type, owner, card, index);
525 }
526
527 pub fn move_cards_to_zone_top(
528 &mut self,
529 zone_type: ZoneType,
530 owner: PlayerId,
531 cards: &[CardId],
532 ) {
533 self.zones.move_cards_to_top(zone_type, owner, cards);
534 }
535
536 pub fn move_cards_to_zone_bottom(
537 &mut self,
538 zone_type: ZoneType,
539 owner: PlayerId,
540 cards: &[CardId],
541 ) {
542 self.zones.move_cards_to_bottom(zone_type, owner, cards);
543 }
544
545 pub fn replace_zone_cards(&mut self, zone_type: ZoneType, owner: PlayerId, cards: Vec<CardId>) {
546 self.zones.replace_cards(zone_type, owner, cards);
547 }
548
549 pub fn shuffle_zone_cards(
550 &mut self,
551 zone_type: ZoneType,
552 owner: PlayerId,
553 rng: &mut dyn crate::game_rng::GameRng,
554 ) {
555 self.zones.shuffle_cards(zone_type, owner, rng);
556 }
557
558 pub fn shuffle_zone_cards_with_rand<R: rand::Rng + ?Sized>(
559 &mut self,
560 zone_type: ZoneType,
561 owner: PlayerId,
562 rng: &mut R,
563 ) {
564 self.zones.shuffle_cards_with_rand(zone_type, owner, rng);
565 }
566
567 pub(crate) fn save_zone_lki(
568 &mut self,
569 zone_type: ZoneType,
570 owner: PlayerId,
571 card: CardId,
572 from: ZoneType,
573 ) {
574 self.zones.save_lki(zone_type, owner, card, from);
575 }
576
577 pub fn active_player(&self) -> PlayerId {
578 self.turn.active_player
579 }
580
581 pub fn is_day(&self) -> bool {
582 self.day_night_started && !self.is_night
583 }
584
585 pub fn is_neither_day_nor_night(&self) -> bool {
586 !self.day_night_started
587 }
588
589 pub fn next_player(&self, player: PlayerId) -> PlayerId {
590 let current_idx = self
591 .player_order
592 .iter()
593 .position(|&p| p == player)
594 .unwrap_or(0);
595 for i in 1..self.player_order.len() {
596 let next_idx = (current_idx + i) % self.player_order.len();
597 let next_pid = self.player_order[next_idx];
598 if self.player(next_pid).is_alive() {
599 return next_pid;
600 }
601 }
602 player
603 }
604
605 pub fn last_combat_turn_of(&self, player: PlayerId) -> Option<i32> {
614 if self.turn.active_player == player {
615 Some(self.turn.turn_number as i32)
616 } else {
617 None
618 }
619 }
620
621 pub fn opponent_of(&self, player: PlayerId) -> PlayerId {
622 for &pid in &self.player_order {
623 if pid != player && self.player(pid).is_alive() {
624 return pid;
625 }
626 }
627 player }
629
630 pub fn alive_players(&self) -> Vec<PlayerId> {
631 self.player_order
632 .iter()
633 .filter(|&&pid| self.player(pid).is_alive())
634 .copied()
635 .collect()
636 }
637
638 pub fn cards_in_zone(&self, zone_type: ZoneType, owner: PlayerId) -> &[CardId] {
640 &self.zone(zone_type, owner).cards
641 }
642
643 pub fn creatures_on_battlefield(&self, player: PlayerId) -> Vec<CardId> {
645 self.cards_in_zone(ZoneType::Battlefield, player)
646 .iter()
647 .filter(|&&cid| self.card(cid).is_creature())
648 .copied()
649 .collect()
650 }
651
652 pub fn assign_zone_timestamp(&mut self, card_id: CardId) -> u64 {
655 let ts = self.next_zone_timestamp;
656 self.next_zone_timestamp += 1;
657 self.cards[card_id.index()].zone_timestamp = ts;
658 ts
659 }
660
661 pub fn next_effect_timestamp(&mut self) -> i64 {
663 let ts = self
664 .next_effect_timestamp
665 .max(self.next_zone_timestamp as i64);
666 self.next_effect_timestamp = ts.saturating_add(1);
667 self.next_zone_timestamp = self.next_effect_timestamp as u64;
668 ts
669 }
670
671 pub fn ensure_pending_damage_maps(&mut self) {
673 if self.pending_damage_map.is_none() {
674 self.pending_damage_map = Some(CardDamageMap::default());
675 }
676 if self.pending_prevent_map.is_none() {
677 self.pending_prevent_map = Some(CardDamageMap::default());
678 }
679 }
680
681 pub fn clear_pending_damage_maps(&mut self) {
683 self.pending_damage_map = None;
684 self.pending_prevent_map = None;
685 }
686
687 pub fn ensure_pending_change_zone_table(&mut self) {
689 if self.pending_change_zone_table.is_none() {
690 self.pending_change_zone_table = Some(CardZoneTable::default());
691 }
692 }
693
694 pub fn clear_pending_change_zone_table(&mut self) {
696 self.pending_change_zone_table = None;
697 }
698
699 pub fn lands_on_battlefield(&self, player: PlayerId) -> Vec<CardId> {
701 self.cards_in_zone(ZoneType::Battlefield, player)
702 .iter()
703 .filter(|&&cid| self.card(cid).is_land())
704 .copied()
705 .collect()
706 }
707}
708
709#[cfg(test)]
710mod tests {
711 use super::*;
712 use forge_foundation::{CardTypeLine, ColorSet, ManaCost};
713
714 #[test]
715 fn create_game() {
716 let game = GameState::new(&["Alice", "Bob"], 20);
717 assert_eq!(game.players.len(), 2);
718 assert_eq!(game.player(PlayerId(0)).name, "Alice");
719 assert_eq!(game.player(PlayerId(1)).name, "Bob");
720 assert_eq!(game.player(PlayerId(0)).life, 20);
721 assert!(game.zone(ZoneType::Sideboard, PlayerId(0)).is_empty());
722 assert!(game.zone(ZoneType::AttractionDeck, PlayerId(0)).is_empty());
723 assert!(game.zone(ZoneType::ContraptionDeck, PlayerId(0)).is_empty());
724 }
725
726 #[test]
727 fn create_card_and_zone() {
728 let mut game = GameState::new(&["Alice", "Bob"], 20);
729 let card = Card::new(
730 CardId(0),
731 "Grizzly Bears".to_string(),
732 PlayerId(0),
733 CardTypeLine::parse("Creature Bear"),
734 ManaCost::parse("1 G"),
735 ColorSet::GREEN,
736 Some(2),
737 Some(2),
738 vec![],
739 vec![],
740 );
741 let cid = game.create_card(card);
742 game.add_card_to_zone(ZoneType::Library, PlayerId(0), cid);
743 game.card_mut(cid).zone = ZoneType::Library;
744 assert_eq!(game.zone(ZoneType::Library, PlayerId(0)).len(), 1);
745 assert_eq!(game.card_zone(cid), Some(ZoneType::Library));
746 }
747
748 #[test]
749 fn opponent_lookup() {
750 let game = GameState::new(&["Alice", "Bob"], 20);
751 assert_eq!(game.opponent_of(PlayerId(0)), PlayerId(1));
752 assert_eq!(game.opponent_of(PlayerId(1)), PlayerId(0));
753 }
754
755 #[test]
756 fn lki_snapshot_captures_battlefield_state() {
757 let mut game = GameState::new(&["Alice", "Bob"], 20);
758
759 let mut card = Card::new(
761 CardId(0),
762 "Grizzly Bears".to_string(),
763 PlayerId(0),
764 CardTypeLine::parse("Creature Bear"),
765 ManaCost::parse("1 G"),
766 ColorSet::GREEN,
767 Some(3),
768 Some(3),
769 vec![],
770 vec![],
771 );
772 card.zone = ZoneType::Battlefield;
773 let cid = game.create_card(card);
774
775 game.copy_last_state();
777
778 let snapshot = game.get_lki_snapshot(cid).expect("snapshot should exist");
780 assert_eq!(snapshot.power, 3);
781 assert_eq!(snapshot.toughness, 3);
782 assert_eq!(snapshot.card_name, "Grizzly Bears");
783
784 game.card_mut(cid).zone = ZoneType::Graveyard;
786 let snapshot = game
787 .get_lki_snapshot(cid)
788 .expect("snapshot should still exist");
789 assert_eq!(snapshot.power, 3);
790
791 game.copy_last_state();
794 assert!(
795 game.get_lki_snapshot(cid).is_some(),
796 "stale LKI should persist"
797 );
798 }
799}