First chunk of battling is now fully working, along with integration tests! 🎉
continuous-integration/drone/push Build is failing Details

This commit is contained in:
Deukhoofd 2022-06-17 19:53:33 +02:00
parent 59cc150643
commit b6ddd1ee13
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F
34 changed files with 1934 additions and 1293 deletions

View File

@ -13,7 +13,7 @@ path = "src/lib.rs"
[features] [features]
c_interface = [] c_interface = []
serde = ["dep:serde", "dep:serde_json"] serde = ["dep:serde"]
default = ["serde"] default = ["serde"]
[profile.dev] [profile.dev]
@ -52,9 +52,11 @@ hashbrown = "0.12.1"
indexmap = "1.8.2" indexmap = "1.8.2"
parking_lot = "0.12.1" parking_lot = "0.12.1"
serde = { version = "1.0.137", optional = true, features = ["derive"] } serde = { version = "1.0.137", optional = true, features = ["derive"] }
serde_json = { version = "1.0.81", optional = true }
[dev-dependencies] [dev-dependencies]
csv = "1.1.6" csv = "1.1.6"
project-root = "0.2.2" project-root = "0.2.2"
syn = "1.0.96" datatest = "0.7.1"
serde_yaml = "0.8.24"
serde_json = "1.0.81"
serde_plain = "1.0.0"

View File

@ -204,6 +204,20 @@ pub struct ItemChoice<'user, 'library> {
choice_data: Box<CommonChoiceData<'user, 'library>>, choice_data: Box<CommonChoiceData<'user, 'library>>,
} }
impl<'user, 'library> ItemChoice<'user, 'library> {
pub fn new(user: Arc<RwLock<Pokemon<'user, 'library>>>) -> Self {
Self {
choice_data: Box::new(CommonChoiceData {
user,
speed: 0,
random_value: 0,
has_failed: false,
script_source_data: Default::default(),
}),
}
}
}
impl<'user, 'library> ScriptSource<'user> for ItemChoice<'user, 'library> { impl<'user, 'library> ScriptSource<'user> for ItemChoice<'user, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
0 0
@ -225,6 +239,20 @@ pub struct SwitchChoice<'user, 'library> {
choice_data: Box<CommonChoiceData<'user, 'library>>, choice_data: Box<CommonChoiceData<'user, 'library>>,
} }
impl<'user, 'library> SwitchChoice<'user, 'library> {
pub fn new(user: Arc<RwLock<Pokemon<'user, 'library>>>) -> Self {
Self {
choice_data: Box::new(CommonChoiceData {
user,
speed: 0,
random_value: 0,
has_failed: false,
script_source_data: Default::default(),
}),
}
}
}
impl<'user, 'library> ScriptSource<'user> for SwitchChoice<'user, 'library> { impl<'user, 'library> ScriptSource<'user> for SwitchChoice<'user, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
0 0
@ -246,6 +274,20 @@ pub struct FleeChoice<'user, 'library> {
choice_data: Box<CommonChoiceData<'user, 'library>>, choice_data: Box<CommonChoiceData<'user, 'library>>,
} }
impl<'user, 'library> FleeChoice<'user, 'library> {
pub fn new(user: Arc<RwLock<Pokemon<'user, 'library>>>) -> Self {
Self {
choice_data: Box::new(CommonChoiceData {
user,
speed: 0,
random_value: 0,
has_failed: false,
script_source_data: Default::default(),
}),
}
}
}
impl<'user, 'library> ScriptSource<'user> for FleeChoice<'user, 'library> { impl<'user, 'library> ScriptSource<'user> for FleeChoice<'user, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
0 0
@ -267,6 +309,20 @@ pub struct PassChoice<'user, 'library> {
choice_data: Box<CommonChoiceData<'user, 'library>>, choice_data: Box<CommonChoiceData<'user, 'library>>,
} }
impl<'user, 'library> PassChoice<'user, 'library> {
pub fn new(user: Arc<RwLock<Pokemon<'user, 'library>>>) -> Self {
Self {
choice_data: Box::new(CommonChoiceData {
user,
speed: 0,
random_value: 0,
has_failed: false,
script_source_data: Default::default(),
}),
}
}
}
impl<'user, 'library> ScriptSource<'user> for PassChoice<'user, 'library> { impl<'user, 'library> ScriptSource<'user> for PassChoice<'user, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
0 0

View File

