Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as JavaScript by xxx ( 2 years ago )
'use strict';

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;
}

const Square = ({value, onClick}) => {
	return <button className="square" onClick={onClick}>{value}</button>;
}

const Board = ({ xIsNext, squares, onPlay }) => {
	function handler(i) {
		if (squares[i] || calculateWinner(squares))
			return;

		const nextSquares = squares.slice();
		nextSquares[i] = xIsNext ? "X" : "O";

		return onPlay(nextSquares);
	}

	const winner = calculateWinner(squares);
	let status = winner ? "Winner: "+winner
		: "Next player: " + (xIsNext ? "X" : "O");

	return (
		<div>
			<div className="status">{status}</div>
			<div className="board-row">
				<Square value={squares[0]} onClick={() => handler(0)} />
				<Square value={squares[1]} onClick={() => handler(1)} />
				<Square value={squares[2]} onClick={() => handler(2)} />
			</div>
			<div className="board-row">
				<Square value={squares[3]} onClick={() => handler(3)} />
				<Square value={squares[4]} onClick={() => handler(4)} />
				<Square value={squares[5]} onClick={() => handler(5)} />
			</div>
			<div className="board-row">
				<Square value={squares[6]} onClick={() => handler(6)} />
				<Square value={squares[7]} onClick={() => handler(7)} />
				<Square value={squares[8]} onClick={() => handler(8)} />
			</div>
		</div>
	);
}

const Game = () => {
	const [history, setHistory] = React.useState([Array(9).fill(null)]);
	const [currentMove, setCurrentMove] = React.useState(0);
	const currentSquares = history[currentMove];
	var xIsNext = currentMove % 2 == 0;

	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) => {
		let descr = move > 0 ? "Go to move #"+move
			: "Go to game start";
		return (
			<li key={move}>
				<button onClick={() => jumpTo(move)}>{descr}</button>
			</li>
		);
	});

	return (
		<div className="game">
			<div className="game-board">
				<Board xIsNext={xIsNext} squares={currentSquares}
					onPlay={handlePlay} />
			</div>
			<div className="game-info">
				<ol>{moves}</ol>
			</div>
		</div>
	)
}

const root = ReactDOM.createRoot(document.getElementById("react-root"));
root.render(
  <React.StrictMode>
    <Game />
  </React.StrictMode>
);

 

Revise this Paste

Your Name: Code Language: