React 开发一个井字棋(tic-tac-toe)后续改进功能

好久没看React了,最近又想重新看下。
除了视频课,前几天跟着官网的教程做了井字棋(tic-tac-toe),后面有一些可以改进游戏的想法,下面我就把这些自己练手的代码记录一下,这些功能是:
  1. 在游戏历史记录列表显示每一步棋的坐标,格式为 (列号, 行号)。
  2. 在历史记录列表中加粗显示当前选择的项目
  3. 使用两个循环来渲染出棋盘的格子,而不是在代码里写死(hardcode)
  4. 添加一个可以升序或降序显示历史记录的按钮
  5. 每当有人获胜时,高亮显示连成一线的 3 颗棋子
  6. 当无人获胜时,显示一个平局的消息。

P.S. 除了有注释的代码,其他原始功能我都是按照官网上的写的
先来各个组件的代码,最后再把全部代码贴在文末。
1. Square组件:没变化,跟官网代码一样
2. Board组件
Board renderSquare方法
Board render方法
3. Game 组件
Game state
Game handelClick方法
Game jumpTo方法
Game order排序方法
Game render方法
4. calculateWinner方法
caculateWinner方法
别忘了,涉及到样式变化,还有index.css的变化,就是补充一个样式:
css 样式
以下是index.js的全部代码:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css'

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

class Board extends React.Component {

    renderSquare(i) {
        return <Square
            // 这里给Square加上key
            key={i}
            value={this.props.squares[i]}
            onClick={() => {
                this.props.onClick(i)
            }}
        />
    }
    render() {
        return (
            <div>
                {
                    // 使用两个循环来渲染出棋盘的格子
                    Array(3).fill(null).map((item1, index) => (
                        <div className="board-row" key={index}>
                            {
                                Array(3).fill(null).map((item2, index2) => (
                                    this.renderSquare(3 * index + index2)
                                ))
                            }
                        </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 {
    constructor(props) {
        super(props)
        this.state = {
            history: [{
                squares: Array(9).fill(null)
            }],
            xIsNext: true,
            stepNumber: 0,
            isHistorySort: true,  // 增加一个 isHistorySort 用来记录是否对历史记录排序
        }
    }

    handleClick(i) {
        const history = this.state.history.slice(0, this.state.stepNumber + 1);
        const current = history[history.length - 1]
        const squares = current.squares.slice();
        if (calculateWinner(squares) || squares[i]) {
            return
        }

        squares[i] = this.state.xIsNext ? 'X' : 'O'
        this.setState({
            history: history.concat([{
                squares,
                lastIndex: i    // 增加一个 lastIndex 用来判断最后一步
            }]),
            xIsNext: !this.state.xIsNext,
            stepNumber: history.length
        })
    }

    jumpTo(step) {
        // 给 square 去掉样式
        for (let i = 0; i < 9; i++) {
            document.getElementsByClassName('square')[i].style = ''
        }

        this.setState({
            stepNumber: step,
            xIsNext: (step % 2) === 0
        })
    }

    // 历史记录排序方法
    // 由于this指向问题,这种写法会报错 Cannot read property 'setState' of undefined
    /* order() {
        this.setState({
            isHistorySort: !this.state.isHistorySort
        })
    } */
    // 这种定义方法可以避免上面的报错
    order = () => {
        this.setState({
            isHistorySort: !this.state.isHistorySort
        })
    }


    render() {
        const history = this.state.history;
        const current = history[this.state.stepNumber];
        const winner = calculateWinner(current.squares)

        const moves = history.map((step, move) => {
            const desc = move ?
                'Go to #' + move + '最后落棋点(列号,行号):(' + parseInt(step.lastIndex / 3) + ',' + step.lastIndex % 3 + ')' :
                'Go to game start'
            return (
                <li key={move}>
                    <button
                        onClick={() => this.jumpTo(move)}
                        className={move === this.state.stepNumber ? 'currentBtn' : ''}  // 在历史记录列表中加粗显示当前选择的项目
                    >{desc}</button>
                </li>
            )
        })


        let status;
        if (winner) {
            status = 'winner: ' + winner.winnerName   // 这里winner的名字是  winner.winnerName
            // 有人获胜时,高亮显示连成一线的3颗棋子
            for (let i of winner.winnerIndex) {
                document.getElementsByClassName('square')[i].style = 'background: #ccc; color: #fff;'
            }
        } else {
            if (this.state.history.length > 9) {   // 判断平局的情况
                status = 'No player win! It ends in a draw!'
            }
            else {
                status = 'Next Player: ' + (this.state.xIsNext ? 'X' : 'O')
            }
        }

        return (
            <div className="game">
                <div className="game-board">
                    <Board
                        squares={current.squares}
                        onClick={(i) => this.handleClick(i)}
                    />
                </div>
                <div className="game-info">
                    <div> {status} </div>
                    {/* 增加历史记录排序按钮 */}
                    <button onClick={this.order}>
                        {this.state.isHistorySort ? '倒序' : '正序'}
                    </button>
                    {/* <ol> {moves} </ol> */}
                    {/* 点击排序按钮,改变历史记录的顺序 */}
                    <ol> {this.state.isHistorySort ? moves : moves.reverse()} </ol>
                </div>
            </div>
        )
    }
}

function calculateWinner(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++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            // return squares[a]
            // 改为返回 胜利者名称 和 胜利的位置信息,便于后面高亮显示
            return {
                winnerName: squares[a],
                winnerIndex: [a, b, c]
            }
        }
    }
    return null
}


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

以下是index.css的全部内容:

body{
    font: 14px 'Century Gothic', Futura, sans-serif;
    margin: 20px;
}
ol, li{
    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;
    height: 34px;
    line-height: 34px;
    margin-top: -1px;
    margin-right: -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;
}

/* 在历史记录列表中加粗显示当前选择的项目------样式 */
button.currentBtn{
    font-weight: bold;
    background: skyblue;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值