React ile Tic Tac Toe oyunu
App.jsx
JavaScript:
import Game from "./components/Game";
export default function App() {
return (
<>
<Game />
</>
);
}
Game.jsx
JavaScript:
import { useState } from "react";
import Board from "./Board";
import calculateWinner from "./helpers";
export default function Game() {
const [gameState, setGameState] = useState({
historyArray: [Array(9).fill(null)],
currentMoveIndex: 0,
});
const { historyArray, currentMoveIndex } = gameState;
const xIsNext = currentMoveIndex % 2 === 0;
const currentSquares = historyArray[currentMoveIndex];
const winner = calculateWinner(currentSquares);
const status = winner
? `Winner: ${winner}`
: `Next player: ${xIsNext ? "X" : "O"}`;
function handleSquareClick(nextSquares) {
const nextHistory = [
...historyArray.slice(0, currentMoveIndex + 1),
nextSquares,
];
setGameState({
historyArray: nextHistory,
currentMoveIndex: nextHistory.length - 1,
});
}
function jumpTo(nextMoveIndex) {
setGameState({
historyArray: historyArray,
currentMoveIndex: nextMoveIndex,
});
}
function renderMovesHistoryList(historyArray, jumpTo) {
return historyArray.map((squares, move) => {
const description =
move > 0
? historyArray.length - 1 === move
? `You are at move #${move}`
: `Go to move #${move}`
: "Go to game start";
return (
<li key={squares.join("")}>
<button onClick={() => jumpTo(move)}>{description}</button>
</li>
);
});
}
return (
<div className="game">
<div className="game-board">
<Board
xIsNext={xIsNext}
squares={currentSquares}
onPlay={handleSquareClick}
/>
</div>
<div className="game-info">
<div>{status}</div>
<ol>{renderMovesHistoryList(historyArray, jumpTo)}</ol>
</div>
</div>
);
}
Board.jsx
JavaScript:
import Square from "./Square";
import calculateWinner from "./helpers";
export default function Board(props) {
const { xIsNext, squares, onPlay } = props;
function handleClick(i) {
const isSquareFilled = squares[i] !== null;
const isGameFinished = calculateWinner(squares) !== null;
if (isSquareFilled || isGameFinished) {
return;
}
const nextSquares = [...squares];
nextSquares[i] = xIsNext ? "X" : "O";
onPlay(nextSquares);
}
function renderSquare(i) {
return (
<Square
key={i}
value={squares[i]}
onSquareClick={() => handleClick(i)}
/>
);
}
const boardRows = [0, 1, 2].map((row) => (
<div className="board-row" key={row}>
{[0, 1, 2].map((col) => renderSquare(row * 3 + col))}
</div>
));
return <>{boardRows}</>;
}
Square.jsx
JavaScript:
export default function Square(props) {
const { value, onSquareClick } = props;
return (
<button className="square" onClick={onSquareClick}>
{value}
</button>
);
}
helper.js
JavaScript:
export default 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 null;
}