manabrew-engine 0.6.0

Magic: The Gathering rules engine — a Rust port of Forge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Partial parity module for Java `CardFactoryUtil`.

use std::collections::HashSet;

use crate::card::Card;
use crate::parsing::{keys, Params};
use crate::replacement::parse_replacement_effect;
use crate::replacement::ReplacementEffect;
use crate::spellability::SpellAbility;
use crate::staticability::StaticAbility;
use crate::trigger::Trigger;

pub fn ability_cast_face_down(card: &Card, _intrinsic: bool, key: &str) -> SpellAbility {
    SpellAbility::new_simple(Some(card.id), card.controller, &format!("FaceDown:{key}"))
}

pub fn resolve(sa: &SpellAbility, card: &mut Card) {
    if let Some(raw) = sa.ir.add_keywords.as_deref() {
        for kw in raw.split('&').map(str::trim).filter(|s| !s.is_empty()) {
            card.add_intrinsic_keyword(kw);
        }
    }
    if let Some(raw) = sa.ir.add_types.as_deref() {
        for ty in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
            card.add_type(ty);
        }
    }
}

pub fn can_play(sa: &SpellAbility, card: &Card) -> bool {
    sa.source == Some(card.id) && sa.activating_player == card.controller
}

pub fn ability_unlock_room(card: &Card) -> SpellAbility {
    SpellAbility::new_simple(Some(card.id), card.controller, "UnlockRoom")
}

pub fn ability_morph_up(card: &Card, cost_str: &str, mega: bool, _intrinsic: bool) -> SpellAbility {
    SpellAbility::new_simple(
        Some(card.id),
        card.controller,
        &format!("MorphUp:{cost_str}:{mega}"),
    )
}

pub fn ability_disguise_up(card: &Card, cost_str: &str, _intrinsic: bool) -> SpellAbility {
    SpellAbility::new_simple(
        Some(card.id),
        card.controller,
        &format!("DisguiseUp:{cost_str}"),
    )
}

pub fn ability_turn_face_up(card: &Card, key: &str, desc: &str) -> SpellAbility {
    SpellAbility::new_simple(
        Some(card.id),
        card.controller,
        &format!("TurnFaceUp:{key}:{desc}"),
    )
}

pub fn handle_hidden_agenda(_player: crate::ids::PlayerId, _card: &mut Card) -> bool {
    false
}

pub fn extract_operators(expression: &str) -> String {
    expression
        .chars()
        .filter(|c| matches!(c, '+' | '-' | '*' | '/' | '<' | '>' | '=' | '!'))
        .collect()
}

pub fn sort_colors_from_list(list: &[Card]) -> [i32; 5] {
    let mut out = [0; 5];
    for c in list {
        if c.color.has_white() {
            out[0] += 1;
        }
        if c.color.has_blue() {
            out[1] += 1;
        }
        if c.color.has_black() {
            out[2] += 1;
        }
        if c.color.has_red() {
            out[3] += 1;
        }
        if c.color.has_green() {
            out[4] += 1;
        }
    }
    out
}

pub fn shared_keywords(
    keywords: impl IntoIterator<Item = String>,
    restrictions: &[String],
) -> Vec<String> {
    let restrictions_lc: HashSet<String> = restrictions
        .iter()
        .map(|s| s.to_ascii_lowercase())
        .collect();
    keywords
        .into_iter()
        .filter(|kw| {
            if restrictions_lc.is_empty() {
                return true;
            }
            restrictions_lc
                .iter()
                .any(|r| kw.to_ascii_lowercase().contains(r))
        })
        .collect()
}

pub fn add_ability_factory_abilities(card: &mut Card, abilities: &[String]) {
    for raw in abilities {
        let sa =
            crate::spellability::build_spell_ability_from_host_card(card, raw, card.controller);
        card.add_spell_ability(&sa);
    }
}

pub fn setup_keyworded_abilities(card: &mut Card) {
    card.generate_keyword_abilities();
    card.generate_keyword_triggers();
    card.base_ability_count = card.activated_abilities.len();
}

/// Generate Dredge replacement effects from the `Dredge:N` keyword.
///
/// Mirrors Java `CardFactoryUtil` Dredge keyword handling which creates a
/// Draw replacement effect:
/// ```text
/// R$ Event$ Draw | ActiveZones$ Graveyard | ValidPlayer$ You
///   | Secondary$ True | Optional$ True
///   | DredgeAmount$ N
///   | Description$ CARDNAME - Dredge N
/// ```
///
/// We use `DredgeAmount$` as a Rust-specific tag (instead of Java's
/// `CheckSVar$` / overriding ability) to keep the implementation simple.
/// The actual mill + return logic is in `replace_draw::execute`.
pub fn add_dredge_replacement(card: &mut Card) {
    let keywords = card.keywords.as_string_list();
    for keyword in keywords {
        let Some(rest) = keyword.strip_prefix("Dredge:") else {
            continue;
        };
        let Ok(amount) = rest.trim().parse::<usize>() else {
            continue;
        };
        let repl_str = format!(
            "R$ Event$ Draw | ActiveZones$ Graveyard | ValidPlayer$ You \
             | Secondary$ True | Optional$ True \
             | DredgeAmount$ {} \
             | Description$ {} - Dredge {}",
            amount, card.card_name, amount
        );
        if let Some(repl) = parse_replacement_effect(&repl_str) {
            card.add_replacement_effect(repl);
        }
    }
}

/// Java parity: convert `ETBReplacement:*` keywords into intrinsic
/// `Event$ Moved` replacement effects during card construction.
///
/// Mirrors `CardFactoryUtil.createETBReplacement(...)` plus the
/// `keyword.startsWith("ETBReplacement")` branch in Java.
pub fn add_etb_keyword_replacements(card: &mut Card) {
    let keywords = card.keywords.as_string_list();
    for keyword in keywords {
        if !keyword.starts_with("ETBReplacement") {
            continue;
        }
        let splitkw: Vec<&str> = keyword.split(':').collect();
        if splitkw.len() < 3 {
            continue;
        }

        let layer = splitkw[1].trim();
        let svar_name = splitkw[2].trim();
        let optional = splitkw.len() >= 4 && splitkw[3].contains("Optional");
        let zone = if splitkw.len() >= 5 {
            splitkw[4].trim()
        } else {
            ""
        };
        let valid = if splitkw.len() >= 6 {
            splitkw[5].trim()
        } else {
            "Card.Self"
        };

        let Some(svar_text) = card.svars.get(svar_name).cloned() else {
            continue;
        };
        let desc = Params::from_raw(&svar_text)
            .get(keys::SPELL_DESCRIPTION)
            .unwrap_or("Replacement effect")
            .replace('|', "/");

        let mut raw = format!(
            "R$ Event$ Moved | Layer$ {} | ValidCard$ {} | Destination$ Battlefield | ReplacementResult$ Updated | ReplaceWith$ {} | Description$ {}",
            layer, valid, svar_name, desc
        );
        if optional {
            raw.push_str(" | Optional$ True");
        }
        if !zone.is_empty() {
            raw.push_str(" | ActiveZones$ ");
            raw.push_str(zone);
        }

        if let Some(re) = parse_replacement_effect(&raw) {
            card.add_replacement_effect(re);
        }
    }
}

pub fn make_etb_counter(kw: &str, card: &Card, intrinsic: bool) -> Option<ReplacementEffect> {
    let splitkw: Vec<&str> = kw.split(':').collect();
    if splitkw.len() < 3 {
        return None;
    }

    let counter_type = splitkw[1].trim();
    let amount = splitkw[2].trim();
    if counter_type.is_empty() || amount.is_empty() {
        return None;
    }

    let extra_params = splitkw
        .get(3)
        .map(|value| value.trim())
        .filter(|value| !value.is_empty() && *value != "no Condition");
    let desc = splitkw
        .get(4)
        .map(|value| value.trim())
        .filter(|value| !value.is_empty() && *value != "no desc")
        .map(str::to_string)
        .unwrap_or_else(|| {
            format!(
                "CARDNAME enters with {} {} counter on it.",
                amount,
                counter_type.to_ascii_lowercase()
            )
        });

    let ability_text = format!(
        "DB$ PutCounter | Defined$ Self | CounterType$ {counter_type} | ETB$ True | CounterNum$ {amount}"
    );
    let mut ability = crate::spellability::build_spell_ability_from_host_card(
        card,
        &ability_text,
        card.controller,
    );
    ability.set_intrinsic(intrinsic);

    let mut replacement_text = format!(
        "R$ Event$ Moved | ValidCard$ Card.Self | Destination$ Battlefield | Secondary$ True | ReplacementResult$ Updated | Description$ {desc}"
    );
    if let Some(extra) = extra_params {
        replacement_text.push_str(" | ");
        replacement_text.push_str(extra);
    }

    let mut replacement = parse_replacement_effect(&replacement_text)?;
    replacement.base.card_trait_base.set_intrinsic(intrinsic);
    replacement.base.set_overriding_ability(ability);
    Some(replacement)
}

