Equipment is being read from the database and displayed

This commit is contained in:
2019-06-01 04:50:23 +10:00
parent 29e86e4032
commit 13842a5da9
9 changed files with 343 additions and 130 deletions
+78 -27
View File
@@ -4,44 +4,95 @@ require('dotenv').config();
//utilities //utilities
let { log } = require('../common/utilities.js'); let { log } = require('../common/utilities.js');
//the statistics const statistics = (connection, req, res, cb) => {
let equipmentStatistics = require('./equipment_statistics.json'); return cb(undefined, { 'statistics': require('./equipment_statistics.json') });
}
const statisticsRequest = () => (req, res) => { const owned = (connection, req, res, cb) => {
res.status(200).json(equipmentStatistics); //verify the credentials
res.end(); let query = 'SELECT COUNT(*) AS total FROM sessions WHERE accountId = ? AND token = ?;';
}; connection.query(query, [req.body.id, req.body.token], (err, results) => {
//TODO: incomplete
const listRequest = (connection) => (req, res) => {
//verify identity
let query = 'SELECT accountId FROM sessions WHERE accountId IN (SELECT id FROM accounts WHERE username = ?) AND token = ?;';
connection.query(query, [req.body.username, req.body.token], (err, results) => {
if (err) throw err; if (err) throw err;
let query = 'SELECT name, quantity, type FROM equipment WHERE accountId = ?;'; if (results[0].total !== 1) {
connection.query(query, [results[0].accountId], (err, results) => { return cb('Invalid equipment owned credentials');
}
let query = 'SELECT name, quantity FROM equipment WHERE accountId = ?;';
connection.query(query, [req.body.id], (err, results) => {
if (err) throw err; if (err) throw err;
//transform the results into a sendable array let res = {}
let list = {};
results.map((record) => { Object.keys(results).map((key) => {
//initialize this type if (res[results[key].name] !== undefined) {
list[record.type] = list[record.type] || {}; log('WARNING: Invalid database state, equipment owned', JSON.stringify(results));
}
//send the quantity of every type res[results[key].name] = results[key].quantity;
list[record.type][record.name] = record.quantity;
}); });
res.status(200).json(list); return cb(undefined, { 'owned': res });
});
});
}
const equipmentRequest = (connection) => (req, res) => {
//if no field received, send everything
if (!req.body.field) {
//compose the returned objects
statistics(connection, req, res, (err, statisticsObj) => {
if (err) {
res.status(400).write(log(err, req.body.id, req.body.token, req.body.field));
res.end();
return;
}
return owned(connection, req, res, (err, ownedObj) => {
if (err) {
res.status(400).write(log(err, req.body.id, req.body.token, req.body.field));
res.end();
return;
}
//finally, compose the resulting objects
res.status(200).json(Object.assign({}, statisticsObj, ownedObj));
res.end(); res.end();
}); });
}); });
};
return;
}
//send specific fields
switch(req.body.field) {
case 'statistics':
return statistics(connection, req, res, (err, obj) => {
if (err) {
res.status(400).write(log(err, req.body.id, req.body.token, req.body.field));
} else {
res.status(200).json(obj);
}
res.end();
});
case 'owned':
return owned(connection, req, res, (err, obj) => {
if (err) {
res.status(400).write(log(err, req.body.id, req.body.token, req.body.field));
} else {
res.status(200).json(obj);
}
res.end();
});
default:
res.status(400).write(log('Unknown field received', req.body.id, req.body.token, req.body.field));
res.end();
}
}
module.exports = { module.exports = {
statisticsRequest: statisticsRequest, equipmentRequest: equipmentRequest
listRequest: listRequest
} }
+9 -9
View File
@@ -1,15 +1,15 @@
{ {
"Weapons": { "Weapons": {
"Stick": { "cost": 50, "combatBoost": 0.02, "scientistsRequired": 1 }, "Stick": { "cost": 50, "combatBoost": 0.02, "scientistsRequired": 1, "purchasable": true },
"Dagger": { "cost": 75, "combatBoost": 0.03, "scientistsRequired": 2 }, "Dagger": { "cost": 75, "combatBoost": 0.03, "scientistsRequired": 2, "purchasable": true },
"Sword": { "cost": 100, "combatBoost": 0.04, "scientistsRequired": 3 }, "Sword": { "cost": 100, "combatBoost": 0.04, "scientistsRequired": 3, "purchasable": true },
"Longsword": { "cost": 150, "combatBoost": 0.05, "scientistsRequired": 4 }, "Longsword": { "cost": 150, "combatBoost": 0.05, "scientistsRequired": 4, "purchasable": true },
"Frying Pan": { "cost": 200, "combatBoost": 0.06, "scientistsRequired": 5 } "Frying Pan": { "cost": 200, "combatBoost": 0.06, "scientistsRequired": 5, "purchasable": true }
}, },
"Armour": { "Armour": {
"Leather": { "cost": 75, "combatBoost": 0.02, "scientistsRequired": 2 }, "Leather": { "cost": 75, "combatBoost": 0.02, "scientistsRequired": 2, "purchasable": true },
"Gambeson": { "cost": 100, "combatBoost": 0.03, "scientistsRequired": 3 }, "Gambeson": { "cost": 100, "combatBoost": 0.03, "scientistsRequired": 3, "purchasable": true },
"Chainmail": { "cost": 150, "combatBoost": 0.04, "scientistsRequired": 4 }, "Chainmail": { "cost": 150, "combatBoost": 0.04, "scientistsRequired": 4, "purchasable": true },
"Platemail": { "cost": 200, "combatBoost": 0.05, "scientistsRequired": 5 } "Platemail": { "cost": 200, "combatBoost": 0.05, "scientistsRequired": 5, "purchasable": true }
} }
} }
+2 -3
View File
@@ -47,9 +47,8 @@ app.post('/attackstatusrequest', combat.attackStatusRequest(connection));
app.post('/combatlogrequest', combat.combatLogRequest(connection)); app.post('/combatlogrequest', combat.combatLogRequest(connection));
combat.runCombatTick(connection); combat.runCombatTick(connection);
//let equipment = require('./equipment.js'); let equipment = require('./equipment.js');
//app.post('/equipmentstatisticsrequest', equipment.statisticsRequest()); app.post('/equipmentrequest', equipment.equipmentRequest(connection));
//app.post('/equipmentlistrequest', equipment.listRequest(connection));
//static directories //static directories
app.use('/styles', express.static(path.resolve(__dirname + '/../public/styles')) ); app.use('/styles', express.static(path.resolve(__dirname + '/../public/styles')) );
+1
View File
@@ -69,6 +69,7 @@ export default class App extends React.Component {
<LazyRoute path='/profile' component={() => import('./pages/profile.jsx')} /> <LazyRoute path='/profile' component={() => import('./pages/profile.jsx')} />
<LazyRoute path='/ladder' component={() => import('./pages/ladder.jsx')} /> <LazyRoute path='/ladder' component={() => import('./pages/ladder.jsx')} />
<LazyRoute path='/combatlog' component={() => import('./pages/combat_log.jsx')} /> <LazyRoute path='/combatlog' component={() => import('./pages/combat_log.jsx')} />
<LazyRoute path='/equipment' component={() => import('./pages/equipment.jsx')} />
<LazyRoute path='*' component={() => import('./pages/page_not_found.jsx')} /> <LazyRoute path='*' component={() => import('./pages/page_not_found.jsx')} />
</Switch> </Switch>
+2 -3
View File
@@ -44,7 +44,6 @@ class CombatLog extends React.Component {
let ButtonHeader = this.buttonHeader.bind(this); let ButtonHeader = this.buttonHeader.bind(this);
return ( return (
<div className='panel'>
<div className='sidePanelPage'> <div className='sidePanelPage'>
<div className='sidePanel'> <div className='sidePanel'>
<CommonLinks /> <CommonLinks />
@@ -67,7 +66,6 @@ class CombatLog extends React.Component {
<ButtonHeader /> <ButtonHeader />
</div> </div>
</div> </div>
</div>
); );
} }
@@ -126,7 +124,8 @@ class CombatLog extends React.Component {
}; };
CombatLog.propTypes = { CombatLog.propTypes = {
username: PropTypes.string.isRequired username: PropTypes.string.isRequired,
loggedIn: PropTypes.bool.isRequired
}; };
const mapStoreToProps = (store) => { const mapStoreToProps = (store) => {
+135
View File
@@ -0,0 +1,135 @@
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
//actions
import { storeScientists, storeGold, clearProfile } from '../../actions/profile.js';
//panels
import CommonLinks from '../panels/common_links.jsx';
import EquipmentPanel from '../panels/equipment.jsx';
class Equipment extends React.Component {
constructor(props) {
super(props);
this.state = {
fetch: null,
warning: ''
};
this.sendRequest('/profilerequest', {username: this.props.username});
}
componentDidMount() {
if (!this.props.loggedIn) {
this.props.history.replace('/login');
}
}
componentWillUnmount() {
this.props.clearProfile();
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (JSON.stringify(this.state) !== JSON.stringify(prevState)) {
this.state.fetch();
this.sendRequest('/profilerequest', {username: this.props.username});
}
}
render() {
let warningStyle = {
display: this.state.warning.length > 0 ? 'flex' : 'none'
};
return (
<div className='sidePanelPage'>
<div className='sidePanel'>
<CommonLinks />
</div>
<div className='mainPanel'>
<div className='warning' style={warningStyle}>
<p>{this.state.warning}</p>
</div>
<EquipmentPanel
getFetch={this.getFetch.bind(this)}
setWarning={this.setWarning.bind(this)}
scientists={this.props.scientists}
gold={this.props.gold}
/>
</div>
</div>
);
}
//gameplay functions
sendRequest(url, args = {}) { //send a unified request, using my credentials
//build the XHR
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let json = JSON.parse(xhr.responseText);
//on success
this.props.storeScientists(json.scientists);
this.props.storeGold(json.gold);
}
else if (xhr.status === 400) {
this.setWarning(xhr.responseText);
}
}
};
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify({
id: this.props.id,
token: this.props.token,
...args
}));
}
//bound callbacks
getFetch(fn) {
this.setState({ fetch: fn });
}
setWarning(s) {
this.setState({ warning: s });
}
};
Equipment.propTypes = {
username: PropTypes.string.isRequired,
loggedIn: PropTypes.bool.isRequired,
storeScientists: PropTypes.func.isRequired,
storeGold: PropTypes.func.isRequired,
clearProfile: PropTypes.func.isRequired
};
const mapStoreToProps = (store) => {
return {
username: store.account.username,
loggedIn: store.account.id !== 0,
scientists: store.profile.scientists,
gold: store.profile.gold
};
};
const mapDispatchToProps = (dispatch) => {
return {
storeScientists: (x) => dispatch(storeScientists(x)),
storeGold: (x) => dispatch(storeGold(x)),
clearProfile: () => dispatch(clearProfile())
};
};
Equipment = connect(mapStoreToProps, mapDispatchToProps)(Equipment);
export default Equipment;
+1
View File
@@ -30,6 +30,7 @@ class CommonLinks extends React.Component {
<div className='panel'> <div className='panel'>
<p><Link to='/' onClick={this.props.onClickHome}>Return Home</Link></p> <p><Link to='/' onClick={this.props.onClickHome}>Return Home</Link></p>
<p><Link to='/profile' onClick={this.props.onClickProfile}>Your Kingdom</Link></p> <p><Link to='/profile' onClick={this.props.onClickProfile}>Your Kingdom</Link></p>
<p><Link to='/equipment' onClick={this.props.onClickCombatLog}>Your Equipment</Link></p>
<p><Link to='/ladder' onClick={this.props.onClickLadder}>Game Ladder</Link></p> <p><Link to='/ladder' onClick={this.props.onClickLadder}>Game Ladder</Link></p>
<p><Link to='/combatlog' onClick={this.props.onClickCombatLog}>Combat Log</Link></p> <p><Link to='/combatlog' onClick={this.props.onClickCombatLog}>Combat Log</Link></p>
<p><Link to='/passwordchange' onClick={this.props.onClickPasswordChange}>Change Password</Link></p> <p><Link to='/passwordchange' onClick={this.props.onClickPasswordChange}>Change Password</Link></p>
+94 -67
View File
@@ -1,114 +1,141 @@
import React from 'react'; import React from 'react';
import { withRouter, Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
//TODO: incomplete
class Equipment extends React.Component { class Equipment extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
statistics: {}, //
equipment: {}
}; };
if (this.props.getFetchStatistics) { if (this.props.getFetch) {
// this.props.getFetchStatistics(this.fetchStatistics.bind(this)); this.props.getFetch((field) => this.sendRequest('/equipmentrequest', {field: field} ));
} }
this.fetchStatistics();
if (this.props.getFetchEquipment) {
// this.props.getFetchEquipment(this.fetchEquipmentList.bind(this));
}
this.fetchEquipmentList();
} }
render() { render() {
//print the purchasable weapons, then purchasable armour, then stuff you can't buy //if there are no scientists
let statistics = JSON.parse(JSON.stringify(this.state.statistics)); if (this.props.scientists <= 0) {
return (
//filter out what you can't get at your current scientist count <div className='panel'>
Object.keys(statistics).forEach((typeKey) => { <p className='centered'>You have no scientists!</p>
Object.keys(statistics[typeKey]).forEach((nameKey) => { <p className='centered'>Go and <Link to='/profile'>train some!</Link></p>
if (statistics[typeKey][nameKey].scientists > this.props.scientists) { </div>
delete statistics[typeKey][nameKey]; );
} }
if (Object.keys(statistics[typeKey]).length === 0) {
delete statistics[typeKey];
}
});
});
console.log(this.state.statistics); let display = this.flattenStructure(this.state, this.props.scientists);
console.log(statistics);
return ( return (
<div className='panel'> <div className='panel'>
<div className='table'> <div className='table'>
<div className='row'> <div className='row'>
<p className='col'>Equipment Name</p> <p className='col centered'>Name</p>
<p className='col'>Equipment Type</p> <p className='col centered'>Type</p>
<p className='col'>Quantity</p> <p className='col centered'>Owned</p>
<p className='col'>Cost</p> <p className='col centered'>Cost</p>
<p className='col'>Buy</p> <p className='col centered'>Buy</p>
<p className='col'>Sell</p> <p className='col centered'>Sell</p>
</div> </div>
{Object.keys(display).map((key) => <div className='row' key={key}>
<p className='col centered'>{display[key].name}</p>
<p className='col centered'>{display[key].type}</p>
<p className='col centered'>{display[key].owned}</p>
<p className='col centered'>{display[key].cost}</p>
<button className='col centered' disabled={display[key].cost > this.props.gold}>+ Buy +</button>
<button className='col centered' disabled={display[key].owned === 0}>- Sell -</button>
</div>)}
</div> </div>
</div> </div>
); );
} }
fetchStatistics() { //gameplay functions
sendRequest(url, args = {}) { //send a unified request, using my credentials
//build the XHR //build the XHR
let xhr = new XMLHttpRequest(); let xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = () => { xhr.onreadystatechange = () => {
if (xhr.readyState === 4) { if (xhr.readyState === 4) {
if (xhr.status === 200) { if (xhr.status === 200) {
let data = JSON.parse(xhr.responseText); let json = JSON.parse(xhr.responseText);
this.setState({ statistics: data });
}
}
}
xhr.open('POST', '/equipmentstatisticsrequest', true); //on success
xhr.send(); this.setState(json);
} }
else if (xhr.status === 400 && this.props.setWarning) {
this.setWarning(xhr.responseText);
}
}
};
fetchEquipmentList(username = this.props.username, token = this.props.token) {
//build the XHR
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let data = JSON.parse(xhr.responseText);
this.setState({ equipment: data });
}
}
}
xhr.open('POST', '/equipmentlistrequest', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.send(JSON.stringify({ xhr.send(JSON.stringify({
username: username, id: this.props.id,
token: token token: this.props.token,
...args
})); }));
} }
flattenStructure(structure, scientists) {
if (!structure || !structure.statistics) {
return [];
}
let ret = []; //return value: ret[0] = { name: '', type: '', owned: 0, cost: 0 }
Object.keys(structure.statistics).map((type) => {
Object.keys(structure.statistics[type]).map((name) => {
//don't render high level items
if (structure.statistics[type][name].scientistsRequired > scientists) {
return;
}
//if you can't buy it and you down own it, don't render it (for legendary items)
if (!structure.statistics[type][name].purchasable && !structure.owned[name]) {
return;
}
//finally
ret.push({
name: name,
type: type,
owned: (structure.owned && structure.owned[name]) || 0,
cost: structure.statistics[type][name].cost
});
});
});
return ret;
}
}; };
Equipment.propTypes = { Equipment.propTypes = {
username: PropTypes.string.isRequired, id: PropTypes.number.isRequired,
token: PropTypes.number.isRequired, token: PropTypes.number.isRequired,
scientists: PropTypes.number.isRequired,
getFetchStatistics: PropTypes.func, setWarning: PropTypes.func,
getFetchEquipmentList: PropTypes.func getFetch: PropTypes.func
}; };
export default Equipment; const mapStoreToProps = (store) => {
return {
id: store.account.id,
token: store.account.token
};
};
const mapDispatchToProps = (dispatch) => {
return {
//
};
};
Equipment = connect(mapStoreToProps, mapDispatchToProps)(Equipment);
export default withRouter(Equipment);
+1 -1
View File
@@ -24,7 +24,7 @@ module.exports = {
] ]
}, },
optimization: { optimization: {
minimize: true, minimize: false,
minimizer: [ minimizer: [
new TerserPlugin({ new TerserPlugin({
terserOptions: { terserOptions: {