Guest User

React Native Tutorial: Tic Tac Toe

a guest
Aug 6th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | Source Code | 0 0
  1. import { useState } from "react";
  2.  
  3. function Square({ value, onSquareClick }) {
  4. return (
  5. <button className="square" onClick={onSquareClick}>
  6. {value}
  7. </button>
  8. );
  9. }
  10.  
  11. export default function Board() {
  12. const [xIsNext, setXIsNext] = useState(true);
  13. const [squares, setSquares] = useState(Array(9).fill(null));
  14.  
  15. function handleClick(i) {
  16. if (squares[i] || calculateWinner(squares)) {
  17. return;
  18. }
  19.  
  20. const nextSquares = squares.slice();
  21.  
  22. if (xIsNext) {
  23. nextSquares[i] = "X";
  24. } else {
  25. nextSquares[i] = "O";
  26. }
  27. setSquares(nextSquares);
  28. setXIsNext(!xIsNext);
  29. }
  30. const winner = calculateWinner(squares);
  31. let status;
  32. if (winner) {
  33. status = "Winner: " + winner;
  34. } else {
  35. status = "Next player: " + (xIsNext ? "X" : "O");
  36. }
  37.  
  38. return (
  39. <>
  40. <div className="status">{status}</div>
  41. <div className="board-row">
  42. <Square value={squares[0]} onSquareClick={() => handleClick(0)} />
  43. <Square value={squares[1]} onSquareClick={() => handleClick(1)} />
  44. <Square value={squares[2]} onSquareClick={() => handleClick(2)} />
  45. </div>
  46. <div className="board-row">
  47. <Square value={squares[3]} onSquareClick={() => handleClick(3)} />
  48. <Square value={squares[4]} onSquareClick={() => handleClick(4)} />
  49. <Square value={squares[5]} onSquareClick={() => handleClick(5)} />
  50. </div>
  51. <div className="board-row">
  52. <Square value={squares[6]} onSquareClick={() => handleClick(6)} />
  53. <Square value={squares[7]} onSquareClick={() => handleClick(7)} />
  54. <Square value={squares[8]} onSquareClick={() => handleClick(8)} />
  55. </div>
  56. </>
  57. );
  58. }
  59.  
  60. function calculateWinner(squares) {
  61. const lines = [
  62. [0, 1, 2],
  63. [3, 4, 5],
  64. [6, 7, 8],
  65. [0, 3, 6],
  66. [1, 4, 7],
  67. [2, 5, 8],
  68. [0, 4, 8],
  69. [2, 4, 6]
  70. ];
  71. for (let i = 0; i < lines.length; i++) {
  72. const [a, b, c] = lines[i];
  73. if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
  74. return squares[a];
  75. }
  76. }
  77. return null;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment