mnml/server/src/game.rs
2018-10-23 16:51:12 +11:00

758 lines
19 KiB
Rust
Executable File

use uuid::Uuid;
use rand::prelude::*;
// Db Commons
use serde_cbor::{from_slice, to_vec};
use postgres::transaction::Transaction;
use failure::Error;
use failure::err_msg;
use account::Account;
use rpc::{GameStateParams, GameSkillParams, GamePveParams, GamePvpParams, GameTargetParams, GameJoinParams};
use cryp::{Cryp, cryp_get};
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub struct Roll {
pub base: u64,
pub result: u64,
}
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub enum Skill {
Attack,
Block,
Heal,
}
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub struct GameSkill {
id: Uuid,
skill: Skill,
cryp_id: Uuid,
roll: Option<Roll>,
target_cryp_id: Option<Uuid>,
target_team_id: Uuid,
}
impl GameSkill {
pub fn new(cryp_id: Uuid, target_team_id: Uuid, skill: Skill) -> GameSkill {
return GameSkill {
id: Uuid::new_v4(),
cryp_id,
target_cryp_id: None,
target_team_id,
roll: None,
skill,
};
}
fn roll(&self, c: &Cryp) -> Roll {
let mut rng = thread_rng();
let base: u64 = rng.gen();
let stat = match self.skill {
Skill::Attack => &c.str,
Skill::Block => &c.str,
Skill::Heal => &c.int,
};
let mut roll = Roll { base, result: base };
// // apply skills
// roll = c.skills.iter().fold(roll, |roll, s| s.apply(roll));
// finally combine with stat
println!("{:064b} <- finalised", roll.result);
roll.result = roll.result & stat.value;
println!("{:064b} & <- attribute roll", stat.value);
println!("{:064b} = {:?}", roll.result, roll.result);
println!("");
return roll;
}
pub fn resolve(&mut self, cryp: &mut Cryp, target: &mut Cryp) -> &mut GameSkill {
let roll = self.roll(&cryp);
println!("{:?} gettin clapped for {:?}", target.name, roll.result);
target.hp.reduce(roll.result);
self
}
pub fn set_target(&mut self, cryp_id: Uuid) -> &mut GameSkill {
self.target_cryp_id = Some(cryp_id);
self
}
}
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Team {
id: Uuid,
cryps: Vec<Cryp>,
skills: Vec<GameSkill>,
incoming: Vec<GameSkill>,
}
impl Team {
pub fn new(account: Uuid) -> Team {
return Team {
id: account,
cryps: vec![],
skills: vec![],
incoming: vec![],
};
}
pub fn set_cryps(&mut self, cryps: Vec<Cryp>) -> &mut Team {
self.cryps = cryps;
self
}
pub fn cryp_by_id(&mut self, id: Uuid) -> Option<&mut Cryp> {
self.cryps.iter_mut().find(|c| c.id == id)
}
pub fn skill_by_id(&mut self, id: Uuid) -> &mut GameSkill {
match self.incoming.iter_mut().find(|a| a.id == id) {
Some(a) => a,
None => panic!("abiltity not in game"),
}
}
}
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
pub enum Phase {
Start,
Skill,
Target,
Damage,
Finish,
}
#[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Game {
pub id: Uuid,
pub team_size: usize,
pub team_num: usize,
pub teams: Vec<Team>,
pub is_pve: bool,
pub phase: Phase,
pub log: Vec<String>,
}
impl Game {
fn new() -> Game {
return Game {
id: Uuid::new_v4(),
team_size: 0,
team_num: 0,
teams: vec![],
is_pve: true,
phase: Phase::Start,
log: vec![],
};
}
fn set_team_num(&mut self, size: usize) -> &mut Game {
self.team_num = size;
self
}
fn set_team_size(&mut self, size: usize) -> &mut Game {
self.team_size = size;
self
}
fn set_pve(&mut self, pve: bool) -> &mut Game {
self.is_pve = pve;
self
}
// check team not already in
fn add_team(&mut self, team: Team) -> Result<&mut Game, Error> {
if self.teams.len() == self.team_num {
return Err(err_msg("maximum number of teams"));
}
self.teams.push(team);
Ok(self)
}
// handle missing team properly
fn team_by_id(&mut self, id: Uuid) -> &mut Team {
match self.teams.iter_mut().find(|t| t.id == id) {
Some(t) => t,
None => panic!("id not in game {:?}", id),
}
}
fn cryp_by_id(&mut self, id: Uuid) -> &mut Cryp {
for team in self.teams.iter_mut() {
let in_team = team.cryp_by_id(id);
if in_team.is_some() {
return in_team.unwrap();
}
}
panic!("cryp not in game");
}
// fn update_team(&mut self, updated: Team) -> &mut Game {
// match self.teams.iter().position(|t| t.id == updated.id) {
// Some(index) => {
// self.teams.remove(index);
// self.teams.push(updated);
// self
// }
// None => panic!("team not in game"),
// }
// }
fn update_cryp(&mut self, updated: Cryp) -> &mut Game {
for team in self.teams.iter_mut() {
if let Some(index) = team.cryps.iter().position(|c| c.id == updated.id) {
team.cryps.remove(index);
team.cryps.push(updated);
break;
}
}
self
}
fn can_start(&self) -> bool {
self.teams.len() == self.team_num
}
fn start(&mut self) -> &mut Game {
self.skill_phase_start();
self
}
fn skill_phase_start(&mut self) -> &mut Game {
if ![Phase::Start, Phase::Damage].contains(&self.phase) {
panic!("game not in damage or start phase");
}
self.phase = Phase::Skill;
for team in self.teams.iter_mut() {
team.skills.clear();
team.incoming.clear();
}
if self.is_pve {
self.pve_add_skills();
}
self
}
fn pve_add_skills(&mut self) -> &mut Game {
{
let mob_team_id = Uuid::nil();
let teams = self.teams.clone();
let mobs = self.team_by_id(mob_team_id).clone();
// TODO attack multiple players based on some criteria
let player_team = teams.iter().find(|t| t.id != mob_team_id).unwrap();
for mob in &mobs.cryps {
self.add_skill(mob_team_id, mob.id, player_team.id, Skill::Attack).unwrap();
}
}
self
}
// skills can target any team, but we have to check if the caller is the owner of the cryp
// and that the cryp has the skill they are trying to add
fn add_skill(&mut self, team_id: Uuid, cryp_id: Uuid, target_team_id: Uuid, skill: Skill) -> Result<Uuid, Error> {
if self.phase != Phase::Skill {
return Err(err_msg("game not in skill phase"));
}
let team = self.team_by_id(team_id);
{
let cryp = match team.cryp_by_id(cryp_id) {
Some(c) => c,
None => return Err(err_msg("cryp not in team")),
};
// check the cryp has the skill
if !cryp.skills.contains(&skill) {
return Err(err_msg("cryp does not have that skill"));
}
}
// replace cryp skill
if let Some(s) = team.skills.iter_mut().position(|s| s.cryp_id == cryp_id) {
team.skills.remove(s);
}
let skill = GameSkill::new(cryp_id, target_team_id, skill);
team.skills.push(skill);
return Ok(skill.id);
}
fn skill_phase_finished(&self) -> bool {
self.teams.iter().all(|t| t.skills.len() == self.team_size)
}
// move all skills into their target team's targets list
fn target_phase_start(&mut self) -> &mut Game {
if self.phase != Phase::Skill {
panic!("game not in skill phase");
}
self.phase = Phase::Target;
// have to clone the teams because we change them while iterating
let teams = self.teams.clone();
for mut team in teams {
for skill in team.skills.iter_mut() {
let target_team = self.team_by_id(skill.target_team_id);
target_team.incoming.push(*skill);
}
}
if self.is_pve {
self.pve_add_targets();
}
self
}
fn pve_add_targets(&mut self) -> &mut Game {
{
let mob_team_id = Uuid::nil();
let mobs = self.team_by_id(mob_team_id).clone();
// TODO attack multiple players based on some criteria
for incoming in &mobs.incoming {
self.add_target(mob_team_id, mobs.cryps[0].id, incoming.id).unwrap();
}
}
self
}
// targets can only be added by the owner of the team
fn add_target(&mut self, team_id: Uuid, cryp_id: Uuid, skill_id: Uuid) -> Result<&mut GameSkill, Error> {
// whose team is this?
let team = self.team_by_id(team_id);
// is the target in the team?
match team.cryp_by_id(cryp_id) {
Some(c) => c,
None => return Err(err_msg("cryp not in team")),
};
// set the target
let skill = team.skill_by_id(skill_id);
Ok(skill.set_target(cryp_id))
}
fn target_phase_finished(&self) -> bool {
self.teams.iter().all(|t| t.incoming.iter().all(|i| i.target_cryp_id.is_some()))
}
// requires no input
// just do it
fn damage_phase_start(&mut self) -> &mut Game {
if self.phase != Phase::Target {
panic!("game not in target phase");
}
self.phase = Phase::Damage;
self.resolve_skills();
if self.is_finished() {
return self.finish()
}
self.skill_phase_start();
self
}
fn resolve_skills(&mut self) -> &mut Game {
if self.phase != Phase::Damage {
panic!("game not in damage phase");
}
// sometimes... you just gotta
for team in self.teams.clone().iter_mut() {
for incoming in team.incoming.clone().iter_mut() {
// they better fuckin be there
let mut cryp = self.cryp_by_id(incoming.target_cryp_id.unwrap()).clone();
let mut target_cryp = self.cryp_by_id(incoming.target_cryp_id.unwrap()).clone();
incoming.resolve(&mut cryp, &mut target_cryp);
self.update_cryp(target_cryp);
}
}
self
}
fn is_finished(&self) -> bool {
self.teams.iter().any(|t| t.cryps.iter().all(|c| c.is_ko()))
}
fn finish(&mut self) -> &mut Game {
self.phase = Phase::Finish;
for team in self.teams.iter_mut() {
team.skills.clear();
team.incoming.clear();
}
self
}
}
pub fn game_skill(params: GameSkillParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let query = "
SELECT *
FROM games
WHERE id = $1
";
let result = tx
.query(query, &[&params.game_id])?;
let returned = match result.iter().next() {
Some(row) => row,
None => return Err(err_msg("game not found")),
};
// tells from_slice to cast into a cryp
let game_bytes: Vec<u8> = returned.get("data");
let mut game = from_slice::<Game>(&game_bytes)?;
game.add_skill(account.id, params.cryp_id, params.target_team_id, params.skill)?;
if game.skill_phase_finished() {
game.target_phase_start();
}
game_update(&game, tx)?;
Ok(game)
}
pub fn game_target(params: GameTargetParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let query = "
SELECT *
FROM games
WHERE id = $1
";
let result = tx
.query(query, &[&params.game_id])?;
let returned = match result.iter().next() {
Some(row) => row,
None => return Err(err_msg("game not found")),
};
// tells from_slice to cast into a cryp
let game_bytes: Vec<u8> = returned.get("data");
let mut game = from_slice::<Game>(&game_bytes)?;
game.add_target(account.id, params.cryp_id, params.skill_id)?;
if game.target_phase_finished() {
game.damage_phase_start();
}
game_update(&game, tx)?;
Ok(game)
}
pub fn game_new(game: &Game, tx: &mut Transaction) -> Result<(), Error> {
let game_bytes = to_vec(&game)?;
let query = "
INSERT INTO games (id, data)
VALUES ($1, $2)
RETURNING id;
";
let result = tx
.query(query, &[&game.id, &game_bytes])?;
result.iter().next().ok_or(format_err!("no game written"))?;
println!("{:?} wrote game", game.id);
return Ok(());
}
pub fn game_state(params: GameStateParams, tx: &mut Transaction, _account: &Account) -> Result<Game, Error> {
return game_get(tx, params.id)
}
pub fn game_get(tx: &mut Transaction, id: Uuid) -> Result<Game, Error> {
let query = "
SELECT *
FROM games
WHERE id = $1
";
let result = tx
.query(query, &[&id])?;
let returned = match result.iter().next() {
Some(row) => row,
None => return Err(err_msg("game not found")),
};
// tells from_slice to cast into a cryp
let game_bytes: Vec<u8> = returned.get("data");
let game = from_slice::<Game>(&game_bytes)?;
return Ok(game);
}
/// write a row for every cryp in a team when added to a battle
pub fn players_write(team: &Team, game_id: Uuid, tx: &mut Transaction) -> Result<(), Error> {
// pve
if !team.id.is_nil() {
for cryp in &team.cryps {
let id = Uuid::new_v4();
let query = "
INSERT INTO players (id, game, cryp, account)
VALUES ($1, $2, $3, $4)
RETURNING id, account;
";
let result = tx
.query(query, &[&id, &game_id, &cryp.id, &team.id])?;
let _returned = result.iter().next().expect("no row written");
println!("wrote player entry game:{:?} cryp:{:?} account:{:?}", game_id, cryp.id, team.id);
}
}
return Ok(());
}
pub fn game_update(game: &Game, tx: &mut Transaction) -> Result<(), Error> {
let game_bytes = to_vec(&game)?;
let query = "
UPDATE games
SET data = $1
WHERE id = $2
RETURNING id, data;
";
let result = tx
.query(query, &[&game_bytes, &game.id])?;
result.iter().next().ok_or(format_err!("game {:?} could not be written", game))?;
println!("{:?} wrote game", game.id);
return Ok(());
}
fn generate_mob(plr: &Cryp) -> Cryp {
let mut rng = thread_rng();
// rng panics on min == max
let mob_lvl: u8 = match plr.lvl {
1 => 1,
_ => rng.gen_range(1, plr.lvl)
};
return Cryp::new()
.named(&"bamboo basher".to_string())
.level(mob_lvl)
.create();
}
pub fn game_pve(params: GamePveParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let query = "
SELECT *
FROM cryps
WHERE id = $1
AND account = $2;
";
let result = tx
.query(query, &[&params.id, &account.id])?;
let returned = match result.iter().next() {
Some(row) => row,
None => return Err(err_msg("cryp not found")),
};
// tells from_slice to cast into a cryp
let cryp_bytes: Vec<u8> = returned.get("data");
let plr: Cryp = from_slice::<Cryp>(&cryp_bytes)?;
// TEMP
if plr.hp.value == 0 {
return Err(err_msg("cryp is ko"));
// plr.rez();
}
let mob = generate_mob(&plr);
let mut game = Game::new();
let game_id = game.id;
game
.set_team_num(2)
.set_team_size(1);
let mut plr_team = Team::new(account.id);
plr_team
.set_cryps(vec![plr]);
let mut mob_team = Team::new(Uuid::nil());
mob_team
.set_cryps(vec![mob]);
game
.add_team(plr_team)?
.add_team(mob_team)?;
game.start();
// persist
game_new(&game, tx)?;
players_write(&game.team_by_id(account.id), game_id, tx)?;
Ok(game)
}
pub fn game_pvp(params: GamePvpParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let cryps = params.cryp_ids
.iter()
.map(|id| cryp_get(tx, *id, account.id))
.collect::<Result<Vec<Cryp>, Error>>()?;
// create the game
let mut game = Game::new();
let game_id = game.id;
game
.set_pve(false)
.set_team_num(2)
.set_team_size(1);
// create the initiators team
let mut team = Team::new(account.id);
team.set_cryps(cryps);
game.add_team(team)?;
// persist
game_new(&game, tx)?;
players_write(&game.team_by_id(account.id), game_id, tx)?;
Ok(game)
}
pub fn game_join(params: GameJoinParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let mut game = game_get(tx, params.game_id)?;
let game_id = game.id;
let cryps = params.cryp_ids
.iter()
.map(|id| cryp_get(tx, *id, account.id))
.collect::<Result<Vec<Cryp>, Error>>()?;
let mut team = Team::new(account.id);
team.set_cryps(cryps);
game.add_team(team)?;
if game.can_start() {
game.start();
}
game_update(&game, tx)?;
players_write(&game.team_by_id(account.id), game_id, tx)?;
Ok(game)
}
#[cfg(test)]
mod tests {
use game::*;
use cryp::*;
#[test]
fn game_test() {
let x = Cryp::new()
.named(&"pronounced \"creeep\"".to_string())
.level(8)
.create();
let x_id = x.id;
let y = Cryp::new()
.named(&"lemongrass tea".to_string())
.level(8)
.create();
let y_id = y.id;
let mut game = Game::new();
game
.set_team_num(2)
.set_team_size(1)
.set_pve(false);
let x_team_id = Uuid::new_v4();
let mut x_team = Team::new(x_team_id);
x_team
.set_cryps(vec![x]);
let y_team_id = Uuid::new_v4();
let mut y_team = Team::new(y_team_id);
y_team
.set_cryps(vec![y]);
game
.add_team(x_team).unwrap()
.add_team(y_team).unwrap();
assert!(game.can_start());
game.start();
let x_attack_id = game.add_skill(x_team_id, x_id, y_team_id, Skill::Attack);
let y_attack_id = game.add_skill(y_team_id, y_id, x_team_id, Skill::Attack);
assert!(game.skill_phase_finished());
game.target_phase_start();
println!("{:?}", game);
game.add_target(x_team_id, x_id, y_attack_id.unwrap()).unwrap();
game.add_target(y_team_id, y_id, x_attack_id.unwrap()).unwrap();
assert!(game.target_phase_finished());
game.damage_phase_start();
assert!([Phase::Skill, Phase::Finish].contains(&game.phase));
println!("{:?}", game);
return;
}
}