본문 바로가기

React + React Native + Expo

[React 연습 4일차] 리액트 TicTacToe Game 구현

반응형

 

 

 

승자 결정하기까지 완료

앞으로 시간여행 추가하기가 남았는데 뭔가 두렵다,,, 요건 내일 시작해봐야겟다!

 

 


function Square(props){
    return(
        <button classNam="square" onClick = {props.onClick}>
            {props.value}
        </button>
    )
}

class Board extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            squares: Array(9).fill(null),
            xIsNext: true,
        }
    }

    handleClick = (i) => {
        const squares = this.state.squares.slice();
        if (calculateWinner(squares) || square[i]) {
            return;
        }

        square[i] = this.state.xIsNext ? 'X' : 'O';
        this.setState({
            xIsNext: !this.state.xIsNext,
            squares: squares
        })
    }

    renderSqaure = (i) => {
        return (
            <Square
                value={this.state.squares[i]}
                onClick={() => this.handleClick(i)}
            />
        )
    }

    render() {
        const winner = calculateWinner(this.state.squares)
        const status;
        if (winner) {
            status = 'Winner : ' + winner;
        } else {
            status = 'Next Player : ' + (this.state.xIsNext ? 'X' : 'O');
        }
        return (
            <div>
                <div className="status">{status}</div>
                <div className="board-row">
                    {this.renderSquare(0)}
                    {this.renderSquare(1)}
                    {this.renderSquare(2)}
                </div>
                <div className="board-row">
                    {this.renderSquare(3)}
                    {this.renderSquare(4)}
                    {this.renderSquare(5)}
                </div>
                <div className="board-row">
                    {this.renderSquare(6)}
                    {this.renderSquare(7)}
                    {this.renderSquare(8)}
                </div>
            </div>
        )
    }
}




class Game extends React.Component {
    render() {
        return (
            <div className="game">
                <div className="game-board">
                    <Board />
                </div>
                <div className="game-info">
                    <div>{/* status */}</div>
                    <ol>{/* todo */}</ol>
                </div>
            </div>
        )
    }
}


ReactDOM.render(
    <Game />,
    document.querySelector('#root')
)

 

 

반응형