cryps list

This commit is contained in:
ntr 2018-09-24 23:18:15 +10:00
parent 25058e185c
commit 162ddd1fb4
12 changed files with 119 additions and 53 deletions

View File

@ -1,8 +1,11 @@
export const SET_ACCOUNT = 'SET_ACCOUNT'; export const SET_ACCOUNT = 'SET_ACCOUNT';
export const setAccount = (value) => ({ type: SET_ACCOUNT, value }); export const setAccount = (value) => ({ type: SET_ACCOUNT, value });
export const SET_CRYP = 'SET_CRYP'; export const SET_CRYPS = 'SET_CRYPS';
export const setCryp = (value) => ({ type: SET_CRYP, value }); export const setCryps = (value) => ({ type: SET_CRYPS, value });
export const SET_ACTIVE_CRYP = 'SET_ACTIVE_CRYP';
export const setActiveCryp = (value) => ({ type: SET_ACTIVE_CRYP, value });
export const SET_WS = 'SET_WS'; export const SET_WS = 'SET_WS';
export const setWs = (value) => ({ type: SET_WS, value }); export const setWs = (value) => ({ type: SET_WS, value });

View File

@ -1,16 +0,0 @@
const { connect } = require('preact-redux');
const CrypPanel = require('./cryp.panel');
const addState = connect(
function receiveState(state) {
const { ws, cryp } = state;
function sendCombatPve() {
return ws.sendCombatPve(cryp.id);
}
return { cryp, sendCombatPve };
}
);
module.exports = addState(CrypPanel);

View File

@ -0,0 +1,16 @@
const { connect } = require('preact-redux');
const CrypsPanel = require('./cryps.panel');
const addState = connect(
function receiveState(state) {
const { ws, cryps } = state;
function sendCombatPve(crypId) {
return ws.sendCombatPve(crypId);
}
return { cryps, sendCombatPve };
}
);
module.exports = addState(CrypsPanel);

View File

