Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.1 kB
1
Indexable
Never
import React, { useEffect, useState } from "react";
export default function App() {
  const [grid] = useState(3);
  const [gridState, setGridState] = useState(Array(grid * grid).fill(null));
  const [isXNext, setIsXNext] = useState(true);
  const handleClick = (index) => {
    console.log(gridState[index]);
    if (gridState[index] || calculateWinner(gridState)) {
      return;
    }
    const newGridState = gridState.slice();
    newGridState[index] = isXNext ? "X" : "O";
    setGridState(newGridState);
    setIsXNext(!isXNext);
  };
  const calculateWinner = (squares) => {
    const winCombos = [
      [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 < winCombos.length; i++) {
      const [a, b, c] = winCombos[i];
      if (
        squares[a] &&
        squares[a] === squares[b] &&
        squares[a] === squares[c]
      ) {
        return squares[a];
      }
    }
    return null;
  };
  const renderSquare = (index) => {
    return (
      <div
        id={"elem" + index}
        style={{
          margin: "2px",
          border: "1px solid #f00",
          height: "20px",
          width: "20px",
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          fontSize: "16px",
          fontWeight: "bold",
        }}
        key={"key" + index}
        onClick={() => handleClick(index)}
      >
        {gridState[index]}
      </div>
    );
  };
  const makeRow = (start) => {
    const row = [];
    for (let i = start; i < start + grid; i++) {
      row.push(renderSquare(i));
    }
    return row;
  };
  const makeGrid = () => {
    const rows = [];
    for (let i = 0; i < grid; i++) {
      rows.push(
        <div key={i} style={{ display: "flex" }}>
          {makeRow(i * grid)}
        </div>
      );
    }
    return rows;
  };
  const winner = calculateWinner(gridState);
  const status = winner
    ? `Winner: ${winner}`
    : `Next player: ${isXNext ? "X" : "O"}`;

  return (
    <div>
      <div>{status}</div>
      {makeGrid()}
    </div>
  );
}
Leave a Comment