Skip to content

Instantly share code, notes, and snippets.

@hpstuff
Last active February 28, 2017 13:22
Show Gist options
  • Save hpstuff/3e034fe851a076c9c53d54396f8268a0 to your computer and use it in GitHub Desktop.
Save hpstuff/3e034fe851a076c9c53d54396f8268a0 to your computer and use it in GitHub Desktop.
ReactGame
class Dispatcher {
id = 0;
_callbacks = [];
register(callback){
const id = this.id + 1;
this._callbacks[id] = callback;
return id;
}
unregister(id) {
delete this._callbacks[id];
}
dispatch(event) {
for (var id in this._callbacks) {
this._callbacks[id](event);
}
}
}
const dispatcher = new Dispatcher();
const score = (state = { player: 10, computer: 10 }, action) => {
switch (action.type) {
case 'COMPUTER':
if (state.player == 0){
return state;
}
return {
player: state.player - 1,
computer: state.computer + 1
};
case 'PLAYER':
if (state.computer == 0){
return state;
}
return {
player: state.player + 1,
computer: state.computer - 1
};
default:
return state;
}
}
class ScoreBar extends React.Component {
state = score(undefined, {});
constructor(args) {
super(...args)
dispatcher.register(action => this.setState(prevState => score(prevState, action)));
}
render() {
const player = ("00"+this.state.player).slice(-2);
const computer = ("00"+this.state.computer).slice(-2);
return (
<h4>Player: {player} | Computer : {computer}</h4>
)
}
}
class Game extends React.Component {
state = ({
title: "Game",
...score(undefined, {})
});
constructor(args) {
super(...args)
dispatcher.register(action => this.setState(prevState => score(prevState, action)));
}
computerWin = () => {
dispatcher.dispatch({ type: 'COMPUTER' });
};
playerWin = () => {
dispatcher.dispatch({ type: 'PLAYER' });
};
render() {
return (
<div>
<h1>{this.state.title}</h1>
<ScoreBar />
<br />
WHO WIN? <button className="btn btn--dark" onClick={this.computerWin}>Computer</button>
<span>&nbsp;</span>
<button className="btn btn--dark" onClick={this.playerWin}>Player</button>
</div>
)
}
}
ReactDOM.render(<Game/>, mountNode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment