Skip to main content

manabrew_engine/cost/
cost_part.rs

1//! Shared helpers for Java `CostPart` parity on top of enum-based Rust cost parts.
2
3use std::cmp::Ordering;
4
5use crate::card::CounterType;
6use crate::cost::CostPart;
7use crate::game::GameState;
8use crate::ids::{CardId, PlayerId};
9
10/// Mirrors Java's `CostPart.payCostFromSource()`.
11pub fn pay_cost_from_source(part: &CostPart) -> bool {
12    match part {
13        CostPart::Sacrifice { type_filter, .. }
14        | CostPart::Discard { type_filter, .. }
15        | CostPart::Exile { type_filter, .. }
16        | CostPart::Return { type_filter, .. }
17        | CostPart::TapType { type_filter, .. }
18        | CostPart::UntapType { type_filter, .. }
19        | CostPart::GainControl { type_filter, .. }
20        | CostPart::RemoveAnyCounter { type_filter, .. }
21        | CostPart::ExiledMoveToGrave { type_filter, .. }
22        | CostPart::ExileFromStack { type_filter, .. }
23        | CostPart::PutCardToLib { type_filter, .. }
24        | CostPart::Enlist { type_filter, .. }
25        | CostPart::Behold { type_filter, .. }
26        | CostPart::ExileCtrlOrGrave { type_filter, .. }
27        | CostPart::Unattach { type_filter, .. } => {
28            type_filter == "CARDNAME" || type_filter == "NICKNAME"
29        }
30        _ => false,
31    }
32}
33
34/// Mirrors Java's `CostPart.convertAmount()`. Returns the raw amount slot
35/// without resolving — callers that need an `i32` should pair this with
36/// [`AmountSpec::resolve`].
37pub fn convert_amount(part: &CostPart) -> Option<&crate::cost::AmountSpec> {
38    match part {
39        CostPart::PayLife(v)
40        | CostPart::PayEnergy(v)
41        | CostPart::PayShards(v)
42        | CostPart::DamageYou(v)
43        | CostPart::Draw(v)
44        | CostPart::Mill(v)
45        | CostPart::GainLife(v)
46        | CostPart::CollectEvidence(v)
47        | CostPart::ChooseColor(v)
48        | CostPart::ChooseCreatureType(v)
49        | CostPart::FlipCoin(v)
50        | CostPart::Blight(v) => Some(v),
51        CostPart::SubCounter { amount, .. }
52        | CostPart::AddCounter { amount, .. }
53        | CostPart::Sacrifice { amount, .. }
54        | CostPart::Discard { amount, .. }
55        | CostPart::Exile { amount, .. }
56        | CostPart::ExileFromAnyGrave { amount, .. }
57        | CostPart::ExileFromSameGrave { amount, .. }
58        | CostPart::Return { amount, .. }
59        | CostPart::TapType { amount, .. }
60        | CostPart::UntapType { amount, .. }
61        | CostPart::GainControl { amount, .. }
62        | CostPart::RemoveAnyCounter { amount, .. }
63        | CostPart::ExiledMoveToGrave { amount, .. }
64        | CostPart::AddMana { amount, .. }
65        | CostPart::ExileFromStack { amount, .. }
66        | CostPart::PutCardToLib { amount, .. }
67        | CostPart::Enlist { amount, .. }
68        | CostPart::Behold { amount, .. }
69        | CostPart::ExileCtrlOrGrave { amount, .. } => Some(amount),
70        CostPart::Waterbend { amount } => Some(amount),
71        CostPart::Reveal { amount, .. } => Some(amount),
72        CostPart::Exert { amount, .. } => Some(amount),
73        CostPart::RollDice { amount, .. } => Some(amount),
74        _ => None,
75    }
76}
77
78/// Mirrors Java's `CostPart.refund(Card source)` dispatch.
79pub fn refund(game: &mut GameState, source: CardId, player: PlayerId, part: &CostPart) {
80    let resolve = |a: &crate::cost::AmountSpec, g: &GameState| a.resolve(g, source, player);
81    match part {
82        CostPart::Tap => crate::cost::cost_tap::refund(game, source),
83        CostPart::Untap => crate::cost::cost_untap::refund(game, source),
84        CostPart::PayLife(amount) => {
85            let n = resolve(amount, game);
86            crate::cost::cost_pay_life::refund(game, player, n);
87        }
88        CostPart::PayEnergy(amount) => {
89            let n = resolve(amount, game);
90            crate::cost::cost_pay_energy::refund(game, player, n);
91        }
92        CostPart::PayShards(amount) => {
93            let n = resolve(amount, game);
94            crate::cost::cost_pay_shards::refund(game, player, n);
95        }
96        CostPart::SubCounter {
97            amount,
98            counter_type,
99            ..
100        } => {
101            let n = resolve(amount, game);
102            crate::cost::cost_remove_counter::refund(game, source, n, counter_type);
103        }
104        CostPart::AddCounter {
105            amount,
106            counter_type,
107        } => {
108            let n = resolve(amount, game);
109            crate::cost::cost_put_counter::refund(game, source, n, counter_type);
110        }
111        CostPart::ChooseColor(_) => crate::cost::cost_choose_color::refund(game, source),
112        _ => {}
113    }
114}
115
116/// Mirrors Java's `CostPart.applyTextChangeEffects(CardTraitBase)`.
117///
118/// The current Rust `CostPart` representation does not store immutable original
119/// type/description fields like Java, so this is currently a no-op parity shim.
120pub fn apply_text_change_effects(_part: &mut CostPart, _game: &GameState, _host: CardId) {}
121
122/// Mirrors Java's `CostPart.paymentOrder()`.
123pub fn payment_order(part: &CostPart) -> i32 {
124    part.payment_order()
125}
126
127/// Mirrors Java's `CostPart.copy()`.
128pub fn copy(part: &CostPart) -> CostPart {
129    part.clone()
130}
131
132/// Mirrors Java's `CostPart.getMaxAmountX(...)`.
133pub fn get_max_amount_x(
134    game: &GameState,
135    ability: &crate::spellability::SpellAbility,
136    player: PlayerId,
137    part: &CostPart,
138    _effect: bool,
139) -> Option<i32> {
140    let source = ability.source?;
141    match part {
142        CostPart::PayEnergy(_) => Some(game.player(player).energy_counters),
143        CostPart::PayShards(_) => Some(game.player(player).mana_shards),
144        CostPart::PayLife(_) => Some(game.player(player).life.max(0)),
145        CostPart::SubCounter {
146            amount,
147            counter_type,
148            ..
149        } => {
150            let current = game.card(source).counter_count(counter_type);
151            Some(current.min(amount.resolve(game, source, player)))
152        }
153        CostPart::Sacrifice { type_filter, .. } => {
154            let (type_filter, different_names) =
155                if let Some(stripped) = strip_with_different_names(type_filter) {
156                    (stripped, true)
157                } else {
158                    (type_filter.clone(), false)
159                };
160            let type_list = if type_filter.contains('X') {
161                game.cards_in_zone(forge_foundation::ZoneType::Battlefield, player)
162                    .iter()
163                    .copied()
164                    .filter(|&cid| {
165                        !crate::staticability::static_ability_cant_sacrifice::cant_sacrifice(
166                            &game.cards,
167                            game.card(cid),
168                            Some(ability),
169                            true,
170                        )
171                    })
172                    .collect()
173            } else {
174                crate::cost::get_sacrifice_targets_for_cost(
175                    game,
176                    player,
177                    &type_filter,
178                    Some(ability),
179                )
180            };
181            if different_names {
182                Some(different_names_count(game, &type_list))
183            } else {
184                Some(type_list.len() as i32)
185            }
186        }
187        CostPart::Discard { type_filter, .. } => {
188            let (type_filter, different_names) =
189                if let Some(stripped) = strip_with_different_names(type_filter) {
190                    (stripped, true)
191                } else {
192                    (type_filter.clone(), false)
193                };
194            let hand_list: Vec<CardId> = game
195                .cards_in_zone(forge_foundation::ZoneType::Hand, player)
196                .iter()
197                .copied()
198                .filter(|&cid| {
199                    type_filter == "Random"
200                        || crate::ability::effects::matches_change_type(
201                            game.card(cid),
202                            &type_filter,
203                            &[],
204                        )
205                })
206                .collect();
207            if different_names {
208                Some(different_names_count(game, &hand_list))
209            } else {
210                Some(hand_list.len() as i32)
211            }
212        }
213        CostPart::Return { type_filter, .. } => {
214            Some(crate::cost::get_sacrifice_targets(game, player, type_filter).len() as i32)
215        }
216        CostPart::TapType { type_filter, .. } => {
217            Some(crate::cost::get_tap_type_targets(game, player, type_filter, source).len() as i32)
218        }
219        CostPart::Reveal {
220            type_filter, from, ..
221        } => {
222            let zone = match from {
223                crate::cost::RevealFrom::Hand
224                | crate::cost::RevealFrom::HandOrBattlefield
225                | crate::cost::RevealFrom::All => forge_foundation::ZoneType::Hand,
226                crate::cost::RevealFrom::Exile => forge_foundation::ZoneType::Exile,
227            };
228            let list: Vec<CardId> = game
229                .cards_in_zone(zone, player)
230                .iter()
231                .copied()
232                .filter(|&cid| {
233                    !(ability.is_spell && cid == source)
234                        && (type_filter == "Card"
235                            || type_filter.is_empty()
236                            || crate::ability::effects::matches_change_type(
237                                game.card(cid),
238                                type_filter,
239                                &[],
240                            ))
241                })
242                .collect();
243            Some(list.len() as i32)
244        }
245        CostPart::Exile {
246            type_filter, from, ..
247        } => Some(crate::cost::get_zone_targets(game, player, *from, type_filter).len() as i32),
248        _ => None,
249    }
250}
251
252fn strip_with_different_names(type_filter: &str) -> Option<String> {
253    type_filter
254        .contains("+WithDifferentNames")
255        .then(|| type_filter.replace("+WithDifferentNames", ""))
256}
257
258fn different_names_count(game: &GameState, cards: &[CardId]) -> i32 {
259    cards
260        .iter()
261        .map(|&cid| game.card(cid).card_name.as_str())
262        .collect::<std::collections::BTreeSet<_>>()
263        .len() as i32
264}
265
266/// Mirrors Java's `CostPart.getAbilityAmount(SpellAbility)`.
267pub fn get_ability_amount(
268    game: &GameState,
269    source: CardId,
270    player: PlayerId,
271    part: &CostPart,
272) -> i32 {
273    convert_amount(part)
274        .map(|spec| spec.resolve(game, source, player))
275        .unwrap_or(0)
276}
277
278/// Mirrors Java's `CostPart.isReusable()`.
279pub fn is_reusable(part: &CostPart) -> bool {
280    match part {
281        CostPart::Tap
282        | CostPart::Untap
283        | CostPart::Mana { .. }
284        | CostPart::Reveal { .. }
285        | CostPart::TapType { .. }
286        | CostPart::UntapType { .. }
287        | CostPart::Unattach { .. }
288        | CostPart::FlipCoin(_)
289        | CostPart::RollDice { .. } => true,
290        CostPart::AddCounter { counter_type, .. } => *counter_type != CounterType::M1M1,
291        _ => false,
292    }
293}
294
295/// Mirrors Java's `CostPart.isRenewable()`.
296pub fn is_renewable(part: &CostPart) -> bool {
297    matches!(
298        part,
299        CostPart::Tap
300            | CostPart::Untap
301            | CostPart::Reveal { .. }
302            | CostPart::TapType { .. }
303            | CostPart::UntapType { .. }
304    )
305}
306
307/// Mirrors Java's `CostPart.isUndoable()`.
308pub fn is_undoable(part: &CostPart) -> bool {
309    matches!(
310        part,
311        CostPart::Tap | CostPart::Untap | CostPart::ChooseColor(_) | CostPart::Mana { .. }
312    )
313}
314
315/// Mirrors Java's `CostPart.getTypeDescription()`.
316pub fn get_type_description(part: &CostPart) -> Option<&str> {
317    match part {
318        CostPart::Unattach {
319            description: Some(d),
320            ..
321        } => Some(d.as_str()),
322        _ => None,
323    }
324}
325
326/// Mirrors Java's `CostPart.getDescriptiveType()`.
327pub fn get_descriptive_type(part: &CostPart) -> String {
328    if let Some(desc) = get_type_description(part) {
329        return desc.to_string();
330    }
331
332    match part {
333        CostPart::Sacrifice { type_filter, .. }
334        | CostPart::Discard { type_filter, .. }
335        | CostPart::Exile { type_filter, .. }
336        | CostPart::Return { type_filter, .. }
337        | CostPart::TapType { type_filter, .. }
338        | CostPart::UntapType { type_filter, .. }
339        | CostPart::GainControl { type_filter, .. }
340        | CostPart::RemoveAnyCounter { type_filter, .. }
341        | CostPart::ExiledMoveToGrave { type_filter, .. }
342        | CostPart::ExileFromStack { type_filter, .. }
343        | CostPart::PutCardToLib { type_filter, .. }
344        | CostPart::Enlist { type_filter, .. }
345        | CostPart::Behold { type_filter, .. }
346        | CostPart::ExileCtrlOrGrave { type_filter, .. }
347        | CostPart::ExileFromAnyGrave { type_filter, .. }
348        | CostPart::ExileFromSameGrave { type_filter, .. }
349        | CostPart::Reveal { type_filter, .. }
350        | CostPart::Exert { type_filter, .. }
351        | CostPart::Unattach { type_filter, .. } => type_filter.to_lowercase(),
352        _ => format!("{part:?}").to_lowercase(),
353    }
354}
355
356pub fn is_core_type(s: &str) -> bool {
357    matches!(
358        s,
359        "Creature"
360            | "Artifact"
361            | "Enchantment"
362            | "Land"
363            | "Planeswalker"
364            | "Instant"
365            | "Sorcery"
366            | "Tribal"
367            | "Battle"
368            | "Kindred"
369    )
370}
371
372impl PartialEq for CostPart {
373    fn eq(&self, other: &Self) -> bool {
374        payment_order(self) == payment_order(other)
375    }
376}
377
378impl Eq for CostPart {}
379
380impl PartialOrd for CostPart {
381    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
382        Some(self.cmp(other))
383    }
384}
385
386impl Ord for CostPart {
387    fn cmp(&self, other: &Self) -> Ordering {
388        payment_order(self).cmp(&payment_order(other))
389    }
390}