react 写一个五子棋代码
时间: 2023-04-06 20:01:59 浏览: 112
好的,我可以回答这个问题。以下是一个简单的 React 五子棋代码示例:
```jsx
import React, { useState } from 'react';
const Board = () => {
const [board, setBoard] = useState(Array(9).fill(null));
const [xIsNext, setXIsNext] = useState(true);
const handleClick = (i) => {
const newBoard = [...board];
if (calculateWinner(board) || newBoard[i]) {
return;
}
newBoard[i] = xIsNext ? 'X' : 'O';
setBoard(newBoard);
setXIsNext(!xIsNext);
};
const renderSquare = (i) => {
return (
<button className="square" onClick={() => handleClick(i)}>
{board[i]}
</button>
);
};
const winner = calculateWinner(board);
const status = winner ? `Winner: ${winner}` : `Next player: ${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>
);
};
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;
};
export default Board;
```
这个代码创建了一个 `Board` 组件,它包含了一个 3x3 的棋盘和一些状态。每个棋子都是一个按钮,当点击按钮时,会在棋盘上放置一个 X 或 O。`calculateWinner` 函数用于判断是否有一方获胜。
阅读全文