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}; use skill::{Skill, Cooldown, Effect, Cast, Immunity, Disable}; 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.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, PhysDmg, SpellDmg, Hp, Stamina, } #[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)] pub struct CrypStat { base: u64, pub stat: Stat, } impl CrypStat { pub fn set(&mut self, v: u64) -> &CrypStat { self.base = v; self } pub fn reduce(&mut self, amt: u64) -> &mut CrypStat { self.base = self.base.saturating_sub(amt); self } pub fn increase(&mut self, amt: u64) -> &mut CrypStat { self.base = self.base.saturating_add(amt); self } } #[derive(Debug,Clone,Serialize,Deserialize)] pub struct Cryp { pub id: Uuid, pub account: Uuid, pub phys_dmg: CrypStat, pub spell_dmg: CrypStat, pub stamina: CrypStat, pub hp: CrypStat, pub xp: u64, pub lvl: u8, pub skills: Vec, pub effects: Vec, pub name: String, } 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, stat: Stat::PhysDmg }, spell_dmg: CrypStat { base: 0, stat: Stat::SpellDmg }, stamina: CrypStat { base: 0, stat: Stat::Stamina }, hp: CrypStat { base: 0, stat: Stat::Hp }, lvl: 0, xp: 0, skills: vec![CrypSkill::new(Skill::Attack)], effects: vec![], name: String::new() }; } 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 create(mut self) -> Cryp { let mut rng = thread_rng(); let max = match self.lvl == 64 { true => u64::max_value(), false => 2_u64.pow(self.lvl.saturating_sub(1).into()), }; let min = match self.lvl == 1 { true => 2_u64, false => 2_u64.pow(self.lvl.saturating_sub(2).into()), }; self.xp = max; self.phys_dmg.set(rng.gen_range(min, max)); self.spell_dmg.set(rng.gen_range(min, max)); self.stamina.set(rng.gen_range(min, max)); self.hp.set(self.stamina.base); self } pub fn is_ko(&self) -> bool { self.hp.base == 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() { 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 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 let Some(cd) = skill.skill.cd() { // if the cd is 1 it becomes none if cd == 1 { // println!("{:?} is now off cd", skill.skill); skill.cd = None; continue; } // otherwise decrement it skill.cd = Some(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::PhysDmg)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); // println!("{:?} phys_dmg mods : {:?}", self.name, phys_dmg_mods); let modified_phys_dmg = phys_dmg_mods.iter().fold(self.phys_dmg.base, |acc, m| m.apply(acc)); // println!("{:?} phys_dmg : {:?}", self.name, modified_phys_dmg); return modified_phys_dmg; } pub fn spell_dmg(&self) -> u64 { let spell_dmg_mods = self.effects.iter() .filter(|e| e.effect.modifications().contains(&Stat::SpellDmg)) .map(|cryp_effect| cryp_effect.effect) .collect::>(); // println!("{:?} spell_dmg mods : {:?}", self.name, spell_dmg_mods); let modified_spell_dmg = spell_dmg_mods.iter().fold(self.spell_dmg.base, |acc, m| m.apply(acc)); // println!("{:?} spell_dmg : {:?}", self.name, modified_spell_dmg); return modified_spell_dmg; } pub fn hp(&self) -> u64 { self.hp.base } pub fn stamina(&self) -> u64 { self.stamina.base } // Stat modifications pub fn heal(&mut self, amount: u64) -> (u64, u64) { let current_hp = self.hp(); let new_hp = *[ self.hp().saturating_add(amount), self.stamina() ].iter().min().unwrap(); self.hp.set(new_hp); let healing = new_hp - current_hp; let overhealing = amount - healing; return (healing, overhealing); } pub fn deal_phys_dmg(&mut self, amount: u64) -> (u64, u64) { self.hp.reduce(amount); // println!("{:?} dealt {:?} phys dmg", self.name, amount); return (amount, 0); } pub fn deal_spell_dmg(&mut self, amount: u64) -> (u64, u64) { self.hp.reduce(amount); return (amount, 0); } } 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) .level(10) .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_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; } } // pub fn assign_str(&mut self, opp: &Cryp, plr_t: &mut Turn, opp_t: &Turn) -> &mut Cryp { // // let final_str = opp_t.phys_dmg.result.saturating_sub(plr_t.agi.result); // // let blocked = opp_t.phys_dmg.result.saturating_sub(final_str); // let final_str = opp_t.phys_dmg.result & !plr_t.agi.result; // let blocked = opp_t.phys_dmg.result & plr_t.agi.result; // plr_t.log.push(format!("{:064b} <- attacking roll {:?}", opp_t.phys_dmg.result, opp_t.phys_dmg.result)); // // plr_t.log.push(format!("{:064b} <- blocking roll {:?}", plr_t.agi.result, plr_t.agi.result)); // plr_t.log.push(format!("{:064b} <- final str {:?} ({:?} blocked)", final_str, final_str, blocked)); // self.hp.reduce(final_str); // plr_t.log.push(format!("{:?} deals {:?} str to {:?} ({:?} blocked / {:?} hp remaining)" // ,opp.name // ,final_str // ,self.name // ,blocked // ,self.hp.base)); // plr_t.log.push(format!("")); // self // } // fn roll(&self, c: &Cryp, log: &mut Vec) -> Roll { // let mut rng = thread_rng(); // let base: u64 = rng.gen(); // let mut roll = Roll { kind: self.kind, base, result: base }; // log.push(format!("{:?}", self.kind)); // log.push(format!("{:064b} <- base roll", base)); // // apply skills // roll = c.skills.iter().fold(roll, |roll, s| s.apply(roll)); // // finally combine with CrypStat // log.push(format!("{:064b} <- finalised", roll.result)); // roll.result = roll.result & self.base; // log.push(format!("{:064b} & <- attribute roll", self.base)); // log.push(format!("{:064b} = {:?}", roll.result, roll.result)); // log.push(format!("")); // return roll; // }