use uuid::Uuid; use rand::prelude::*; use serde_cbor::{from_slice, to_vec}; use postgres::transaction::Transaction; use failure::Error; use failure::err_msg; use account::Account; use rpc::{CrypSpawnParams, CrypLearnParams, CrypForgetParams, CrypUnspecParams}; use skill::{Skill, Cooldown, Effect, Cast, Category, Immunity, Disable, ResolutionResult}; use spec::{Spec, SpecLevel}; use game::{Log}; #[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)] pub struct CrypSkill { pub skill: Skill, pub self_targeting: bool, pub cd: Cooldown, } impl CrypSkill { pub fn new(skill: Skill) -> CrypSkill { CrypSkill { skill, self_targeting: skill.self_targeting(), cd: skill.base_cd(), } } } #[derive(Debug,Clone,PartialEq,Serialize,Deserialize)] pub struct CrypEffect { pub effect: Effect, pub duration: u8, pub tick: Option, } #[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)] pub enum Stat { Str, Agi, Int, Hp, Speed, Stamina, PhysicalDamage, PhysicalDamageTaken, SpellDamage, SpellDamageTaken, Healing, HealingTaken, Armour, SpellShield, Evasion, } #[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)] pub struct CrypStat { base: u64, value: u64, pub stat: Stat, } impl CrypStat { pub fn set(&mut self, v: u64, specs: &CrypSpecs) -> &mut CrypStat { self.base = v; self.recalculate(specs) } pub fn recalculate(&mut self, specs: &CrypSpecs) -> &mut CrypStat { let specs = specs.affects(self.stat); // applied with fold because it can be zeroed or multiplied // but still needs access to the base amount let value = specs.iter().fold(self.base, |acc, s| s.apply(acc, self.base)); self.value = value; self } pub fn reduce(&mut self, amt: u64) -> &mut CrypStat { self.value = self.value.saturating_sub(amt); self } pub fn increase(&mut self, amt: u64) -> &mut CrypStat { self.value = self.value.saturating_add(amt); self } pub fn force(&mut self, v: u64) -> &mut CrypStat { self.base = v; self.value = v; self } } #[derive(Debug,Clone,Serialize,Deserialize)] pub struct CrypSpecs { common: Vec, uncommon: Vec, rare: Vec, } impl CrypSpecs { fn new() -> CrypSpecs { CrypSpecs { common: vec![], uncommon: vec![], rare: vec![], } } fn affects(&self, stat: Stat) -> Vec { [&self.common, &self.uncommon, &self.rare] .iter() .flat_map(|specs| specs.iter().filter(|s| s.affects == stat)) .map(|s| *s) .collect::>() } } #[derive(Debug,Clone,Serialize,Deserialize)] pub struct CrypRecover { pub id: Uuid, pub account: Uuid, pub xp: u64, pub lvl: u8, pub name: String, } #[derive(Debug,Clone,Serialize,Deserialize)] pub struct Cryp { pub id: Uuid, pub account: Uuid, pub phys_dmg: CrypStat, pub spell_dmg: CrypStat, pub speed: CrypStat, pub stamina: CrypStat, pub hp: CrypStat, pub armour: CrypStat, pub spell_shield: CrypStat, pub evasion: CrypStat, pub xp: u64, pub lvl: u8, pub skills: Vec, pub effects: Vec, pub specs: CrypSpecs, pub name: String, pub ko_logged: bool, } fn check_lvl(lvl: u8) -> u8 { if lvl > 64 { return 64; } return lvl; } impl Cryp { pub fn new() -> Cryp { let id = Uuid::new_v4(); return Cryp { id, account: id, phys_dmg: CrypStat { base: 0, value: 0, stat: Stat::PhysicalDamage }, spell_dmg: CrypStat { base: 0, value: 0, stat: Stat::SpellDamage }, speed: CrypStat { base: 0, value: 0, stat: Stat::Speed }, stamina: CrypStat { base: 0, value: 0, stat: Stat::Stamina }, hp: CrypStat { base: 0, value: 0, stat: Stat::Hp }, armour: CrypStat { base: 0, value: 0, stat: Stat::Armour }, spell_shield: CrypStat { base: 0, value: 0, stat: Stat::SpellShield }, evasion: CrypStat { base: 0, value: 0, stat: Stat::Evasion }, lvl: 0, xp: 0, skills: vec![], effects: vec![], specs: CrypSpecs::new(), name: String::new(), ko_logged: false, }; } pub fn named(mut self, name: &String) -> Cryp { self.name = name.clone(); self } pub fn set_account(mut self, account: Uuid) -> Cryp { self.account = account; self } pub fn level(mut self, lvl: u8) -> Cryp { self.lvl = check_lvl(lvl); self } pub fn learn(mut self, s: Skill) -> Cryp { self.skills.push(CrypSkill::new(s)); self } pub fn forget(mut self, skill: Skill) -> Result { match self.skills.iter().position(|s| s.skill == skill) { Some(i) => { self.skills.remove(i); return Ok(self); }, None => Err(format_err!("{:?} does not know {:?}", self.name, skill)), } } // pub fn add_xp(mut self) -> Cryp { // self.xp = self.xp.saturating_add(1); // if self.xp.is_power_of_two() { // return self.level_up(); // } // self // } // pub fn level_up(mut self) -> Cryp { // self.lvl = self.lvl.saturating_add(1); // self.create() // } pub fn roll_stat(&mut self, stat: Stat) -> &mut Cryp { let mut rng = thread_rng(); let stam_min = 512u64.saturating_mul(self.lvl.into()); let stam_max = 1024u64.saturating_mul(self.lvl.into()); let stat_min = 128u64.saturating_mul(self.lvl.into()); let stat_max = 256u64.saturating_mul(self.lvl.into()); let evasion_min = 1u64; let evasion_max = 5; match stat { Stat::PhysicalDamage => self.phys_dmg.set(rng.gen_range(stat_min, stat_max), &self.specs), Stat::SpellDamage => self.spell_dmg.set(rng.gen_range(stat_min, stat_max), &self.specs), Stat::Speed => self.speed.set(rng.gen_range(stat_min, stat_max), &self.specs), Stat::Stamina => { self.stamina.set(rng.gen_range(stam_min, stam_max), &self.specs); self.hp.set(self.stamina.base, &self.specs) }, Stat::SpellShield => self.spell_shield.set(rng.gen_range(stat_min, stat_max), &self.specs), Stat::Armour => self.armour.set(rng.gen_range(stat_min, stat_max), &self.specs), Stat::Evasion => self.evasion.set(rng.gen_range(evasion_min, evasion_max), &self.specs), _ => panic!("{:?} not a rollable stat", stat), }; self } pub fn create(mut self) -> Cryp { let xp = match self.lvl == 64 { true => u64::max_value(), false => 2_u64.pow(self.lvl.into()), }; self.xp = xp; self.roll_stat(Stat::PhysicalDamage); self.roll_stat(Stat::SpellDamage); self.roll_stat(Stat::Speed); self.roll_stat(Stat::Stamina); self } pub fn spec_add(&mut self, spec: Spec) -> Result<&mut Cryp, Error> { let max_common = 20; let max_uncommon = 10; let max_rare = 5; match spec.level { SpecLevel::Common => { if self.specs.common.len() >= max_common { return Err(format_err!("cryp at maximum common specalisations ({:})", max_common)) } self.specs.common.push(spec); }, SpecLevel::Uncommon => { if self.specs.uncommon.len() >= max_uncommon { return Err(format_err!("cryp at maximum uncommon specalisations ({:})", max_uncommon)) } self.specs.uncommon.push(spec); }, SpecLevel::Rare => { if self.specs.rare.len() >= max_rare { return Err(format_err!("cryp at maximum rare specalisations ({:})", max_rare)) } if self.specs.rare.iter().find(|s| s.spec == spec.spec).is_some() { return Err(format_err!("duplicate rare specialisation {:?}", spec.spec)); } self.specs.rare.push(spec); }, }; return Ok(self.recalculate_stats()); } pub fn spec_remove(mut self, spec: Spec) -> Result { let find_spec = |spec_v: &Vec| spec_v.iter().position(|s| s.spec == spec.spec); match spec.level { SpecLevel::Common => match find_spec(&self.specs.common) { Some(p) => self.specs.common.remove(p), None => return Err(err_msg("spec not found")), }, SpecLevel::Uncommon => match find_spec(&self.specs.uncommon) { Some(p) => self.specs.uncommon.remove(p), None => return Err(err_msg("spec not found")), }, SpecLevel::Rare => match find_spec(&self.specs.rare) { Some(p) => self.specs.rare.remove(p), None => return Err(err_msg("spec not found")), }, }; Ok(self) } fn recalculate_stats(&mut self) -> &mut Cryp { self.stamina.recalculate(&self.specs); self.hp.recalculate(&self.specs); self.phys_dmg.recalculate(&self.specs); self.spell_dmg.recalculate(&self.specs); self.evasion.recalculate(&self.specs); self.armour.recalculate(&self.specs); self.spell_shield.recalculate(&self.specs); self.speed.recalculate(&self.specs); self } pub fn is_ko(&self) -> bool { self.hp.value == 0 } pub fn immune(&self, skill: Skill) -> Immunity { if self.is_ko() { return Immunity { immune: true, effects: vec![Effect::Ko]}; } let immunities = self.effects.iter() .filter(|e| e.effect.immune(skill)) .map(|e| e.effect) .collect::>(); if immunities.len() > 0 { return Immunity { immune: true, effects: immunities}; } return Immunity { immune: false, effects: vec![]}; } pub fn disabled(&self, skill: Skill) -> Disable { if self.is_ko() && !skill.ko_castable() { return Disable { disabled: true, effects: vec![Effect::Ko]}; } let disables = self.effects.iter() .filter(|e| e.effect.disables_skill(skill)) .map(|e| e.effect) .collect::>(); if disables.len() > 0 { return Disable { disabled: true, effects: disables}; } return Disable { disabled: false, effects: vec![]}; } pub fn is_stunned(&self) -> bool { self.effects.iter().any(|s| s.effect == Effect::Stun) } pub fn available_skills(&self) -> Vec<&CrypSkill> { self.skills.iter() .filter(|s| s.cd.is_none()) .filter(|s| !self.disabled(s.skill).disabled) .collect() } pub fn mob_select_skill(&self) -> Option { let available = self.available_skills(); if available.len() == 0 { return None; } let highest_cd = available.iter() .filter(|s| s.skill.base_cd().is_some()) .max_by_key(|s| s.skill.base_cd().unwrap()); return match highest_cd { Some(s) => Some(s.skill), None => Some(available[0].skill), }; } pub fn knows(&self, skill: Skill) -> bool { self.skills.iter().any(|s| s.skill == skill) } pub fn skill_on_cd(&self, skill: Skill) -> Option<&CrypSkill> { self.skills.iter().find(|s| s.skill == skill && s.cd.is_some()) } pub fn skill_set_cd(&mut self, skill: Skill) -> &mut Cryp { let i = self.skills.iter().position(|s| s.skill == skill).unwrap(); self.skills.remove(i); self.skills.push(CrypSkill::new(skill)); self } pub fn reduce_cooldowns(&mut self) -> &mut Cryp { for skill in self.skills.iter_mut() { // if used cooldown if skill.skill.base_cd().is_some() { // what is the current cd if let Some(current_cd) = skill.cd { // if it's 1 set it to none if current_cd == 1 { skill.cd = None; continue; } // otherwise decrement it skill.cd = Some(current_cd.saturating_sub(1)); } } } self } pub fn reduce_effect_durations(&mut self, _log: &mut Log) -> &mut Cryp { self.effects = self.effects.clone().into_iter().filter_map(|mut effect| { effect.duration = effect.duration.saturating_sub(1); if effect.duration == 0 { return None; } // println!("reduced effect {:?}", effect); return Some(effect); }).collect::>(); self } // pub fn rez(&mut self) -> &mut Cryp { // self.hp.set(self.stamina.base); // self // } // Stats pub fn phys_dmg(&self) -> u64 { let phys_dmg_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::PhysicalDamage)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); let modified_phys_dmg = phys_dmg_mods.iter().fold(self.phys_dmg.value, |acc, m| m.apply(acc)); return modified_phys_dmg; } pub fn spell_dmg(&self) -> u64 { let spell_dmg_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::SpellDamage)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); let modified_spell_dmg = spell_dmg_mods.iter().fold(self.spell_dmg.value, |acc, m| m.apply(acc)); return modified_spell_dmg; } pub fn skill_speed(&self, s: Skill) -> u64 { self.speed().saturating_mul(s.speed() as u64) } pub fn speed(&self) -> u64 { let speed_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::Speed)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); let modified_speed = speed_mods.iter().fold(self.speed.value, |acc, m| m.apply(acc)); return modified_speed; } pub fn hp(&self) -> u64 { self.hp.value } pub fn stamina(&self) -> u64 { self.stamina.value } pub fn heal(&mut self, skill: Skill, amount: u64) -> ResolutionResult { let immunity = self.immune(skill); let immune = immunity.immune; if immune { ResolutionResult::Healing { amount: 0, overhealing: 0, category: Category::PhysHeal, immunity: immunity.clone(), }; } let healing_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::HealingTaken)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); // println!("{:?}", healing_mods); let modified_healing = healing_mods.iter().fold(amount, |acc, m| m.apply(acc)); let current_hp = self.hp(); let new_hp = *[ self.hp().saturating_add(modified_healing), self.stamina() ].iter().min().unwrap(); let healing = new_hp - current_hp; let overhealing = amount - healing; self.hp.increase(healing); return ResolutionResult::Healing { amount: healing, overhealing, category: Category::PhysHeal, immunity, }; } pub fn deal_phys_dmg(&mut self, skill: Skill, amount: u64) -> ResolutionResult { let immunity = self.immune(skill); let immune = immunity.immune; if immune { return ResolutionResult::Damage { amount: 0, mitigation: 0, category: Category::PhysDmg, immunity, }; } let phys_dmg_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::PhysicalDamageTaken)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); // println!("{:?}", phys_dmg_mods); let modified_dmg = phys_dmg_mods.iter().fold(amount, |acc, m| m.apply(acc)); // calculate amount of damage armour will not absorb // eg 50 armour 25 dmg -> 0 remainder 25 mitigation // 50 armour 100 dmg -> 50 remainder 50 mitigation // 50 armour 5 dmg -> 0 remainder 5 mitigation let remainder = modified_dmg.saturating_sub(self.armour.value); let mitigation = modified_dmg.saturating_sub(remainder); // reduce armour by mitigation amount self.armour.reduce(mitigation); // deal remainder to hp self.hp.reduce(remainder); return ResolutionResult::Damage { amount: remainder, mitigation, category: Category::PhysDmg, immunity, }; } pub fn deal_spell_dmg(&mut self, skill: Skill, amount: u64) -> ResolutionResult { let immunity = self.immune(skill); let immune = immunity.immune; if immune { return ResolutionResult::Damage { amount: 0, mitigation: 0, category: Category::SpellDmg, immunity, }; } let spell_dmg_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::SpellDamageTaken)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); // println!("{:?}", spell_dmg_mods); let modified_dmg = spell_dmg_mods.iter().fold(amount, |acc, m| m.apply(acc)); let remainder = modified_dmg.saturating_sub(self.armour.value); let mitigation = modified_dmg.saturating_sub(remainder); self.armour.reduce(mitigation); self.hp.reduce(remainder); return ResolutionResult::Damage { amount: remainder, mitigation, category: Category::SpellDmg, immunity, }; } pub fn add_effect(&mut self, skill: Skill, effect: CrypEffect) -> ResolutionResult { let immunity = self.immune(skill); let immune = immunity.immune; // todo modified durations cause of buffs let result = ResolutionResult::Effect { effect: effect.effect, duration: effect.effect.duration(), immunity, }; if !immune { // println!("{:?} {:?} adding effect", self.name, effect.effect); self.effects.push(effect); } return result; } pub fn evade(&self, skill: Skill) -> Option { if self.evasion.value == 0 { return None; } let mut rng = thread_rng(); let hp_pct = (self.hp.value * 100) / self.stamina.value; let evasion_rating = (self.evasion.value * hp_pct) / 100; let roll = rng.gen_range(0, 100); println!("{:} < {:?}", roll, evasion_rating); match roll < evasion_rating { true => Some(ResolutionResult::Evasion { skill, evasion_rating: evasion_rating, }), false => None, } } } pub fn cryp_get(tx: &mut Transaction, id: Uuid, account_id: Uuid) -> Result { let query = " SELECT data FROM cryps WHERE id = $1 AND account = $2; "; let result = tx .query(query, &[&id, &account_id])?; let result = result.iter().next().ok_or(format_err!("cryp {:} not found", id))?; let cryp_bytes: Vec = result.get(0); let cryp = from_slice::(&cryp_bytes)?; return Ok(cryp); } pub fn cryp_spawn(params: CrypSpawnParams, tx: &mut Transaction, account: &Account) -> Result { let cryp = Cryp::new() .named(¶ms.name) .learn(Skill::Attack) .level(1) .set_account(account.id) .create(); let cryp_bytes = to_vec(&cryp)?; let query = " INSERT INTO cryps (id, account, data) VALUES ($1, $2, $3) RETURNING id, account; "; let result = tx .query(query, &[&cryp.id, &account.id, &cryp_bytes])?; let _returned = result.iter().next().ok_or(err_msg("no row returned"))?; // println!("{:?} spawned cryp {:}", account.id, cryp.id); return Ok(cryp); } pub fn cryp_learn(params: CrypLearnParams, tx: &mut Transaction, account: &Account) -> Result { let mut cryp = cryp_get(tx, params.id, account.id)?; // done here because i teach them a tonne of skills for tests let max_skills = 4; if cryp.skills.len() >= max_skills { return Err(format_err!("cryp at max skills ({:?})", max_skills)); } cryp = cryp.learn(params.skill); return cryp_write(cryp, tx); } pub fn cryp_forget(params: CrypForgetParams, tx: &mut Transaction, account: &Account) -> Result { let mut cryp = cryp_get(tx, params.id, account.id)?; cryp = cryp.forget(params.skill)?; return cryp_write(cryp, tx); } pub fn cryp_unspec(params: CrypUnspecParams, tx: &mut Transaction, account: &Account) -> Result { let mut cryp = cryp_get(tx, params.id, account.id)?; cryp = cryp.spec_remove(params.spec)?; return cryp_write(cryp, tx); } pub fn cryp_write(cryp: Cryp, tx: &mut Transaction) -> Result { let cryp_bytes = to_vec(&cryp)?; let query = " UPDATE cryps SET data = $1 WHERE id = $2 RETURNING id, account, data; "; let result = tx .query(query, &[&cryp_bytes, &cryp.id])?; let _returned = result.iter().next().expect("no row returned"); // println!("{:?} wrote cryp", cryp.id); return Ok(cryp); } #[cfg(test)] mod tests { use cryp::*; // use skill::*; #[test] fn create_cryp_test() { let max_level = Cryp::new() .named(&"hatchling".to_string()) .level(64) // .learn(Skill::Stoney) .create(); assert_eq!(max_level.lvl, 64); return; } }