@ -1,10 +1,10 @@
const preact = require('preact'); const preact = require('preact');
function CrypPanel({ cryp, sendCombatPve }) { function CrypPanel({ cryps, sendCombatPve }) {
if (!cryp) return <div>not ready</div>; if (!cryps) return <div>not ready</div>;
return ( const crypPanels = cryps.map(cryp => (
<div className="tile is-ancestor has-text-centered has-background-grey is-dark is-10"> <div key={cryp.id} className="tile is-ancestor has-text-centered has-background-grey is-dark is-10">
<div className="tile is-6"> <div className="tile is-6">
<div className="tile is-parent is-vertical is-3"> <div className="tile is-parent is-vertical is-3">
<section className="tile is-child notification is-success"> <section className="tile is-child notification is-success">
@ -51,16 +51,22 @@ function CrypPanel({ cryp, sendCombatPve }) {
<button <button
className="button is-success" className="button is-success"
type="submit" type="submit"
onClick={() => sendCombatPve()}> onClick={() => sendCombatPve(cryp.id)}>
Start PVE Start PVE
</button> </button>
</section> </section>
</div> </div>
</div> </div>
); ));
// map is a function that is called on every element of an array // map is a function that is called on every element of an array
// so in this ^^ case it calls Icon('Mashy') which returns some jsx // so in this ^^ case it calls Icon('Mashy') which returns some jsx
// that gets put into the dom // that gets put into the dom
return (
<section>
{crypPanels}
</section>
);
} }
module.exports = CrypPanel; module.exports = CrypPanel;

View File

@ -9,17 +9,17 @@ const actions = require('./actions');
const fizzyText = require('../lib/fizzy-text'); const fizzyText = require('../lib/fizzy-text');
const createSocket = require('./socket'); const createSocket = require('./socket');
const CrypContainer = require('./components/cryp.container'); const CrypsContainer = require('./components/cryps.container');
const LoginContainer = require('./components/login.container'); const LoginContainer = require('./components/login.container');
const Navbar = require('./components/navbar'); // const Navbar = require('./components/navbar');
// Redux Store // Redux Store
const store = createStore( const store = createStore(
combineReducers({ combineReducers({
account: reducers.accountReducer, account: reducers.accountReducer,
cryp: reducers.crypReducer, cryps: reducers.crypsReducer,
ws: reducers.wsReducer, ws: reducers.wsReducer,
}), })
); );
store.subscribe(() => console.log(store.getState())); store.subscribe(() => console.log(store.getState()));
@ -36,10 +36,9 @@ jdenticon.config = {
const Cryps = () => ( const Cryps = () => (
<section> <section>
<Navbar />
<LoginContainer /> <LoginContainer />
<div id="fizzytext" /> <div id="fizzytext" />
<CrypContainer /> <CrypsContainer />
</section> </section>
); );

View File

@ -10,10 +10,10 @@ function accountReducer(state = defaultAccount, action) {
} }
} }
const defaultCryp = null; const defaultCryps = null;
function crypReducer(state = defaultCryp, action) { function crypsReducer(state = defaultCryps, action) {
switch (action.type) { switch (action.type) {
case actions.SET_CRYP: case actions.SET_CRYPS:
return action.value; return action.value;
default: default:
return state; return state;
@ -32,6 +32,6 @@ function wsReducer(state = defaultWs, action) {
module.exports = { module.exports = {
accountReducer, accountReducer,
crypReducer, crypsReducer,
wsReducer, wsReducer,
}; };

View File

@ -31,14 +31,19 @@ function createSocket(store) {
account = login; account = login;
store.dispatch(actions.setAccount(login)); store.dispatch(actions.setAccount(login));
send({ method: 'account_cryps', params: {} });
console.log(account); console.log(account);
return send({ method: 'cryp_spawn', params: { name: 'drake' } }); }
function accountCryps(response) {
const [structName, cryps] = response;
store.dispatch(actions.setCryps(cryps));
console.log('got my cryps', cryps);
} }
function crypSpawn(response) { function crypSpawn(response) {
const [structName, cryp] = response; const [structName, cryp] = response;
console.log('got a new cryp', cryp); console.log('got a new cryp', cryp);
return store.dispatch(actions.setCryp(cryp));
} }
function combatPve(response) { function combatPve(response) {
@ -74,6 +79,7 @@ function createSocket(store) {
combat_pve: combatPve, combat_pve: combatPve,
account_login: accountLogin, account_login: accountLogin,
account_create: accountLogin, account_create: accountLogin,
account_cryps: accountCryps,
}; };
// decodes the cbor and // decodes the cbor and
@ -93,8 +99,7 @@ function createSocket(store) {
// Connection opened // Connection opened
ws.addEventListener('open', function wsOpen(event) { ws.addEventListener('open', function wsOpen(event) {
// send({ method: 'account_create', params: { name: 'ntr', password: 'grepgrepgrep' }}); send({ method: 'account_login', params: { name: 'ntr', password: 'grepgrepgrep' } });
// send({ method: 'account_login', params: { name: 'ntr', password: 'grepgrepgrep' } });
}); });
// Listen for messages // Listen for messages

View File

@ -34,5 +34,17 @@ items give skills
gem td style attr combinations gem td style attr combinations
stoney + spikey = jagged stoney + spikey = jagged
plants
animals
viruses
fungus
artificial
elementals
first strike
techno artists for the soundtrack
slimey slimey
ghostly ghostly

View File

@ -3,12 +3,16 @@ use bcrypt::{hash, verify};
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric; use rand::distributions::Alphanumeric;
use std::iter; use std::iter;
use serde_cbor::{from_slice, to_vec};
use std::str; use std::str;
use net::Db; use net::Db;
use rpc::{AccountCreateParams, AccountLoginParams, RpcResult}; use rpc::{AccountCreateParams, AccountLoginParams, RpcResult};
use cryp::Cryp;
use failure::Error; use failure::Error;
use failure::err_msg; use failure::err_msg;
@ -55,7 +59,7 @@ pub fn from_token(token: String, db: &Db) -> Result<Account, Error> {
return Ok(entry); return Ok(entry);
} }
pub fn create(params: AccountCreateParams, db: Db) -> Result<RpcResult, Error> { pub fn create(params: AccountCreateParams, db: Db) -> Result<Account, Error> {
let id = Uuid::new_v4(); let id = Uuid::new_v4();
if params.password.len() < PASSWORD_MIN_LEN { if params.password.len() < PASSWORD_MIN_LEN {
@ -99,10 +103,10 @@ pub fn create(params: AccountCreateParams, db: Db) -> Result<RpcResult, Error> {
tx.commit()?; tx.commit()?;
return Ok(RpcResult::Account(entry)); return Ok(entry);
} }
pub fn login(params: AccountLoginParams, db: Db) -> Result<RpcResult, Error> { pub fn login(params: AccountLoginParams, db: Db) -> Result<Account, Error> {
let query = " let query = "
SELECT id, name, token, password SELECT id, name, token, password
FROM accounts FROM accounts
@ -142,5 +146,31 @@ pub fn login(params: AccountLoginParams, db: Db) -> Result<RpcResult, Error> {
token: entry.token, token: entry.token,
}; };
return Ok(RpcResult::Account(account)); return Ok(account);
} }
pub fn fetch_cryps(db: Db, account: Account) -> Result<Vec<Cryp>, Error> {
let query = "
SELECT data
FROM cryps
WHERE account = $1;
";
let result = db
.query(query, &[&account.id])?;
let cryps: Result<Vec<Cryp>, _> = result.iter().map(|row| {
let cryp_bytes: Vec<u8> = row.get(0);
from_slice::<Cryp>(&cryp_bytes)
}).collect();
// catch any errors
if cryps.is_err() {
return Err(err_msg("could not deserialize a cryp"));
}
// now unwrap is safe
return Ok(cryps.unwrap());
}

View File

@ -121,10 +121,7 @@ where F: Fn(&Battle) -> Result<(), Error>
loop { loop {
battle.next(); battle.next();
match send(&battle) { send(&battle)?;
Err(e) => break Err(err_msg("could not reply")),
_ => (),
};
if battle.finished() { if battle.finished() {
break Ok(battle) break Ok(battle)

View File

@ -1,7 +1,7 @@
use uuid::Uuid; use uuid::Uuid;
use rand::prelude::*; use rand::prelude::*;
use serde_cbor::*; use serde_cbor::*;
use serde_cbor::{to_vec}; use serde_cbor::{from_slice, to_vec};
use failure::Error; use failure::Error;
use failure::err_msg; use failure::err_msg;
@ -217,7 +217,6 @@ pub fn spawn(params: CrypSpawnParams, db: Db, account: Account) -> Result<Cryp,
return Ok(cryp); return Ok(cryp);
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use cryp::*; use cryp::*;

View File

@ -8,7 +8,7 @@ use net::Db;
use cryp::{Cryp, spawn}; use cryp::{Cryp, spawn};
use battle::{Battle}; use battle::{Battle};
use combat::{pve}; use combat::{pve};
use account::{Account, create, login, from_token}; use account::{Account, create, login, from_token, fetch_cryps};
pub struct Rpc; pub struct Rpc;
@ -75,7 +75,7 @@ impl Rpc {
match from_slice::<AccountCreateMsg>(&data) { match from_slice::<AccountCreateMsg>(&data) {
Ok(v) => Ok(RpcResponse { Ok(v) => Ok(RpcResponse {
method: v.method, method: v.method,
params: create(v.params, db)? params: RpcResult::Account(create(v.params, db)?)
}), }),
Err(_e) => Err(err_msg("invalid params")), Err(_e) => Err(err_msg("invalid params")),
} }
@ -84,12 +84,20 @@ impl Rpc {
match from_slice::<AccountLoginMsg>(&data) { match from_slice::<AccountLoginMsg>(&data) {
Ok(v) => Ok(RpcResponse { Ok(v) => Ok(RpcResponse {
method: v.method, method: v.method,
params: login(v.params, db)? params: RpcResult::Account(login(v.params, db)?)
}), }),
Err(_e) => Err(err_msg("invalid params")), Err(_e) => Err(err_msg("invalid params")),
} }
}, },
"account_cryps" => {
match account {
Some(u) => Ok(RpcResponse {
method: v.method,
params: RpcResult::CrypList(fetch_cryps(db, u)?)
}),
None => Err(err_msg("auth required")),
}
},
_ => Err(err_msg("unknown method")), _ => Err(err_msg("unknown method")),
} }
}, },
@ -108,6 +116,7 @@ pub struct RpcResponse {
pub enum RpcResult { pub enum RpcResult {
SpawnCryp(Cryp), SpawnCryp(Cryp),
Account(Account), Account(Account),
CrypList(Vec<Cryp>),
Pve(Battle), Pve(Battle),
} }
@ -163,6 +172,12 @@ pub struct AccountLoginParams {
pub password: String, pub password: String,
} }
#[derive(Debug,Clone,Serialize,Deserialize)]
struct AccountCrypsMsg {
method: String,
params: (),
}
// #[cfg(test)] // #[cfg(test)]
// mod tests { // mod tests {
// use super::*; // use super::*;