@ -43,12 +43,12 @@ pub enum Event<'own, 'battle, 'library> {
}, },
SpeciesChange { SpeciesChange {
pokemon: &'own Pokemon<'battle, 'library>, pokemon: &'own Pokemon<'battle, 'library>,
species: &'own Species<'library>, species: &'own Species,
form: &'own Form<'library>, form: &'own Form,
}, },
FormChange { FormChange {
pokemon: &'own Pokemon<'battle, 'library>, pokemon: &'own Pokemon<'battle, 'library>,
form: &'own Form<'library>, form: &'own Form,
}, },
Damage { Damage {
pokemon: &'own Pokemon<'battle, 'library>, pokemon: &'own Pokemon<'battle, 'library>,

View File

@ -83,7 +83,11 @@ impl<'own, 'library> Battle<'own, 'library> {
return Ok(()); return Ok(());
} }
match choice_guard.deref() { match choice_guard.deref() {
TurnChoice::Move(..) => self.execute_move_choice(&choice)?, TurnChoice::Move(..) => {
drop(user);
drop(choice_guard);
self.execute_move_choice(&choice)?
}
TurnChoice::Item(_) => {} TurnChoice::Item(_) => {}
TurnChoice::Switch(_) => {} TurnChoice::Switch(_) => {}
TurnChoice::Flee(_) => {} TurnChoice::Flee(_) => {}
@ -100,13 +104,12 @@ impl<'own, 'library> Battle<'own, 'library> {
let choice = write_guard.get_move_turn_data(); let choice = write_guard.get_move_turn_data();
let used_move = choice.used_move(); let used_move = choice.used_move();
let move_data_lock = used_move.read(); let move_data_lock = used_move.read();
let mut move_data = move_data_lock.move_data(); let move_data = move_data_lock.move_data();
let mut move_name = move_data.name().clone(); let mut move_name = move_data.name().clone();
script_hook!(change_move, choice, choice, &mut move_name); script_hook!(change_move, choice, choice, &mut move_name);
if move_name != *move_data.name() { let move_data = self.library().static_data().moves().get(&move_name).unwrap();
move_data = self.library().static_data().moves().get(&move_name).unwrap(); drop(move_data_lock);
// FIXME: also change the script on the choice. // FIXME: also change the script on the choice if changed;
}
let target_type = move_data.target(); let target_type = move_data.target();
let targets = resolve_targets(choice.target_side(), choice.target_index(), target_type, self); let targets = resolve_targets(choice.target_side(), choice.target_index(), target_type, self);
@ -154,8 +157,8 @@ impl<'own, 'library> Battle<'own, 'library> {
fn handle_move_for_target( fn handle_move_for_target(
&self, &self,
executing_move: &mut ExecutingMove<'_, 'own, '_>, executing_move: &mut ExecutingMove<'_, 'own, 'library>,
target: &Arc<RwLock<Pokemon<'own, '_>>>, target: &Arc<RwLock<Pokemon<'own, 'library>>>,
) -> PkmnResult<()> { ) -> PkmnResult<()> {
{ {
let mut fail = false; let mut fail = false;

View File

@ -40,6 +40,7 @@ pub trait DamageLibrary: std::fmt::Debug {
hit_data: &HitData, hit_data: &HitData,
) -> f32; ) -> f32;
} }
#[derive(Debug)] #[derive(Debug)]
pub struct Gen7DamageLibrary { pub struct Gen7DamageLibrary {
has_randomness: bool, has_randomness: bool,
@ -93,8 +94,14 @@ impl DamageLibrary for Gen7DamageLibrary {
} }
if self.has_randomness { if self.has_randomness {
let battle = executing_move.user().read().get_battle().unwrap().upgrade().unwrap(); let random_percentage = 85
let random_percentage = 85 + battle.read().random().get_between(0, 16); + executing_move
.user()
.read()
.get_battle()
.unwrap()
.random()
.get_between(0, 16);
float_damage = (float_damage * (random_percentage as f32 / 100.0)).floor(); float_damage = (float_damage * (random_percentage as f32 / 100.0)).floor();
} }

View File

@ -10,14 +10,32 @@ use crate::{PkmnResult, StringKey};
#[derive(Debug)] #[derive(Debug)]
pub struct DynamicLibrary { pub struct DynamicLibrary {
static_data: StaticData<'static>, static_data: StaticData,
stat_calculator: BattleStatCalculator, stat_calculator: BattleStatCalculator,
damage_calculator: Box<dyn DamageLibrary>, damage_calculator: Box<dyn DamageLibrary>,
misc_library: Box<dyn MiscLibrary<'static>>, misc_library: Box<dyn MiscLibrary<'static>>,
} }
impl<'library> DynamicLibrary { unsafe impl Sync for DynamicLibrary {}
pub fn static_data(&self) -> &StaticData<'library> {
unsafe impl Send for DynamicLibrary {}
impl DynamicLibrary {
pub fn new(
static_data: StaticData,
stat_calculator: BattleStatCalculator,
damage_calculator: Box<dyn DamageLibrary>,
misc_library: Box<dyn MiscLibrary<'static>>,
) -> Self {
Self {
static_data,
stat_calculator,
damage_calculator,
misc_library,
}
}
pub fn static_data(&self) -> &StaticData {
&self.static_data &self.static_data
} }
pub fn stat_calculator(&self) -> &BattleStatCalculator { pub fn stat_calculator(&self) -> &BattleStatCalculator {

View File

@ -47,14 +47,18 @@ impl<'own, 'library> Battle<'own, 'library> {
number_of_sides: u8, number_of_sides: u8,
pokemon_per_side: u8, pokemon_per_side: u8,
random_seed: Option<u128>, random_seed: Option<u128>,
) -> Arc<RwLock<Self>> { ) -> Self {
let random = if let Some(seed) = random_seed { let random = if let Some(seed) = random_seed {
BattleRandom::new_with_seed(seed) BattleRandom::new_with_seed(seed)
} else { } else {
BattleRandom::default() BattleRandom::default()
}; };
let sides = Vec::with_capacity(number_of_sides as usize); let mut sides = Vec::with_capacity(number_of_sides as usize);
let battle = Arc::new(RwLock::new(Self { for i in 0..number_of_sides {
sides.push(BattleSide::new(i, pokemon_per_side));
}
let mut battle = Self {
library, library,
parties, parties,
can_flee, can_flee,
@ -71,11 +75,13 @@ impl<'own, 'library> Battle<'own, 'library> {
volatile_scripts: Default::default(), volatile_scripts: Default::default(),
last_turn_time: chrono::Duration::zero(), last_turn_time: chrono::Duration::zero(),
script_source_data: Default::default(), script_source_data: Default::default(),
})); };
for i in 0..number_of_sides { let ptr: *mut Battle = &mut battle;
battle.write().sides[i as usize] = BattleSide::new(i, Arc::downgrade(&battle), pokemon_per_side); for side in &mut battle.sides {
side.set_battle(ptr);
} }
battle battle
} }

View File

@ -1,12 +1,21 @@
use crate::dynamic_data::models::pokemon::Pokemon;
use crate::dynamic_data::models::pokemon_party::PokemonParty; use crate::dynamic_data::models::pokemon_party::PokemonParty;
use parking_lot::RwLock;
use std::sync::Arc;
#[derive(Debug)] #[derive(Debug)]
pub struct BattleParty<'own, 'library> { pub struct BattleParty<'own, 'library> {
party: &'own PokemonParty<'own, 'library>, party: Arc<PokemonParty<'own, 'library>>,
responsible_indices: Vec<(u8, u8)>, responsible_indices: Vec<(u8, u8)>,
} }
impl<'own, 'library> BattleParty<'own, 'library> { impl<'own, 'library> BattleParty<'own, 'library> {
pub fn new(party: Arc<PokemonParty<'own, 'library>>, responsible_indices: Vec<(u8, u8)>) -> Self {
Self {
party,
responsible_indices,
}
}
pub fn is_responsible_for_index(&self, side: u8, index: u8) -> bool { pub fn is_responsible_for_index(&self, side: u8, index: u8) -> bool {
for responsible_index in &self.responsible_indices { for responsible_index in &self.responsible_indices {
if responsible_index.0 == side && responsible_index.1 == index { if responsible_index.0 == side && responsible_index.1 == index {
@ -18,11 +27,15 @@ impl<'own, 'library> BattleParty<'own, 'library> {
pub fn has_pokemon_not_in_field(&self) -> bool { pub fn has_pokemon_not_in_field(&self) -> bool {
for pokemon in self.party.pokemon().iter().flatten() { for pokemon in self.party.pokemon().iter().flatten() {
let pokemon = pokemon.read().unwrap(); let pokemon = pokemon.read();
if pokemon.is_usable() && !pokemon.is_on_battlefield() { if pokemon.is_usable() && !pokemon.is_on_battlefield() {
return true; return true;
} }
} }
false false
} }
pub fn get_pokemon(&self, index: usize) -> &Option<Arc<RwLock<Pokemon<'own, 'library>>>> {
self.party.at(index)
}
} }

View File

@ -9,8 +9,7 @@ use crate::dynamic_data::script_handling::volatile_scripts::VolatileScripts;
use crate::dynamic_data::script_handling::{ScriptSource, ScriptSourceData, ScriptWrapper}; use crate::dynamic_data::script_handling::{ScriptSource, ScriptSourceData, ScriptWrapper};
use crate::{script_hook, PkmnResult, StringKey}; use crate::{script_hook, PkmnResult, StringKey};
use parking_lot::RwLock; use parking_lot::RwLock;
use std::ops::Deref; use std::sync::Arc;
use std::sync::{Arc, Weak};
#[derive(Debug)] #[derive(Debug)]
pub struct BattleSide<'own, 'library> { pub struct BattleSide<'own, 'library> {
@ -20,7 +19,7 @@ pub struct BattleSide<'own, 'library> {
choices: Vec<Option<Arc<RwLock<TurnChoice<'own, 'library>>>>>, choices: Vec<Option<Arc<RwLock<TurnChoice<'own, 'library>>>>>,
fillable_slots: Vec<bool>, fillable_slots: Vec<bool>,
choices_set: u8, choices_set: u8,
battle: Weak<RwLock<Battle<'own, 'library>>>, battle: *mut Battle<'own, 'library>,
has_fled_battle: bool, has_fled_battle: bool,
volatile_scripts: Arc<RwLock<ScriptSet>>, volatile_scripts: Arc<RwLock<ScriptSet>>,
@ -28,15 +27,15 @@ pub struct BattleSide<'own, 'library> {
} }
impl<'own, 'library> BattleSide<'own, 'library> { impl<'own, 'library> BattleSide<'own, 'library> {
pub fn new(index: u8, battle: Weak<RwLock<Battle<'own, 'library>>>, pokemon_per_side: u8) -> Self { pub fn new(index: u8, pokemon_per_side: u8) -> Self {
let mut pokemon = Vec::with_capacity(pokemon_per_side as usize); let mut pokemon = Vec::with_capacity(pokemon_per_side as usize);
let mut choices = Vec::with_capacity(pokemon_per_side as usize); let mut choices = Vec::with_capacity(pokemon_per_side as usize);
let mut fillable_slots = Vec::with_capacity(pokemon_per_side as usize); let mut fillable_slots = Vec::with_capacity(pokemon_per_side as usize);
for i in 0..pokemon_per_side { for _i in 0..pokemon_per_side {
pokemon[i as usize] = None; pokemon.push(None);
choices[i as usize] = None; choices.push(None);
fillable_slots[i as usize] = true; fillable_slots.push(true);
} }
Self { Self {
@ -46,12 +45,17 @@ impl<'own, 'library> BattleSide<'own, 'library> {
choices, choices,
fillable_slots, fillable_slots,
choices_set: 0, choices_set: 0,
battle, battle: 0 as *mut Battle,
has_fled_battle: false, has_fled_battle: false,
volatile_scripts: Default::default(), volatile_scripts: Default::default(),
script_source_data: Default::default(), script_source_data: Default::default(),
} }
} }
pub(crate) fn set_battle(&mut self, battle: *mut Battle<'own, 'library>) {
self.battle = battle;
}
pub fn index(&self) -> u8 { pub fn index(&self) -> u8 {
self.index self.index
} }
@ -74,8 +78,8 @@ impl<'own, 'library> BattleSide<'own, 'library> {
pub fn choices_set(&self) -> u8 { pub fn choices_set(&self) -> u8 {
self.choices_set self.choices_set
} }
pub fn battle(&self) -> &Weak<RwLock<Battle<'own, 'library>>> { pub fn battle(&self) -> &Battle<'own, 'library> {
&self.battle unsafe { self.battle.as_ref().unwrap() }
} }
pub fn has_fled_battle(&self) -> bool { pub fn has_fled_battle(&self) -> bool {
self.has_fled_battle self.has_fled_battle
@ -94,12 +98,7 @@ impl<'own, 'library> BattleSide<'own, 'library> {
pub fn all_slots_filled(&self) -> bool { pub fn all_slots_filled(&self) -> bool {
for (i, pokemon) in self.pokemon.iter().enumerate() { for (i, pokemon) in self.pokemon.iter().enumerate() {
if (!pokemon.is_none() || !pokemon.as_ref().unwrap().read().is_usable()) if (!pokemon.is_none() || !pokemon.as_ref().unwrap().read().is_usable())
&& self && self.battle().can_slot_be_filled(self.index, i as u8)
.battle
.upgrade()
.unwrap()
.read()
.can_slot_be_filled(self.index, i as u8)
{ {
return false; return false;
} }
@ -140,12 +139,11 @@ impl<'own, 'library> BattleSide<'own, 'library> {
let pokemon = &self.pokemon[index as usize]; let pokemon = &self.pokemon[index as usize];
if let Some(pokemon_mutex) = pokemon { if let Some(pokemon_mutex) = pokemon {
let mut pokemon = pokemon_mutex.write(); let mut pokemon = pokemon_mutex.write();
pokemon.set_battle_data(self.battle.clone(), self.index); pokemon.set_battle_data(self.battle, self.index);
pokemon.set_on_battlefield(true); pokemon.set_on_battlefield(true);
pokemon.set_battle_index(index); pokemon.set_battle_index(index);
let battle = self.battle.upgrade().unwrap(); let battle = self.battle();
let battle = battle.read();
for side in battle.sides() { for side in battle.sides() {
if side.index() == self.index { if side.index() == self.index {
continue; continue;
@ -163,9 +161,7 @@ impl<'own, 'library> BattleSide<'own, 'library> {
}); });
script_hook!(on_switch_in, pokemon, &pokemon); script_hook!(on_switch_in, pokemon, &pokemon);
} else { } else {
let battle = self.battle.upgrade().unwrap(); self.battle().event_hook().trigger(Event::Switch {
let battle = battle.read();
battle.event_hook().trigger(Event::Switch {
side_index: self.index, side_index: self.index,
index, index,
pokemon: None, pokemon: None,
@ -182,15 +178,8 @@ impl<'own, 'library> BattleSide<'own, 'library> {
false false
} }
pub fn mark_slot_as_unfillable(&mut self, pokemon: &Pokemon<'own, 'library>) { pub fn mark_slot_as_unfillable(&mut self, index: u8) {
for (i, slot) in self.pokemon.iter().enumerate() { self.fillable_slots[index as usize] = false;
if let Some(p) = slot {
if p.read().deref() as *const Pokemon == pokemon as *const Pokemon {
self.fillable_slots[i] = false;
return;
}
}
}
} }
pub fn is_slot_unfillable(&self, pokemon: Arc<Pokemon<'own, 'library>>) -> bool { pub fn is_slot_unfillable(&self, pokemon: Arc<Pokemon<'own, 'library>>) -> bool {
@ -223,12 +212,7 @@ impl<'own, 'library> BattleSide<'own, 'library> {
pub fn get_random_creature_index(&self) -> u8 { pub fn get_random_creature_index(&self) -> u8 {
// TODO: Consider adding parameter to only get index for available creatures. // TODO: Consider adding parameter to only get index for available creatures.
self.battle self.battle().random().get_max(self.pokemon_per_side as i32) as u8
.upgrade()
.unwrap()
.read()
.random()
.get_max(self.pokemon_per_side as i32) as u8
} }
pub fn swap_positions(&mut self, a: u8, b: u8) -> bool { pub fn swap_positions(&mut self, a: u8, b: u8) -> bool {
@ -241,12 +225,10 @@ impl<'own, 'library> BattleSide<'own, 'library> {
return false; return false;
} }
let battle = self.battle.upgrade().unwrap();
let battle = battle.read();
// Fetch parties for the two indices. // Fetch parties for the two indices.
let mut party_a = None; let mut party_a = None;
let mut party_b = None; let mut party_b = None;
for party in battle.parties() { for party in self.battle().parties() {
if party.is_responsible_for_index(self.index, a) { if party.is_responsible_for_index(self.index, a) {
party_a = Some(party); party_a = Some(party);
} }
@ -264,7 +246,7 @@ impl<'own, 'library> BattleSide<'own, 'library> {
} }
self.pokemon.swap(a as usize, b as usize); self.pokemon.swap(a as usize, b as usize);
battle.event_hook().trigger(Event::Swap { self.battle().event_hook().trigger(Event::Swap {
side_index: self.index, side_index: self.index,
index_a: a, index_a: a,
index_b: b, index_b: b,
@ -279,18 +261,13 @@ impl<'own, 'library> VolatileScripts<'own> for BattleSide<'own, 'library> {
} }
fn load_volatile_script(&self, key: &StringKey) -> PkmnResult<Option<Box<dyn Script>>> { fn load_volatile_script(&self, key: &StringKey) -> PkmnResult<Option<Box<dyn Script>>> {
self.battle self.battle().library().load_script(crate::ScriptCategory::Side, key)
.upgrade()
.unwrap()
.read()
.library()
.load_script(crate::ScriptCategory::Side, key)
} }
} }
impl<'own, 'library> ScriptSource<'own> for BattleSide<'own, 'library> { impl<'own, 'library> ScriptSource<'own> for BattleSide<'own, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
self.battle.upgrade().unwrap().read().get_script_count() + 1 self.battle().get_script_count() + 1
} }
fn get_script_source_data(&self) -> &RwLock<ScriptSourceData> { fn get_script_source_data(&self) -> &RwLock<ScriptSourceData> {
@ -303,6 +280,6 @@ impl<'own, 'library> ScriptSource<'own> for BattleSide<'own, 'library> {
fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) { fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) {
self.get_own_scripts(scripts); self.get_own_scripts(scripts);
self.battle.upgrade().unwrap().read().collect_scripts(scripts); self.battle().collect_scripts(scripts);
} }
} }

View File

@ -3,7 +3,7 @@ use crate::dynamic_data::event_hooks::event_hook::Event;
use crate::dynamic_data::libraries::dynamic_library::DynamicLibrary; use crate::dynamic_data::libraries::dynamic_library::DynamicLibrary;
use crate::dynamic_data::models::battle::Battle; use crate::dynamic_data::models::battle::Battle;
use crate::dynamic_data::models::damage_source::DamageSource; use crate::dynamic_data::models::damage_source::DamageSource;
use crate::dynamic_data::models::learned_move::LearnedMove; use crate::dynamic_data::models::learned_move::{LearnedMove, MoveLearnMethod};
use crate::dynamic_data::script_handling::script::{Script, ScriptContainer}; use crate::dynamic_data::script_handling::script::{Script, ScriptContainer};
use crate::dynamic_data::script_handling::script_set::ScriptSet; use crate::dynamic_data::script_handling::script_set::ScriptSet;
use crate::dynamic_data::script_handling::volatile_scripts::VolatileScripts; use crate::dynamic_data::script_handling::volatile_scripts::VolatileScripts;
@ -16,7 +16,7 @@ use crate::static_data::species_data::form::Form;
use crate::static_data::species_data::gender::Gender; use crate::static_data::species_data::gender::Gender;
use crate::static_data::species_data::species::Species; use crate::static_data::species_data::species::Species;
use crate::static_data::statistic_set::{ClampedStatisticSet, StatisticSet}; use crate::static_data::statistic_set::{ClampedStatisticSet, StatisticSet};
use crate::static_data::statistics::Statistic; use crate::static_data::DataLibrary;
use crate::utils::random::Random; use crate::utils::random::Random;
use crate::{script_hook, PkmnResult, ScriptCategory, StringKey}; use crate::{script_hook, PkmnResult, ScriptCategory, StringKey};
use parking_lot::RwLock; use parking_lot::RwLock;
@ -24,7 +24,7 @@ use std::sync::{Arc, Weak};
#[derive(Debug)] #[derive(Debug)]
pub struct PokemonBattleData<'pokemon, 'library> { pub struct PokemonBattleData<'pokemon, 'library> {
battle: Weak<RwLock<Battle<'pokemon, 'library>>>, battle: *mut Battle<'pokemon, 'library>,
battle_side_index: u8, battle_side_index: u8,
index: u8, index: u8,
on_battle_field: bool, on_battle_field: bool,
@ -32,9 +32,13 @@ pub struct PokemonBattleData<'pokemon, 'library> {
} }
impl<'pokemon, 'library> PokemonBattleData<'pokemon, 'library> { impl<'pokemon, 'library> PokemonBattleData<'pokemon, 'library> {
pub fn battle(&mut self) -> &mut Weak<RwLock<Battle<'pokemon, 'library>>> { pub fn battle_mut(&mut self) -> Option<&mut Battle<'pokemon, 'library>> {
&mut self.battle unsafe { self.battle.as_mut() }
} }
pub fn battle(&self) -> Option<&Battle<'pokemon, 'library>> {
unsafe { self.battle.as_ref() }
}
pub fn battle_side_index(&self) -> u8 { pub fn battle_side_index(&self) -> u8 {
self.battle_side_index self.battle_side_index
} }
@ -52,11 +56,11 @@ where
'own: 'library, 'own: 'library,
{ {
library: &'own DynamicLibrary, library: &'own DynamicLibrary,
species: &'own Species<'library>, species: &'own Species,
form: &'own Form<'library>, form: &'own Form,
display_species: Option<&'own Species<'library>>, display_species: Option<&'own Species>,
display_form: Option<&'own Form<'library>>, display_form: Option<&'own Form>,
level: LevelInt, level: LevelInt,
experience: u32, experience: u32,
@ -84,7 +88,7 @@ where
battle_data: Option<PokemonBattleData<'own, 'library>>, battle_data: Option<PokemonBattleData<'own, 'library>>,
moves: [Option<LearnedMove<'library>>; MAX_MOVES], moves: [Option<Arc<RwLock<LearnedMove<'library>>>>; MAX_MOVES],
allowed_experience: bool, allowed_experience: bool,
types: Vec<u8>, types: Vec<u8>,
@ -116,14 +120,13 @@ impl<'own, 'library> Pokemon<'own, 'library> {
.static_data() .static_data()
.growth_rates() .growth_rates()
.calculate_experience(species.growth_rate(), level); .calculate_experience(species.growth_rate(), level);
let health = form.get_base_stat(Statistic::HP) as u32;
let weight = form.weight(); let weight = form.weight();
let height = form.height(); let height = form.height();
let nature = library let nature = library
.static_data() .static_data()
.natures() .natures()
.get_nature(&nature) .get_nature(&nature)
.expect("Unknown nature name was given."); .unwrap_or_else(|| panic!("Unknown nature name was given: {}.", &nature));
let mut pokemon = Self { let mut pokemon = Self {
library, library,
species, species,
@ -136,7 +139,7 @@ impl<'own, 'library> Pokemon<'own, 'library> {
gender, gender,
coloring, coloring,
held_item: None, held_item: None,
current_health: health, current_health: 1,
weight, weight,
height, height,
stat_boost: Default::default(), stat_boost: Default::default(),
@ -162,26 +165,29 @@ impl<'own, 'library> Pokemon<'own, 'library> {
script_source_data: Default::default(), script_source_data: Default::default(),
}; };
pokemon.recalculate_flat_stats(); pokemon.recalculate_flat_stats();
let health = pokemon.flat_stats().hp();
pokemon.current_health = health;
pokemon pokemon
} }
pub fn library(&self) -> &'own DynamicLibrary { pub fn library(&self) -> &'own DynamicLibrary {
self.library self.library
} }
pub fn species(&self) -> &'own Species<'library> { pub fn species(&self) -> &'own Species {
self.species self.species
} }
pub fn form(&self) -> &'own Form<'library> { pub fn form(&self) -> &'own Form {
self.form self.form
} }
pub fn display_species(&self) -> &'own Species<'library> { pub fn display_species(&self) -> &'own Species {
if let Some(v) = self.display_species { if let Some(v) = self.display_species {
v v
} else { } else {
self.species self.species
} }
} }
pub fn display_form(&self) -> &'own Form<'library> { pub fn display_form(&self) -> &'own Form {
if let Some(v) = self.display_form { if let Some(v) = self.display_form {
v v
} else { } else {
@ -254,7 +260,7 @@ impl<'own, 'library> Pokemon<'own, 'library> {
pub fn types(&self) -> &Vec<u8> { pub fn types(&self) -> &Vec<u8> {
&self.types &self.types
} }
pub fn learned_moves(&self) -> &[Option<LearnedMove>; MAX_MOVES] { pub fn learned_moves(&self) -> &[Option<Arc<RwLock<LearnedMove<'library>>>>; MAX_MOVES] {
&self.moves &self.moves
} }
pub fn status(&self) -> &ScriptContainer { pub fn status(&self) -> &ScriptContainer {
@ -276,9 +282,9 @@ impl<'own, 'library> Pokemon<'own, 'library> {
&self.effort_values &self.effort_values
} }
pub fn get_battle(&self) -> Option<&Weak<RwLock<Battle<'own, 'library>>>> { pub fn get_battle(&self) -> Option<&Battle<'own, 'library>> {
if let Some(data) = &self.battle_data { if let Some(data) = &self.battle_data {
Some(&data.battle) Some(&data.battle().unwrap())
} else { } else {
None None
} }
@ -298,7 +304,11 @@ impl<'own, 'library> Pokemon<'own, 'library> {
return v; return v;
} }
} }
self.form.get_ability(self.ability_index) self.library
.static_data()
.abilities()
.get(self.form.get_ability(self.ability_index))
.unwrap()
} }
pub fn ability_script(&self) -> &ScriptContainer { pub fn ability_script(&self) -> &ScriptContainer {
@ -337,17 +347,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
// If we're in battle, use the battle random for predictability // If we're in battle, use the battle random for predictability
if self.battle_data.is_some() { if self.battle_data.is_some() {
let battle_data = self.battle_data.as_mut().unwrap(); let battle_data = self.battle_data.as_mut().unwrap();
self.gender = species.get_random_gender( self.gender =
&mut battle_data species.get_random_gender(&mut battle_data.battle().unwrap().random().get_rng().lock().unwrap());
.battle
.upgrade()
.unwrap()
.read()
.random()
.get_rng()
.lock()
.unwrap(),
);
} else { } else {
// If we're not in battle, just use a new random. // If we're not in battle, just use a new random.
self.gender = species.get_random_gender(&mut Random::default()); self.gender = species.get_random_gender(&mut Random::default());
@ -358,8 +359,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
self.gender = Gender::Genderless; self.gender = Gender::Genderless;
} }
if let Some(battle_data) = &self.battle_data { if let Some(battle_data) = &self.battle_data {
if let Some(battle) = battle_data.battle.upgrade() { if let Some(battle) = battle_data.battle() {
battle.read().event_hook().trigger(Event::SpeciesChange { battle.event_hook().trigger(Event::SpeciesChange {
pokemon: self, pokemon: self,
species, species,
form, form,
@ -408,11 +409,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
// TODO: consider form specific attacks? // TODO: consider form specific attacks?
if let Some(battle_data) = &self.battle_data { if let Some(battle_data) = &self.battle_data {
if let Some(battle) = battle_data.battle.upgrade() { if let Some(battle) = battle_data.battle() {
battle battle.event_hook().trigger(Event::FormChange { pokemon: self, form })
.read()
.event_hook()
.trigger(Event::FormChange { pokemon: self, form })
} }
} }
} }
@ -425,7 +423,7 @@ impl<'own, 'library> Pokemon<'own, 'library> {
self.current_health == 0 self.current_health == 0
} }
pub fn set_battle_data(&mut self, battle: Weak<RwLock<Battle<'own, 'library>>>, battle_side_index: u8) { pub fn set_battle_data(&mut self, battle: *mut Battle<'own, 'library>, battle_side_index: u8) {
if let Some(battle_data) = &mut self.battle_data { if let Some(battle_data) = &mut self.battle_data {
battle_data.battle = battle; battle_data.battle = battle;
battle_data.battle_side_index = battle_side_index; battle_data.battle_side_index = battle_side_index;
@ -485,8 +483,8 @@ impl<'own, 'library> Pokemon<'own, 'library> {
} }
let new_health = self.current_health() - damage; let new_health = self.current_health() - damage;
if let Some(battle_data) = &self.battle_data { if let Some(battle_data) = &self.battle_data {
if let Some(battle) = battle_data.battle.upgrade() { if let Some(battle) = battle_data.battle() {
battle.read().event_hook().trigger(Event::Damage { battle.event_hook().trigger(Event::Damage {
pokemon: self, pokemon: self,
source, source,
original_health: self.current_health(), original_health: self.current_health(),
@ -502,27 +500,47 @@ impl<'own, 'library> Pokemon<'own, 'library> {
} }
} }
pub fn on_faint(&self, source: DamageSource) { pub fn on_faint(&mut self, source: DamageSource) {
if let Some(battle_data) = &self.battle_data { if self.battle_data.is_some() && self.battle_data.as_ref().unwrap().battle().is_some() {
if let Some(battle) = battle_data.battle.upgrade() { self.battle_data
battle.read().event_hook().trigger(Event::Faint { pokemon: self }); .as_ref()
.unwrap()
.battle()
.unwrap()
.event_hook()
.trigger(Event::Faint { pokemon: self });
script_hook!(on_faint, self, self, source); script_hook!(on_faint, self, self, source);
script_hook!(on_remove, self,); script_hook!(on_remove, self,);
}
// TODO: Experience gain
if let Some(battle) = battle_data.battle.upgrade() { let side_index = self.battle_data.as_ref().unwrap().battle_side_index;
if !battle let index = self.battle_data.as_ref().unwrap().index;
.read() if !self
.can_slot_be_filled(battle_data.battle_side_index, battle_data.index) .battle_data
.as_ref()
.unwrap()
.battle()
.unwrap()
.can_slot_be_filled(side_index, index)
{ {
let mut battle = battle.write(); self.battle_data.as_mut().unwrap().battle_mut().unwrap().sides_mut()[side_index as usize]
let side = &mut battle.sides_mut()[battle_data.battle_side_index as usize]; .mark_slot_as_unfillable(index);
side.mark_slot_as_unfillable(self);
} }
battle.write().validate_battle_state(); self.battle_data
.as_mut()
.unwrap()
.battle_mut()
.unwrap()
.validate_battle_state();
} }
} }
pub fn learn_move(&mut self, move_name: &StringKey, learn_method: MoveLearnMethod) {
let move_pos = self.learned_moves().iter().position(|a| a.is_none());
if move_pos.is_none() {
panic!("No more moves with an empty space found.");
}
let move_data = self.library.static_data().moves().get(move_name).unwrap();
self.moves[move_pos.unwrap()] = Some(Arc::new(RwLock::new(LearnedMove::new(move_data, learn_method))));
} }
} }
@ -530,8 +548,8 @@ impl<'own, 'library> ScriptSource<'own> for Pokemon<'own, 'library> {
fn get_script_count(&self) -> usize { fn get_script_count(&self) -> usize {
let mut c = 3; let mut c = 3;
if let Some(battle_data) = &self.battle_data { if let Some(battle_data) = &self.battle_data {
if let Some(battle) = battle_data.battle.upgrade() { if let Some(battle) = battle_data.battle() {
c += battle.read().sides()[battle_data.battle_side_index as usize].get_script_count(); c += battle.sides()[battle_data.battle_side_index as usize].get_script_count();
} }
} }
c c
@ -551,8 +569,8 @@ impl<'own, 'library> ScriptSource<'own> for Pokemon<'own, 'library> {
fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) { fn collect_scripts(&self, scripts: &mut Vec<ScriptWrapper>) {
self.get_own_scripts(scripts); self.get_own_scripts(scripts);
if let Some(battle_data) = &self.battle_data { if let Some(battle_data) = &self.battle_data {
if let Some(battle) = battle_data.battle.upgrade() { if let Some(battle) = battle_data.battle() {
battle.read().sides()[battle_data.battle_side_index as usize].collect_scripts(scripts); battle.sides()[battle_data.battle_side_index as usize].collect_scripts(scripts);
} }
} }
} }

View File

@ -1,5 +1,6 @@
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::dynamic_data::libraries::dynamic_library::DynamicLibrary; use crate::dynamic_data::libraries::dynamic_library::DynamicLibrary;
use crate::dynamic_data::models::learned_move::MoveLearnMethod;
use crate::dynamic_data::models::pokemon::Pokemon; use crate::dynamic_data::models::pokemon::Pokemon;
use crate::static_data::{AbilityIndex, DataLibrary, Gender}; use crate::static_data::{AbilityIndex, DataLibrary, Gender};
use crate::StringKey; use crate::StringKey;
@ -8,6 +9,7 @@ pub struct PokemonBuilder<'own> {
library: &'own DynamicLibrary, library: &'own DynamicLibrary,
species: StringKey, species: StringKey,
level: LevelInt, level: LevelInt,
learned_moves: Vec<StringKey>,
} }
impl<'own> PokemonBuilder<'own> { impl<'own> PokemonBuilder<'own> {
@ -16,13 +18,18 @@ impl<'own> PokemonBuilder<'own> {
library, library,
species, species,
level, level,
learned_moves: vec![],
} }
} }
pub fn learn_move(mut self, learned_move: StringKey) -> Self {
self.learned_moves.push(learned_move);
self
}
pub fn build<'func>(self) -> Pokemon<'own, 'own> { pub fn build(self) -> Pokemon<'own, 'own> {
let species = self.library.static_data().species().get(&self.species).unwrap(); let species = self.library.static_data().species().get(&self.species).unwrap();
let form = species.get_default_form(); let form = species.get_default_form();
Pokemon::new( let mut p = Pokemon::new(
self.library, self.library,
species, species,
form, form,
@ -34,7 +41,12 @@ impl<'own> PokemonBuilder<'own> {
0, 0,
Gender::Male, Gender::Male,
0, 0,
&"test_nature".into(), &"hardy".into(),
) );
for learned_move in self.learned_moves {
p.learn_move(&learned_move, MoveLearnMethod::Unknown);
}
p
} }
} }

View File

@ -1,5 +1,6 @@
use crate::dynamic_data::models::pokemon::Pokemon; use crate::dynamic_data::models::pokemon::Pokemon;
use std::sync::{Arc, RwLock}; use parking_lot::RwLock;
use std::sync::Arc;
#[derive(Debug)] #[derive(Debug)]
pub struct PokemonParty<'pokemon, 'library> { pub struct PokemonParty<'pokemon, 'library> {
@ -15,6 +16,10 @@ impl<'own, 'library> PokemonParty<'own, 'library> {
Self { pokemon } Self { pokemon }
} }
pub fn new_from_vec(pokemon: Vec<Option<Arc<RwLock<Pokemon<'own, 'library>>>>>) -> Self {
Self { pokemon }
}
pub fn at(&self, index: usize) -> &Option<Arc<RwLock<Pokemon<'own, 'library>>>> { pub fn at(&self, index: usize) -> &Option<Arc<RwLock<Pokemon<'own, 'library>>>> {
let opt = self.pokemon.get(index); let opt = self.pokemon.get(index);
if let Some(v) = opt { if let Some(v) = opt {
@ -43,7 +48,7 @@ impl<'own, 'library> PokemonParty<'own, 'library> {
pub fn has_usable_pokemon(&self) -> bool { pub fn has_usable_pokemon(&self) -> bool {
for pokemon in self.pokemon.iter().flatten() { for pokemon in self.pokemon.iter().flatten() {
if pokemon.read().unwrap().is_usable() { if pokemon.read().is_usable() {
return true; return true;
} }
} }

View File

@ -149,10 +149,12 @@ impl ScriptAggregator {
self.index = index; self.index = index;
let wrapper = unsafe { &self.scripts.as_ref().unwrap()[self.index as usize] }; let wrapper = unsafe { &self.scripts.as_ref().unwrap()[self.index as usize] };
if let ScriptWrapper::Set(s) = wrapper { if let ScriptWrapper::Set(s) = wrapper {
if let Some(..) = s.upgrade() { if let Some(set) = s.upgrade() {
if set.read().count() > 0 {
self.set_index = 0; self.set_index = 0;
return true; return true;
} }
}
} else if let ScriptWrapper::Script(script) = wrapper { } else if let ScriptWrapper::Script(script) = wrapper {
if let Some(v) = script.upgrade() { if let Some(v) = script.upgrade() {
if let Some(..) = v.read().as_ref() { if let Some(..) = v.read().as_ref() {

View File

@ -1,6 +1,6 @@
use super::item_category::{BattleItemCategory, ItemCategory}; use super::item_category::{BattleItemCategory, ItemCategory};
use crate::StringKey; use crate::StringKey;
use std::collections::HashSet; use hashbrown::HashSet;
#[derive(Debug)] #[derive(Debug)]
pub struct Item { pub struct Item {

View File

@ -1,4 +1,8 @@
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)] #[repr(u8)]
pub enum ItemCategory { pub enum ItemCategory {
MiscItem, MiscItem,
@ -12,8 +16,10 @@ pub enum ItemCategory {
} }
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)] #[repr(u8)]
pub enum BattleItemCategory { pub enum BattleItemCategory {
None,
Healing, Healing,
StatusHealing, StatusHealing,
Pokeball, Pokeball,

View File

@ -20,7 +20,7 @@ pub trait DataLibrary<'a, T: 'a> {
modifies.1.remove(index); modifies.1.remove(index);
} }
fn get(&self, key: &StringKey) -> Option<&T> { fn get(&'a self, key: &StringKey) -> Option<&'a T> {
self.map().get(key) self.map().get(key)
} }

View File

@ -38,7 +38,7 @@ pub mod tests {
use crate::static_data::items::item_category::{BattleItemCategory, ItemCategory}; use crate::static_data::items::item_category::{BattleItemCategory, ItemCategory};
use crate::static_data::libraries::data_library::DataLibrary; use crate::static_data::libraries::data_library::DataLibrary;
use crate::static_data::libraries::item_library::ItemLibrary; use crate::static_data::libraries::item_library::ItemLibrary;
use std::collections::HashSet; use hashbrown::HashSet;
fn build_item() -> Item { fn build_item() -> Item {
Item::new( Item::new(

View File

@ -4,13 +4,13 @@ use crate::StringKey;
use hashbrown::HashMap; use hashbrown::HashMap;
#[derive(Debug)] #[derive(Debug)]
pub struct SpeciesLibrary<'a> { pub struct SpeciesLibrary {
map: HashMap<StringKey, Box<Species<'a>>>, map: HashMap<StringKey, Box<Species>>,
list: Vec<StringKey>, list: Vec<StringKey>,
} }
impl<'a> SpeciesLibrary<'a> { impl SpeciesLibrary {
pub fn new(capacity: usize) -> SpeciesLibrary<'a> { pub fn new(capacity: usize) -> SpeciesLibrary {
SpeciesLibrary { SpeciesLibrary {
map: HashMap::with_capacity(capacity), map: HashMap::with_capacity(capacity),
list: Vec::with_capacity(capacity), list: Vec::with_capacity(capacity),
@ -18,8 +18,8 @@ impl<'a> SpeciesLibrary<'a> {
} }
} }
impl<'a> DataLibrary<'a, Box<Species<'a>>> for SpeciesLibrary<'a> { impl<'a> DataLibrary<'a, Box<Species>> for SpeciesLibrary {
fn map(&self) -> &HashMap<StringKey, Box<Species<'a>>> { fn map(&self) -> &HashMap<StringKey, Box<Species>> {
&self.map &self.map
} }
@ -27,7 +27,7 @@ impl<'a> DataLibrary<'a, Box<Species<'a>>> for SpeciesLibrary<'a> {
&self.list &self.list
} }
fn get_modify(&mut self) -> (&mut HashMap<StringKey, Box<Species<'a>>>, &mut Vec<StringKey>) { fn get_modify(&mut self) -> (&mut HashMap<StringKey, Box<Species>>, &mut Vec<StringKey>) {
(&mut self.map, &mut self.list) (&mut self.map, &mut self.list)
} }
} }
@ -42,7 +42,7 @@ pub mod tests {
use crate::static_data::statistic_set::StatisticSet; use crate::static_data::statistic_set::StatisticSet;
use hashbrown::HashSet; use hashbrown::HashSet;
fn build_species<'a>() -> Species<'a> { fn build_species<'a>() -> Species {
Species::new( Species::new(
0, 0,
&"foo".into(), &"foo".into(),
@ -65,7 +65,7 @@ pub mod tests {
) )
} }
pub fn build<'a>() -> SpeciesLibrary<'a> { pub fn build<'a>() -> SpeciesLibrary {
let mut lib = SpeciesLibrary::new(1); let mut lib = SpeciesLibrary::new(1);
let species = build_species(); let species = build_species();
// Borrow as mut so we can insert // Borrow as mut so we can insert

View File

@ -8,9 +8,9 @@ use crate::static_data::SpeciesLibrary;
use crate::static_data::TypeLibrary; use crate::static_data::TypeLibrary;
#[derive(Debug)] #[derive(Debug)]
pub struct StaticData<'a> { pub struct StaticData {
settings: LibrarySettings, settings: LibrarySettings,
species: SpeciesLibrary<'a>, species: SpeciesLibrary,
moves: MoveLibrary, moves: MoveLibrary,
items: ItemLibrary, items: ItemLibrary,
growth_rates: GrowthRateLibrary, growth_rates: GrowthRateLibrary,
@ -19,53 +19,66 @@ pub struct StaticData<'a> {
abilities: AbilityLibrary, abilities: AbilityLibrary,
} }
impl<'a> StaticData<'a> { impl StaticData {
pub fn new( pub fn new(settings: LibrarySettings) -> Self {
settings: LibrarySettings,
species: SpeciesLibrary<'a>,
moves: MoveLibrary,
items: ItemLibrary,
growth_rates: GrowthRateLibrary,
types: TypeLibrary,
natures: NatureLibrary,
abilities: AbilityLibrary,
) -> Self {
Self { Self {
settings, settings,
species, species: SpeciesLibrary::new(0),
moves, moves: MoveLibrary::new(0),
items, items: ItemLibrary::new(0),
growth_rates, growth_rates: GrowthRateLibrary::new(0),
types, types: TypeLibrary::new(0),
natures, natures: NatureLibrary::new(0),
abilities, abilities: AbilityLibrary::new(0),
} }
} }
pub fn settings(&self) -> &LibrarySettings { pub fn settings(&self) -> &LibrarySettings {
&self.settings &self.settings
} }
pub fn species(&self) -> &SpeciesLibrary<'a> { pub fn species(&self) -> &SpeciesLibrary {
&self.species &self.species
} }
pub fn species_mut(&mut self) -> &mut SpeciesLibrary {
&mut self.species
}
pub fn moves(&self) -> &MoveLibrary { pub fn moves(&self) -> &MoveLibrary {
&self.moves &self.moves
} }
pub fn moves_mut(&mut self) -> &mut MoveLibrary {
&mut self.moves
}
pub fn items(&self) -> &ItemLibrary { pub fn items(&self) -> &ItemLibrary {
&self.items &self.items
} }
pub fn items_mut(&mut self) -> &mut ItemLibrary {
&mut self.items
}
pub fn growth_rates(&self) -> &GrowthRateLibrary { pub fn growth_rates(&self) -> &GrowthRateLibrary {
&self.growth_rates &self.growth_rates
} }
pub fn growth_rates_mut(&mut self) -> &mut GrowthRateLibrary {
&mut self.growth_rates
}
pub fn types(&self) -> &TypeLibrary { pub fn types(&self) -> &TypeLibrary {
&self.types &self.types
} }
pub fn types_mut(&mut self) -> &mut TypeLibrary {
&mut self.types
}
pub fn natures(&self) -> &NatureLibrary { pub fn natures(&self) -> &NatureLibrary {
&self.natures &self.natures
} }
pub fn natures_mut(&mut self) -> &mut NatureLibrary {
&mut self.natures
}
pub fn abilities(&self) -> &AbilityLibrary { pub fn abilities(&self) -> &AbilityLibrary {
&self.abilities &self.abilities
} }
pub fn abilities_mut<'a>(&'a mut self) -> &'a mut AbilityLibrary {
&mut self.abilities
}
} }
#[cfg(test)] #[cfg(test)]
@ -77,7 +90,7 @@ pub mod test {
}; };
use crate::static_data::natures; use crate::static_data::natures;
pub fn build<'a>() -> StaticData<'a> { pub fn build<'a>() -> StaticData {
StaticData { StaticData {
settings: LibrarySettings::new(100), settings: LibrarySettings::new(100),
species: species_library::tests::build(), species: species_library::tests::build(),

View File

@ -6,23 +6,22 @@ use crate::static_data::StatisticSet;
use crate::Random; use crate::Random;
use crate::StringKey; use crate::StringKey;
use hashbrown::HashSet; use hashbrown::HashSet;
use std::ops::Deref;
#[derive(Debug)] #[derive(Debug)]
pub struct Form<'a> { pub struct Form {
name: StringKey, name: StringKey,
height: f32, height: f32,
weight: f32, weight: f32,
base_experience: u32, base_experience: u32,
types: Vec<u8>, types: Vec<u8>,
base_stats: StatisticSet<u16>, base_stats: StatisticSet<u16>,
abilities: Vec<&'a Ability>, abilities: Vec<StringKey>,
hidden_abilities: Vec<&'a Ability>, hidden_abilities: Vec<StringKey>,
moves: LearnableMoves<'a>, moves: LearnableMoves,
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
} }
impl<'a> Form<'a> { impl Form {
pub fn new( pub fn new(
name: &StringKey, name: &StringKey,
height: f32, height: f32,
@ -30,11 +29,11 @@ impl<'a> Form<'a> {
base_experience: u32, base_experience: u32,
types: Vec<u8>, types: Vec<u8>,
base_stats: StatisticSet<u16>, base_stats: StatisticSet<u16>,
abilities: Vec<&'a Ability>, abilities: Vec<StringKey>,
hidden_abilities: Vec<&'a Ability>, hidden_abilities: Vec<StringKey>,
moves: LearnableMoves<'a>, moves: LearnableMoves,
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> Form<'a> { ) -> Form {
Form { Form {
name: name.clone(), name: name.clone(),
height, height,
@ -67,13 +66,13 @@ impl<'a> Form<'a> {
pub fn base_stats(&self) -> StatisticSet<u16> { pub fn base_stats(&self) -> StatisticSet<u16> {
self.base_stats self.base_stats
} }
pub fn abilities(&self) -> &Vec<&'a Ability> { pub fn abilities(&self) -> &Vec<StringKey> {
&self.abilities &self.abilities
} }
pub fn hidden_abilities(&self) -> &Vec<&'a Ability> { pub fn hidden_abilities(&self) -> &Vec<StringKey> {
&self.hidden_abilities &self.hidden_abilities
} }
pub fn moves(&self) -> &LearnableMoves<'a> { pub fn moves(&self) -> &LearnableMoves {
&self.moves &self.moves
} }
pub fn flags(&self) -> &HashSet<StringKey> { pub fn flags(&self) -> &HashSet<StringKey> {
@ -90,7 +89,7 @@ impl<'a> Form<'a> {
pub fn find_ability_index(&self, ability: &Ability) -> Option<AbilityIndex> { pub fn find_ability_index(&self, ability: &Ability) -> Option<AbilityIndex> {
for (index, a) in self.abilities.iter().enumerate() { for (index, a) in self.abilities.iter().enumerate() {
if std::ptr::eq(a.deref(), ability as *const Ability) { if a == ability.name() {
return Some(AbilityIndex { return Some(AbilityIndex {
hidden: false, hidden: false,
index: index as u8, index: index as u8,
@ -98,7 +97,7 @@ impl<'a> Form<'a> {
} }
} }
for (index, a) in self.hidden_abilities.iter().enumerate() { for (index, a) in self.hidden_abilities.iter().enumerate() {
if std::ptr::eq(a.deref(), ability as *const Ability) { if a == ability.name() {
return Some(AbilityIndex { return Some(AbilityIndex {
hidden: true, hidden: true,
index: index as u8, index: index as u8,
@ -108,19 +107,19 @@ impl<'a> Form<'a> {
None None
} }
pub fn get_ability(&self, index: AbilityIndex) -> &Ability { pub fn get_ability(&self, index: AbilityIndex) -> &StringKey {
if index.hidden { if index.hidden {
self.hidden_abilities[index.index as usize] &self.hidden_abilities[index.index as usize]
} else { } else {
self.abilities[index.index as usize] &self.abilities[index.index as usize]
} }
} }
pub fn get_random_ability(&self, rand: &mut Random) -> &Ability { pub fn get_random_ability(&self, rand: &mut Random) -> &StringKey {
self.abilities[rand.get_between_unsigned(0, self.abilities.len() as u32) as usize] &self.abilities[rand.get_between_unsigned(0, self.abilities.len() as u32) as usize]
} }
pub fn get_random_hidden_ability(&self, rand: &mut Random) -> &Ability { pub fn get_random_hidden_ability(&self, rand: &mut Random) -> &StringKey {
self.hidden_abilities[rand.get_between_unsigned(0, self.hidden_abilities.len() as u32) as usize] &self.hidden_abilities[rand.get_between_unsigned(0, self.hidden_abilities.len() as u32) as usize]
} }
pub fn has_flag(&self, key: &StringKey) -> bool { pub fn has_flag(&self, key: &StringKey) -> bool {

View File

@ -1,112 +1,73 @@
use crate::defines::LevelInt; use crate::defines::LevelInt;
use crate::static_data::MoveData; use crate::StringKey;
use hashbrown::hash_map::Entry::{Occupied, Vacant}; use hashbrown::hash_map::Entry::{Occupied, Vacant};
use hashbrown::HashMap; use hashbrown::HashMap;
#[derive(Default, PartialEq, Debug)] #[derive(Default, PartialEq, Debug)]
pub struct LearnableMoves<'a> { pub struct LearnableMoves {
learned_by_level: HashMap<LevelInt, Vec<&'a MoveData>>, learned_by_level: HashMap<LevelInt, Vec<StringKey>>,
distinct_level_moves: Vec<&'a MoveData>, distinct_level_moves: Vec<StringKey>,
} }
impl<'a> LearnableMoves<'a> { impl LearnableMoves {
pub fn new() -> LearnableMoves<'a> { pub fn new() -> LearnableMoves {
LearnableMoves::default() LearnableMoves::default()
} }
pub fn add_level_move(&mut self, level: LevelInt, m: &'a MoveData) { pub fn add_level_move(&mut self, level: LevelInt, m: &StringKey) {
match self.learned_by_level.entry(level) { match self.learned_by_level.entry(level) {
Occupied(x) => { Occupied(x) => {
x.into_mut().push(m); x.into_mut().push(m.clone());
} }
Vacant(_) => { Vacant(_) => {
self.learned_by_level.insert(level, vec![m]); self.learned_by_level.insert(level, vec![m.clone()]);
} }
} }
if !self.distinct_level_moves.contains(&m) { if !self.distinct_level_moves.contains(&m) {
self.distinct_level_moves.push(m); self.distinct_level_moves.push(m.clone());
} }
} }
pub fn get_learned_by_level(&self, level: LevelInt) -> Option<&Vec<&'a MoveData>> { pub fn get_learned_by_level(&self, level: LevelInt) -> Option<&Vec<StringKey>> {
self.learned_by_level.get(&level) self.learned_by_level.get(&level)
} }
pub fn get_distinct_level_moves(&self) -> &Vec<&'a MoveData> { pub fn get_distinct_level_moves(&self) -> &Vec<StringKey> {
&self.distinct_level_moves &self.distinct_level_moves
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::static_data::moves::move_data::{MoveCategory, MoveData, MoveTarget};
use crate::static_data::moves::secondary_effect::SecondaryEffect;
use crate::static_data::species_data::learnable_moves::LearnableMoves; use crate::static_data::species_data::learnable_moves::LearnableMoves;
#[test] #[test]
fn adds_level_moves() { fn adds_level_moves() {
let move1 = MoveData::new(
&"foo".into(),
0,
MoveCategory::Physical,
0,
0,
0,
MoveTarget::Adjacent,
0,
SecondaryEffect::empty(),
Default::default(),
);
let move2 = MoveData::new(
&"bar".into(),
0,
MoveCategory::Physical,
0,
0,
0,
MoveTarget::Adjacent,
0,
SecondaryEffect::empty(),
Default::default(),
);
let mut moves = LearnableMoves::new(); let mut moves = LearnableMoves::new();
moves.add_level_move(1, &move1); moves.add_level_move(1, &"foo".into());
moves.add_level_move(1, &move2); moves.add_level_move(1, &"bar".into());
let m = moves.get_learned_by_level(1u8).unwrap(); let m = moves.get_learned_by_level(1u8).unwrap();
assert_eq!(m.len(), 2); assert_eq!(m.len(), 2);
assert_eq!(m[0], &move1); assert_eq!(m[0], "foo".into());
assert_eq!(m[1], &move2); assert_eq!(m[1], "bar".into());
} }
#[test] #[test]
fn adds_two_same_moves_at_different_level() { fn adds_two_same_moves_at_different_level() {
let move1 = MoveData::new(
&"foo".into(),
0,
MoveCategory::Physical,
0,
0,
0,
MoveTarget::Adjacent,
0,
SecondaryEffect::empty(),
Default::default(),
);
let mut moves = LearnableMoves::new(); let mut moves = LearnableMoves::new();
moves.add_level_move(1, &move1); moves.add_level_move(1, &"foo".into());
moves.add_level_move(5, &move1); moves.add_level_move(5, &"foo".into());
let m = moves.get_learned_by_level(1u8).unwrap(); let m = moves.get_learned_by_level(1u8).unwrap();
assert_eq!(m.len(), 1); assert_eq!(m.len(), 1);
assert_eq!(m[0], &move1); assert_eq!(m[0], "foo".into());
let m2 = moves.get_learned_by_level(5u8).unwrap(); let m2 = moves.get_learned_by_level(5u8).unwrap();
assert_eq!(m2.len(), 1); assert_eq!(m2.len(), 1);
assert_eq!(m2[0], &move1); assert_eq!(m2[0], "foo".into());
let distinct = moves.get_distinct_level_moves(); let distinct = moves.get_distinct_level_moves();
assert_eq!(distinct.len(), 1); assert_eq!(distinct.len(), 1);
assert_eq!(distinct[0], &move1); assert_eq!(distinct[0], "foo".into());
} }
} }

View File

@ -6,28 +6,28 @@ use hashbrown::{HashMap, HashSet};
use std::lazy::SyncLazy; use std::lazy::SyncLazy;
#[derive(Debug)] #[derive(Debug)]
pub struct Species<'a> { pub struct Species {
id: u16, id: u16,
name: StringKey, name: StringKey,
gender_rate: f32, gender_rate: f32,
growth_rate: StringKey, growth_rate: StringKey,
capture_rate: u8, capture_rate: u8,
forms: HashMap<StringKey, Form<'a>>, forms: HashMap<StringKey, Form>,
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
} }
static DEFAULT_KEY: SyncLazy<StringKey> = SyncLazy::new(|| StringKey::new("default")); static DEFAULT_KEY: SyncLazy<StringKey> = SyncLazy::new(|| StringKey::new("default"));
impl<'a> Species<'a> { impl Species {
pub fn new( pub fn new(
id: u16, id: u16,
name: &StringKey, name: &StringKey,
gender_rate: f32, gender_rate: f32,
growth_rate: &StringKey, growth_rate: &StringKey,
capture_rate: u8, capture_rate: u8,
default_form: Form<'a>, default_form: Form,
flags: HashSet<StringKey>, flags: HashSet<StringKey>,
) -> Species<'a> { ) -> Species {
let mut forms = HashMap::with_capacity(1); let mut forms = HashMap::with_capacity(1);
forms.insert_unique_unchecked(DEFAULT_KEY.clone(), default_form); forms.insert_unique_unchecked(DEFAULT_KEY.clone(), default_form);
Species { Species {
@ -55,14 +55,14 @@ impl<'a> Species<'a> {
pub fn capture_rate(&self) -> u8 { pub fn capture_rate(&self) -> u8 {
self.capture_rate self.capture_rate
} }
pub fn forms(&self) -> &HashMap<StringKey, Form<'a>> { pub fn forms(&self) -> &HashMap<StringKey, Form> {
&self.forms &self.forms
} }
pub fn flags(&self) -> &HashSet<StringKey> { pub fn flags(&self) -> &HashSet<StringKey> {
&self.flags &self.flags
} }
pub fn add_form(&mut self, id: StringKey, form: Form<'a>) { pub fn add_form(&mut self, id: StringKey, form: Form) {
self.forms.insert(id, form); self.forms.insert(id, form);
} }

View File

@ -1,4 +1,8 @@
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Eq, Copy, Clone)] #[derive(Debug, PartialEq, Eq, Copy, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum Statistic { pub enum Statistic {
HP, HP,
Attack, Attack,

View File

@ -1,4 +1,5 @@
use hashbrown::HashMap; use hashbrown::HashMap;
use std::fmt::{Display, Formatter};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::lazy::SyncLazy; use std::lazy::SyncLazy;
use std::sync::{Arc, Mutex, Weak}; use std::sync::{Arc, Mutex, Weak};
@ -86,6 +87,12 @@ impl From<&str> for StringKey {
} }
} }
impl Display for StringKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(&*self.str)
}
}
const fn to_lower(c: u8) -> u8 { const fn to_lower(c: u8) -> u8 {
if c >= b'A' && c <= b'Z' { if c >= b'A' && c <= b'Z' {
return c + (b'a' - b'A'); return c + (b'a' - b'A');

View File

@ -0,0 +1,22 @@
use pkmn_lib::dynamic_data::models::battle::Battle;
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TestDataGetter {
PokemonHealth { index: [u8; 2] },
}
impl TestDataGetter {
pub fn get(&self, battle: &Battle) -> String {
match self {
TestDataGetter::PokemonHealth { index } => battle
.get_pokemon(index[0], index[1])
.as_ref()
.unwrap()
.read()
.current_health()
.to_string(),
}
}
}

View File

@ -0,0 +1,400 @@
use hashbrown::HashSet;
use num_traits::PrimInt;
use pkmn_lib::defines::LevelInt;
use pkmn_lib::dynamic_data::libraries::battle_stat_calculator::BattleStatCalculator;
use pkmn_lib::dynamic_data::libraries::damage_library::Gen7DamageLibrary;
use pkmn_lib::dynamic_data::libraries::dynamic_library::DynamicLibrary;
use pkmn_lib::dynamic_data::libraries::misc_library::Gen7MiscLibrary;
use pkmn_lib::static_data::{
Ability, AbilityLibrary, BattleItemCategory, DataLibrary, EffectParameter, Form, GrowthRateLibrary, Item,
ItemLibrary, LearnableMoves, LibrarySettings, LookupGrowthRate, MoveData, MoveLibrary, Nature, NatureLibrary,
SecondaryEffect, Species, StaticData, Statistic, StatisticSet, TypeLibrary,
};
use pkmn_lib::StringKey;
use project_root::get_project_root;
use serde_json::Value;
use std::convert::TryFrom;
use std::fmt::Debug;
use std::fs::File;
use std::io::Read;
pub fn load_library() -> DynamicLibrary {
let mut path = get_project_root().unwrap();
path.push("tests/data/");
let path = path.to_str().unwrap().to_string();
let mut data = StaticData::new(LibrarySettings::new(100));
load_types(&path, data.types_mut());
load_natures(&path, data.natures_mut());
load_items(&path, data.items_mut());
load_growth_rates(&path, data.growth_rates_mut());
load_abilities(&path, data.abilities_mut());
load_moves(&path, &mut data);
load_species(&path, &mut data);
let dynamic = DynamicLibrary::new(
data,
BattleStatCalculator {},
Box::new(Gen7DamageLibrary::new(false)),
Box::new(Gen7MiscLibrary::new()),
);
dynamic
}
pub fn load_types(path: &String, type_library: &mut TypeLibrary) {
let mut reader = csv::ReaderBuilder::new()
.delimiter(b'|')
.from_path(path.to_string() + "Types.csv")
.unwrap();
let headers = reader.headers().unwrap();
for header in headers.iter().skip(1) {
type_library.register_type(&StringKey::new(header.clone()));
}
for record in reader.records() {
let record = record.unwrap();
let offensive_type = record.get(0).unwrap();
let offensive_type_id = type_library.get_type_id(&StringKey::new(offensive_type.clone()));
for (i, v) in record.iter().skip(1).enumerate() {
let effectiveness = v.parse::<f32>().unwrap();
type_library.set_effectiveness(offensive_type_id, i as u8, effectiveness);
}
}
}
pub fn load_natures(path: &String, nature_library: &mut NatureLibrary) {
let mut reader = csv::ReaderBuilder::new()
.delimiter(b'|')
.from_path(path.to_string() + "Natures.csv")
.unwrap();
for record in reader.records() {
let record = record.unwrap();
let nature_name = StringKey::new(record.get(0).unwrap());
let increased_statistic_str = record.get(1).unwrap();
let decreased_statistic_str = record.get(2).unwrap();
if increased_statistic_str.is_empty() || decreased_statistic_str.is_empty() {
nature_library.load_nature(nature_name, Nature::new(Statistic::HP, Statistic::HP, 1.0, 1.0));
} else {
let increased_statistic = serde_plain::from_str(increased_statistic_str).unwrap();
let decreased_statistic = serde_plain::from_str(decreased_statistic_str).unwrap();
nature_library.load_nature(
nature_name,
Nature::new(increased_statistic, decreased_statistic, 1.1, 0.9),
);
}
}
}
pub fn load_items(path: &String, lib: &mut ItemLibrary) {
let mut file = File::open(path.to_string() + "Items.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let json_array = json.as_array().unwrap();
for v in json_array {
let name = StringKey::new(v["name"].as_str().unwrap());
let category = serde_json::from_value(v["itemType"].clone()).unwrap();
let mut battle_category = BattleItemCategory::None;
if let Some(c) = v.get("battleType") {
battle_category = serde_json::from_value(c.clone()).unwrap();
}
let price = v["price"].as_i64().unwrap();
let mut flags = HashSet::new();
if let Some(f) = v.get("flags") {
let a = f.as_array().unwrap();
for flag in a {
flags.insert(StringKey::new(flag.as_str().unwrap()));
}
}
lib.add(
&name,
Box::new(Item::new(&name, category, battle_category, price as i32, flags)),
);
}
}
pub fn load_growth_rates(path: &String, growth_rate_library: &mut GrowthRateLibrary) {
let mut file = File::open(path.to_string() + "GrowthRates.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let o = json.as_object().unwrap();
for (key, value) in o {
let name = StringKey::new(key);
let experience_required_json = value.as_array().unwrap();
let mut experience_required = Vec::with_capacity(experience_required_json.len());
for v in experience_required_json {
experience_required.push(v.as_i64().unwrap() as u32);
}
growth_rate_library.add_growth_rate(&name, Box::new(LookupGrowthRate::new(experience_required)));
}
}
pub fn load_abilities(path: &String, ability_library: &mut AbilityLibrary) {
let mut file = File::open(path.to_string() + "Abilities.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let o = json.as_object().unwrap();
for (key, value) in o {
let name = StringKey::new(key);
let mut effect = StringKey::empty();
if let Some(e) = value.get("effect") {
effect = StringKey::new(e.as_str().unwrap());
}
let mut parameters = Vec::new();
if let Some(p) = value.get("parameters") {
for par in p.as_array().unwrap() {
parameters.push(parse_effect_parameter(par));
}
}
ability_library.add(&name, Box::new(Ability::new(&name, &effect, parameters)));
}
}
pub fn load_moves(path: &String, lib: &mut StaticData) {
let mut file = File::open(path.to_string() + "Moves.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let data = json.as_object().unwrap().get("data").unwrap().as_array().unwrap();
for move_data in data {
let move_data = move_data.as_object().unwrap();
let move_name = StringKey::new(move_data["name"].as_str().unwrap().clone());
let move_type = StringKey::new(move_data["type"].as_str().unwrap());
let move_type_id = lib.types().get_type_id(&move_type);
let move_category = serde_json::from_value(move_data["category"].clone()).unwrap();
let base_power = move_data["power"].as_i64().unwrap() as u8;
let accuracy = move_data["accuracy"].as_i64().unwrap() as u8;
let pp = move_data["pp"].as_i64().unwrap() as u8;
let target = serde_json::from_value(move_data["target"].clone()).unwrap();
let priority = move_data["priority"].as_i64().unwrap() as i8;
let secondary_effect = if let Some(v) = move_data.get("effect") {
let mut chance = -1.0;
if let Some(chance_value) = v.get("chance") {
chance = chance_value.as_f64().unwrap() as f32;
}
let mut parameters = Vec::new();
if let Some(pars) = v.get("parameters") {
let pars = pars.as_array().unwrap();
for par in pars {
parameters.push(parse_effect_parameter(par));
}
}
SecondaryEffect::new(chance, StringKey::new(v["name"].as_str().unwrap().clone()), parameters)
} else {
SecondaryEffect::empty()
};
let mut flags = HashSet::new();
if let Some(f) = move_data.get("flags") {
let f = f.as_array().unwrap();
for flag in f {
flags.insert(StringKey::new(flag.as_str().unwrap()));
}
}
lib.moves_mut().add(
&move_name,
MoveData::new(
&move_name.clone(),
move_type_id,
move_category,
base_power,
accuracy,
pp,
target,
priority,
secondary_effect,
flags,
),
);
}
}
pub fn load_species(path: &String, library: &mut StaticData) {
let mut file = File::open(path.to_string() + "Pokemon.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let o = json.as_object().unwrap();
for (key, value) in o {
if key.starts_with("$") {
continue;
}
let name = StringKey::new(key);
let id = value["id"].as_i64().unwrap();
let gender_rate = value["genderRatio"].as_f64().unwrap();
let growth_rate_name = StringKey::new(value["growthRate"].as_str().unwrap());
let _base_happiness = value["baseHappiness"].as_i64().unwrap();
let catch_rate = value["catchRate"].as_i64().unwrap();
let _color = value["color"].as_str().unwrap();
// let egg_groups = value["eggGroups"]
// .as_array()
// .unwrap()
// .iter()
// .map(|&a| a.as_str().unwrap())
// .collect();
let _egg_cycle = value["eggCycles"].as_i64().unwrap();
// TODO: tags
// TODO: evolutions
let forms = value["formes"].as_object().unwrap();
let default_form_value = &forms["default"];
let default_form = parse_form("default".into(), default_form_value, library);
let mut species = Box::new(Species::new(
id as u16,
&name,
gender_rate as f32,
&growth_rate_name,
catch_rate as u8,
default_form,
Default::default(),
));
library.species_mut().add(&name, species);
}
}
fn parse_form(name: StringKey, value: &Value, library: &mut StaticData) -> Form {
let mut abilities = Vec::new();
for a in value["abilities"].as_array().unwrap() {
abilities.push(StringKey::new(a.as_str().unwrap()));
}
let mut hidden_abilities = Vec::new();
for a in value["hiddenAbilities"].as_array().unwrap() {
hidden_abilities.push(StringKey::new(a.as_str().unwrap()));
}
let base_stats = parse_statistics(&value["baseStats"]);
// TODO: ev reward
let height = value["height"].as_f64().unwrap();
let weight = value["weight"].as_f64().unwrap();
let base_experience = value["baseExp"].as_u64().unwrap();
let types = value["types"]
.as_array()
.unwrap()
.iter()
.map(|a| library.types().get_type_id(&StringKey::new(a.as_str().unwrap())))
.collect();
let moves = parse_moves(&value["moves"], library.moves());
Form::new(
&name,
height as f32,
weight as f32,
base_experience as u32,
types,
base_stats,
abilities,
hidden_abilities,
moves,
Default::default(),
)
}
fn parse_statistics<T>(value: &Value) -> StatisticSet<T>
where
T: PrimInt + TryFrom<u64>,
<T as TryFrom<u64>>::Error: Debug,
{
StatisticSet::new(
<T as TryFrom<u64>>::try_from(value.get("hp").unwrap_or(&Value::Number(0.into())).as_u64().unwrap()).unwrap(),
<T as TryFrom<u64>>::try_from(
value
.get("attack")
.unwrap_or(&Value::Number(0.into()))
.as_u64()
.unwrap(),
)
.unwrap(),
<T as TryFrom<u64>>::try_from(
value
.get("defense")
.unwrap_or(&Value::Number(0.into()))
.as_u64()
.unwrap(),
)
.unwrap(),
<T as TryFrom<u64>>::try_from(
value
.get("specialAttack")
.unwrap_or(&Value::Number(0.into()))
.as_u64()
.unwrap(),
)
.unwrap(),
<T as TryFrom<u64>>::try_from(
value
.get("specialDefense")
.unwrap_or(&Value::Number(0.into()))
.as_u64()
.unwrap(),
)
.unwrap(),
<T as TryFrom<u64>>::try_from(value.get("speed").unwrap_or(&Value::Number(0.into())).as_u64().unwrap())
.unwrap(),
)
}
fn parse_moves(value: &Value, move_library: &MoveLibrary) -> LearnableMoves {
let mut moves = LearnableMoves::default();
let level_moves = value["levelMoves"].as_array().unwrap();
for level_move in level_moves {
let name = StringKey::new(level_move["name"].as_str().unwrap());
let level = level_move["level"].as_u64().unwrap() as LevelInt;
assert!(move_library.get(&name).is_some());
moves.add_level_move(level, &name);
}
moves
}
fn parse_effect_parameter(value: &Value) -> EffectParameter {
match value {
Value::Null => {
panic!("Unexpected type")
}
Value::Bool(b) => EffectParameter::Bool(*b),
Value::Number(n) => {
if n.is_f64() {
EffectParameter::Float(n.as_f64().unwrap() as f32)
} else {
EffectParameter::Int(n.as_i64().unwrap())
}
}
Value::String(s) => EffectParameter::String(s.clone()),
Value::Array(_) => {
panic!("Unexpected type")
}
Value::Object(_) => {
panic!("Unexpected type")
}
}
}
#[test]
#[cfg_attr(miri, ignore)]
fn test_type_library_loaded() {
let mut path = get_project_root().unwrap();
path.push("tests/data/");
let mut lib = TypeLibrary::new(18);
load_types(&path.to_str().unwrap().to_string(), &mut lib);
assert_eq!(
lib.get_effectiveness(
lib.get_type_id(&StringKey::new("fire")),
&vec![lib.get_type_id(&StringKey::new("grass"))],
),
2.0
);
}

9
tests/common/mod.rs Normal file
View File

@ -0,0 +1,9 @@
pub mod data_getter;
pub mod library_loader;
pub mod test_case;
pub mod test_step;
pub use data_getter::*;
pub use library_loader::*;
pub use test_case::*;
pub use test_step::*;

82
tests/common/test_case.rs Normal file
View File

@ -0,0 +1,82 @@
use super::test_step::TestStep;
use parking_lot::RwLock;
use pkmn_lib::defines::LevelInt;
use pkmn_lib::dynamic_data::libraries::dynamic_library::DynamicLibrary;
use pkmn_lib::dynamic_data::models::battle::Battle;
use pkmn_lib::dynamic_data::models::battle_party::BattleParty;
use pkmn_lib::dynamic_data::models::pokemon::Pokemon;
use pkmn_lib::dynamic_data::models::pokemon_builder::PokemonBuilder;
use pkmn_lib::dynamic_data::models::pokemon_party::PokemonParty;
use pkmn_lib::StringKey;
use serde::Deserialize;
use std::sync::Arc;
#[derive(Deserialize)]
pub struct TestCase {
pub name: String,
battle_setup: TestBattleSetup,
actions: Vec<TestStep>,
}
#[derive(Deserialize)]
struct TestBattleSetup {
seed: u128,
can_flee: bool,
number_of_sides: u8,
pokemon_per_side: u8,
parties: Vec<TestParty>,
}
#[derive(Deserialize)]
struct TestParty {
indices: Vec<[u8; 2]>,
pokemon: Vec<TestPokemon>,
}
#[derive(Deserialize)]
struct TestPokemon {
species: String,
level: LevelInt,
moves: Vec<String>,
}
impl TestCase {
pub fn run_test(&self, library: &DynamicLibrary) {
let mut parties = Vec::new();
for party in &self.battle_setup.parties {
let pokemon = party
.pokemon
.iter()
.map(|a| Some(Arc::new(RwLock::new(a.to_pokemon(library)))))
.collect();
let indices = party.indices.iter().map(|a| (a[0], a[1])).collect();
parties.push((Arc::new(PokemonParty::new_from_vec(pokemon)), indices));
}
let mut battle_parties = Vec::new();
for party in parties {
battle_parties.push(BattleParty::new(party.0.clone(), party.1));
}
let mut battle = Battle::new(
library,
battle_parties,
self.battle_setup.can_flee,
self.battle_setup.number_of_sides,
self.battle_setup.pokemon_per_side,
Some(self.battle_setup.seed),
);
for action in &self.actions {
action.execute(&mut battle);
}
}
}
impl TestPokemon {
fn to_pokemon<'a>(&'a self, library: &'a DynamicLibrary) -> Pokemon {
let mut builder = PokemonBuilder::new(library, StringKey::new(self.species.as_str()), self.level);
for move_name in &self.moves {
builder = builder.learn_move(StringKey::new(move_name));
}
builder.build()
}
}

82
tests/common/test_step.rs Normal file
View File

@ -0,0 +1,82 @@
use super::data_getter::TestDataGetter;
use pkmn_lib::dynamic_data::choices::{MoveChoice, PassChoice, TurnChoice};
use pkmn_lib::dynamic_data::models::battle::Battle;
use pkmn_lib::StringKey;
use serde::Deserialize;
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TestStep {
SetPokemon {
place: [u8; 2],
from_party: [u8; 2],
},
SetMoveChoice {
#[serde(rename = "for")]
for_pokemon: [u8; 2],
#[serde(rename = "move")]
use_move: String,
target: [u8; 2],
},
SetPassChoice {
#[serde(rename = "for")]
for_pokemon: [u8; 2],
},
Assert {
value: TestDataGetter,
expected: String,
},
}
impl TestStep {
pub fn execute(&self, battle: &mut Battle) {
match self {
TestStep::SetPokemon { place, from_party } => {
let p = battle.parties()[from_party[0] as usize]
.get_pokemon(from_party[1] as usize)
.clone();
battle.sides_mut()[place[0] as usize].set_pokemon(place[1], p);
}
TestStep::SetMoveChoice {
for_pokemon,
use_move,
target,
} => {
let p = battle.sides()[for_pokemon[0] as usize].pokemon()[for_pokemon[1] as usize]
.as_ref()
.unwrap()
.clone();
let mut used_move = None;
let pokemon_guard = p.read();
for learned_move in pokemon_guard.learned_moves().iter().flatten() {
if learned_move.read().move_data().name() == &StringKey::new(use_move) {
used_move = Some(learned_move.clone());
break;
}
}
assert!(used_move.is_some());
drop(pokemon_guard);
assert!(battle
.try_set_choice(TurnChoice::Move(MoveChoice::new(
p,
used_move.unwrap(),
target[0],
target[1],
)))
.unwrap());
}
TestStep::SetPassChoice { for_pokemon } => {
let p = battle.sides()[for_pokemon[0] as usize].pokemon()[for_pokemon[1] as usize]
.as_ref()
.unwrap()
.clone();
assert!(battle.try_set_choice(TurnChoice::Pass(PassChoice::new(p))).unwrap());
}
TestStep::Assert { value, expected } => {
let v = value.get(battle);
assert_eq!(&v, expected)
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,136 +0,0 @@
use hashbrown::HashSet;
use pkmn_lib::static_data::{DataLibrary, EffectParameter, MoveData, MoveLibrary, SecondaryEffect, TypeLibrary};
use pkmn_lib::StringKey;
use project_root::get_project_root;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
pub fn load_types(path: &String) -> TypeLibrary {
let mut type_library = TypeLibrary::new(18);
let mut reader = csv::ReaderBuilder::new()
.delimiter(b'|')
.from_path(path.to_string() + "Types.csv")
.unwrap();
let headers = reader.headers().unwrap();
for header in headers.iter().skip(1) {
type_library.register_type(&StringKey::new(header.clone()));
}
for record in reader.records() {
let record = record.unwrap();
let offensive_type = record.get(0).unwrap();
let offensive_type_id = type_library.get_type_id(&StringKey::new(offensive_type.clone()));
for (i, v) in record.iter().skip(1).enumerate() {
let effectiveness = v.parse::<f32>().unwrap();
type_library.set_effectiveness(offensive_type_id, i as u8, effectiveness);
}
}
type_library
}
pub fn load_moves(path: &String, type_library: &TypeLibrary) -> MoveLibrary {
let mut file = File::open(path.to_string() + "Moves.json").unwrap();
let mut data = String::new();
file.read_to_string(&mut data).unwrap();
let json: Value = serde_json::from_str(&data).unwrap();
let data = json.as_object().unwrap().get("data").unwrap().as_array().unwrap();
let mut move_library = MoveLibrary::new(data.len());
for move_data in data {
let move_data = move_data.as_object().unwrap();
let move_name = StringKey::new(move_data["name"].as_str().unwrap().clone());
let move_type = StringKey::new(move_data["type"].as_str().unwrap());
let move_type_id = type_library.get_type_id(&move_type);
let move_category = serde_json::from_value(move_data["category"].clone()).unwrap();
let base_power = move_data["power"].as_i64().unwrap() as u8;
let accuracy = move_data["accuracy"].as_i64().unwrap() as u8;
let pp = move_data["pp"].as_i64().unwrap() as u8;
let target = serde_json::from_value(move_data["target"].clone()).unwrap();
let priority = move_data["priority"].as_i64().unwrap() as i8;
let secondary_effect = if let Some(v) = move_data.get("effect") {
let mut chance = -1.0;
if let Some(chance_value) = v.get("chance") {
chance = chance_value.as_f64().unwrap() as f32;
}
let mut parameters = Vec::new();
if let Some(pars) = v.get("parameters") {
let pars = pars.as_array().unwrap();
for par in pars {
match par {
Value::Null => {
panic!("Unexpected type")
}
Value::Bool(b) => {
parameters.push(EffectParameter::Bool(*b));
}
Value::Number(n) => {
if n.is_f64() {
parameters.push(EffectParameter::Float(n.as_f64().unwrap() as f32));
} else {
parameters.push(EffectParameter::Int(n.as_i64().unwrap()));
}
}
Value::String(s) => {
parameters.push(EffectParameter::String(s.clone()));
}
Value::Array(_) => {
panic!("Unexpected type")
}
Value::Object(_) => {
panic!("Unexpected type")
}
}
}
}
SecondaryEffect::new(chance, StringKey::new(v["name"].as_str().unwrap().clone()), parameters)
} else {
SecondaryEffect::empty()
};
let mut flags = HashSet::new();
if let Some(f) = move_data.get("flags") {
let f = f.as_array().unwrap();
for flag in f {
flags.insert(StringKey::new(flag.as_str().unwrap()));
}
}
move_library.add(
&move_name,
MoveData::new(
&move_name.clone(),
move_type_id,
move_category,
base_power,
accuracy,
pp,
target,
priority,
secondary_effect,
flags,
),
);
}
move_library
}
#[test]
#[cfg_attr(miri, ignore)]
fn test_type_library_loaded() {
let mut path = get_project_root().unwrap();
path.push("tests/data/");
let lib = load_types(&path.to_str().unwrap().to_string());
assert_eq!(
lib.get_effectiveness(
lib.get_type_id(&StringKey::new("fire")),
&vec![lib.get_type_id(&StringKey::new("grass")),]
),
2.0
);
}

38
tests/main.rs Normal file
View File

@ -0,0 +1,38 @@
#![feature(custom_test_frameworks)]
#![feature(once_cell)]
#![test_runner(datatest::runner)]
use crate::common::{library_loader, TestCase};
use pkmn_lib::dynamic_data::libraries::dynamic_library::DynamicLibrary;
use std::fs::File;
use std::io::Read;
use std::lazy::SyncLazy;
use std::path::Path;
pub mod common;
static LIBRARY: SyncLazy<DynamicLibrary> = SyncLazy::new(|| {
let start_time = chrono::Utc::now();
let lib = library_loader::load_library();
let end_time = chrono::Utc::now();
println!("Built library in {} ms", (end_time - start_time).num_milliseconds());
lib
});
#[test]
#[cfg_attr(miri, ignore)]
fn validate_library_load() {
SyncLazy::force(&LIBRARY);
}
#[datatest::files("tests/test_cases", {
input in r"^(.*)\.yaml"
})]
fn integration_tests(input: &Path) {
let mut str: String = "".to_string();
let mut file = File::open(input).unwrap();
file.read_to_string(&mut str).unwrap();
let test_case = serde_yaml::from_str::<TestCase>(&*str).unwrap();
println!("\tRunning integration test {}", test_case.name);
test_case.run_test(&LIBRARY);
}

View File

@ -0,0 +1,44 @@
name: basic_single_turn
battle_setup:
seed: 10
can_flee: false
number_of_sides: 2
pokemon_per_side: 1
parties:
- indices:
- [ 0, 0 ]
pokemon:
- species: charizard
level: 50
moves:
- ember
- indices:
- [ 1, 0 ]
pokemon:
- species: venusaur
level: 50
moves:
- vine_whip
actions:
- set_pokemon:
place: [ 0, 0 ]
from_party: [ 0 ,0 ]
- set_pokemon:
place: [ 1, 0 ]
from_party: [ 1 ,0 ]
- assert:
value:
pokemon_health:
index: [ 1, 0 ]
expected: 140
- set_move_choice:
for: [ 0, 0 ]
move: ember
target: [ 1, 0 ]
- set_pass_choice:
for: [ 1, 0 ]
- assert:
value:
pokemon_health:
index: [ 1, 0 ]
expected: 78

View File

@ -1,13 +0,0 @@
use project_root::get_project_root;
pub mod library_loader;
#[test]
#[cfg_attr(miri, ignore)]
fn run_integration_tests() {
let mut path = get_project_root().unwrap();
path.push("tests/data/");
let path = path.to_str().unwrap().to_string();
let type_library = library_loader::load_types(&path);
let move_library = library_loader::load_moves(&path, &type_library);
}