Skip to content

Instantly share code, notes, and snippets.

@viebel
Last active June 18, 2017 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viebel/2589bcb575a76a893761b40934bd9c16 to your computer and use it in GitHub Desktop.
Save viebel/2589bcb575a76a893761b40934bd9c16 to your computer and use it in GitHub Desktop.
class Board extends React.Component {
constructor() {
super();
this.state = this.vanillaState();
}
vanillaState () {
return {squares: Array(9).fill(null),
xIsNext: true,
winner: null};
}
reset () { this.setState(this.vanillaState()) }
renderSquare(i) {
return (<Square value= {this.state.squares[i]} onClick= {() => this.handleClick(i)}/>);
}
handleClick(i) {
if (this.state.squares[i] || this.state.winner) { return; }
const squares = R.update(i, this.state.xIsNext ? 'X' : 'O', this.state.squares);
const state = R.merge(this.state, {squares: squares,
xIsNext: !this.state.xIsNext});
this.setState(state);
}
render() {
const winner = my.game.calculate_winner(this.state.squares);
let status;
if (winner) {
status = `Winner: ${winner}`;
this.state.winner = winner;
}
else {
status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`;
}
return (
<div>
<div className="status">{status}</div>
<div className="board-row"> {[0,1,2].map ((i) => this.renderSquare(i))} </div>
<div className="board-row"> {[3,4,5].map ((i) => this.renderSquare(i))} </div>
<div className="board-row"> {[6,7,8].map ((i) => this.renderSquare(i))} </div>
<button onClick= {() => this.reset()}> Reset </button>
</div>
);
}
}
window.BoardWithPlayers = Board;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment