battler 0.9.1

Pokémon battle engine for Rust.
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
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
use alloc::{
    boxed::Box,
    format,
    vec::Vec,
};

use anyhow::Error;
use battler_data::{
    Fraction,
    HitEffect,
    Id,
    Identifiable,
    MaxMoveData,
    MoveCategory,
    MoveData,
    MoveFlag,
    SecondaryEffectData,
    Type,
    ZMoveData,
};
use hashbrown::{
    HashMap,
    HashSet,
    hash_map::Entry,
};

use crate::{
    battle::{
        EventResult,
        MonHandle,
    },
    effect::fxlang,
    general_error,
};

/// Dynamic data on how a move hit a target.
#[derive(Clone)]
pub struct MoveHitData {
    /// Did the move critical hit?
    pub crit: bool,
    /// Type modifier on the damage calculation.
    pub type_modifier: i8,
    /// Damage dealt by the hit.
    pub damage: u64,
    /// Arbitrary flags that can be set by moves.
    pub flags: HashSet<Id>,
}

impl MoveHitData {
    pub fn new() -> Self {
        Self {
            crit: false,
            type_modifier: 0,
            damage: 0,
            flags: HashSet::default(),
        }
    }
}

/// The current type of [`HitEffect`] being applied on an active [`Move`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MoveHitEffectType {
    PrimaryEffect,
    SecondaryEffect(MonHandle, u8, usize),
}

impl MoveHitEffectType {
    /// The index of the secondary effect, if any.
    pub fn secondary_index(&self) -> Option<(MonHandle, u8, usize)> {
        match self {
            Self::PrimaryEffect => None,
            Self::SecondaryEffect(mon, hit, index) => Some((*mon, *hit, *index)),
        }
    }
}

/// Secondary effect that occurs after a move is used.
#[derive(Clone)]
pub struct SecondaryEffect {
    pub data: SecondaryEffectData,
    pub effect: fxlang::Effect,
}

impl SecondaryEffect {
    pub fn new(data: SecondaryEffectData) -> Self {
        let effect = data.effect.clone().try_into().unwrap_or_default();
        Self { data, effect }
    }
}

/// The source of an upgraded move.
#[derive(Debug, Clone)]
pub enum UpgradedMoveSource {
    ZMove { base_move: Id },
    MaxMove { base_move: Id },
}

impl UpgradedMoveSource {
    /// The base move of the upgraded move.
    pub fn base_move(&self) -> Option<Id> {
        match self {
            Self::ZMove { base_move, .. } => Some(base_move.clone()),
            Self::MaxMove { base_move, .. } => Some(base_move.clone()),
        }
    }
}

fn default_z_move(
    id: &Id,
    category: MoveCategory,
    multihit: bool,
    mut base_power: u32,
) -> Option<ZMoveData> {
    if category == MoveCategory::Status || id == "struggle" {
        return None;
    }

    if multihit {
        base_power *= 3;
    }

    let base_power = if base_power == 0 {
        100
    } else if base_power >= 140 {
        200
    } else if base_power >= 130 {
        195
    } else if base_power >= 120 {
        190
    } else if base_power >= 110 {
        185
    } else if base_power >= 100 {
        180
    } else if base_power >= 90 {
        175
    } else if base_power >= 80 {
        160
    } else if base_power >= 70 {
        140
    } else if base_power >= 60 {
        120
    } else {
        100
    };
    Some(ZMoveData {
        base_power,
        ..Default::default()
    })
}

fn default_max_move(
    id: &Id,
    category: MoveCategory,
    primary_type: Type,
    base_power: u32,
) -> Option<MaxMoveData> {
    if category == MoveCategory::Status || id == "struggle" {
        return None;
    }

    let base_power = if primary_type == Type::Fighting || primary_type == Type::Poison {
        if base_power >= 150 {
            100
        } else if base_power >= 110 {
            95
        } else if base_power >= 75 {
            90
        } else if base_power >= 65 {
            85
        } else if base_power >= 55 {
            80
        } else if base_power >= 45 {
            75
        } else {
            70
        }
    } else {
        if base_power >= 150 {
            150
        } else if base_power >= 110 {
            140
        } else if base_power >= 75 {
            130
        } else if base_power >= 65 {
            120
        } else if base_power >= 55 {
            110
        } else if base_power >= 45 {
            100
        } else {
            90
        }
    };
    Some(MaxMoveData { base_power })
}

/// An individual move, which can be used by a Mon in battle.
///
/// Unlike other move effects, [`Move`]s are mutable across multiple Mons and turns. A move used by
/// one Mon can have different effects than the ame move used by another Mon.
#[derive(Clone)]
pub struct Move {
    id: Id,
    pub data: MoveData,
    pub effect: fxlang::Effect,
    pub condition: fxlang::Effect,

    /// The effective priority of the move.
    pub priority: i8,
    /// The Mon that used the move.
    pub used_by: Option<MonHandle>,
    /// The move was used externally, rather than directly by a Mon through its moveset.
    pub external: bool,
    /// Whether or not this move hit multiple targets.
    pub spread_hit: bool,
    /// Number of hits dealt by the move.
    pub hit: u8,
    /// Total damage dealt by the move.
    pub total_damage: u64,
    /// The original targets the move was determined to affect.
    pub original_targets: Vec<MonHandle>,
    /// All targets with non-zero damage applied.
    pub damaged_targets: Vec<MonHandle>,
    /// Have the primary user effect been applied?
    pub primary_user_effect_applied: bool,
    /// Is the move upgraded?
    pub upgraded: Option<UpgradedMoveSource>,
    /// Ignore all secondary effects?
    pub ignore_all_secondary_effects: bool,
    /// The index of the last move log associated with this move.
    pub last_move_log: Option<usize>,
    /// Was the move failure logged?
    pub fail_reported: bool,
    /// Forced result of any new `TryHit` event.
    pub force_try_hit_result: Option<EventResult>,

    /// Original HPs of all targets before applying move hits.
    pub target_original_hps: HashMap<MonHandle, u16>,

    /// Fxlang effect state.
    pub effect_state: fxlang::EffectState,
    /// Whether or not the move is unlinked from the original data.
    ///
    /// If set to true, fxlang effect programs will be parsed and cached relative to this
    /// individual move instance, rather than relative to the original move data. In other words,
    /// the effects of this move are "unlinked" from the effects of the original move, allowing
    /// this move to specify different callbacks than the original move, even though they share the
    /// same ID.
    pub unlinked: bool,
    /// Secondary effects for each target.
    ///
    /// Secondary effects can be modified by effects on the user and the individual target.
    pub secondary_effects: HashMap<(MonHandle, u8), Vec<SecondaryEffect>>,

    hit_data: HashMap<(MonHandle, u8), MoveHitData>,
}

impl Move {
    fn apply_defaults_to_data(mut data: MoveData, id: &Id) -> MoveData {
        if data.z_move.is_none() && !data.flags.contains(&MoveFlag::Z) {
            data.z_move =
                default_z_move(id, data.category, data.multihit.is_some(), data.base_power);
        }
        if data.max_move.is_none() && !data.flags.contains(&MoveFlag::Max) {
            data.max_move = default_max_move(id, data.category, data.primary_type, data.base_power);
        }
        data
    }

    fn new_internal(id: Id, data: MoveData, unlinked: bool) -> Self {
        let data = Self::apply_defaults_to_data(data, &id);
        let effect = data.effect.clone().try_into().unwrap_or_default();
        let condition = data.condition.clone().try_into().unwrap_or_default();
        Self {
            id,
            data,
            effect,
            condition,
            priority: 0,
            used_by: None,
            external: false,
            spread_hit: false,
            hit: 0,
            total_damage: 0,
            original_targets: Vec::default(),
            damaged_targets: Vec::default(),
            primary_user_effect_applied: false,
            upgraded: None,
            ignore_all_secondary_effects: false,
            last_move_log: None,
            fail_reported: false,
            force_try_hit_result: None,
            target_original_hps: HashMap::default(),
            effect_state: fxlang::EffectState::default(),
            unlinked,
            secondary_effects: HashMap::default(),
            hit_data: HashMap::default(),
        }
    }

    /// Creates a new active move, which can be modified for the use of the move.
    pub fn new(id: Id, data: MoveData) -> Self {
        Self::new_internal(id, data, false)
    }

    /// Creates a new active move, with unlinked effect callbacks.
    pub fn new_unlinked(id: Id, data: MoveData) -> Self {
        Self::new_internal(id, data, true)
    }

    /// Clones an active move for use in battle.
    ///
    /// Only some fields are truly cloned.
    pub fn clone_for_battle(&self) -> Self {
        let mut clone = Self::new(self.id.clone(), self.data.clone());
        clone.total_damage = self.total_damage;
        clone.effect_state = self.effect_state.clone();
        clone
    }

    /// Returns the hit data for the target, if any.
    pub fn hit_data(&self, target: MonHandle) -> Option<&MoveHitData> {
        self.hit_data.get(&(target, self.hit))
    }

    /// Returns the hit data for the target.
    pub fn hit_data_mut(&mut self, target: MonHandle) -> &mut MoveHitData {
        self.hit_data
            .entry((target, self.hit))
            .or_insert(MoveHitData::new())
    }

    /// Total damage dealt by this move towards the target.
    pub fn total_damage(&self, target: MonHandle) -> u64 {
        self.hit_data
            .iter()
            .filter(|((mon, _), _)| *mon == target)
            .map(|(_, hit_data)| hit_data.damage)
            .sum()
    }

    /// Returns a reference to the hit effect.
    pub fn target_hit_effect(&self, hit_effect_type: MoveHitEffectType) -> Option<&HitEffect> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => self.data.hit_effect.as_ref(),
            MoveHitEffectType::SecondaryEffect(target, hit, index) => self
                .secondary_effects
                .get(&(target, hit))?
                .get(index)?
                .data
                .target
                .as_ref(),
        }
    }

    /// Returns a mutable reference to the hit effect.
    pub fn target_hit_effect_mut(
        &mut self,
        hit_effect_type: MoveHitEffectType,
    ) -> Option<&mut HitEffect> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => self.data.hit_effect.as_mut(),
            MoveHitEffectType::SecondaryEffect(target, hit, index) => self
                .secondary_effects
                .get_mut(&(target, hit))?
                .get_mut(index)?
                .data
                .target
                .as_mut(),
        }
    }

    /// Returns a reference to the hit effect on the user.
    pub fn user_hit_effect(&self, hit_effect_type: MoveHitEffectType) -> Option<&HitEffect> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => self.data.user_effect.as_ref(),
            MoveHitEffectType::SecondaryEffect(target, hit, index) => self
                .secondary_effects
                .get(&(target, hit))?
                .get(index)?
                .data
                .user
                .as_ref(),
        }
    }

    /// Returns a mutable reference to the hit effect on the user.
    pub fn user_hit_effect_mut(
        &mut self,
        hit_effect_type: MoveHitEffectType,
    ) -> Option<&mut HitEffect> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => self.data.user_effect.as_mut(),
            MoveHitEffectType::SecondaryEffect(target, hit, index) => self
                .secondary_effects
                .get_mut(&(target, hit))?
                .get_mut(index)?
                .data
                .user
                .as_mut(),
        }
    }

    /// Returns the source effect for the hit effect.
    pub fn hit_effect_source_effect(&self, hit_effect_type: MoveHitEffectType) -> Option<&str> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => None,
            MoveHitEffectType::SecondaryEffect(target, hit, index) => self
                .secondary_effects
                .get(&(target, hit))?
                .get(index)?
                .data
                .source_effect
                .as_ref()
                .map(|s| s.as_str()),
        }
    }

    /// Returns the corresponding fxlang effect for the hit effect.
    pub fn fxlang_effect(&self, hit_effect_type: MoveHitEffectType) -> Option<&fxlang::Effect> {
        match hit_effect_type {
            MoveHitEffectType::PrimaryEffect => Some(&self.effect),
            MoveHitEffectType::SecondaryEffect(target, hit, index) => Some(
                &self
                    .secondary_effects
                    .get(&(target, hit))?
                    .get(index)?
                    .effect,
            ),
        }
    }

    /// Saves secondary effects for the given target.
    ///
    /// Fails if there are already secondary effects for the target.
    ///
    /// Returns a copy of the secondary effects.
    pub fn save_secondary_effects(
        &mut self,
        target: MonHandle,
        secondary_effects: Vec<SecondaryEffect>,
    ) -> Result<(), Error> {
        match self.secondary_effects.entry((target, self.hit)) {
            Entry::Occupied(_) => Err(general_error(format!(
                "target {target} already has secondary effects saved for hit {}",
                self.hit,
            ))),
            Entry::Vacant(entry) => {
                entry.insert(secondary_effects);
                Ok(())
            }
        }
    }

    /// Returns an iterator over the secondary effect chances that should be run for applying the
    /// secondary effect at the given index.
    pub fn secondary_effect_chances<'a>(
        &'a self,
        target: MonHandle,
    ) -> Box<dyn Iterator<Item = (usize, Option<Fraction<u16>>)> + 'a> {
        match self.secondary_effects.get(&(target, self.hit)) {
            Some(secondary_effects) => Box::new(
                secondary_effects
                    .iter()
                    .map(|secondary_effect| secondary_effect.data.chance)
                    .enumerate(),
            ),
            None => Box::new(core::iter::empty::<(usize, Option<Fraction<u16>>)>()),
        }
    }

    /// This move is callable from other moves.
    pub fn callable(&self) -> bool {
        !self.data.flags.contains(&MoveFlag::Max)
    }
}

impl Identifiable for Move {
    fn id(&self) -> &Id {
        &self.id
    }
}