【React】从 0 开始学 React —— 实现井字棋小游戏
import React, { useState } from 'react';
import Board from './Board';
const Game = () => {
// 初始化游戏状态
const [history, setHistory] = useState([{
squares: Array(9).fill(null),
}]);
const [stepNumber, setStepNumber] = useState(0);
const [xIsNext, setXIsNext] = useState(true);
// 回溯函数
const jumpTo = step => {
setStepNumber(step);
};
// 下棋函数
const handleSquareClick = (i) => {
const historyCopy = history.slice(0, stepNumber + 1);
const current = historyCopy[historyCopy.length - 1];
const squares = current.squares.slice();
if (calculateWinner(squares) || squares[i]) {
return;
}
squares[i] = xIsNext ? 'X' : 'O';
setHistory(historyCopy.concat([{
squares: squares,
}]));
setStepNumber(historyCopy.length);
setXIsNext(!xIsNext);
};
// 计算胜利者的函数
const 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 null;
};
const winner = calculateWinner(history[stepNumber].squares);
const status = winner ? 'Winner: ' + winner : `Next player: ${xIsNext ? 'X' : 'O'}`;
const moves = history.map((step, move) => {
const desc = move ? 'Go to move #' + move : 'Go to game start';
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{desc}</button>
</li>
);
});
return (
<div className="game">
<div className="game-board">
<Board
squares={history[stepNumber].squares}
onClick={handleSquareClick}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{moves}</ol>
</div>
</div>
);
};
export default Game;
这个代码实例提供了一个React组件,用于实现井字棋小游戏的用户界面。它包括游戏状态的管理、下棋逻辑、计算胜利者的函数,以及一个回溯功能,允许用户在移动列表中跳转。这个例子简洁明了,并且遵循了React函数组件的最佳实践。
评论已关闭