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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
use forge_foundation::ZoneType;
use crate::agent::PlayerAgent;
use crate::card::{Card, CounterType};
use crate::event::RunParams;
use crate::game::GameState;
use crate::ids::{CardId, PlayerId};
use crate::replacement::replacement_handler::{
apply_replacements, apply_replacements_with_agents, ReplacementEvent, ReplacementRuntime,
};
use crate::replacement::GameLossReason;
use crate::replacement::ReplacementResult;
use crate::staticability::layer::{apply_continuous_effects, apply_etb_tapped_with_agents};
use crate::trigger::handler::TriggerHandler;
use crate::trigger::TriggerType;
/// Game state mutation methods — moving cards, dealing damage, state-based actions.
impl GameState {
pub fn record_player_damage_assignment(
&mut self,
source: Option<CardId>,
target_player: Option<PlayerId>,
amount: i32,
is_combat: bool,
) {
self.player_record_damage_assignment(source, target_player, amount, is_combat);
}
/// Move a card from its current zone to a new zone.
/// Move a card to a new zone. For Graveyard destinations, checks for zone-redirect
/// replacement effects (Rest in Peace, Leyline of the Void) and redirects to the
/// correct zone. Use `move_card_final` to skip the replacement check.
pub fn move_card(&mut self, card_id: CardId, dest_zone: ZoneType, dest_owner: PlayerId) {
self.move_card_internal(card_id, dest_zone, dest_owner, None, None, true, false);
}
pub fn move_card_with_agents(
&mut self,
card_id: CardId,
dest_zone: ZoneType,
dest_owner: PlayerId,
agents: &mut [Box<dyn PlayerAgent>],
) {
self.move_card_internal(
card_id,
dest_zone,
dest_owner,
Some(agents),
None,
true,
false,
);
}
pub fn move_card_with_agents_and_replacement_runtime(
&mut self,
card_id: CardId,
dest_zone: ZoneType,
dest_owner: PlayerId,
agents: &mut [Box<dyn PlayerAgent>],
runtime: &mut ReplacementRuntime<'_>,
) {
self.move_card_internal(
card_id,
dest_zone,
dest_owner,
Some(agents),
Some(runtime.trigger_handler),
true,
false,
);
}
fn move_card_without_replacement(
&mut self,
card_id: CardId,
dest_zone: ZoneType,
dest_owner: PlayerId,
) {
self.move_card_internal(card_id, dest_zone, dest_owner, None, None, false, false);
}
/// Discard a card. Mirrors Java's `Player.discard()`.
///
/// Records the discard, marks the card, and moves it to graveyard through
/// the normal zone-change machinery (which runs replacement effects like
/// Madness automatically). Fires Discarded triggers afterwards.
pub fn discard_card(
&mut self,
card_id: CardId,
discard_player: PlayerId,
sa: Option<&crate::spellability::SpellAbility>,
agents: Option<&mut [Box<dyn PlayerAgent>]>,
trigger_handler: &mut TriggerHandler,
) {
let owner = self.card(card_id).owner;
self.player_record_discard(discard_player, 1);
self.card_mut(card_id).set_discarded(true);
// Move to graveyard through normal zone-change with is_discard=true.
// Replacement effects (e.g. Madness → Exile) are handled generically.
self.move_card_internal(
card_id,
ZoneType::Graveyard,
owner,
agents,
Some(trigger_handler),
true,
true, // is_discard
);
// RememberDiscarded
if let Some(sa) = sa {
if sa.ir.remember_discarded {
if let Some(source_id) = sa.source {
self.card_mut(source_id).add_remembered_card(card_id);
}
}
}
// Register active triggers on the card in its new zone.
trigger_handler.register_active_trigger(self, card_id);
// Emit zone-change trigger for Hand → actual destination.
let dest_zone = self.card(card_id).zone;
crate::ability::effects::zone_triggers::emit_zone_trigger(
trigger_handler,
card_id,
ZoneType::Hand,
dest_zone,
);
// Fire Discarded trigger.
trigger_handler.run_trigger(
TriggerType::Discarded,
RunParams {
card: Some(card_id),
player: Some(discard_player),
..Default::default()
},
false,
);
trigger_handler.run_trigger(
TriggerType::DiscardedAll,
RunParams {
card: Some(card_id),
cards: Some(vec![card_id]),
player: Some(discard_player),
..Default::default()
},
false,
);
}
fn move_card_internal(
&mut self,
card_id: CardId,
dest_zone: ZoneType,
dest_owner: PlayerId,
mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
mut trigger_handler: Option<&mut TriggerHandler>,
apply_move_replacement: bool,
is_discard: bool,
) {
let (src_zone, src_owner, was_permanent, was_land, is_token) = {
let card = &self.cards[card_id.index()];
(
card.zone,
card.controller,
card.type_line.is_permanent(),
card.is_land(),
card.is_token,
)
};
if let Ok(filter) = std::env::var("FORGE_CARD_TRACE") {
if !filter.is_empty()
&& self.cards[card_id.index()]
.card_name
.eq_ignore_ascii_case(&filter)
{
eprintln!(
"[card-trace] move {} {:?} {:?} -> {:?} (owner={:?} sick={} cast_from={:?})",
self.cards[card_id.index()].card_name,
card_id,
src_zone,
dest_zone,
dest_owner,
self.cards[card_id.index()].summoning_sick,
self.cards[card_id.index()].cast_from,
);
}
}
let mut etb_counters = std::collections::BTreeMap::new();
if dest_zone == ZoneType::Battlefield {
for keyword in self.cards[card_id.index()].keywords.as_string_list() {
let mut parts = keyword.split(':');
if !parts
.next()
.is_some_and(|head| head.eq_ignore_ascii_case("etbCounter"))
{
continue;
}
let counter_type =
crate::ability::effects::parse_counter_type(parts.next().unwrap_or_default());
let amount_text = parts.next().unwrap_or_default();
let amount = amount_text.parse::<i32>().unwrap_or_else(|_| {
let card = &self.cards[card_id.index()];
card.svars
.get(amount_text)
.map(|expression| {
if matches!(expression.as_str(), "Count$xPaid" | "Count$XPaid") {
card.svars
.get("XPaid")
.and_then(|value| value.parse().ok())
.unwrap_or(0)
} else {
expression.parse().unwrap_or_else(|_| {
crate::svar::resolve_count_svar(
expression, self, card_id, dest_owner,
)
})
}
})
.unwrap_or(0)
});
*etb_counters.entry(counter_type).or_default() += amount.max(0);
}
let card = &self.cards[card_id.index()];
if card.type_line.has_subtype("Saga") && card.has_chapter() {
let amount = if card.has_keyword("Read ahead") {
agents
.as_deref_mut()
.and_then(|agents| {
agents[dest_owner.index()].choose_number(
dest_owner,
Some(card_id),
"How many lore counters?",
Some("Choose a chapter and start with that many lore counters."),
1,
card.get_final_chapter_nr(),
)
})
.unwrap_or(1)
.clamp(1, card.get_final_chapter_nr())
} else {
1
};
*etb_counters.entry(CounterType::Lore).or_default() += amount;
}
if card.type_line.is_planeswalker() {
let loyalty = card
.initial_loyalty
.as_deref()
.and_then(|value| value.parse::<i32>().ok())
.unwrap_or(0);
*etb_counters
.entry(crate::card::CounterType::Loyalty)
.or_default() += loyalty.max(0);
}
*etb_counters
.entry(crate::card::CounterType::P1P1)
.or_default() += card.etb_counters_p1p1.max(0);
let sunburst = card.sunburst_count();
if sunburst > 0 && card.has_keyword("Sunburst") {
let counter_type = if card.is_creature() {
crate::card::CounterType::P1P1
} else {
crate::card::CounterType::Charge
};
*etb_counters.entry(counter_type).or_default() += sunburst;
}
etb_counters.retain(|_, amount| *amount > 0);
}
let counter_cause = self.cards[card_id.index()].cast_sa.clone();
let counter_map = (!etb_counters.is_empty()).then(|| {
vec![crate::replacement::replacement_handler::CounterMapValue {
source: Some(dest_owner),
counters: etb_counters,
}]
});
let mut moved_event = ReplacementEvent::Moved {
card: card_id,
origin: src_zone,
destination: dest_zone,
is_discard,
counter_map,
counter_cause,
counter_is_effect: dest_zone == ZoneType::Battlefield,
after_replacement_static_abilities: Vec::new(),
};
let tapped_before_replacement = self.card(card_id).tapped;
if apply_move_replacement {
if let Some(agents) = agents.as_deref_mut() {
apply_replacements_with_agents(self, agents, &mut moved_event);
} else {
apply_replacements(self, &mut moved_event);
}
}
let (dest_zone, etb_counter_map, counter_cause, after_replacement_static_abilities) =
match moved_event {
ReplacementEvent::Moved {
destination,
counter_map,
counter_cause,
after_replacement_static_abilities,
..
} => (
destination,
counter_map,
counter_cause,
after_replacement_static_abilities,
),
_ => (dest_zone, None, None, Vec::new()),
};
let replacement_marked_etb_tapped = dest_zone == ZoneType::Battlefield
&& self.card(card_id).tapped
&& !tapped_before_replacement;
let dest_owner = if dest_zone == ZoneType::Command {
self.card(card_id).owner
} else {
dest_owner
};
let host_left_battlefield =
src_zone == ZoneType::Battlefield && dest_zone != ZoneType::Battlefield;
if host_left_battlefield && was_permanent {
self.player_record_permanent_left_battlefield(src_owner);
}
// Java `Card.clearCastSA` — the cast-SA link dies once the instance
// leaves the battlefield (a new cast produces a fresh instance).
if host_left_battlefield {
self.card_mut(card_id).cast_sa = None;
// `ControlGain$ LoseControl$ LeavesPlay` — drop the scheduled
// revert since the card is no longer on the battlefield.
crate::ability::effects::control_gain_effect::leaves_play_hook(self, card_id);
}
if dest_zone == ZoneType::Graveyard && was_permanent && !is_token {
self.player_record_permanent_put_into_graveyard(self.card(card_id).owner);
}
let forget_effects: Vec<CardId> = self
.cards
.iter()
.filter(|c| {
c.zone == ZoneType::Command
&& c.forget_on_moved_origin == Some(src_zone)
&& c.remembered_cards.contains(&card_id)
})
.map(|c| c.id)
.collect();
// Tokens and copy-tokens cease to exist when leaving the battlefield (CR 110.5g).
// Set zone to None (limbo) and remove from source zone without adding to destination.
if is_token && dest_zone != ZoneType::Battlefield {
if let Some(table) = self.pending_change_zone_table.as_mut() {
table.put(Some(src_zone), Some(ZoneType::None), card_id);
}
let mut exile_effects = Vec::new();
for eff_id in forget_effects.iter().copied() {
let eff = &mut self.cards[eff_id.index()];
eff.remembered_cards.retain(|&rid| rid != card_id);
if eff.exile_when_no_remembered && eff.remembered_cards.is_empty() {
exile_effects.push(eff_id);
}
}
self.cards[card_id.index()].zone = ZoneType::None;
if src_zone != ZoneType::None {
self.remove_card_from_zone(src_zone, src_owner, card_id);
}
// Effect cards with ForgetOnMoved should be removed from the game
// entirely (zone = None), not moved to Exile. Moving them to Exile
// creates phantom cards that diverge from Java parity.
for eff_id in exile_effects {
let controller = self.card(eff_id).controller;
self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
self.cards[eff_id.index()].zone = ZoneType::None;
}
apply_continuous_effects(self);
debug_assert!(self.card_zone_location_matches_card(card_id));
return;
}
// Remove from source zone
if src_zone != ZoneType::None {
self.remove_card_from_zone(src_zone, src_owner, card_id);
}
if src_zone == ZoneType::Exile && dest_zone != ZoneType::Exile {
self.cards[card_id.index()]
.keywords
.retain(|kw| !kw.starts_with(crate::card::KEYWORD_PLOTTED_PREFIX));
}
// Update card's zone
self.cards[card_id.index()].zone = dest_zone;
if src_zone != dest_zone {
self.cards[card_id.index()].turn_in_zone = self.turn.turn_number;
}
if let Some(table) = self.pending_change_zone_table.as_mut() {
table.put(Some(src_zone), Some(dest_zone), card_id);
}
// Assign a zone timestamp so same-player triggers are ordered by
// zone entry order (matching Java's Zone.cardList insertion order).
if dest_zone != ZoneType::Stack {
self.assign_zone_timestamp(card_id);
}
// Track LKI: record which zone this card came from on the destination zone.
self.save_zone_lki(dest_zone, dest_owner, card_id, src_zone);
// Reset state on zone change
match dest_zone {
ZoneType::Battlefield => {
// A permanent enters under the destination player's control.
// This must be updated before ETB-trigger registration so
// triggered abilities inherit the correct controller.
self.cards[card_id.index()].controller = dest_owner;
self.cards[card_id.index()].enter_battlefield();
if replacement_marked_etb_tapped {
self.cards[card_id.index()].set_tapped(true);
}
// Add to destination zone first so the card is "on the
// battlefield" when ETB-tapped checks run against it.
self.add_card_to_zone(dest_zone, dest_owner, card_id);
if was_land {
self.player_record_landfall(dest_owner);
}
// Apply ETB-tapped effects (intrinsic + extrinsic). When the
// replacement chain already tapped this card it also already
// prompted the affected player to choose the applied effect,
// so neither the prompt nor the apply pass should fire again
// here — Java's flow runs the choose-and-apply step exactly
// once via the replacement chain.
if !replacement_marked_etb_tapped {
apply_etb_tapped_with_agents(self, card_id, agents);
}
if let Some(handler) = trigger_handler.as_deref_mut() {
handler.register_active_trigger(self, card_id);
}
if let Some(counter_map) = etb_counter_map {
let table =
crate::game_entity_counter_table::GameEntityCounterTable::from_counter_map(
crate::agent::GameEntity::Card(card_id),
counter_map,
);
table.apply_replaced_counter_effect(
self,
trigger_handler.as_deref_mut(),
counter_cause.as_deref(),
RunParams::default(),
);
for (source, static_abilities) in after_replacement_static_abilities {
crate::replacement::replace_add_counter::apply_after_replacement_static_abilities(
self,
source,
static_abilities,
);
}
}
self.cards[card_id.index()].etb_counters_p1p1 = 0;
// Update LKI snapshot: card just entered the battlefield.
// Ensures it's available for later TriggeredCard$CardPower lookups
// even if it dies within the same resolution chain.
self.update_lki_snapshot(card_id);
apply_continuous_effects(self);
debug_assert!(self.card_zone_location_matches_card(card_id));
return;
}
ZoneType::Graveyard | ZoneType::Hand | ZoneType::Exile | ZoneType::Library => {
// Detach any attachments before resetting state.
let attachments: Vec<CardId> = self.cards[card_id.index()].attachments.clone();
for aura_id in attachments {
self.cards[aura_id.index()].attached_to = None;
// Bestow: when host leaves, revert aura to creature
self.cards[aura_id.index()].is_bestowed = false;
}
self.cards[card_id.index()].attachments.clear();
// Also detach this card from its host if it was an Aura/Equipment.
self.detach(card_id);
// Save last-known information before resetting.
// Mirrors Java's LKI system for trigger SVars like TriggeredCard$CardPower.
if src_zone == ZoneType::Battlefield {
let card = &self.cards[card_id.index()];
let lki_p = card.power();
let lki_t = card.toughness();
let card = &mut self.cards[card_id.index()];
card.lki_power = Some(lki_p);
card.lki_toughness = Some(lki_t);
}
// Reset battlefield state when leaving (including static modifiers).
let keep_counters =
crate::staticability::static_ability_counters_remain::counters_remain(
&self.cards,
&self.cards[card_id.index()],
dest_zone,
);
let card = &mut self.cards[card_id.index()];
card.tapped = false;
card.damage = 0;
card.power_modifier = 0;
card.toughness_modifier = 0;
card.static_power_modifier = 0;
card.static_toughness_modifier = 0;
card.static_set_power = None;
card.static_set_toughness = None;
card.granted_keywords.clear();
if let Some(type_line) = card.static_type_line_base.take() {
card.set_type_line(type_line);
}
card.static_added_subtypes.clear();
card.restore_changed_characteristics_baseline();
card.cant_attack_static = false;
card.cant_block_static = false;
card.summoning_sick = true;
card.monstrous = false;
card.controller = card.owner;
card.face_down = false;
card.is_bestowed = false;
// CR 400.7: a permanent that changes zones becomes a new
// object with no cast history. Mirrors Java's
// changeZone-creates-new-Card behaviour.
card.cast_from = None;
card.reset_crewed();
if !keep_counters {
card.counters.clear();
}
// Clear temporary triggers added by Animate effects (e.g.
// Supernatural Stamina's "when this creature dies, return it").
// Per CR 400.7 a permanent that changes zones becomes a new
// object; it must not retain one-shot death-return triggers.
// Without this, a creature that dies-and-returns would still
// carry the trigger, making it "immortal" for the rest of the
// turn.
card.clear_pump_triggers();
card.clear_pump_keywords();
// Restore intrinsic keywords from the animate snapshot so
// Animate-granted keywords (e.g. Sneak Attack's `Keywords$
// Haste`) do not persist into the new object the card
// becomes when it changes zones (CR 400.7).
if let Some(state) = card.animate_state.take() {
if let Some(orig_kws) = state.original_keywords {
card.keywords = orig_kws;
card.update_keywords();
}
}
if let Some(state) = card.clone_state.take() {
card.restore_clone_snapshot(state);
} else {
card.remove_clone_states();
}
}
ZoneType::Command => {
// Detach any attachments before resetting state.
let attachments: Vec<CardId> = self.cards[card_id.index()].attachments.clone();
for aura_id in attachments {
self.cards[aura_id.index()].attached_to = None;
}
self.cards[card_id.index()].attachments.clear();
self.detach(card_id);
// Commander returning to command zone: reset battlefield state.
let keep_counters =
crate::staticability::static_ability_counters_remain::counters_remain(
&self.cards,
&self.cards[card_id.index()],
dest_zone,
);
let card = &mut self.cards[card_id.index()];
card.tapped = false;
card.damage = 0;
card.power_modifier = 0;
card.toughness_modifier = 0;
card.static_power_modifier = 0;
card.static_toughness_modifier = 0;
card.static_set_power = None;
card.static_set_toughness = None;
card.granted_keywords.clear();
if let Some(type_line) = card.static_type_line_base.take() {
card.set_type_line(type_line);
}
card.static_added_subtypes.clear();
card.restore_changed_characteristics_baseline();
card.cant_attack_static = false;
card.cant_block_static = false;
card.summoning_sick = true;
card.monstrous = false;
card.controller = card.owner;
card.cast_from = None;
if !keep_counters {
card.counters.clear();
}
if let Some(state) = card.clone_state.take() {
card.restore_clone_snapshot(state);
} else {
card.remove_clone_states();
}
}
_ => {}
}
// Add to destination zone
self.add_card_to_zone(dest_zone, dest_owner, card_id);
// Commander 903.9a tracking: once a commander enters graveyard or exile,
// SBA may offer moving it to the command zone exactly once.
let commander_entered_gy_or_exile = self.card(card_id).is_commander
&& matches!(dest_zone, ZoneType::Graveyard | ZoneType::Exile);
self.cards[card_id.index()].move_to_command_zone = commander_entered_gy_or_exile;
// Forget remembered objects for command effects with ForgetOnMoved.
let mut exile_effects = Vec::new();
for eff_id in forget_effects {
let eff = &mut self.cards[eff_id.index()];
eff.remembered_cards.retain(|&rid| rid != card_id);
if eff.exile_when_no_remembered && eff.remembered_cards.is_empty() {
exile_effects.push(eff_id);
}
}
// Effect cards with ForgetOnMoved should be removed from the game
// entirely (zone = None), not moved to Exile.
for eff_id in exile_effects {
let controller = self.card(eff_id).controller;
self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
self.cards[eff_id.index()].zone = ZoneType::None;
}
// Expire temporary effect cards linked to this host leaving play
// (Duration$ UntilHostLeavesPlay / UntilHostLeavesPlayOrEOT).
if host_left_battlefield {
let linked_effects: Vec<CardId> = self
.cards
.iter()
.filter(|c| c.zone == ZoneType::Command && c.temp_effect_host == Some(card_id))
.map(|c| c.id)
.collect();
for eff_id in linked_effects {
let controller = self.card(eff_id).controller;
self.remove_card_from_zone(ZoneType::Command, controller, eff_id);
self.cards[eff_id.index()].zone = ZoneType::None;
}
// Return cards exiled by this host via ChangeZoneAll Duration$ UntilHostLeavesPlay
// (e.g. Deputy of Detention: exiled permanents return when it leaves).
let exiled_by_host: Vec<(CardId, PlayerId)> = self
.cards
.iter()
.filter(|c| c.zone == ZoneType::Exile && c.exiled_by == Some(card_id))
.map(|c| (c.id, c.owner))
.collect();
for (exiled_id, owner) in exiled_by_host {
self.cards[exiled_id.index()].exiled_by = None;
self.move_card(exiled_id, ZoneType::Battlefield, owner);
if let Some(handler) = trigger_handler.as_deref_mut() {
let returned_zone = self.card(exiled_id).zone;
handler.register_active_trigger(self, exiled_id);
crate::ability::effects::zone_triggers::emit_zone_trigger(
handler,
exiled_id,
ZoneType::Exile,
returned_zone,
);
}
}
}
apply_continuous_effects(self);
debug_assert!(self.card_zone_location_matches_card(card_id));
}
/// Deal damage to a card (creature).
///
/// Runs replacement effects (e.g. damage prevention) before applying.
/// Mirrors Java `GameAction.addDamage()` calling `ReplacementHandler.run()`.
pub fn deal_damage_to_card(&mut self, target: CardId, amount: i32) {
self.deal_damage_to_card_from(target, amount, None, false);
}
/// Deal damage to a card with source tracking for replacement effects.
pub fn deal_damage_to_card_from(
&mut self,
target: CardId,
amount: i32,
source: Option<CardId>,
is_combat: bool,
) {
self.deal_damage_to_card_from_with_agents(target, amount, source, is_combat, None);
}
/// Deal damage to a card with source tracking and optional agents for RNG parity.
pub fn deal_damage_to_card_from_with_agents(
&mut self,
target: CardId,
amount: i32,
source: Option<CardId>,
is_combat: bool,
agents: Option<&mut [Box<dyn crate::agent::PlayerAgent>]>,
) {
if amount <= 0 {
return;
}
if !self.card(target).can_be_dealt_damage() {
return;
}
let mut event = ReplacementEvent::DamageToCard {
target,
amount,
source,
is_combat,
};
if let Some(agents) = agents {
apply_replacements_with_agents(self, agents, &mut event);
} else {
apply_replacements(self, &mut event);
}
if let ReplacementEvent::DamageToCard {
amount: mut final_amount,
..
} = event
{
// Consume PreventDamage shields. Each shield prevents 1 damage and
// is removed. Mirrors Java's per-shield ReplaceDamage effect cards
// in the Command zone, but using the legacy `damage_prevention`
// counter pending the proper Command-zone effect-card port.
let shields = self.cards[target.index()].damage_prevention;
if shields > 0 && final_amount > 0 {
let consumed = shields.min(final_amount);
self.cards[target.index()].damage_prevention -= consumed;
final_amount -= consumed;
}
if final_amount > 0 {
let dealt = self.cards[target.index()].add_damage_after_prevention(final_amount);
// Fire DealtDamage replacement event after damage is applied.
let mut dealt_event = ReplacementEvent::DealtDamage {
target,
amount: dealt,
source,
};
if dealt > 0 {
apply_replacements(self, &mut dealt_event);
}
}
}
}
/// Deal damage to a player.
///
/// Runs replacement effects (e.g. damage prevention) before applying.
/// Mirrors Java `GameAction.addDamage()` calling `ReplacementHandler.run()`.
pub fn deal_damage_to_player(&mut self, target: PlayerId, amount: i32) -> i32 {
self.deal_damage_to_player_from(target, amount, None, false)
}
/// Deal damage to a player with source tracking for replacement effects.
pub fn deal_damage_to_player_from(
&mut self,
target: PlayerId,
amount: i32,
source: Option<CardId>,
is_combat: bool,
) -> i32 {
self.deal_damage_to_player_from_with_agents(target, amount, source, is_combat, None)
}
/// Deal damage to a player with source tracking and optional agents for RNG parity.
/// Used by combat damage and spell damage to pass the source card and
/// combat flag so replacement effects like Torbran and Furnace of Rath
/// can check ValidSource$ and IsCombat$.
pub fn deal_damage_to_player_from_with_agents(
&mut self,
target: PlayerId,
amount: i32,
source: Option<CardId>,
is_combat: bool,
agents: Option<&mut [Box<dyn crate::agent::PlayerAgent>]>,
) -> i32 {
if amount <= 0 {
return 0;
}
if crate::staticability::static_ability_cant_gain_lose_pay_life::cant_lose_life(
self, target,
) {
return 0;
}
if crate::player::has_keyword(self, target, "Protection from everything") {
return 0;
}
let mut event = ReplacementEvent::DamageToPlayer {
target,
amount,
source,
is_combat,
};
if let Some(agents) = agents {
apply_replacements_with_agents(self, agents, &mut event);
} else {
apply_replacements(self, &mut event);
}
if let ReplacementEvent::DamageToPlayer {
amount: final_amount,
..
} = event
{
if final_amount > 0 {
return self.player_deal_damage(target, final_amount);
}
}
0
}
/// Check and apply state-based actions. Returns true if any were applied.
pub fn check_state_based_actions(&mut self) -> bool {
self.check_state_based_actions_with_triggers(None, None)
}
/// Check and apply state-based actions. Returns true if any were applied.
/// If provided, emits ChangesZone triggers for SBA zone moves.
/// `legend_keep_fn` — optional callback for legend rule: given (player, duplicates),
/// returns the CardId to keep. Mirrors Java's `chooseSingleEntityForEffect`.
pub fn check_state_based_actions_with_triggers(
&mut self,
trigger_handler: Option<&mut TriggerHandler>,
legend_keep_fn: Option<&mut dyn FnMut(PlayerId, &[CardId]) -> CardId>,
) -> bool {
self.check_state_based_actions_impl(trigger_handler, legend_keep_fn, None)
}
pub fn check_state_based_actions_with_trigger_agents(
&mut self,
trigger_handler: Option<&mut TriggerHandler>,
agents: &mut [Box<dyn PlayerAgent>],
) -> bool {
self.check_state_based_actions_impl(trigger_handler, None, Some(agents))
}
fn state_based_action_saga(
&self,
cid: CardId,
trigger_handler: Option<&TriggerHandler>,
sacrifice_list: &mut Vec<CardId>,
) -> bool {
let card = self.card(cid);
if !card.type_line.has_subtype("Saga") || !card.has_chapter() {
return false;
}
if crate::staticability::static_ability_cant_sacrifice::cant_sacrifice(
&self.cards,
card,
None,
true,
) {
return false;
}
if card.counter_count(&CounterType::Lore) < card.get_final_chapter_nr() {
return false;
}
if self.stack.has_source_chapter_on_stack(self, cid)
|| trigger_handler.is_some_and(|handler| handler.has_source_chapter_pending(self, cid))
{
return false;
}
sacrifice_list.push(cid);
true
}
fn on_player_lost(
&mut self,
player: PlayerId,
trigger_handler: &mut Option<&mut TriggerHandler>,
) {
self.player_mut(player).left_game = true;
let is_multiplayer = self.player_order.len() > 2;
let all_cards: Vec<CardId> = (0..self.cards.len()).map(|i| CardId(i as u32)).collect();
if !is_multiplayer {
// CR 707.9: at the end of the game every face-down card is revealed.
for &cid in &all_cards {
self.cards[cid.index()].force_turn_face_up();
}
return;
}
// CR 724.4 / CR 725.4. Reassigned before the sweep so the old effect
if self.monarch == Some(player) {
let heir = if self.turn.active_player == player {
self.next_player(player)
} else {
self.turn.active_player
};
self.player_set_monarch(heir, trigger_handler.as_deref_mut());
}
if self.initiative_holder == Some(player) {
let heir = if self.turn.active_player == player {
self.next_player(player)
} else {
self.turn.active_player
};
self.player_take_initiative(heir, trigger_handler.as_deref_mut());
}
let next = self.next_player(player);
for &cid in &all_cards {
let (zone, owner, controller) = {
let card = &self.cards[cid.index()];
(card.zone, card.owner, card.controller)
};
if zone == ZoneType::None {
continue;
}
if owner != player {
// CR 800.4c: nothing stays enchanting the leaving player.
if self.cards[cid.index()].attached_to_player == Some(player) {
self.cards[cid.index()].attached_to_player = None;
}
continue;
}
if self.cards[cid.index()].effect_source.is_some() && zone == ZoneType::Command {
// Mirrors Java: lingering effects move to the next player so
// they continue to work.
self.remove_card_from_zone(ZoneType::Command, controller, cid);
self.cards[cid.index()].controller = next;
self.add_card_to_zone(ZoneType::Command, next, cid);
continue;
}
// CR 800.4a: objects owned by the leaving player leave the game.
for &other in &all_cards {
if other == cid {
continue;
}
let other_card = &mut self.cards[other.index()];
other_card.imprinted_cards.retain(|&r| r != cid);
other_card.remembered_cards.retain(|&r| r != cid);
other_card.attachments.retain(|&r| r != cid);
other_card.gain_control_targets.retain(|&r| r != cid);
if other_card.attached_to == Some(cid) {
other_card.attached_to = None;
}
}
if let Some(handler) = trigger_handler.as_deref_mut() {
crate::ability::effects::emit_zone_trigger(handler, cid, zone, ZoneType::None);
}
self.remove_card_from_zone(zone, controller, cid);
self.cards[cid.index()].zone = ZoneType::None;
}
apply_continuous_effects(self);
// CR 800.4d as Java implements it: permanents the leaving player
for &cid in &all_cards {
let (zone, owner, controller) = {
let card = &self.cards[cid.index()];
(card.zone, card.owner, card.controller)
};
if zone == ZoneType::Battlefield && controller == player && owner != player {
if let Some(handler) = trigger_handler.as_deref_mut() {
crate::ability::effects::emit_zone_trigger(
handler,
cid,
ZoneType::Battlefield,
ZoneType::Exile,
);
}
self.move_card_without_replacement(cid, ZoneType::Exile, owner);
}
}
}
fn move_battlefield_card_to_graveyard_for_sba(
&mut self,
cid: CardId,
trigger_handler: &mut Option<&mut TriggerHandler>,
agents: &mut Option<&mut [Box<dyn PlayerAgent>]>,
) {
let owner = self.card(cid).owner;
let mut moved_event = ReplacementEvent::Moved {
card: cid,
origin: ZoneType::Battlefield,
destination: ZoneType::Graveyard,
is_discard: false,
counter_map: None,
counter_cause: None,
counter_is_effect: false,
after_replacement_static_abilities: Vec::new(),
};
if let Some(agents) = agents.as_deref_mut() {
apply_replacements_with_agents(self, agents, &mut moved_event);
} else {
apply_replacements(self, &mut moved_event);
}
let final_dest = if let ReplacementEvent::Moved { destination, .. } = moved_event {
destination
} else {
ZoneType::Graveyard
};
let old_zone = self.card(cid).zone;
// Emit trigger BEFORE move_card so LKI state is still available for
// trigger matching. Persist/Undying and Modular inspect the dying card.
if let Some(handler) = trigger_handler.as_deref_mut() {
let lki_p1p1 = *self
.card(cid)
.counters
.get(&CounterType::P1P1)
.unwrap_or(&0);
let lki_power = self.card(cid).power();
let lki_toughness = self.card(cid).toughness();
let lki_counters = self.card(cid).counters.clone();
self.card_mut(cid).lki_counters = Some(lki_counters);
self.card_mut(cid)
.set_lki_power_toughness(Some(lki_power), Some(lki_toughness));
crate::ability::effects::emit_zone_trigger_with_lki_counters(
handler,
cid,
old_zone,
final_dest,
lki_p1p1,
lki_power,
lki_toughness,
);
handler.flush_waiting_triggers(self);
}
self.move_card_without_replacement(cid, final_dest, owner);
}
fn check_state_based_actions_impl(
&mut self,
mut trigger_handler: Option<&mut TriggerHandler>,
mut legend_keep_fn: Option<&mut dyn FnMut(PlayerId, &[CardId]) -> CardId>,
mut agents: Option<&mut [Box<dyn PlayerAgent>]>,
) -> bool {
// Capture battlefield state before SBA processing. Used by DisableTriggers
// (Hushbringer) to check LKI — if a creature with DisableTriggers dies in
// the same SBA batch as another creature, it still suppresses death triggers.
// Mirrors Java's LastStateBattlefield passed through RunParams.
self.pre_sba_battlefield = self
.cards
.iter()
.filter(|c| c.zone == ZoneType::Battlefield)
.map(|c| c.id)
.collect();
let mut any_changes = false;
let mut newly_lost_players: Vec<PlayerId> = Vec::new();
let mut sacrifice_list: Vec<CardId> = Vec::new();
// Check players with 0 or less life
for pid in self.player_order.clone() {
if self.player(pid).tried_to_draw_from_empty_library && self.player(pid).is_alive() {
self.player_mut(pid).tried_to_draw_from_empty_library = false;
let mut event = ReplacementEvent::GameLoss {
player: pid,
reason: GameLossReason::Milled,
};
let result = apply_replacements(self, &mut event);
if result != ReplacementResult::Replaced && !self.player(pid).has_lost {
self.player_mark_lost(pid, GameLossReason::Milled);
newly_lost_players.push(pid);
any_changes = true;
}
}
if self.player(pid).life <= 0 && self.player(pid).is_alive() {
let mut event = ReplacementEvent::GameLoss {
player: pid,
reason: GameLossReason::LifeReachedZero,
};
let result = apply_replacements(self, &mut event);
if result != ReplacementResult::Replaced && !self.player(pid).has_lost {
self.player_mark_lost(pid, GameLossReason::LifeReachedZero);
newly_lost_players.push(pid);
any_changes = true;
}
}
// Check poison counters (10+ = lose)
if self.player(pid).poison_counters >= 10 && self.player(pid).is_alive() {
let mut event = ReplacementEvent::GameLoss {
player: pid,
reason: GameLossReason::Poisoned,
};
let result = apply_replacements(self, &mut event);
if result != ReplacementResult::Replaced {
if !self.player(pid).has_lost {
self.player_mark_lost(pid, GameLossReason::Poisoned);
newly_lost_players.push(pid);
}
any_changes = true;
}
}
// Check commander damage (21+ from a single commander source = lose)
if self.player(pid).commander_damage_enabled {
let commander_dmg_entries: Vec<(u32, i32)> = self
.player(pid)
.commander_damage_received
.iter()
.map(|(&k, &v)| (k, v))
.collect();
for (_card_raw_id, dmg) in commander_dmg_entries {
if dmg >= 21 && self.player(pid).is_alive() && !self.player(pid).has_lost {
self.player_mark_lost(pid, GameLossReason::CommanderDamage);
newly_lost_players.push(pid);
any_changes = true;
}
}
}
// CR 704.5z: If a player controls a permanent with Start your
// engines! and that player has no speed, their speed becomes 1.
if self.player(pid).speed == 0
&& self
.cards_in_zone(ZoneType::Battlefield, pid)
.iter()
.any(|&cid| self.card(cid).has_keyword("Start your engines"))
{
self.increase_player_speed(pid, None);
any_changes = true;
}
}
for pid in self.player_order.clone() {
if !self.player(pid).is_alive()
&& !self.player(pid).left_game
&& !newly_lost_players.contains(&pid)
{
newly_lost_players.push(pid);
any_changes = true;
}
}
if !newly_lost_players.is_empty() {
for pid in &newly_lost_players {
self.on_player_lost(*pid, &mut trigger_handler);
self.stack.remove_instances_controlled_by(*pid);
}
if let Some(handler) = trigger_handler.as_deref_mut() {
for pid in &newly_lost_players {
handler.run_trigger(
TriggerType::LosesGame,
RunParams {
player: Some(*pid),
..Default::default()
},
false,
);
handler.on_player_lost(*pid);
}
}
}
// Check creatures with lethal damage or 0 toughness
let battlefield_cards: Vec<CardId> = self
.player_order
.clone()
.iter()
.flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
.collect();
for cid in battlefield_cards {
let (is_creature, zero_toughness, lethal, should_die) = {
let card = &self.cards[cid.index()];
let is_creature = card.is_creature();
let zero_toughness = card.toughness() <= 0;
let lethal = card.lethal_damage() || card.has_deathtouch_damage;
let should_die = zero_toughness || lethal;
(is_creature, zero_toughness, lethal, should_die)
};
if is_creature && should_die {
// Clear deathtouch flag regardless of outcome (mirrors Java
// GameAction.java line 1491: c.setHasBeenDealtDeathtouchDamage(false)).
self.cards[cid.index()].has_deathtouch_damage = false;
// CR 702.12: Indestructible prevents death from lethal damage and
// "destroy" effects, but NOT from toughness ≤ 0 (CR 704.5f vs 704.5g).
// This covers K:Indestructible from Forge card scripts (e.g. Darksteel Myr).
if lethal
&& !zero_toughness
&& self.cards[cid.index()].has_keyword("Indestructible")
{
continue;
}
// CR 702.89: Umbra armor (Totem Armor) — if enchanted creature
// would be destroyed, instead remove all damage and destroy the aura.
let has_umbra = self.cards[cid.index()].attachments.iter().any(|&aid| {
aid.index() < self.cards.len()
&& self.cards[aid.index()].zone == ZoneType::Battlefield
&& (self.cards[aid.index()].has_keyword("Umbra armor")
|| self.cards[aid.index()].has_keyword("Totem armor"))
});
if has_umbra && !zero_toughness {
// Find the first umbra armor aura and destroy it instead
let umbra_id =
self.cards[cid.index()]
.attachments
.iter()
.copied()
.find(|&aid| {
aid.index() < self.cards.len()
&& self.cards[aid.index()].zone == ZoneType::Battlefield
&& (self.cards[aid.index()].has_keyword("Umbra armor")
|| self.cards[aid.index()].has_keyword("Totem armor"))
});
if let Some(umbra_id) = umbra_id {
// Remove all damage from the creature
self.cards[cid.index()].damage = 0;
self.cards[cid.index()].has_deathtouch_damage = false;
// Destroy the aura instead
let umbra_owner = self.cards[umbra_id.index()].owner;
let old_zone = self.cards[umbra_id.index()].zone;
self.move_card(umbra_id, ZoneType::Graveyard, umbra_owner);
if let Some(handler) = trigger_handler.as_deref_mut() {
crate::ability::effects::emit_zone_trigger(
handler,
umbra_id,
old_zone,
ZoneType::Graveyard,
);
}
any_changes = true;
continue; // Creature survives
}
}
if zero_toughness {
self.move_battlefield_card_to_graveyard_for_sba(
cid,
&mut trigger_handler,
&mut agents,
);
any_changes = true;
continue;
}
// Run Destroy replacement effects (R$-based indestructible, etc.).
// Mirrors Java GameAction.destroy() → ReplacementHandler.run(Destroy, …).
let mut destroy_event = ReplacementEvent::Destroy { target: cid };
let result = apply_replacements(self, &mut destroy_event);
if result != ReplacementResult::Replaced {
self.move_battlefield_card_to_graveyard_for_sba(
cid,
&mut trigger_handler,
&mut agents,
);
// Same-SBA-batch LTB lookback is derived per-event from
// `pre_sba_battlefield` in `TriggerHandler::ltb_trigger_refs_for_event`.
// No global registration needed.
any_changes = true;
} else {
// Indestructible — destruction was replaced; creature stays.
// Damage is still marked but the creature does not die.
}
}
}
let battlefield_cards: Vec<CardId> = self
.player_order
.clone()
.iter()
.flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
.collect();
for cid in battlefield_cards {
let should_put_in_graveyard = {
let card = self.card(cid);
card.type_line.is_planeswalker() && card.counter_count(&CounterType::Loyalty) <= 0
};
if !should_put_in_graveyard {
continue;
}
self.move_battlefield_card_to_graveyard_for_sba(cid, &mut trigger_handler, &mut agents);
any_changes = true;
}
let saga_cards: Vec<CardId> = self
.player_order
.clone()
.iter()
.flat_map(|&pid| self.cards_in_zone(ZoneType::Battlefield, pid).to_vec())
.collect();
for cid in saga_cards {
any_changes |=
self.state_based_action_saga(cid, trigger_handler.as_deref(), &mut sacrifice_list);
}
if !sacrifice_list.is_empty() {
if let (Some(handler), Some(agents)) =
(trigger_handler.as_deref_mut(), agents.as_deref_mut())
{
if !crate::game_loop::perform_sacrifice(self, handler, agents, &sacrifice_list)
.is_empty()
{
any_changes = true;
}
} else {
for cid in sacrifice_list.drain(..) {
let owner = self.card(cid).owner;
self.move_card_without_replacement(cid, ZoneType::Graveyard, owner);
}
any_changes = true;
}
}
// CR 704.5q: +1/+1 and -1/-1 counter cancellation
for &pid in &self.player_order.clone() {
let battlefield = self.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
for cid in battlefield {
let p1 = self.card(cid).counter_count(&CounterType::P1P1);
let m1 = self.card(cid).counter_count(&CounterType::M1M1);
if p1 > 0 && m1 > 0 {
let cancel = p1.min(m1);
self.card_mut(cid)
.remove_counter(&CounterType::P1P1, cancel);
self.card_mut(cid)
.remove_counter(&CounterType::M1M1, cancel);
any_changes = true;
}
}
}
// CR 903.9a: a commander in graveyard or exile may move to command zone.
for &pid in &self.player_order.clone() {
let mut commander_candidates = self.cards_in_zone(ZoneType::Graveyard, pid).to_vec();
commander_candidates.extend(self.cards_in_zone(ZoneType::Exile, pid).iter().copied());
for cid in commander_candidates {
if !self.card(cid).can_move_to_command_zone() {
continue;
}
self.card_mut(cid).move_to_command_zone = false;
let accepted = if let Some(agents) = agents.as_deref_mut() {
let name = self.card(cid).card_name.clone();
let message = format!(
"{name}: If a commander is in a graveyard or in exile and that card was put into that zone since the last time state-based actions were checked, its owner may put it into the command zone."
);
agents[pid.index()].confirm_action(
pid,
Some("ChangeZoneToAltDestination"),
&message,
&[],
Some(cid),
None,
)
} else {
false
};
if accepted {
self.move_card_without_replacement(cid, ZoneType::Command, pid);
any_changes = true;
}
}
}
// Legend rule: for each player, if they control multiple legendary
// permanents with the same name, keep one and move the rest to graveyard.
// IgnoreLegendRule statics exempt matching cards.
for &pid in &self.player_order.clone() {
let battlefield = self.cards_in_zone(ZoneType::Battlefield, pid).to_vec();
let mut by_name: std::collections::BTreeMap<String, Vec<CardId>> =
std::collections::BTreeMap::new();
for cid in battlefield {
let c = self.card(cid);
if !c.type_line.is_legendary() {
continue;
}
if crate::staticability::static_ability_ignore_legend_rule::ignore_legend_rule(
&self.cards,
c,
) {
continue;
}
by_name.entry(c.card_name.clone()).or_default().push(cid);
}
for (_name, ids) in by_name {
if ids.len() <= 1 {
continue;
}
// Choose which to keep: delegate to callback (mirrors Java's
// chooseSingleEntityForEffect), or default to first in zone order.
let keep = if let Some(ref mut chooser) = legend_keep_fn {
chooser(pid, &ids)
} else if let Some(agents) = agents.as_deref_mut() {
agents[pid.index()].choose_legend_keep(pid, &ids)
} else {
ids[0]
};
for cid in ids {
if cid == keep {
continue;
}
let owner = self.card(cid).owner;
let old_zone = self.card(cid).zone;
if let Some(agents) = agents.as_deref_mut() {
self.move_card_with_agents(cid, ZoneType::Graveyard, owner, agents);
} else {
self.move_card(cid, ZoneType::Graveyard, owner);
}
if let Some(handler) = trigger_handler.as_deref_mut() {
crate::ability::effects::emit_zone_trigger(
handler,
cid,
old_zone,
ZoneType::Graveyard,
);
}
any_changes = true;
}
}
}
// CR 704.5n: Aura SBA — an Aura on the battlefield that is not attached
// to a legal permanent (or whose host left the battlefield) is put into
// its owner's graveyard.
{
let aura_ids: Vec<CardId> = self
.cards
.iter()
.filter(|c| {
c.zone == ZoneType::Battlefield
&& c.type_line.has_subtype("Aura")
&& !c.type_line.is_creature() // Bestowed auras that became creatures stay
})
.filter(|c| {
match (c.attached_to, c.attached_to_player) {
(None, None) => true, // Not attached to anything — orphaned
(None, Some(player_id)) => {
if player_id.index() >= self.players.len() {
return true;
}
let player = &self.players[player_id.index()];
let enchant_type = c
.keywords
.iter_strings()
.find_map(|kw| {
crate::keyword::extract_keyword_cost_str(kw, "Enchant")
})
.unwrap_or_default();
player.has_lost || !enchant_type.eq_ignore_ascii_case("Player")
}
(Some(host_id), _) => {
if host_id.index() >= self.cards.len() {
return true; // Invalid host ID
}
let host = &self.cards[host_id.index()];
// CR 704.5n: check if the enchant restriction is still met.
// E.g. "Enchant creature" requires a battlefield creature, while
// Animate Dead's "Enchant creature card in a graveyard" remains legal
// while attached to a creature card in a graveyard.
let enchant_type = c
.keywords
.iter_strings()
.find_map(|kw| {
crate::keyword::extract_keyword_cost_str(kw, "Enchant")
})
.unwrap_or_default();
!crate::parsing::enchant_type_matches_card(enchant_type, host, Some(c))
|| !can_attachment_remain_attached(&self.cards, c, host, true)
}
}
})
.map(|c| c.id)
.collect();
for aura_id in aura_ids {
let owner = self.card(aura_id).owner;
let old_zone = self.card(aura_id).zone;
self.move_card(aura_id, ZoneType::Graveyard, owner);
if let Some(handler) = trigger_handler.as_deref_mut() {
crate::ability::effects::emit_zone_trigger(
handler,
aura_id,
old_zone,
ZoneType::Graveyard,
);
}
any_changes = true;
}
}
// Check game over
let alive = self.alive_players();
if alive.len() <= 1 {
self.game_over = true;
if alive.len() == 1 {
self.winner = Some(alive[0]);
}
}
any_changes
}
/// Untap all permanents controlled by a player.
/// Runs Untap replacement effects for each permanent.
pub fn untap_all(&mut self, player: PlayerId) {
let cards: Vec<CardId> = self.cards_in_zone(ZoneType::Battlefield, player).to_vec();
for cid in cards {
// Use untap() which runs replacement effects
self.untap_during_untap_step(cid, player);
}
}
/// Draw a card for a player. Returns the drawn card ID, or None if the draw
/// was skipped or the library is empty.
///
/// Runs Draw replacement effects before drawing. If the draw is replaced
/// (e.g. "skip your draw step"), returns `None`.
///
/// Mirrors Java `GameAction.draw()` calling `ReplacementHandler.run(Draw, …)`.
pub fn draw_card(&mut self, player: PlayerId) -> Option<CardId> {
self.player_draw_one(player)
}
/// Draw a card with agent access for Optional replacement effects (Dredge).
pub fn draw_card_with_agents(
&mut self,
player: PlayerId,
agents: &mut [Box<dyn crate::agent::PlayerAgent>],
) -> Option<CardId> {
self.player_draw_one_internal(player, false, Some(agents))
}
/// Draw N cards for a player. Returns drawn card IDs.
pub fn draw_cards(&mut self, player: PlayerId, n: usize) -> Vec<CardId> {
self.player_draw_cards(player, n)
}
/// Shuffle a player's library using the provided RNG.
pub fn shuffle_library(&mut self, player: PlayerId, rng: &mut impl rand::Rng) {
self.shuffle_zone_cards_with_rand(ZoneType::Library, player, rng);
}
/// Reset per-turn state for all cards and players of a given player.
pub fn new_turn_for_player(&mut self, player: PlayerId) {
self.player_new_turn(player);
// Reset turn-scoped player stats for ALL non-active players too.
// These counters are "this turn" in the global turn sense, not "that
// player's own turn". Without this, effects like Resplendent Angel can
// incorrectly carry life gained from the previous player's turn.
for pid in &self.player_order.clone() {
if *pid != player {
self.player_reset_drawn_this_turn(*pid);
let p = self.player_mut(*pid);
p.life_started_this_turn_with = p.life;
p.life_gained_this_turn = 0;
p.life_gained_by_team_this_turn = 0;
p.life_gained_times_this_turn = 0;
p.life_lost_last_turn = p.life_lost_this_turn;
p.life_lost_this_turn = 0;
}
}
let all_card_ids: Vec<CardId> = (0..self.cards.len()).map(|i| CardId(i as u32)).collect();
for cid in all_card_ids {
if self.cards[cid.index()].zone == ZoneType::Battlefield {
self.cards[cid.index()].started_turn_tapped = self.cards[cid.index()].tapped;
}
if self.cards[cid.index()].controller == player {
self.cards[cid.index()].new_turn();
} else {
self.cards[cid.index()].clear_global_turn_state();
}
}
}
/// Tap a card. Returns true if it was untapped.
/// Runs Tap replacement effects before tapping.
pub fn tap(&mut self, card_id: CardId) -> bool {
let card = &self.cards[card_id.index()];
if card.tapped {
return false;
}
// Run Tap replacement effects.
let mut event = ReplacementEvent::Tap { card: card_id };
let result = apply_replacements(self, &mut event);
if result == ReplacementResult::Skipped || result == ReplacementResult::Replaced {
return false; // Tap was prevented
}
self.cards[card_id.index()].tapped = true;
true
}
/// Untap a card. Returns true if it was tapped.
/// Runs Untap replacement effects before untapping.
pub fn untap(&mut self, card_id: CardId) -> bool {
self.untap_internal(card_id, None)
}
pub fn untap_during_untap_step(&mut self, card_id: CardId, player: PlayerId) -> bool {
self.untap_internal(card_id, Some(player))
}
fn untap_internal(&mut self, card_id: CardId, player: Option<PlayerId>) -> bool {
let card = &self.cards[card_id.index()];
if !card.tapped {
return false;
}
let stun = CounterType::Named("STUN".to_string());
if card.counter_count(&stun) > 0 && card.can_remove_counters(&stun) {
// Stun counters replace the untap event: remove one counter and keep the
// permanent tapped. This mirrors Java's built-in stun untap replacement.
self.cards[card_id.index()].remove_counter(&stun, 1);
return false;
}
// Run Untap replacement effects.
let mut event = ReplacementEvent::Untap {
card: card_id,
player,
};
let result = apply_replacements(self, &mut event);
if result == ReplacementResult::Skipped || result == ReplacementResult::Replaced {
return false; // Untap was prevented
}
self.cards[card_id.index()].tapped = false;
// `ControlGain$ LoseControl$ Untap` — revert scheduled steal now.
crate::ability::effects::control_gain_effect::untap_hook(self, card_id);
true
}
/// Change the controller of a permanent to `new_controller`.
/// Mirrors Java's `GameAction.controllerChangeZoneCorrection()` — moves the
/// card between per-player zone lists and updates the controller field.
pub fn change_controller(&mut self, card_id: CardId, new_controller: PlayerId) {
let card = &self.cards[card_id.index()];
if card.controller == new_controller {
return;
}
let old_controller = card.controller;
let zone = card.zone;
// Move between zone lists
if zone != ZoneType::None {
self.remove_card_from_zone(zone, old_controller, card_id);
self.add_card_to_zone(zone, new_controller, card_id);
}
self.cards[card_id.index()].controller = new_controller;
}
/// Attach `aura_id` to `target_id`.
/// If `aura_id` was already attached elsewhere, detach it first.
/// Mirrors Java's `Card.enchantEntity()` / `Card.equip()`.
pub fn attach_to(&mut self, aura_id: CardId, target_id: CardId) {
// Detach from previous host if any
self.detach(aura_id);
self.cards[aura_id.index()].attached_to = Some(target_id);
self.cards[aura_id.index()].attached_to_player = None;
self.cards[aura_id.index()].attached_this_turn = true;
self.cards[target_id.index()].attachments.push(aura_id);
}
pub fn attach_to_player(&mut self, aura_id: CardId, player_id: PlayerId) {
self.detach(aura_id);
self.cards[aura_id.index()].attached_to = None;
self.cards[aura_id.index()].attached_to_player = Some(player_id);
self.cards[aura_id.index()].attached_this_turn = true;
}
/// Detach `aura_id` from whatever it is currently attached to.
/// Mirrors Java's `Card.unattachFromEntity()`.
pub fn detach(&mut self, aura_id: CardId) {
if let Some(host_id) = self.cards[aura_id.index()].attached_to.take() {
self.cards[host_id.index()]
.attachments
.retain(|&a| a != aura_id);
// Bestow: when unattached, revert to a creature
self.cards[aura_id.index()].is_bestowed = false;
}
self.cards[aura_id.index()].attached_to_player = None;
}
/// Move a card from its current zone to the bottom of a player's library.
/// Unlike `move_card`, this places the card at the bottom rather than the top.
pub fn put_on_bottom_of_library(&mut self, card_id: CardId, owner: PlayerId) {
let card = &self.cards[card_id.index()];
let src_zone = card.zone;
let src_owner = card.controller;
if src_zone != ZoneType::None {
self.remove_card_from_zone(src_zone, src_owner, card_id);
}
self.cards[card_id.index()].zone = ZoneType::Library;
self.assign_zone_timestamp(card_id);
self.add_card_to_zone_bottom(ZoneType::Library, owner, card_id);
}
/// Remove a spell from the stack by its entry ID (used by Counter).
/// Mirrors Java's `Game.getStack().remove(sa)`.
pub fn remove_from_stack(&mut self, entry_id: u32) -> bool {
self.stack.remove_by_id(entry_id).is_some()
}
}
fn can_attachment_remain_attached(
cards: &[Card],
attachment: &Card,
target: &Card,
check_sba: bool,
) -> bool {
if target.zone != ZoneType::Battlefield {
return true;
}
if crate::staticability::static_ability_cant_attach::cant_attach(
cards, attachment, target, check_sba,
) {
return false;
}
!crate::staticability::static_ability_colorless_damage_source::target_is_protected_from_source(
cards, target, attachment,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::card::Card;
use crate::player::RegisteredPlayer;
use forge_foundation::{CardTypeLine, ColorSet, ManaCost};
fn make_creature(game: &mut GameState, name: &str, owner: PlayerId, p: i32, t: i32) -> CardId {
let card = Card::new(
CardId(0),
name.to_string(),
owner,
CardTypeLine::parse("Creature Bear"),
ManaCost::parse("1 G"),
ColorSet::GREEN,
Some(p),
Some(t),
vec![],
vec![],
);
game.create_card(card)
}
#[test]
fn move_card_to_battlefield() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
game.move_card(cid, ZoneType::Hand, PlayerId(0));
assert_eq!(game.zone(ZoneType::Hand, PlayerId(0)).len(), 1);
game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
assert_eq!(game.zone(ZoneType::Hand, PlayerId(0)).len(), 0);
assert_eq!(game.zone(ZoneType::Battlefield, PlayerId(0)).len(), 1);
assert_eq!(game.card(cid).zone, ZoneType::Battlefield);
}
#[test]
fn state_based_actions_lethal_damage() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
game.deal_damage_to_card(cid, 2);
assert!(game.check_state_based_actions());
assert_eq!(game.zone(ZoneType::Graveyard, PlayerId(0)).len(), 1);
}
#[test]
fn state_based_actions_zero_life() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
game.deal_damage_to_player(PlayerId(0), 20);
game.check_state_based_actions();
assert!(game.player(PlayerId(0)).has_lost);
assert!(game.game_over);
assert_eq!(game.winner, Some(PlayerId(1)));
}
#[test]
fn draw_card() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
game.move_card(cid, ZoneType::Library, PlayerId(0));
let drawn = game.draw_card(PlayerId(0));
assert_eq!(drawn, Some(cid));
assert_eq!(game.card(cid).zone, ZoneType::Hand);
}
#[test]
fn tap_untap() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
assert!(game.tap(cid));
assert!(game.card(cid).tapped);
assert!(!game.tap(cid)); // already tapped
assert!(game.untap(cid));
assert!(!game.card(cid).tapped);
}
#[test]
fn stun_counter_replaces_untap() {
let mut game = GameState::new(&["Alice", "Bob"], 20);
let cid = make_creature(&mut game, "Bear", PlayerId(0), 2, 2);
game.move_card(cid, ZoneType::Battlefield, PlayerId(0));
game.tap(cid);
game.card_mut(cid)
.add_counter(&CounterType::Named("STUN".to_string()), 1);
assert!(!game.untap(cid));
assert!(game.card(cid).tapped);
assert_eq!(
game.card(cid)
.counter_count(&CounterType::Named("STUN".to_string())),
0
);
}
}