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