> 技术文档 > 使用react编写一个简单的井字棋游戏

使用react编写一个简单的井字棋游戏


用React实现井棋棋游戏:从状态管理到时间旅行功能详解

引言

井字棋是学习React状态管理和组件交互的经典案例。本文将逐行解析一个完整实现,包含历史回溯功能胜者判定逻辑,即使是React初学者也能彻底理解。


核心组件架构

#mermaid-svg-es8lRx287inqM4ID {font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-es8lRx287inqM4ID .error-icon{fill:#552222;}#mermaid-svg-es8lRx287inqM4ID .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-es8lRx287inqM4ID .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-es8lRx287inqM4ID .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-es8lRx287inqM4ID .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-es8lRx287inqM4ID .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-es8lRx287inqM4ID .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-es8lRx287inqM4ID .marker{fill:#333333;stroke:#333333;}#mermaid-svg-es8lRx287inqM4ID .marker.cross{stroke:#333333;}#mermaid-svg-es8lRx287inqM4ID svg{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-es8lRx287inqM4ID .label{font-family:\"trebuchet ms\",verdana,arial,sans-serif;color:#333;}#mermaid-svg-es8lRx287inqM4ID .cluster-label text{fill:#333;}#mermaid-svg-es8lRx287inqM4ID .cluster-label span{color:#333;}#mermaid-svg-es8lRx287inqM4ID .label text,#mermaid-svg-es8lRx287inqM4ID span{fill:#333;color:#333;}#mermaid-svg-es8lRx287inqM4ID .node rect,#mermaid-svg-es8lRx287inqM4ID .node circle,#mermaid-svg-es8lRx287inqM4ID .node ellipse,#mermaid-svg-es8lRx287inqM4ID .node polygon,#mermaid-svg-es8lRx287inqM4ID .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-es8lRx287inqM4ID .node .label{text-align:center;}#mermaid-svg-es8lRx287inqM4ID .node.clickable{cursor:pointer;}#mermaid-svg-es8lRx287inqM4ID .arrowheadPath{fill:#333333;}#mermaid-svg-es8lRx287inqM4ID .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-es8lRx287inqM4ID .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-es8lRx287inqM4ID .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-es8lRx287inqM4ID .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-es8lRx287inqM4ID .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-es8lRx287inqM4ID .cluster text{fill:#333;}#mermaid-svg-es8lRx287inqM4ID .cluster span{color:#333;}#mermaid-svg-es8lRx287inqM4ID div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-es8lRx287inqM4ID :root{--mermaid-font-family:\"trebuchet ms\",verdana,arial,sans-serif;}Game组件Board棋盘历史记录Square格子


1. Square组件:最基础的交互单元
function Square({ value, onSquareClick }) { return (  );}
  • 功能解析:
    • value:接收父组件传递的X/O/null
    • onSquareClick:点击时触发父组件的回调函数
    • 设计要点:组件本身不维护状态,由父组件完全控制(受控组件)

2. Board组件:游戏逻辑核心
function Board({ xIsNext, square, onPlay }) { // 处理格子点击事件 function handleClick(i) { // 存在胜者或格子已被占用时阻止操作 if (calculateWinner(square) || square[i]) return; const nextSquares = square.slice(); // 浅拷贝当前棋盘状态 nextSquares[i] = xIsNext ? \'X\' : \'O\'; // 设置当前玩家符号 onPlay(nextSquares); // 传递新状态给父组件 } // 判断胜负状态 const winner = calculateWinner(square); const status = winner ? `Winner: ${winner}` : `Next player: ${xIsNext ? \'X\' : \'O\'}`; // 渲染9宫格棋盘 return (  
{status}
{[0, 3, 6].map((rowStart) => (
{[0, 1, 2].map((offset) => { const index = rowStart + offset; return ( handleClick(index)} /> ); })}
))} );}

关键逻辑解析

  1. 点击处理流程
    • 通过square[i]检查格子是否为空
    • 使用slice()浅拷贝数组避免直接修改状态
    • 根据xIsNext决定放置XO
  2. 状态提升(Lifting State Up)
    • 通过onPlay将新状态回调给Game组件
    • 符合React单向数据流原则

3. Game组件:全局状态管理
export default function Game() { // 历史记录保存所有棋盘状态 const [history, setHistory] = useState([Array(9).fill(null)]); // 当前查看的历史步骤 const [currentMove, setCurrentMove] = useState(0); // 派生状态 const xIsNext = currentMove % 2 === 0; const currentSquare = history[currentMove]; // 处理棋盘状态更新 function handlePlay(nextSquares) { // 裁剪历史记录(用于时间旅行后重新落子) const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]; setHistory(nextHistory); setCurrentMove(nextHistory.length - 1); } // 时间旅行:跳转到指定历史步骤 function jumpTo(nextMove) { setCurrentMove(nextMove); } // 生成历史步骤按钮 const moves = history.map((squares, move) => { const desc = move > 0 ? `Go to move #${move}` : \'Go to game start\'; return ( 
  • ); }); return (
      {moves}
    );}

    核心机制解析

    1. 历史记录管理
      • history:存储棋盘状态数组的数组
      • currentMove:当前展示的历史步骤索引
    2. 时间旅行实现原理
      • 点击历史按钮时jumpTo修改currentMove
      • 渲染对应历史索引的状态:currentSquare = history[currentMove]
      • 重新落子时裁剪历史分支
        history.slice(0, currentMove + 1)确保历史线性的正确性

    4. 胜者判定算法
    function calculateWinner(squares) { // 8种获胜组合(三行/三列/两对角线) 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 (const [a, b, c] of lines) { if ( squares[a] && squares[a] === squares[b] && squares[a] === squares[c] ) { return squares[a]; // 返回胜者符号\'X\'/\'O\' } } return null; // 无胜者}

    算法特点

    • 时间复杂度:O(1)(固定8种判断)
    • 返回值\'X\'/\'O\'(胜者)或null(未结束)
    • 空值检查squares[a] &&防止访问未填充格子

    总结
    1. 组件层级清晰

      • Game(状态容器)→ Board(逻辑核心)→ Square(UI展示)
    2. 符合React最佳实践

      • 状态提升:子组件通过回调修改父组件状态
      • 不可变数据:使用slice()创建新数组
      • 派生状态:xIsNextcurrentMove计算得出
    3. 进阶功能实现

      • 时间旅行:通过历史索引切换棋盘状态
      • 历史裁剪:重新落子时自动清理分叉历史
    4. 可扩展方向

      #mermaid-svg-Is98V4Qfc97f5Yob {font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .error-icon{fill:#552222;}#mermaid-svg-Is98V4Qfc97f5Yob .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-Is98V4Qfc97f5Yob .edge-thickness-normal{stroke-width:2px;}#mermaid-svg-Is98V4Qfc97f5Yob .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-Is98V4Qfc97f5Yob .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-Is98V4Qfc97f5Yob .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-Is98V4Qfc97f5Yob .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-Is98V4Qfc97f5Yob .marker{fill:#333333;stroke:#333333;}#mermaid-svg-Is98V4Qfc97f5Yob .marker.cross{stroke:#333333;}#mermaid-svg-Is98V4Qfc97f5Yob svg{font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-Is98V4Qfc97f5Yob .label{font-family:\"trebuchet ms\",verdana,arial,sans-serif;color:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .cluster-label text{fill:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .cluster-label span{color:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .label text,#mermaid-svg-Is98V4Qfc97f5Yob span{fill:#333;color:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .node rect,#mermaid-svg-Is98V4Qfc97f5Yob .node circle,#mermaid-svg-Is98V4Qfc97f5Yob .node ellipse,#mermaid-svg-Is98V4Qfc97f5Yob .node polygon,#mermaid-svg-Is98V4Qfc97f5Yob .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-Is98V4Qfc97f5Yob .node .label{text-align:center;}#mermaid-svg-Is98V4Qfc97f5Yob .node.clickable{cursor:pointer;}#mermaid-svg-Is98V4Qfc97f5Yob .arrowheadPath{fill:#333333;}#mermaid-svg-Is98V4Qfc97f5Yob .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-Is98V4Qfc97f5Yob .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-Is98V4Qfc97f5Yob .edgeLabel{background-color:#e8e8e8;text-align:center;}#mermaid-svg-Is98V4Qfc97f5Yob .edgeLabel rect{opacity:0.5;background-color:#e8e8e8;fill:#e8e8e8;}#mermaid-svg-Is98V4Qfc97f5Yob .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-Is98V4Qfc97f5Yob .cluster text{fill:#333;}#mermaid-svg-Is98V4Qfc97f5Yob .cluster span{color:#333;}#mermaid-svg-Is98V4Qfc97f5Yob div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:\"trebuchet ms\",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-Is98V4Qfc97f5Yob :root{--mermaid-font-family:\"trebuchet ms\",verdana,arial,sans-serif;}当前实现添加移动高亮显示每步坐标平局判定


    通过这个实现,我们展示了React的核心概念:组件化状态提升不可变数据派生状态。即使从未接触过React,按照组件分解的思维方式也能逐步理解整个应用的数据流动和交互逻辑。