1use crate::ability::activated::parse_activated_ability;
8use crate::card::svar_cache::ParsedSVarKind;
9use crate::parsing::keys;
10use crate::parsing::Params;
11use crate::staticability::parse_static_ability;
12use crate::trigger::parse_trigger;
13
14use super::Card;
15
16fn roman_chapter(mut chapter: usize) -> String {
17 let mut result = String::new();
18 for (value, numeral) in [
19 (1000, "M"),
20 (900, "CM"),
21 (500, "D"),
22 (400, "CD"),
23 (100, "C"),
24 (90, "XC"),
25 (50, "L"),
26 (40, "XL"),
27 (10, "X"),
28 (9, "IX"),
29 (5, "V"),
30 (4, "IV"),
31 (1, "I"),
32 ] {
33 while chapter >= value {
34 result.push_str(numeral);
35 chapter -= value;
36 }
37 }
38 result
39}
40
41impl Card {
42 fn parsed_svar_params(&mut self, name: &str) -> Option<Params> {
43 match self.parsed_s_var(name)?.kind {
44 ParsedSVarKind::Ability { params, .. } | ParsedSVarKind::ParamRecord { params } => {
45 Some(params)
46 }
47 ParsedSVarKind::Number { .. }
48 | ParsedSVarKind::Count { .. }
49 | ParsedSVarKind::NumericExpression { .. }
50 | ParsedSVarKind::Raw { .. } => None,
51 }
52 }
53
54 pub(crate) fn generate_basic_land_mana_abilities(&mut self) {
57 const SUBTYPE_MANA: &[(&str, &str, &str)] = &[
58 ("Plains", "W", "Add {W}."),
59 ("Island", "U", "Add {U}."),
60 ("Swamp", "B", "Add {B}."),
61 ("Mountain", "R", "Add {R}."),
62 ("Forest", "G", "Add {G}."),
63 ];
64 for &(subtype, letter, desc) in SUBTYPE_MANA {
65 if self.type_line.has_subtype(subtype) {
66 let already_produces = self.activated_abilities.iter().any(|ab| {
67 ab.is_mana_ability
68 && ab
69 .produced_ir
70 .as_ref()
71 .is_some_and(|ir| ir.as_script_text() == letter)
72 });
73 if !already_produces {
74 let raw = format!(
75 "AB$ Mana | Cost$ T | Produced$ {letter} | SpellDescription$ {desc}"
76 );
77 let idx = self.abilities.len();
78 self.abilities.push(raw.clone());
79 if let Some(ab) = parse_activated_ability(&raw, idx) {
80 self.activated_abilities.push(ab);
81 }
82 }
83 }
84 }
85 }
86
87 pub(super) fn generate_keyword_abilities(&mut self) {
90 if let Some(cycling_cost) = self.get_keyword_cost("Cycling") {
92 let ab_text = format!(
93 "AB$ Draw | Cost$ {cycling_cost} Discard<1/CARDNAME> | ActivationZone$ Hand | NumCards$ 1 | Defined$ You"
94 );
95 let next_idx = self.activated_abilities.len();
96 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
97 self.activated_abilities.push(ab);
98 }
99 }
100
101 for kw in self
104 .keywords
105 .iter_strings()
106 .chain(self.granted_keywords.iter_strings())
107 {
108 if let Some(rest) = kw.strip_prefix("TypeCycling:") {
109 let parts: Vec<&str> = rest.splitn(2, ':').collect();
110 if parts.len() == 2 {
111 let cycle_type = parts[0].trim(); let mana_cost = parts[1].trim(); let precost_desc = format!(
115 "{}cycling",
116 cycle_type
117 .chars()
118 .next()
119 .map(|c| c.to_uppercase().to_string())
120 .unwrap_or_default()
121 + &cycle_type[1..]
122 );
123 let ab_text = format!(
124 "AB$ ChangeZone | Cost$ {mana_cost} Discard<1/CARDNAME> | ActivationZone$ Hand | PrecostDesc$ {precost_desc} | Origin$ Library | Destination$ Hand | ChangeType$ {cycle_type}"
125 );
126 let next_idx = self.activated_abilities.len();
127 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
128 self.activated_abilities.push(ab);
129 }
130 }
131 }
132 }
133
134 for equip_raw in self
138 .keywords
139 .iter_strings()
140 .chain(self.granted_keywords.iter_strings())
141 .filter_map(|kw| crate::keyword::extract_keyword_cost_str(kw, "Equip"))
142 {
143 let payload = equip_raw.split(":::").next().unwrap_or(equip_raw).trim();
144 let mut parts = payload.split(':');
145 let equip_cost = parts.next().unwrap_or(payload).trim();
146 let target_filter = parts
147 .next()
148 .map(str::trim)
149 .filter(|s| !s.is_empty())
150 .unwrap_or("Creature.YouCtrl");
151 if !equip_cost.is_empty() {
152 let ab_text = format!(
153 "AB$ Attach | Cost$ {equip_cost} | ValidTgts$ {target_filter} | SorcerySpeed$ True | SpellDescription$ Equip {equip_cost}"
154 );
155 let next_idx = self.activated_abilities.len();
156 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
157 self.activated_abilities.push(ab);
158 }
159 }
160 }
161
162 for kw in self
166 .keywords
167 .iter_strings()
168 .chain(self.granted_keywords.iter_strings())
169 {
170 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Crew") {
171 let n = n_str.trim();
172 let ab_text = format!(
173 "AB$ Animate | Cost$ tapXType<Any/Creature.Other+withTotalPowerGE{{{n}}}> | Defined$ Self | Types$ Artifact,Creature | Secondary$ True | SpellDescription$ Crew {n}"
174 );
175 let next_idx = self.activated_abilities.len();
176 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
177 self.activated_abilities.push(ab);
178 }
179 }
180 }
181
182 for kw in self
187 .keywords
188 .iter_strings()
189 .chain(self.granted_keywords.iter_strings())
190 {
191 if let Some(_n_str) = crate::keyword::extract_keyword_cost_str(kw, "Station") {
192 let ab_text = "AB$ PutCounter | Cost$ tapXType<1/Creature.Other> | Defined$ Self | CounterType$ CHARGE | CounterNum$ StationX | SorcerySpeed$ True | CostDesc$ | SpellDescription$ Station";
193 let next_idx = self.activated_abilities.len();
194 if let Some(ab) = parse_activated_ability(ab_text, next_idx) {
195 self.activated_abilities.push(ab);
196 }
197 self.svars
198 .entry("StationX".to_string())
199 .or_insert_with(|| "TappedCards$TapPowerValue".to_string());
200 }
201 }
202
203 for kw in self
206 .keywords
207 .iter_strings()
208 .chain(self.granted_keywords.iter_strings())
209 {
210 if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Embalm") {
211 let cost = cost_str.trim();
212 let ab_text = format!(
213 "AB$ CopyPermanent | Cost$ {cost} ExileFromGrave<1/CARDNAME> | ActivationZone$ Graveyard | SorcerySpeed$ True | Defined$ Self | SetColor$ White | AddTypes$ Zombie | SpellDescription$ Embalm"
214 );
215 let next_idx = self.activated_abilities.len();
216 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
217 self.activated_abilities.push(ab);
218 }
219 }
220 }
221
222 for kw in self
225 .keywords
226 .iter_strings()
227 .chain(self.granted_keywords.iter_strings())
228 {
229 if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Eternalize") {
230 let cost = cost_str.trim();
231 let ab_text = format!(
232 "AB$ CopyPermanent | Cost$ {cost} ExileFromGrave<1/CARDNAME> | ActivationZone$ Graveyard | SorcerySpeed$ True | Defined$ Self | SetColor$ Black | SetPower$ 4 | SetToughness$ 4 | AddTypes$ Zombie | SpellDescription$ Eternalize"
233 );
234 let next_idx = self.activated_abilities.len();
235 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
236 self.activated_abilities.push(ab);
237 }
238 }
239 }
240
241 if self
243 .keywords
244 .iter_strings()
245 .chain(self.granted_keywords.iter_strings())
246 .any(|k| k.eq_ignore_ascii_case("Enlist"))
247 {
248 let raw = "S:Mode$ OptionalAttackCost | ValidCard$ Card.Self | Cost$ Enlist<1/CARDNAME/creature> | Secondary$ True | Trigger$ TrigEnlist";
249 if let Some(sa) = parse_static_ability(raw) {
250 self.add_static_ability(sa);
251 }
252 self.svars.entry("TrigEnlist".to_string()).or_insert_with(|| {
253 "DB$ Pump | NumAtt$ TriggerRemembered$CardPower | SpellDescription$ When you do, add its power to this creature's until end of turn.".to_string()
254 });
255 }
256
257 if self
260 .keywords
261 .iter_strings()
262 .chain(self.granted_keywords.iter_strings())
263 .any(|k| k.starts_with("Morph:") || k.starts_with("Megamorph:"))
264 {
265 self.has_morph = true;
266 }
267
268 if let Some(plot_cost) = self.get_keyword_cost("Plot") {
272 let ab_text = format!(
273 "AB$ Plot | Cost$ {plot_cost} | ActivationZone$ Hand | SorcerySpeed$ True | Secondary$ True | SpellDescription$ Plot"
274 );
275 let next_idx = self.activated_abilities.len();
276 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
277 self.activated_abilities.push(ab);
278 }
279 }
280
281 if let Some(cost) = self.get_keyword_cost("Level up") {
282 let raw = format!("AB$ PutCounter | Cost$ {cost} | PrecostDesc$ Level up | SorcerySpeed$ True | Secondary$ True | CounterType$ LEVEL | CounterNum$ 1 | StackDescription$ {{p:You}} levels up {{c:Self}}. | SpellDescription$ Level up");
283 let index = self.activated_abilities.len();
284 if let Some(mut ability) = parse_activated_ability(&raw, index) {
285 ability.is_level_up = true;
286 self.activated_abilities.push(ability);
287 }
288 }
289
290 let class_keywords: Vec<String> = self
293 .keywords
294 .iter_strings()
295 .chain(self.granted_keywords.iter_strings())
296 .filter(|kw| kw.starts_with("Class:"))
297 .map(|kw| kw.to_string())
298 .collect();
299 for kw in class_keywords {
300 if let Some(rest) = kw.strip_prefix("Class:") {
301 let mut parts = rest.splitn(3, ':');
302 let level = parts.next().unwrap_or_default().trim();
303 let cost = parts.next().unwrap_or_default().trim();
304 let params = parts.next().unwrap_or_default().trim();
305
306 let Ok(level_num) = level.parse::<i32>() else {
307 continue;
308 };
309 if cost.is_empty() {
310 continue;
311 }
312
313 let ab_text = format!(
314 "AB$ ClassLevelUp | Cost$ {} | ClassLevel$ EQ{} | SorcerySpeed$ True | StackDescription$ SpellDescription | SpellDescription$ Level {}",
315 cost,
316 level_num - 1,
317 level_num
318 );
319 let next_idx = self.activated_abilities.len();
320 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
321 self.activated_abilities.push(ab);
322 }
323
324 if !params.is_empty() {
325 let parsed = Params::from_raw(params);
326 let mut desc_parts: Vec<String> = Vec::new();
327
328 if let Some(add_trigger) = parsed.get("AddTrigger") {
329 for svar_name in add_trigger
330 .split(" & ")
331 .map(str::trim)
332 .filter(|s| !s.is_empty())
333 {
334 if let Some(svar_params) = self.parsed_svar_params(svar_name) {
335 if let Some(desc) = svar_params.get(keys::TRIGGER_DESCRIPTION) {
336 desc_parts.push(desc.to_string());
337 }
338 }
339 }
340 }
341
342 if let Some(add_static) = parsed.get("AddStaticAbility") {
343 for svar_name in add_static
344 .split(" & ")
345 .map(str::trim)
346 .filter(|s| !s.is_empty())
347 {
348 if let Some(svar_params) = self.parsed_svar_params(svar_name) {
349 if let Some(desc) = svar_params.get(keys::DESCRIPTION) {
350 desc_parts.push(desc.to_string());
351 }
352 }
353 }
354 }
355
356 if let Some(add_replacement) = parsed.get("AddReplacementEffect") {
357 for svar_name in add_replacement
358 .split(" & ")
359 .map(str::trim)
360 .filter(|s| !s.is_empty())
361 {
362 if let Some(svar_params) = self.parsed_svar_params(svar_name) {
363 if let Some(desc) = svar_params.get(keys::DESCRIPTION) {
364 desc_parts.push(desc.to_string());
365 }
366 }
367 }
368 }
369
370 let mut effect = format!(
371 "Mode$ Continuous | Affected$ Card.Self | ClassLevel$ {level_num} | {params}"
372 );
373 if !desc_parts.is_empty() {
374 effect.push_str(" | Description$ ");
375 effect.push_str(&desc_parts.join("\r\n"));
376 }
377 if let Some(st) = parse_static_ability(&effect) {
378 self.add_static_ability(st);
379 }
380 }
381 }
382 }
383 }
384
385 pub fn ensure_crew_activated_ability(&mut self) {
386 if self.activated_abilities.iter().any(|ab| {
387 ab.spell_description
388 .as_deref()
389 .is_some_and(|desc| desc.starts_with("Crew"))
390 }) {
391 return;
392 }
393 for kw in self.keywords.iter_strings() {
394 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Crew") {
395 let n = n_str.trim();
396 let ab_text = format!(
397 "AB$ Animate | Cost$ tapXType<Any/Creature.Other+withTotalPowerGE{{{n}}}> | Defined$ Self | Types$ Artifact,Creature | Secondary$ True | SpellDescription$ Crew {n}"
398 );
399 let next_idx = self.activated_abilities.len();
400 if let Some(ab) = parse_activated_ability(&ab_text, next_idx) {
401 self.activated_abilities.push(ab);
402 self.base_ability_count = self.activated_abilities.len();
403 }
404 return;
405 }
406 }
407 }
408
409 pub fn generate_keyword_triggers(&mut self) {
412 let mut next_id = self.triggers.len() as u32;
413
414 for kw in self.keywords.as_string_list() {
415 self.generate_keyword_trigger_combat(&kw, &mut next_id);
416 self.generate_keyword_trigger_zone(&kw, &mut next_id);
417 self.generate_keyword_trigger_misc(&kw, &mut next_id);
418 }
419 }
420
421 fn generate_keyword_trigger_combat(&mut self, kw: &str, next_id: &mut u32) {
422 if kw == "Prowess" {
423 let raw = "Mode$ SpellCast | ValidCard$ Card.nonCreature | ValidActivatingPlayer$ You | Execute$ TrigProwess | TriggerZones$ Battlefield | TriggerDescription$ Prowess";
424 if let Some(mut trig) = parse_trigger(raw, next_id) {
425 trig.execute = "TrigProwess".to_string();
426 self.add_trigger(trig);
427 }
428 self.svars
429 .entry("TrigProwess".to_string())
430 .or_insert_with(|| "DB$ Pump | Defined$ Self | NumAtt$ 1 | NumDef$ 1".to_string());
431 }
432
433 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Bushido") {
434 if n_str.parse::<i32>().is_ok() {
435 let raw1 = format!(
436 "Mode$ Blocks | ValidCard$ Card.Self | Execute$ TrigBushido | TriggerZones$ Battlefield | TriggerDescription$ Bushido {n_str}"
437 );
438 if let Some(mut trig) = parse_trigger(&raw1, next_id) {
439 trig.execute = "TrigBushido".to_string();
440 self.add_trigger(trig);
441 }
442 let raw2 = format!(
443 "Mode$ AttackerBlocked | ValidCard$ Card.Self | Execute$ TrigBushido | TriggerZones$ Battlefield | TriggerDescription$ Bushido {n_str}"
444 );
445 if let Some(mut trig) = parse_trigger(&raw2, next_id) {
446 trig.execute = "TrigBushido".to_string();
447 self.add_trigger(trig);
448 }
449 self.svars
450 .entry("TrigBushido".to_string())
451 .or_insert_with(|| {
452 format!("DB$ Pump | Defined$ Self | NumAtt$ {n_str} | NumDef$ {n_str}")
453 });
454 }
455 }
456
457 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Annihilator") {
458 if n_str.parse::<i32>().is_ok() {
459 let raw = format!(
460 "Mode$ Attacks | ValidCard$ Card.Self | Execute$ TrigAnnihilator | TriggerZones$ Battlefield | TriggerDescription$ Annihilator {n_str}"
461 );
462 if let Some(mut trig) = parse_trigger(&raw, next_id) {
463 trig.execute = "TrigAnnihilator".to_string();
464 self.add_trigger(trig);
465 }
466 self.svars
467 .entry("TrigAnnihilator".to_string())
468 .or_insert_with(|| {
469 format!("DB$ Sacrifice | Defined$ TriggeredDefendingPlayer | SacValid$ Permanent | Amount$ {n_str}")
470 });
471 }
472 }
473
474 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Afflict") {
475 if n_str.parse::<i32>().is_ok() {
476 let raw = format!(
477 "Mode$ AttackerBlocked | ValidCard$ Card.Self | TriggerZones$ Battlefield | Secondary$ True | Execute$ TrigAfflict | TriggerDescription$ Afflict {n_str}"
478 );
479 if let Some(mut trig) = parse_trigger(&raw, next_id) {
480 trig.execute = "TrigAfflict".to_string();
481 self.add_trigger(trig);
482 }
483 self.svars
484 .entry("TrigAfflict".to_string())
485 .or_insert_with(|| {
486 format!("DB$ LoseLife | Defined$ TriggeredDefendingPlayer | LifeAmount$ {n_str}")
487 });
488 }
489 }
490
491 if kw == "Exalted" {
492 let raw = "Mode$ Attacks | ValidCard$ Creature.YouCtrl | Alone$ True | Execute$ TrigExalted | TriggerZones$ Battlefield | TriggerDescription$ Exalted";
493 if let Some(mut trig) = parse_trigger(raw, next_id) {
494 trig.execute = "TrigExalted".to_string();
495 self.add_trigger(trig);
496 }
497 self.svars
498 .entry("TrigExalted".to_string())
499 .or_insert_with(|| {
500 "DB$ Pump | Defined$ TriggeredAttacker | NumAtt$ +1 | NumDef$ +1".to_string()
501 });
502 }
503
504 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Renown") {
505 if n_str.parse::<i32>().is_ok() {
506 let raw = format!(
507 "Mode$ DamageDone | ValidSource$ Card.Self | ValidTarget$ Player | CombatDamage$ True | Execute$ TrigRenown | TriggerZones$ Battlefield | TriggerDescription$ Renown {n_str}"
508 );
509 if let Some(mut trig) = parse_trigger(&raw, next_id) {
510 trig.execute = "TrigRenown".to_string();
511 self.add_trigger(trig);
512 }
513 self.svars
514 .entry("TrigRenown".to_string())
515 .or_insert_with(|| {
516 format!("DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ {n_str} | Renown$ True")
517 });
518 }
519 }
520
521 if kw == "Flanking" {
522 let raw = "Mode$ AttackerBlockedByCreature | ValidBlocked$ Card.Self | ValidCard$ Creature.withoutFlanking | Execute$ TrigFlanking | TriggerZones$ Battlefield | TriggerDescription$ Flanking";
523 if let Some(mut trig) = parse_trigger(raw, next_id) {
524 trig.execute = "TrigFlanking".to_string();
525 self.add_trigger(trig);
526 }
527 self.svars
528 .entry("TrigFlanking".to_string())
529 .or_insert_with(|| {
530 "DB$ Pump | Defined$ TriggeredBlocker | NumAtt$ -1 | NumDef$ -1".to_string()
531 });
532 }
533
534 if kw == "Extort" {
535 let raw = "Mode$ SpellCast | ValidActivatingPlayer$ You | Execute$ TrigExtort | TriggerZones$ Battlefield | TriggerDescription$ Extort";
536 if let Some(mut trig) = parse_trigger(raw, next_id) {
537 trig.execute = "TrigExtort".to_string();
538 trig.optional = true;
539 self.add_trigger(trig);
540 }
541 self.svars.entry("TrigExtort".to_string()).or_insert_with(|| {
542 "DB$ LoseLife | Defined$ Player.Opponent | LifeAmount$ 1 | SubAbility$ ExtortGain"
543 .to_string()
544 });
545 self.svars
546 .entry("ExtortGain".to_string())
547 .or_insert_with(|| "DB$ GainLife | Defined$ You | LifeAmount$ 1".to_string());
548 }
549 }
550
551 fn generate_keyword_trigger_zone(&mut self, kw: &str, next_id: &mut u32) {
552 self.generate_keyword_trigger_zone_graveyard(kw, next_id);
553 self.generate_keyword_trigger_zone_battlefield(kw, next_id);
554 }
555
556 fn generate_keyword_trigger_zone_graveyard(&mut self, kw: &str, next_id: &mut u32) {
557 if kw == "Undying" {
558 let raw = "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self+counters_EQ0_P1P1 | TriggerZones$ Battlefield | Execute$ TrigUndying | TriggerDescription$ Undying";
559 if let Some(mut trig) = parse_trigger(raw, next_id) {
560 trig.execute = "TrigUndying".to_string();
561 self.add_trigger(trig);
562 }
563 self.svars.entry("TrigUndying".to_string()).or_insert_with(|| {
564 "DB$ ChangeZone | Defined$ TriggeredNewCardLKICopy | Origin$ Graveyard | Destination$ Battlefield | WithCountersType$ P1P1".to_string()
565 });
566 }
567
568 if kw == "Persist" {
569 let raw = "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self+counters_EQ0_M1M1 | TriggerZones$ Battlefield | Execute$ TrigPersist | TriggerDescription$ Persist";
570 if let Some(mut trig) = parse_trigger(raw, next_id) {
571 trig.execute = "TrigPersist".to_string();
572 self.add_trigger(trig);
573 }
574 self.svars.entry("TrigPersist".to_string()).or_insert_with(|| {
575 "DB$ ChangeZone | Defined$ TriggeredNewCardLKICopy | Origin$ Graveyard | Destination$ Battlefield | WithCountersType$ M1M1".to_string()
576 });
577 }
578
579 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Afterlife") {
580 if n_str.parse::<i32>().is_ok() {
581 let raw = format!(
582 "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self | TriggerZones$ Battlefield | Execute$ TrigAfterlife | TriggerDescription$ Afterlife {n_str}"
583 );
584 if let Some(mut trig) = parse_trigger(&raw, next_id) {
585 trig.execute = "TrigAfterlife".to_string();
586 self.add_trigger(trig);
587 }
588 self.svars
589 .entry("TrigAfterlife".to_string())
590 .or_insert_with(|| {
591 format!(
592 "DB$ Token | TokenAmount$ {n_str} | TokenScript$ wb_1_1_spirit_flying"
593 )
594 });
595 }
596 }
597
598 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Modular") {
599 if let Ok(n) = n_str.parse::<i32>() {
600 self.etb_counters_p1p1 += n;
601
602 let raw = format!(
603 "Mode$ ChangesZone | Origin$ Battlefield | Destination$ Graveyard | ValidCard$ Card.Self | TriggerZones$ Battlefield | Execute$ TrigModular | TriggerDescription$ Modular {n_str}"
604 );
605 if let Some(mut trig) = parse_trigger(&raw, next_id) {
606 trig.execute = "TrigModular".to_string();
607 trig.optional = true;
608 self.add_trigger(trig);
609 }
610 self.svars
611 .entry("TrigModular".to_string())
612 .or_insert_with(|| "SP$ Charm | Choices$ ModularMove".to_string());
613 self.svars
614 .entry("ModularMove".to_string())
615 .or_insert_with(|| {
616 format!("DB$ PutCounter | Defined$ Targeted | CounterType$ P1P1 | CounterNum$ {n_str} | Modular$ true | ValidTgts$ Creature.Artifact | SpellDescription$ Put +1/+1 counter(s) on target artifact creature")
617 });
618 }
619 }
620 }
621
622 fn generate_keyword_trigger_zone_battlefield(&mut self, kw: &str, next_id: &mut u32) {
623 if kw == "Exploit" {
624 let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigExploit | TriggerDescription$ Exploit";
625 if let Some(mut trig) = parse_trigger(raw, next_id) {
626 trig.execute = "TrigExploit".to_string();
627 self.add_trigger(trig);
628 }
629 self.svars
630 .entry("TrigExploit".to_string())
631 .or_insert_with(|| {
632 "DB$ Sacrifice | SacValid$ Creature | Optional$ True | Exploit$ True"
633 .to_string()
634 });
635 }
636
637 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Fabricate") {
638 if n_str.parse::<i32>().is_ok() {
639 let raw = format!(
640 "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigFabricate | Secondary$ True | TriggerDescription$ Fabricate {n_str}"
641 );
642 if let Some(mut trig) = parse_trigger(&raw, next_id) {
643 trig.execute = "TrigFabricate".to_string();
644 self.add_trigger(trig);
645 }
646 self.svars
647 .entry("TrigFabricate".to_string())
648 .or_insert_with(|| {
649 format!(
650 "DB$ Token | TokenAmount$ {n_str} | TokenScript$ c_1_1_a_servo \
651 | UnlessCost$ AddCounter<{n_str}/P1P1> | UnlessPayer$ You \
652 | SpellDescription$ Fabricate {n_str}"
653 )
654 });
655 }
656 }
657
658 if kw == "Living Weapon" {
659 let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Secondary$ True | TriggerDescription$ Living Weapon";
660 if let Some(mut trig) = parse_trigger(raw, next_id) {
661 trig.execute = "TrigLivingWeapon".to_string();
662 self.add_trigger(trig);
663 }
664 self.svars
665 .entry("TrigLivingWeapon".to_string())
666 .or_insert_with(|| {
667 "DB$ Token | TokenScript$ b_0_0_phyrexian_germ | TokenOwner$ You | RememberTokens$ True | SubAbility$ DBLivingWeaponAttach".to_string()
668 });
669 self.svars
670 .entry("DBLivingWeaponAttach".to_string())
671 .or_insert_with(|| {
672 "DB$ Attach | Defined$ Remembered | SubAbility$ DBLivingWeaponCleanup"
673 .to_string()
674 });
675 self.svars
676 .entry("DBLivingWeaponCleanup".to_string())
677 .or_insert_with(|| "DB$ Cleanup | ClearRemembered$ True".to_string());
678 }
679
680 if let Some(n_str) = crate::keyword::extract_keyword_cost_str(kw, "Bloodthirst") {
681 if n_str.parse::<i32>().is_ok() {
682 let raw = format!(
683 "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigBloodthirst | TriggerDescription$ Bloodthirst {n_str}"
684 );
685 if let Some(mut trig) = parse_trigger(&raw, next_id) {
686 trig.execute = "TrigBloodthirst".to_string();
687 self.add_trigger(trig);
688 }
689 self.svars
690 .entry("TrigBloodthirst".to_string())
691 .or_insert_with(|| {
692 format!("DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ {n_str} | Bloodthirst$ True")
693 });
694 }
695 }
696
697 if kw == "Riot" {
698 let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigRiot | TriggerDescription$ Riot";
699 if let Some(mut trig) = parse_trigger(raw, next_id) {
700 trig.execute = "TrigRiot".to_string();
701 self.add_trigger(trig);
702 }
703 self.svars
704 .entry("TrigRiot".to_string())
705 .or_insert_with(|| "SP$ Charm | Choices$ RiotCounter,RiotHaste".to_string());
706 self.svars
707 .entry("RiotCounter".to_string())
708 .or_insert_with(|| {
709 "DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ 1 | SpellDescription$ Put a +1/+1 counter on this creature".to_string()
710 });
711 self.svars
712 .entry("RiotHaste".to_string())
713 .or_insert_with(|| {
714 "DB$ Pump | Defined$ Self | KW$ Haste | SpellDescription$ This creature gains haste".to_string()
715 });
716 }
717
718 if kw == "Unleash" {
719 let raw = "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Execute$ TrigUnleash | TriggerDescription$ Unleash";
720 if let Some(mut trig) = parse_trigger(raw, next_id) {
721 trig.execute = "TrigUnleash".to_string();
722 self.add_trigger(trig);
723 }
724 self.svars
725 .entry("TrigUnleash".to_string())
726 .or_insert_with(|| {
727 "DB$ PutCounter | Defined$ Self | CounterType$ P1P1 | CounterNum$ 1".to_string()
728 });
729 }
730 }
731
732 pub(crate) fn generate_keyword_chapter_triggers(&mut self) {
733 if !self.has_subtype("Saga") {
734 return;
735 }
736
737 let mut next_id = self.triggers.len() as u32;
738 for kw in self.keywords.as_string_list() {
739 if !kw.starts_with("Chapter") {
740 continue;
741 }
742 let Some((count, svars)) = kw
743 .strip_prefix("Chapter:")
744 .and_then(|value| value.split_once(':'))
745 else {
746 panic!("invalid Chapter keyword: {kw}");
747 };
748 let count = count
749 .parse::<usize>()
750 .unwrap_or_else(|_| panic!("invalid Chapter count: {count}"));
751 let svars: Vec<&str> = svars.split(',').collect();
752 assert!(
753 !svars.iter().any(|svar| svar.is_empty()),
754 "Chapter ability list must not contain empty SVars"
755 );
756 assert_eq!(svars.len(), count, "Saga max differ from Ability amount");
757
758 let mut groups: Vec<(String, Vec<usize>)> = Vec::new();
759 for (chapter, svar) in svars.iter().enumerate() {
760 let chapter = chapter + 1;
761 if let Some((_, chapters)) = groups
762 .iter_mut()
763 .find(|(existing_svar, _)| existing_svar == svar)
764 {
765 chapters.push(chapter);
766 } else {
767 groups.push(((*svar).to_string(), vec![chapter]));
768 }
769 }
770
771 for (svar, chapters) in groups {
772 let description = self
773 .get_s_var(&svar)
774 .and_then(|raw| {
775 raw.split('|').find_map(|param| {
776 param
777 .trim()
778 .strip_prefix("SpellDescription$")
779 .map(str::trim)
780 })
781 })
782 .map(str::to_string)
783 .unwrap_or_default();
784 let grouped_chapters = chapters
785 .iter()
786 .map(|chapter| roman_chapter(*chapter))
787 .collect::<Vec<_>>()
788 .join(", ");
789
790 for (index, chapter) in chapters.iter().enumerate() {
791 let mut trigger = format!(
792 "Mode$ CounterAdded | ValidCard$ Card.Self | TriggerZones$ Battlefield | Chapter$ {chapter} | CounterType$ LORE | CounterAmount$ EQ{chapter} | Execute$ {svar}"
793 );
794 if index > 0 {
795 trigger.push_str(" | Secondary$ True");
796 }
797 trigger.push_str(&format!(
798 " | TriggerDescription$ {grouped_chapters} — {description}"
799 ));
800 let Some(trigger) = parse_trigger(&trigger, &mut next_id) else {
801 panic!("invalid Chapter trigger");
802 };
803 self.add_trigger(trigger);
804 }
805 }
806 }
807 }
808
809 fn generate_keyword_trigger_misc(&mut self, kw: &str, next_id: &mut u32) {
810 if kw == "Suspend" || kw.starts_with("Suspend:") {
811 let upkeep = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Exile | IsPresent$ Card.Self+suspended | PresentZone$ Exile | Secondary$ True | Execute$ TrigSuspendRemove | TriggerDescription$ At the beginning of your upkeep, if this card is suspended, remove a time counter from it.";
812 if let Some(trigger) = parse_trigger(upkeep, next_id) {
813 self.add_trigger(trigger);
814 }
815 self.svars
816 .entry("TrigSuspendRemove".to_string())
817 .or_insert_with(|| {
818 "DB$ RemoveCounter | Defined$ Self | CounterType$ TIME | CounterNum$ 1"
819 .to_string()
820 });
821 let play = "Mode$ CounterRemoved | TriggerZones$ Exile | ValidCard$ Card.Self | CounterType$ TIME | NewCounterAmount$ 0 | Secondary$ True | Execute$ TrigSuspendPlay | TriggerDescription$ When the last time counter is removed from this card, if it's exiled, you may play it without paying its mana cost if able.";
822 if let Some(trigger) = parse_trigger(play, next_id) {
823 self.add_trigger(trigger);
824 }
825 let permanent = self.is_permanent();
826 self.svars.entry("TrigSuspendPlay".to_string()).or_insert_with(|| {
827 if permanent {
828 "DB$ Play | Defined$ Self | WithoutManaCost$ True | Optional$ True | ConditionPresent$ Card.Self | ConditionPresentZone$ Exile | RememberPlayed$ True | SubAbility$ DBSuspendHaste".to_string()
829 } else {
830 "DB$ Play | Defined$ Self | WithoutManaCost$ True | Optional$ True | ConditionPresent$ Card.Self | ConditionPresentZone$ Exile".to_string()
831 }
832 });
833 if permanent {
834 self.svars.entry("DBSuspendHaste".to_string()).or_insert_with(|| {
835 "DB$ Pump | Defined$ Remembered | KW$ Haste | PumpZone$ Stack | ConditionDefined$ Remembered | ConditionPresent$ Creature | Duration$ UntilLoseControlOfHost | SubAbility$ DBSuspendCleanup".to_string()
836 });
837 self.svars
838 .entry("DBSuspendCleanup".to_string())
839 .or_insert_with(|| "DB$ Cleanup | ClearRemembered$ True".to_string());
840 }
841 }
842
843 if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Ward") {
844 let raw = "Mode$ BecomesTarget | ValidSource$ SpellAbility.OppCtrl | ValidTarget$ Card.Self | Secondary$ True | TriggerZones$ Battlefield | TriggerDescription$ Ward";
845 if let Some(mut trig) = parse_trigger(raw, next_id) {
846 trig.execute = "TrigWard".to_string();
847 self.add_trigger(trig);
848 }
849 self.svars.entry("TrigWard".to_string()).or_insert_with(|| {
850 format!("DB$ Counter | Defined$ TriggeredSourceSA | UnlessCost$ {cost_str}")
851 });
852 }
853
854 if let Some(rest) = kw.strip_prefix("Cumulative upkeep:") {
855 let cost_spec = rest.split(':').next().unwrap_or(rest);
856 let raw = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield | TriggerDescription$ Cumulative upkeep";
857 if let Some(mut trig) = parse_trigger(raw, next_id) {
858 trig.execute = "TrigCumulativeUpkeep".to_string();
859 self.add_trigger(trig);
860 }
861 self.svars
862 .entry("TrigCumulativeUpkeep".to_string())
863 .or_insert_with(|| {
864 format!("DB$ Sacrifice | SacValid$ Self | CumulativeUpkeep$ {cost_spec}")
865 });
866 }
867
868 if let Some(cost_str) = crate::keyword::extract_keyword_cost_str(kw, "Echo") {
869 let cost_spec = cost_str.split(':').next().unwrap_or(cost_str);
870 let raw = "Mode$ Phase | Phase$ Upkeep | ValidPlayer$ You | TriggerZones$ Battlefield | IsPresent$ Card.Self+cameUnderControlSinceLastUpkeep | Secondary$ True | TriggerDescription$ Echo";
871 if let Some(mut trig) = parse_trigger(raw, next_id) {
872 trig.execute = "TrigEcho".to_string();
873 self.add_trigger(trig);
874 }
875 self.svars
876 .entry("TrigEcho".to_string())
877 .or_insert_with(|| format!("DB$ Sacrifice | SacValid$ Self | Echo$ {cost_spec}"));
878 }
879
880 if let Some(madness_cost) = crate::keyword::extract_keyword_cost_str(kw, "Madness") {
881 let raw = "Mode$ ChangesZone | Origin$ Hand | Destination$ Exile | ValidCard$ Card.Self | Secondary$ True | TriggerZones$ Exile | TriggerDescription$ You may cast this card for its madness cost.";
882 if let Some(mut trig) = parse_trigger(raw, next_id) {
883 trig.execute = "TrigMadnessPlay".to_string();
884 self.add_trigger(trig);
885 }
886 self.svars
887 .entry("TrigMadnessPlay".to_string())
888 .or_insert_with(|| {
889 format!(
890 "DB$ Play | Defined$ Self | ValidSA$ Spell | PlayCost$ {madness_cost} | Optional$ True | RememberPlayed$ True | SubAbility$ MadnessMoveToYard"
891 )
892 });
893 self.svars
894 .entry("MadnessMoveToYard".to_string())
895 .or_insert_with(|| {
896 "DB$ ChangeZone | Defined$ Self | Origin$ Exile | Destination$ Graveyard | TrackDiscarded$ True | ConditionDefined$ Remembered | ConditionPresent$ Card | ConditionCompare$ EQ0 | SubAbility$ MadnessCleanup".to_string()
897 });
898 self.svars
899 .entry("MadnessCleanup".to_string())
900 .or_insert_with(|| "DB$ Cleanup | ClearRemembered$ True".to_string());
901 }
902
903 if let Some(partner_name) = kw.strip_prefix("Partner with:") {
904 let mut partner_name = partner_name.trim().to_string();
905 let raw = format!(
906 "Mode$ ChangesZone | Destination$ Battlefield | ValidCard$ Card.Self | Secondary$ True | TriggerDescription$ Partner with {partner_name}"
907 );
908 if let Some(mut trig) = parse_trigger(&raw, next_id) {
909 trig.execute = "TrigPartnerWith".to_string();
910 self.add_trigger(trig);
911 }
912 partner_name = partner_name.replace(',', ";");
913 self.svars
914 .entry("TrigPartnerWith".to_string())
915 .or_insert_with(|| {
916 format!(
917 "DB$ ChangeZone | ValidTgts$ Player | Origin$ Library | Destination$ Hand | ChangeType$ Card.named{partner_name} | Hidden$ True | Chooser$ Targeted | Optional$ True"
918 )
919 });
920 }
921 }
922}