Cute Bow Tie Hearts Blinking Pink Pointer

프론트엔드/React

[React] 틱택토게임(2) 승자정하기

청포도 에이드 2022. 4. 15. 17:10
728x90

기본 세팅

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <!-- 객체 -->
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <!-- 객체 -->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<body>
    <div id="root"></div>
    <script type="text/babel">
        class App extends React.Component{
            render(){
                return(
                    <div>
                    </div>
                )
            }
        }

        ReactDOM.render(
            <App />,
            document.querySelector('#root')
        )
    </script>
</body>
</html>


코드

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <!-- 객체 -->
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <!-- 객체 -->
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
</head>
<style>
    body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}

ol, ul {
padding-left: 30px;
}

.board-row:after {
clear: both;
content: "";
display: table;
}

.status {
margin-bottom: 10px;
}

.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}

.square:focus {
outline: none;
}

.kbd-navigation .square:focus {
background: #ddd;
}

.game {
display: flex;
flex-direction: row;
}

.game-info {
margin-left: 20px;
}

</style>
<body>
    <div id="root"></div>
    <script type="text/babel">
        const calcuateWinner = (squares)=>{
            const lines = [
                [0,1,2],
                [3,4,5],
                [6,7,8],
                [0,3,6],
                [1,4,7],
                [2,5,8],
                [0,4,8],
                [2,4,6]
            ]

            for(let i=0; i<lines.length; i++){

                let a2 = lines[i][0]
                let b2 = lines[i][1]
                let c2 = lines[i][2]
                
                const [a,b,c] = lines[i] // [0,1,2]
                // console.log(a,b,c)
                console.log("이거임",squares[a],squares[b],squares[c], squares[a] === squares[b], squares[a] === squares[c])

              
                if(squares[a] != null && squares[a] === squares[b] && squares[a] === squares[c]){
                    return squares[a]
                }
            }

            return null
        }


        class Square extends React.Component{
            render(){
                return(
                    <button className="square"
                        onClick = {this.props.onClick}
                    >
                        {this.props.value}
                    </button>
                )
            }
        }


        class Board extends React.Component{

            state = {
                squares:Array(9).fill(null),
                xIsNext:true

            }

            handleClick = i => {
                console.log(i)
                const squares = [...this.state.squares]
                console.log("선택" ,squares[i])
                // calcuateWinner(squares) //8개 경우의 수 다 나옴
                // console.log('이거눠지', squares[i] !== null, calcuateWinner(squares) != null)
                if(squares[i] !== null || calcuateWinner(squares) != null){
                    return
                }
                // console.log(this.state.xIsNext) // true

                const xIsNext = this.state.xIsNext

                // let flag = 'X'

                // if(xIsNext) {
                //     flag = 'X'
                // } else{
                //     flag = "O"
                // }
                // squares[i] = flag
                //줄이면? 아래코드 한줄 삼항연산자

                squares[i] = xIsNext ? "X" : "O"
                this.setState({
                    ...this.state,
                    squares,
                    xIsNext:!xIsNext // 상태 변경 true -> false
                })

                // 처음 눌렀을 땐 X
                // 두번 눌렀을 땐 O
                // 세번 눌렀을 땐 X
                // 네번 눌렀을 땐 O
            }


            renderSquare = (i) => {
                return (
                    <Square
                        value={this.state.squares[i]} //[null, null............]
                        onClick = {()=>{ this.handleClick(i) }}
                    />
                )
            }
            //X 넣어보니까 전부 다 X가 됨 null 넣으니까 전부 다 안보임.
            // 클릭했을 때, X가 나오게 하고 싶음.

            // 클릭했을 때, 해당 인자값에 있는 숫자가 콘솔에 찍히게.

            //내가 만약에 i번을 클릭했을 때 i번에 해당되는 내용을 null-> 'X'로 바꾸는 거야.
            // [null,null,null,null......]
            render(){
                const {renderSquare, state:{squares}} = this
                const winner = calcuateWinner(squares) // null, "O", "X"

                
                if(winner != null){
                    console.log('승자가 있다.')
                    console.log(winner)
                } else{
                    console.log('승자가 없다.')
                    if(this.state.xIsNext == true){
                    console.log('X')
                    } else{
                        console.log('O')
                    }
                }


                const status = winner != null ? `Winner: ${winner} `: `Next Player ${this.state.xIsNext ? 'X' : 'O'}`
                return(

                    <div>
                        <div className="status">{status}</div>

                        <div className="board-row">
                            {renderSquare(0)}
                            {renderSquare(1)}
                            {renderSquare(2)}
                        </div>
                        <div className="board-row">
                            {renderSquare(3)}
                            {renderSquare(4)}
                            {renderSquare(5)}
                        </div>
                        <div className="board-row">
                            {renderSquare(6)}
                            {renderSquare(7)}
                            {renderSquare(8)}
                        </div>

                    </div>
                )
            }
        }

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



        ReactDOM.render(
            <Game />,
            document.querySelector('#root')
        )
    </script>
</body>
</html>
728x90