pub fn make_read_ahead(card: &Card, intrinsic: bool) -> Option<ReplacementEffect> {
    let ability_text = "DB$ PutCounter | Defined$ Self | CounterType$ LORE | ETB$ True | UpTo$ True | UpToMin$ 1 | CounterNum$ Count$FinalChapterNr";
    let mut ability = crate::spellability::build_spell_ability_from_host_card(
        card,
        ability_text,
        card.controller,
    );
    ability.set_intrinsic(intrinsic);

    let replacement_text = "R$ Event$ Moved | ValidCard$ Card.Self | Destination$ Battlefield | Secondary$ True | ReplacementResult$ Updated | Description$ Choose a chapter and start with that many lore counters.";
    let mut replacement = parse_replacement_effect(replacement_text)?;
    replacement.base.card_trait_base.set_intrinsic(intrinsic);
    replacement.base.set_overriding_ability(ability);
    Some(replacement)
}

pub fn add_madness_replacement(card: &mut Card) {
    let keywords = card.keywords.as_string_list();
    for keyword in keywords {
        let Some(cost) = keyword.strip_prefix("Madness:") else {
            continue;
        };
        let cost = cost.trim();
        let desc = if cost == "ManaCost" {
            "Madness: If you discard this card, discard it into exile.".to_string()
        } else {
            let display = forge_foundation::ManaCost::parse(cost);
            format!(
                "Madness {}: If you discard this card, discard it into exile.",
                display
            )
        };
        let repl_str = format!(
            "R$ Event$ Moved | ActiveZones$ Hand | ValidCard$ Card.Self | Discard$ True \
             | Secondary$ True | NewDestination$ Exile \
             | Description$ {}",
            desc
        );
        if let Some(repl) = parse_replacement_effect(&repl_str) {
            card.add_replacement_effect(repl);
        }
    }
}

/// Mirrors Java `CardFactoryUtil.aaFlashback()` — registers a replacement effect
/// that exiles the card instead of sending it to the graveyard from the stack.
/// Java uses `ValidStackSa$ Spell.Flashback+castKeyword` but in practice the
/// replacement fires for ANY card with the Flashback keyword leaving the stack,
/// because `castKeyword` matches the keyword's presence, not the cast mode.
pub fn add_flashback_replacement(card: &mut Card) {
    let keywords = card.keywords.as_string_list();
    let has_flashback = keywords.iter().any(|kw| kw.starts_with("Flashback:"));
    if !has_flashback {
        return;
    }
    let cost_display = keywords
        .iter()
        .find_map(|kw| kw.strip_prefix("Flashback:"))
        .map(|c| {
            let mc = forge_foundation::ManaCost::parse(c.trim());
            format!("{}", mc)
        })
        .unwrap_or_default();
    let desc = format!(
        "Flashback {} (You may cast this card from your graveyard for its flashback cost. Then exile it.)",
        cost_display
    );
    let repl_str = format!(
        "R$ Event$ Moved | ValidCard$ Card.Self | Origin$ Stack | ExcludeDestination$ Exile \
         | FlashbackCast$ True | Secondary$ True | NewDestination$ Exile \
         | Description$ {}",
        desc
    );
    if let Some(repl) = parse_replacement_effect(&repl_str) {
        card.add_replacement_effect(repl);
    }
}

pub fn add_harmonize_replacement(card: &mut Card) {
    let keywords = card.keywords.as_string_list();
    let Some(cost) = keywords
        .iter()
        .find_map(|kw| kw.strip_prefix("Harmonize:").map(str::trim))
    else {
        return;
    };
    let cost_display = forge_foundation::ManaCost::parse(cost);
    let desc = format!(
        "Harmonize {} (You may cast this card from your graveyard for its harmonize cost. You may tap a creature you control to reduce that cost by {{X}}, where X is its power. Then exile this spell.)",
        cost_display
    );
    let repl_str = format!(
        "R$ Event$ Moved | ValidCard$ Card.Self | Origin$ Stack | ExcludeDestination$ Exile \
         | HarmonizeCast$ True | Secondary$ True | NewDestination$ Exile \
         | Description$ {}",
        desc
    );
    if let Some(repl) = parse_replacement_effect(&repl_str) {
        card.add_replacement_effect(repl);
    }
}

pub fn add_trigger_ability(card: &mut Card, trig: Trigger) {
    card.add_trigger(trig);
}

pub fn add_replacement_effect(card: &mut Card, re: ReplacementEffect) {
    card.add_replacement_effect(re);
}

pub fn add_spell_ability(card: &mut Card, sa: &SpellAbility) {
    card.add_spell_ability(sa);
}

pub fn add_static_ability(card: &mut Card, st: StaticAbility) {
    card.add_static_ability(st);
}

pub fn setup_siege_abilities(card: &mut Card) {
    card.update_triggers();
}

pub fn setup_adventure_ability(_card: &mut Card) -> Option<ReplacementEffect> {
    None
}

pub fn setup_omen_ability(_card: &mut Card) -> Option<ReplacementEffect> {
    None
}

pub fn run() {
    let _ = extract_operators("X+Y");
}