Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react';
- import ReactDOM from 'react-dom';
- import { tttButton } from './style';
- import { isndef } from './type';
- var tictactoe = require('./games/tictactoe.js');
- class Game extends React.Component {
- constructor(props) {
- super(props);
- this.checkEnd = this.checkEnd.bind(this);
- this.handleClick = this.handleClick.bind(this);
- this.reset = this.reset.bind(this);
- }
- componentWillMount() {
- this.reset();
- }
- reset() {
- tictactoe.newGame();
- this.setState({field: tictactoe.getField()});
- }
- handleClick(row, col) {
- if (tictactoe.play(row, col)) {
- this.setState({field: tictactoe.getField()});
- setTimeout(this.checkEnd, 100);
- }
- }
- checkEnd() {
- let gameEnd = tictactoe.checkEnd();
- if (isndef(gameEnd)) {
- alert('Draw');
- this.reset();
- }
- else {
- if (gameEnd === 0) {
- alert('First player won!');
- this.reset();
- }
- else if (gameEnd === 1) {
- alert('Second player won!');
- this.reset();
- }
- }
- }
- makeSquare(row, col, val, key) {
- return <Square value={val} row={row} col={col} key={key} handleClick={this.handleClick}/>;
- }
- render() {
- let rows = [];
- for (let row of [0, 1, 2]) {
- let cols = [];
- for (let col of [0, 1, 2]) {
- let val = this.state.field[row][col];
- cols.push(this.makeSquare(row, col, val, col));
- }
- rows.push(<div key={row}> {cols} </div>);
- }
- return <div> {rows} </div>;
- }
- }
- class Square extends React.Component {
- constructor(props) {
- super(props);
- this.onClick = this.onClick.bind(this);
- }
- shouldComponentUpdate(newProps, newState) {
- return this.props.value != newProps.value;
- }
- onClick(event) {
- this.props.handleClick(this.props.row, this.props.col);
- }
- render() {
- return <button style={tictactoe.buttonStyle(this.props.value)} onClick={this.onClick}/>
- }
- }
- class App extends React.Component {
- render() {
- return <Game/>;
- }
- }
- document.addEventListener('DOMContentLoaded', function() {
- ReactDOM.render(<App/>, document.getElementById('app'));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement