rename battle -> game

This commit is contained in:
ntr 2018-10-20 12:06:00 +11:00
parent 9419b1cc3d
commit 5a3a126086
15 changed files with 163 additions and 123 deletions

View File

@ -7,8 +7,8 @@ export const setCryps = (value) => ({ type: SET_CRYPS, value });
export const SET_ITEMS = 'SET_ITEMS'; export const SET_ITEMS = 'SET_ITEMS';
export const setItems = (value) => ({ type: SET_ITEMS, value }); export const setItems = (value) => ({ type: SET_ITEMS, value });
export const SET_BATTLE = 'SET_BATTLE'; export const SET_GAME = 'SET_GAME';
export const setBattle = (value) => ({ type: SET_BATTLE, value }); export const setGame = (value) => ({ type: SET_GAME, value });
export const SET_ACTIVE_CRYP = 'SET_ACTIVE_CRYP'; export const SET_ACTIVE_CRYP = 'SET_ACTIVE_CRYP';
export const setActiveCryp = (value) => ({ type: SET_ACTIVE_CRYP, value }); export const setActiveCryp = (value) => ({ type: SET_ACTIVE_CRYP, value });

View File

@ -1,19 +0,0 @@
const preact = require('preact');
function CrypPanel({ battle }) {
if (!battle) return <div>...</div>;
return (
<div>{JSON.stringify(battle)}</div>
)
// return (
// <div className="">
// <div>{JSON.stringify(battle.a)}</div>
// <div>{JSON.stringify(battle.b)}</div>
// <div>
// {battle.log.map((l, i) => (<p key={i} >{l}</p>))}
// </div>
// </div>
// );
}
module.exports = CrypPanel;

View File

@ -4,7 +4,7 @@ const preact = require('preact');
const ItemListContainer = require('./item.list.container'); const ItemListContainer = require('./item.list.container');
const CrypSpawnContainer = require('./cryp.spawn.container'); const CrypSpawnContainer = require('./cryp.spawn.container');
const CrypListContainer = require('./cryp.list.container'); const CrypListContainer = require('./cryp.list.container');
const BattleContainer = require('./battle.container'); const GameContainer = require('./game.container');
function renderBody() { function renderBody() {
return ( return (
@ -25,7 +25,7 @@ function renderBody() {
</div> </div>
</div> </div>
<div className="column"> <div className="column">
<BattleContainer /> <GameContainer />
</div> </div>
</section> </section>
); );

View File

@ -1,16 +1,16 @@
const { connect } = require('preact-redux'); const { connect } = require('preact-redux');
const Battle = require('./battle'); const Game = require('./game');
const addState = connect( const addState = connect(
function receiveState(state) { function receiveState(state) {
const { battle } = state; const { game } = state;
// function sendCombatPve(crypId) { // function sendCombatPve(crypId) {
// return ws.sendCombatPve(crypId); // return ws.sendCombatPve(crypId);
// } // }
return { battle }; return { game };
} }
); );
module.exports = addState(Battle); module.exports = addState(Game);

View File

@ -0,0 +1,19 @@
const preact = require('preact');
function GamePanel({ game }) {
if (!game) return <div>...</div>;
return (
<div>{JSON.stringify(game)}</div>
)
// return (
// <div className="">
// <div>{JSON.stringify(game.a)}</div>
// <div>{JSON.stringify(game.b)}</div>
// <div>
// {game.log.map((l, i) => (<p key={i} >{l}</p>))}
// </div>
// </div>
// );
}
module.exports = GamePanel;

View File

@ -18,7 +18,7 @@ const store = createStore(
combineReducers({ combineReducers({
activeItem: reducers.activeItemReducer, activeItem: reducers.activeItemReducer,
account: reducers.accountReducer, account: reducers.accountReducer,
battle: reducers.battleReducer, game: reducers.gameReducer,
cryps: reducers.crypsReducer, cryps: reducers.crypsReducer,
items: reducers.itemsReducer, items: reducers.itemsReducer,
ws: reducers.wsReducer, ws: reducers.wsReducer,

View File

@ -40,10 +40,10 @@ function activeItemReducer(state = defaultActiveItem, action) {
} }
} }
const defaultBattle = null; const defaultGame = null;
function battleReducer(state = defaultBattle, action) { function gameReducer(state = defaultGame, action) {
switch (action.type) { switch (action.type) {
case actions.SET_BATTLE: case actions.SET_GAME:
return action.value; return action.value;
default: default:
return state; return state;
@ -62,7 +62,7 @@ function wsReducer(state = defaultWs, action) {
module.exports = { module.exports = {
activeItemReducer, activeItemReducer,
battleReducer, gameReducer,
accountReducer, accountReducer,
crypsReducer, crypsReducer,
itemsReducer, itemsReducer,

View File

@ -69,9 +69,9 @@ function createSocket(store) {
console.log('got my cryps', cryps); console.log('got my cryps', cryps);
} }
function battleState(response) { function gameState(response) {
const [structName, battle] = response; const [structName, game] = response;
store.dispatch(actions.setBattle(battle)); store.dispatch(actions.setGame(game));
} }
function crypSpawn(response) { function crypSpawn(response) {
@ -80,8 +80,8 @@ function createSocket(store) {
} }
function combatPve(response) { function combatPve(response) {
const [structName, battle] = response; const [structName, game] = response;
console.log('got a new battle', battle); console.log('got a new game', game);
} }
function itemList(response) { function itemList(response) {
@ -124,7 +124,7 @@ function createSocket(store) {
const handlers = { const handlers = {
cryp_spawn: crypSpawn, cryp_spawn: crypSpawn,
combat_pve: combatPve, combat_pve: combatPve,
battle_state: battleState, game_state: gameState,
account_login: accountLogin, account_login: accountLogin,
account_create: accountLogin, account_create: accountLogin,
account_cryps: accountCryps, account_cryps: accountCryps,

View File

@ -0,0 +1,40 @@
exports.up = async knex => {
knex.schema.createTable('games', table => {
table.uuid('id').primary();
table.timestamps();
table.binary('data').notNullable();
table.index('id');
});
knex.schema.createTable('combatants', table => {
table.uuid('id').primary();
table.index('id');
// the game itself
table.uuid('game').notNullable()
table.foreign('game')
.references('id')
.inTable('games')
.onDelete('CASCADE');
table.index('game');
// cryp in a game
table.uuid('cryp').notNullable()
table.foreign('cryp')
.references('id')
.inTable('cryps')
.onDelete('CASCADE');
table.index('cryp');
// account in a game
table.uuid('account').notNullable()
table.foreign('account')
.references('id')
.inTable('accounts')
.onDelete('CASCADE');
table.index('account');
});
};
exports.down = async () => {};

View File

@ -74,7 +74,7 @@ gem td style attr combinations
* 1: Fighting against human nature is a losing battle * 1: Fighting against human nature is a losing game
* 2: Aesthetics matter * 2: Aesthetics matter
* 3: Resonance is important * 3: Resonance is important
* 4: Make use of piggybacking * 4: Make use of piggybacking

View File

@ -11,7 +11,7 @@ use account::Account;
use rpc::{CombatPveParams}; use rpc::{CombatPveParams};
use cryp::{Cryp, cryp_write}; use cryp::{Cryp, cryp_write};
use battle::{Battle, Team}; use game::{Game, Team};
// use skill::Skill; // use skill::Skill;
fn generate_mob(plr: &Cryp) -> Cryp { fn generate_mob(plr: &Cryp) -> Cryp {
@ -30,7 +30,7 @@ fn generate_mob(plr: &Cryp) -> Cryp {
} }
pub fn pve(params: CombatPveParams, tx: &mut Transaction, account: &Account) -> Result<Battle, Error> { pub fn pve(params: CombatPveParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let query = " let query = "
SELECT * SELECT *
FROM cryps FROM cryps
@ -58,9 +58,9 @@ pub fn pve(params: CombatPveParams, tx: &mut Transaction, account: &Account) ->
let mob = generate_mob(&plr); let mob = generate_mob(&plr);
let mut battle = Battle::new(); let mut game = Game::new();
battle game
.set_team_num(2) .set_team_num(2)
.set_team_size(1); .set_team_size(1);
@ -72,11 +72,11 @@ pub fn pve(params: CombatPveParams, tx: &mut Transaction, account: &Account) ->
mob_team mob_team
.set_cryps(vec![mob]); .set_cryps(vec![mob]);
battle game
.add_team(plr_team) .add_team(plr_team)
.add_team(mob_team); .add_team(mob_team);
battle.start(); game.start();
Ok(battle) Ok(game)
} }

View File

@ -8,7 +8,7 @@ use failure::Error;
use failure::err_msg; use failure::err_msg;
use account::Account; use account::Account;
use rpc::BattleAbilityParams; use rpc::GameAbilityParams;
use cryp::{Cryp, CrypStat, Stat}; use cryp::{Cryp, CrypStat, Stat};
#[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)] #[derive(Debug,Clone,Copy,PartialEq,Serialize,Deserialize)]
@ -125,13 +125,13 @@ impl Team {
pub fn ability_by_id(&mut self, id: Uuid) -> &mut Ability { pub fn ability_by_id(&mut self, id: Uuid) -> &mut Ability {
match self.incoming.iter_mut().find(|a| a.id == id) { match self.incoming.iter_mut().find(|a| a.id == id) {
Some(a) => a, Some(a) => a,
None => panic!("abiltity not in battle"), None => panic!("abiltity not in game"),
} }
} }
} }
#[derive(Debug,Clone,Serialize,Deserialize)] #[derive(Debug,Clone,Serialize,Deserialize)]
pub struct Battle { pub struct Game {
pub id: Uuid, pub id: Uuid,
pub team_size: usize, pub team_size: usize,
pub team_num: usize, pub team_num: usize,
@ -141,9 +141,9 @@ pub struct Battle {
pub log: Vec<String>, pub log: Vec<String>,
} }
impl Battle { impl Game {
pub fn new() -> Battle { pub fn new() -> Game {
return Battle { return Game {
id: Uuid::new_v4(), id: Uuid::new_v4(),
team_size: 0, team_size: 0,
team_num: 0, team_num: 0,
@ -154,17 +154,17 @@ impl Battle {
}; };
} }
pub fn set_team_num(&mut self, size: usize) -> &mut Battle { pub fn set_team_num(&mut self, size: usize) -> &mut Game {
self.team_num = size; self.team_num = size;
self self
} }
pub fn set_team_size(&mut self, size: usize) -> &mut Battle { pub fn set_team_size(&mut self, size: usize) -> &mut Game {
self.team_size = size; self.team_size = size;
self self
} }
pub fn add_team(&mut self, team: Team) -> &mut Battle { pub fn add_team(&mut self, team: Team) -> &mut Game {
if self.teams.len() == self.team_num { if self.teams.len() == self.team_num {
panic!("maximum number of teams"); panic!("maximum number of teams");
} }
@ -176,7 +176,7 @@ impl Battle {
pub fn team_by_id(&mut self, id: Uuid) -> &mut Team { pub fn team_by_id(&mut self, id: Uuid) -> &mut Team {
match self.teams.iter_mut().find(|t| t.id == id) { match self.teams.iter_mut().find(|t| t.id == id) {
Some(t) => t, Some(t) => t,
None => panic!("id not in battle {:?}", id), None => panic!("id not in game {:?}", id),
} }
} }
@ -188,10 +188,10 @@ impl Battle {
} }
} }
panic!("cryp not in battle"); panic!("cryp not in game");
} }
fn replace_cryp(&mut self, updated: Cryp) -> &mut Battle { fn replace_cryp(&mut self, updated: Cryp) -> &mut Game {
for team in self.teams.iter_mut() { for team in self.teams.iter_mut() {
if let Some(index) = team.cryps.iter().position(|c| c.id == updated.id) { if let Some(index) = team.cryps.iter().position(|c| c.id == updated.id) {
team.cryps.remove(index); team.cryps.remove(index);
@ -206,14 +206,14 @@ impl Battle {
self.teams.len() == self.team_num self.teams.len() == self.team_num
} }
pub fn start(&mut self) -> &mut Battle { pub fn start(&mut self) -> &mut Game {
self.ability_phase_start(); self.ability_phase_start();
self self
} }
pub fn ability_phase_start(&mut self) -> &mut Battle { pub fn ability_phase_start(&mut self) -> &mut Game {
if ![Phase::Start, Phase::Damage].contains(&self.phase) { if ![Phase::Start, Phase::Damage].contains(&self.phase) {
panic!("battle not in damage or start phase"); panic!("game not in damage or start phase");
} }
self.phase = Phase::Ability; self.phase = Phase::Ability;
@ -244,9 +244,9 @@ impl Battle {
} }
// move all abilities into their target team's targets list // move all abilities into their target team's targets list
pub fn targets_phase_start(&mut self) -> &mut Battle { pub fn targets_phase_start(&mut self) -> &mut Game {
if self.phase != Phase::Ability { if self.phase != Phase::Ability {
panic!("battle not in ability phase"); panic!("game not in ability phase");
} }
self.phase = Phase::Target; self.phase = Phase::Target;
@ -286,9 +286,9 @@ impl Battle {
// requires no input // requires no input
// just do it // just do it
pub fn damage_phase_start(&mut self) -> &mut Battle { pub fn damage_phase_start(&mut self) -> &mut Game {
if self.phase != Phase::Target { if self.phase != Phase::Target {
panic!("battle not in target phase"); panic!("game not in target phase");
} }
self.phase = Phase::Damage; self.phase = Phase::Damage;
@ -305,9 +305,9 @@ impl Battle {
self self
} }
fn resolve_abilities(&mut self) -> &mut Battle { fn resolve_abilities(&mut self) -> &mut Game {
if self.phase != Phase::Damage { if self.phase != Phase::Damage {
panic!("battle not in damage phase"); panic!("game not in damage phase");
} }
// sometimes... you just gotta // sometimes... you just gotta
@ -331,79 +331,79 @@ impl Battle {
// add client function call // add client function call
// check for cryp ability ownership // check for cryp ability ownership
// check for battle participation // check for game participation
pub fn battle_ability(params: BattleAbilityParams, tx: &mut Transaction, account: &Account) -> Result<Battle, Error> { pub fn game_ability(params: GameAbilityParams, tx: &mut Transaction, account: &Account) -> Result<Game, Error> {
let query = " let query = "
SELECT * SELECT *
FROM battles FROM games
WHERE id = $1 WHERE id = $1
"; ";
let result = tx let result = tx
.query(query, &[&params.battle_id])?; .query(query, &[&params.game_id])?;
let returned = match result.iter().next() { let returned = match result.iter().next() {
Some(row) => row, Some(row) => row,
None => return Err(err_msg("battle not found")), None => return Err(err_msg("game not found")),
}; };
// tells from_slice to cast into a cryp // tells from_slice to cast into a cryp
let battle_bytes: Vec<u8> = returned.get("data"); let game_bytes: Vec<u8> = returned.get("data");
let mut battle = from_slice::<Battle>(&battle_bytes)?; let mut game = from_slice::<Game>(&game_bytes)?;
battle.add_ability(account.id, params.cryp_id, params.target_team_id, params.kind); game.add_ability(account.id, params.cryp_id, params.target_team_id, params.kind);
return battle_write(battle, tx); return game_write(game, tx);
} }
pub fn battle_new(battle: Battle, tx: &mut Transaction) -> Result<Battle, Error> { pub fn game_new(game: Game, tx: &mut Transaction) -> Result<Game, Error> {
let battle_bytes = to_vec(&battle)?; let game_bytes = to_vec(&game)?;
let query = " let query = "
INSERT INTO battles (id, data) INSERT INTO games (id, data)
VALUES ($1, $2, $3) VALUES ($1, $2, $3)
RETURNING id, account; RETURNING id, account;
"; ";
let result = tx let result = tx
.query(query, &[&battle_bytes, &battle.id])?; .query(query, &[&game_bytes, &game.id])?;
let _returned = result.iter().next().expect("no row returned"); let _returned = result.iter().next().expect("no row returned");
println!("{:?} wrote battle", battle.id); println!("{:?} wrote game", game.id);
return Ok(battle); return Ok(game);
} }
pub fn battle_write(battle: Battle, tx: &mut Transaction) -> Result<Battle, Error> { pub fn game_write(game: Game, tx: &mut Transaction) -> Result<Game, Error> {
let battle_bytes = to_vec(&battle)?; let game_bytes = to_vec(&game)?;
let query = " let query = "
UPDATE battles UPDATE games
SET data = $1 SET data = $1
WHERE id = $2 WHERE id = $2
RETURNING id, data; RETURNING id, data;
"; ";
let result = tx let result = tx
.query(query, &[&battle_bytes, &battle.id])?; .query(query, &[&game_bytes, &game.id])?;
let _returned = result.iter().next().expect("no row returned"); let _returned = result.iter().next().expect("no row returned");
println!("{:?} wrote battle", battle.id); println!("{:?} wrote game", game.id);
return Ok(battle); return Ok(game);
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use battle::*; use game::*;
use cryp::*; use cryp::*;
#[test] #[test]
fn battle_test() { fn game_test() {
let x = Cryp::new() let x = Cryp::new()
.named(&"pronounced \"creeep\"".to_string()) .named(&"pronounced \"creeep\"".to_string())
.level(8) .level(8)
@ -418,9 +418,9 @@ mod tests {
let y_id = y.id; let y_id = y.id;
let mut battle = Battle::new(); let mut game = Game::new();
battle game
.set_team_num(2) .set_team_num(2)
.set_team_size(1); .set_team_size(1);
@ -434,33 +434,33 @@ mod tests {
y_team y_team
.set_cryps(vec![y]); .set_cryps(vec![y]);
battle game
.add_team(x_team) .add_team(x_team)
.add_team(y_team); .add_team(y_team);
assert!(battle.can_start()); assert!(game.can_start());
battle.start(); game.start();
let x_attack_id = battle.add_ability(x_team_id, x_id, y_team_id, AbilityKind::Attack); let x_attack_id = game.add_ability(x_team_id, x_id, y_team_id, AbilityKind::Attack);
let y_attack_id = battle.add_ability(y_team_id, y_id, x_team_id, AbilityKind::Attack); let y_attack_id = game.add_ability(y_team_id, y_id, x_team_id, AbilityKind::Attack);
assert!(battle.ability_phase_finished()); assert!(game.ability_phase_finished());
battle.targets_phase_start(); game.targets_phase_start();
println!("{:?}", battle); println!("{:?}", game);
battle.add_target(x_team_id, x_id, y_attack_id); game.add_target(x_team_id, x_id, y_attack_id);
battle.add_target(y_team_id, y_id, x_attack_id); game.add_target(y_team_id, y_id, x_attack_id);
assert!(battle.target_phase_finished()); assert!(game.target_phase_finished());
battle.damage_phase_start(); game.damage_phase_start();
assert!([Phase::Ability, Phase::Finish].contains(&battle.phase)); assert!([Phase::Ability, Phase::Finish].contains(&game.phase));
println!("{:?}", battle); println!("{:?}", game);
return; return;
} }

View File

@ -18,7 +18,7 @@ extern crate failure;
// #[macro_use] extern crate failure_derive; // #[macro_use] extern crate failure_derive;
mod cryp; mod cryp;
mod battle; mod game;
mod net; mod net;
mod combat; mod combat;
// mod skill; // mod skill;

View File

@ -11,7 +11,7 @@ use failure::err_msg;
use net::Db; use net::Db;
use cryp::{Cryp, cryp_spawn}; use cryp::{Cryp, cryp_spawn};
use battle::{Battle, AbilityKind, battle_ability}; use game::{Game, AbilityKind, game_ability};
use combat::{pve}; use combat::{pve};
use account::{Account, account_create, account_login, account_from_token, account_cryps}; use account::{Account, account_create, account_login, account_from_token, account_cryps};
use item::{Item, items_list, item_use}; use item::{Item, items_list, item_use};
@ -40,7 +40,7 @@ impl Rpc {
let response = match v.method.as_ref() { let response = match v.method.as_ref() {
"cryp_spawn" => Rpc::cryp_spawn(data, &mut tx, account, client), "cryp_spawn" => Rpc::cryp_spawn(data, &mut tx, account, client),
"combat_pve" => Rpc::combat_pve(data, &mut tx, account, client), "combat_pve" => Rpc::combat_pve(data, &mut tx, account, client),
"battle_ability" => Rpc::battle_ability(data, &mut tx, account, client), "game_ability" => Rpc::game_ability(data, &mut tx, account, client),
"account_create" => Rpc::account_create(data, &mut tx, account, client), "account_create" => Rpc::account_create(data, &mut tx, account, client),
"account_login" => Rpc::account_login(data, &mut tx, account, client), "account_login" => Rpc::account_login(data, &mut tx, account, client),
"account_cryps" => Rpc::account_cryps(data, &mut tx, account, client), "account_cryps" => Rpc::account_cryps(data, &mut tx, account, client),
@ -74,8 +74,8 @@ impl Rpc {
let msg = from_slice::<CombatPveMsg>(&data).or(Err(err_msg("invalid params")))?; let msg = from_slice::<CombatPveMsg>(&data).or(Err(err_msg("invalid params")))?;
let battle_response = RpcResponse { let game_response = RpcResponse {
method: "battle_state".to_string(), method: "game_state".to_string(),
params: RpcResult::Pve(pve(msg.params, tx, &a)?) params: RpcResult::Pve(pve(msg.params, tx, &a)?)
}; };
@ -84,20 +84,20 @@ impl Rpc {
params: RpcResult::CrypList(account_cryps(tx, &a)?) params: RpcResult::CrypList(account_cryps(tx, &a)?)
})?; })?;
return Ok(battle_response); return Ok(game_response);
} }
fn battle_ability(data: Vec<u8>, tx: &mut Transaction, account: Option<Account>, _client: &mut WebSocket<TcpStream>) -> Result<RpcResponse, Error> { fn game_ability(data: Vec<u8>, tx: &mut Transaction, account: Option<Account>, _client: &mut WebSocket<TcpStream>) -> Result<RpcResponse, Error> {
let a = match account { let a = match account {
Some(a) => a, Some(a) => a,
None => return Err(err_msg("auth required")), None => return Err(err_msg("auth required")),
}; };
let msg = from_slice::<BattleAbilityMsg>(&data).or(Err(err_msg("invalid params")))?; let msg = from_slice::<GameAbilityMsg>(&data).or(Err(err_msg("invalid params")))?;
let battle_response = RpcResponse { let game_response = RpcResponse {
method: "battle_state".to_string(), method: "game_state".to_string(),
params: RpcResult::Pve(battle_ability(msg.params, tx, &a)?) params: RpcResult::Pve(game_ability(msg.params, tx, &a)?)
}; };
// Rpc::send_msg(client, RpcResponse { // Rpc::send_msg(client, RpcResponse {
@ -105,7 +105,7 @@ impl Rpc {
// params: RpcResult::CrypList(account_cryps(tx, &a)?) // params: RpcResult::CrypList(account_cryps(tx, &a)?)
// })?; // })?;
return Ok(battle_response); return Ok(game_response);
} }
fn cryp_spawn(data: Vec<u8>, tx: &mut Transaction, account: Option<Account>, _client: &mut WebSocket<TcpStream>) -> Result<RpcResponse, Error> { fn cryp_spawn(data: Vec<u8>, tx: &mut Transaction, account: Option<Account>, _client: &mut WebSocket<TcpStream>) -> Result<RpcResponse, Error> {
@ -195,7 +195,7 @@ pub enum RpcResult {
SpawnCryp(Cryp), SpawnCryp(Cryp),
Account(Account), Account(Account),
CrypList(Vec<Cryp>), CrypList(Vec<Cryp>),
Pve(Battle), Pve(Game),
ItemList(Vec<Item>), ItemList(Vec<Item>),
ItemUse(()), ItemUse(()),
} }
@ -229,14 +229,14 @@ pub struct CombatPveParams {
} }
#[derive(Debug,Clone,Serialize,Deserialize)] #[derive(Debug,Clone,Serialize,Deserialize)]
struct BattleAbilityMsg { struct GameAbilityMsg {
method: String, method: String,
params: BattleAbilityParams, params: GameAbilityParams,
} }
#[derive(Debug,Clone,Serialize,Deserialize)] #[derive(Debug,Clone,Serialize,Deserialize)]
pub struct BattleAbilityParams { pub struct GameAbilityParams {
pub battle_id: Uuid, pub game_id: Uuid,
pub cryp_id: Uuid, pub cryp_id: Uuid,
pub target_team_id: Uuid, pub target_team_id: Uuid,
pub kind: AbilityKind, pub kind: AbilityKind,