|
| 1 | +import React, { Component } from 'react'; |
| 2 | + |
| 3 | +export default class GameBoard extends Component { |
| 4 | + currentPlayer() { |
| 5 | + // determine the current player by counting the filled cells |
| 6 | + // if even, then it's first player, otherwise it's second player |
| 7 | + let filledCount = 0; |
| 8 | + for (let r = 0; r < 3; r++) { |
| 9 | + for (let c = 0; c < 3; c++) { |
| 10 | + if (this.props.game.board[r][c] !== null) filledCount++; |
| 11 | + } |
| 12 | + } |
| 13 | + return (filledCount % 2 === 0? 0: 1); |
| 14 | + } |
| 15 | + |
| 16 | + handleCellClick(row, col) { |
| 17 | + let currentPlayer = this.currentPlayer(); |
| 18 | + let game = this.props.game; |
| 19 | + game.board[row][col] = currentPlayer; |
| 20 | + Games.update(game._id, { |
| 21 | + $set: {board: game.board} |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + renderCell(row, col) { |
| 26 | + let value = this.props.game.board[row][col]; |
| 27 | + if (value === 0) return (<td>O</td>); |
| 28 | + if (value === 1) return (<td>X</td>); |
| 29 | + if (value === null) return ( |
| 30 | + <td onClick={this.handleCellClick.bind(this, row, col)}></td> |
| 31 | + ); |
| 32 | + } |
| 33 | + render() { |
| 34 | + return ( |
| 35 | + <table className="game-board"> |
| 36 | + <tbody> |
| 37 | + <tr> |
| 38 | + {this.renderCell(0, 0)} |
| 39 | + {this.renderCell(0, 1)} |
| 40 | + {this.renderCell(0, 2)} |
| 41 | + </tr> |
| 42 | + <tr> |
| 43 | + {this.renderCell(1, 0)} |
| 44 | + {this.renderCell(1, 1)} |
| 45 | + {this.renderCell(1, 2)} |
| 46 | + </tr> |
| 47 | + <tr> |
| 48 | + {this.renderCell(2, 0)} |
| 49 | + {this.renderCell(2, 1)} |
| 50 | + {this.renderCell(2, 2)} |
| 51 | + </tr> |
| 52 | + </tbody> |
| 53 | + </table> |
| 54 | + ) |
| 55 | + } |
| 56 | +} |
0 commit comments