🌐
50 React Coding Puzzles
  • 50 React Coding Puzzles
  • Contact
  • Reviews
  • Table of Contents
  • Introduction
  • 1 - Simple Counter App
  • 2 - Dynamic List of Items with Strikethrough
  • 3 - Color Picker with Hex Code Display
  • 4 - Password Strength Checker
  • 5 - Countdown Timer with Audio
  • 6 - Dynamic Movie List with Filtering and Sorting
  • 7 - Text Animation Component (Fade/Scroll)
  • 8 - Dynamically Generated Text Art
  • 9 - Meme Generator with Custom Text
  • 10 - "What Should I Eat?" Random Recipe Generator
  • 11 - Simple Quiz App with Multiple Choice
  • 12 - Unit Converter
  • 13 - Dynamic Image Gallery with Lightbox
  • 14 - Weather Widget with Temperature and Description
  • 15 - Contact Form with Email and Message Validation
  • 16 - Color Palette Generator
  • 17 - Drag-and-Drop Feature for Rearranging Items
  • 18 - Interactive Quiz with Dynamic Results and Feedback
  • 19 - To-Do List with Task Categorization
  • 20 - Note-Taking App with Markdown Support
  • 21 - Simple Calculator with Basic Operations
  • 22 - Word Scramble Game with Timer and Score
  • 23 - Number Guessing Game
  • 24 - Digital Clock with Time Zone Support
  • 25 - Interactive Time Zone Converter
  • 26 - Weather Forecast App with Location Detection
  • 27 - Real-Time Stock Ticker with Updates
  • 28 - Virtual Dice Roller with Multiple Dice
  • 29 - Responsive Navigation Menu with Dropdowns
  • 30 - Progress Bar for Loading or Task Completion
  • 31 - Modal Window for Alerts and Confirmations
  • 32 - Infinite Scroll for Loading More Content
  • 33 - Form Validation with Error Messages
  • 34 - Search Bar with Filtering and Suggestions
  • 35 - Drag-and-Drop File Upload
  • 36 - Interactive Color Picker with Sliders
  • 37 - Image Carousel with Autoplay
  • 38 - Rating System with Stars or Thumbs Up/Down
  • 39 - Comment Section with Nested Replies
  • 40 - Pagination for Long Lists of Data
  • 41 - Stopwatch app that tracks elapsed time
  • 42 - Responsive E-commerce Product Grid
  • 43 - Random Movie/Book Recommender
  • 44 - Kanban board for managing tasks with drag-and-drop
  • 45 - Chat application with real-time messaging using WebSockets
  • 46 - Calendar that displays events and allows scheduling
  • 47 - Tic-Tac-Toe Game
  • 48 - Hangman Game
  • 49 - Notes App
  • 50 - Expense Tracker
  • Afterword
  • Appendix
Powered by GitBook
On this page
  • Description
  • Algorithm
  • Classes
  • Code
  • Explanation
  • Possible Future Enhancements

47 - Tic-Tac-Toe Game

Description

Create a Tic-Tac-Toe game that displays a 3x3 grid of buttons representing squares, allows players to take turns clicking squares to mark them with X or O, detects horizontal, vertical, or diagonal wins for either player, and announces the winner or draw when the game ends.

Algorithm

  1. Render a 3x3 grid of buttons

  2. Initialize game state (player turn, board state)

  3. Handle button clicks (mark square with X or O, update game state)

  4. Check for wins (horizontal, vertical, diagonal) after each move

  5. Announce winner or draw when game ends

Classes

  • TicTacToe: The main game component

  • Square: A single square in the grid

  • GameBoard: The 3x3 grid of squares

Code

TicTacToe.js

import React, { useState } from 'react';
import GameBoard from './GameBoard';

const TicTacToe = () => {
  const [playerTurn, setPlayerTurn] = useState('X');
  const [boardState, setBoardState] = useState([
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
  ]);
  const [winner, setWinner] = useState(null);

  const handleClick = (row, col) => {
    const newBoardState = [...boardState];
    newBoardState[row][col] = playerTurn;
    setBoardState(newBoardState);
    setPlayerTurn(playerTurn === 'X' ? 'O' : 'X');
    checkForWin();
  };

  const checkForWin = () => {
    const winConditions = [
      [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 < winConditions.length; i++) {
      const condition = winConditions[i];
      if (
        boardState[condition[0]] === playerTurn &&
        boardState[condition[1]] === playerTurn &&
        boardState[condition[2]] === playerTurn
      ) {
        setWinner(playerTurn);
        return;
      }
    }
    if (!boardState.includes('')) {
      setWinner('draw');
    }
  };

  return (
    <div>
      <GameBoard
        boardState={boardState}
        handleClick={handleClick}
      />
      {winner && <p>Winner: {winner}</p>}
    </div>
  );
};

export default TicTacToe;

GameBoard.js

import React from 'react';
import Square from './Square';

const GameBoard = ({ boardState, handleClick }) => {
  return (
    <div>
      {boardState.map((row, rowIndex) => (
        <div key={rowIndex}>
          {row.map((square, colIndex) => (
            <Square
              key={colIndex}
              value={square}
              handleClick={() => handleClick(rowIndex, colIndex)}
            />
          ))}
        </div>
      ))}
    </div>
  );
};

export default GameBoard;

Square.js

import React from 'react';

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

export default Square;

Explanation

The TicTacToe component renders a 3x3 grid of Square components, which represent the game board. The GameBoard component handles the logic for rendering the squares and detecting wins. The Square component renders a single square with an X or O, depending on the game state. The game state is managed using the useState hook, which keeps track of the current player turn, board state, and winner. The handleClick function updates the game state when a square is clicked, and the checkForWin function checks for wins after each move.

Possible Future Enhancements

  • Game history: Keep a history of past games and allow users to review them.

  • Multiplayer: Add support for multiplayer games, where two users can play against each other.

  • Customizable game board: Allow users to customize the game board size and design.

  • Animations and sound effects: Add animations and sound effects to enhance the game experience.

Previous46 - Calendar that displays events and allows schedulingNext48 - Hangman Game

Last updated 10 months ago