Skip to content

Savaxc/Tic-Tac-Toe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

47 Commits
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŽฎ Tic-Tac-Toe Multiplayer (Full-Stack)

A full-stack multiplayer Tic-Tac-Toe web application built with React (TypeScript), Node.js, PostgreSQL, and Socket.IO, featuring real-time gameplay, JWT authentication, game history tracking, and a modern UI using Material UI.


Features

  • Multiplayer real-time gameplay using Socket.IO
  • JWT Authentication & secure access
  • Create & join game rooms using Room ID
  • Turn-based game validation (prevents cheating / invalid moves)
  • Automatic win / draw detection
  • Game restart system with player confirmation + countdown
  • Side swapping after restart (X โ†” O)
  • Persistent move tracking in database (game_moves)
  • Match history page (Win / Loss / Draw results)
  • Replay system (load game moves from database)
  • Modern responsive UI built with Material UI
  • Sound effects + confetti celebration

Tech Stack

Frontend

  • React
  • TypeScript
  • Material UI
  • Axios
  • Socket.IO Client

Backend

  • Node.js
  • Express.js
  • TypeScript
  • Socket.IO
  • JWT Authentication

Database

  • PostgreSQL
  • Tables:
    • users
    • games
    • game_moves

Project Structure

tic-tac-toe/
โ”‚
โ”œโ”€โ”€ frontend/             # React frontend
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ api/          # Axios/Fetch configurations
โ”‚   โ”‚   โ”œโ”€โ”€ assets/       # Styles, images, and fonts
โ”‚   โ”‚   โ”œโ”€โ”€ components/   # Reusable UI components
โ”‚   โ”‚   โ”œโ”€โ”€ hooks/        # Custom React hooks
โ”‚   โ”‚   โ”œโ”€โ”€ pages/        # Main screen views
โ”‚   โ”‚   โ””โ”€โ”€ utils/        # Helper functions
โ”‚   โ””โ”€โ”€ package.json
โ”‚
โ”œโ”€โ”€ backend/              # Node.js backend
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ config/       # Database and env configurations
โ”‚   โ”‚   โ”œโ”€โ”€ controllers/  # Request handlers
โ”‚   โ”‚   โ”œโ”€โ”€ middleware/   # Auth and validation logic
โ”‚   โ”‚   โ”œโ”€โ”€ models/       # Database schemas
โ”‚   โ”‚   โ”œโ”€โ”€ routes/       # API endpoints
โ”‚   โ”‚   โ”œโ”€โ”€ sockets/      # Socket.IO event logic
โ”‚   โ”‚   โ”œโ”€โ”€ utils/        # Shared utility functions
โ”‚   โ”‚   โ”œโ”€โ”€ app.ts        # Express app setup
โ”‚   โ”‚   โ””โ”€โ”€ server.ts     # Server entry point
โ”‚   โ””โ”€โ”€ package.json
โ”‚
โ””โ”€โ”€ README.md

Installation & Setup

1 Clone Repository

git clone https://github.com/savaxc/tic-tac-toe-multiplayer.git
cd tic-tac-toe-multiplayer

2 Setup Database (PostgreSQL)

#Create a PostgreSQL database:
CREATE DATABASE tictactoe;
#Then create the required tables (example):
CREATE TABLE games (
  id SERIAL PRIMARY KEY,
  room_id VARCHAR(255) NOT NULL,
  player_x_user_id INT NOT NULL,
  player_o_user_id INT,
  winner VARCHAR(10),
  created_at TIMESTAMP DEFAULT NOW(),
  finished_at TIMESTAMP
);

CREATE TABLE game_moves (
  id SERIAL PRIMARY KEY,
  game_id INT NOT NULL REFERENCES games(id) ON DELETE CASCADE,
  move_index INT NOT NULL,
  board TEXT NOT NULL
);

3 Backend Setup

#Go to backend(server) folder:
cd server
npm install
#Create .env file inside /backend:
PORT=8080
JWT_SECRET=your_secret_key
DB_HOST=localhost
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=tictactoe
DB_PORT=5432
#Run backend:
npm run dev
#Backend will run on:
http://localhost:8080

4 Frontend Setup

#Go to frontend(client) folder:
cd ../frontend
npm install
#Run frontend
npm run dev
#Frontend will run on:
http://localhost:5173

Authentication

This project uses JWT authentication.

  • Users must log in to generate a token.
  • Token is stored in localStorage.
  • Socket.IO connection requires JWT token via handshake.

How to Play

  1. Create a Game: Player 1 creates a new game session.
  2. Room ID: The system generates a unique Room ID.
  3. Join: Player 2 enters the Room ID to join the match.
  4. Gameplay: Players take turns placing their symbols (X or O).
  5. Detection: The system automatically detects the Winner or a Draw.
  6. Storage: All game results are automatically stored in the database.
  7. Restart: Restart option allows both players to restart with a confirmation system.

Restart System

The game features a synchronized restart mechanism to ensure both players are ready for a rematch.

  • Mutual Confirmation: Restarting requires approval from both players.
  • Countdown Timer: A timer starts as soon as the first player requests a restart.
  • New Match Logic: Once both players confirm:
    • The old game is closed.
    • A new game is created within the same room.
    • Symbol Swap: Players automatically swap symbols ($X \leftrightarrow O$) for the new round.

Game History & Replay

Each player has access to a personalized history of their past performance.

History Details

You can track your progress through the following match data:

  • Opponent Username: See who you played against.
  • Match Result: Clear indicators of WIN, LOSS, or DRAW.
  • Date and Time: Precise timestamp of when the match took place.

Replay

Stored moves allow replaying a full game by fetching:

GET /game/:gameId/moves

API Endpoints

Create Game

POST /game/create

Get Game History

GET /game/history

Get Game Moves (Replay)

GET /game/:gameId/moves

Socket.IO Events

The real-time communication is handled via Socket.IO events to ensure seamless synchronization between players.

Client โ†’ Server (Emits)

These events are sent from the player's browser to the server.

Event Description
joinRoom Sent when a player enters a Room ID to join a session.
playerMove Sent when a player clicks on a cell to place their symbol.
gameOver Triggered when a terminal state (Win/Draw) is reached locally.
requestRestart Sent when a player initiates or confirms a rematch request.

Server โ†’ Client (Listen)

The client listens for these events to update the UI in real-time.

Event Description
assignSymbol Informs the player if they are playing as X or O.
opponentMove Notifies the client of the specific move made by the other player.
opponentConnected Sent when the second player successfully enters the room.
opponentLeft Alerts the player if their opponent disconnects during the game.
restartCountdown Triggers the visual timer when the first restart request is made.
restartConfirmed Notifies both clients to reset the board and swap symbols.
restartCanceled Sent if the countdown expires without a mutual confirmation.
gameFinished Finalizes the match state and triggers the database storage.

๐Ÿ‘จโ€๐Ÿ’ป Author

Developed by [Savaxc]

๐Ÿ“Œ Full-Stack Developer (React + Node.js + PostgreSQL)

About

The classic Tic Tac Toe multiplayer game (Fullstack, WebSocket, JWT authentication, PostgreSQL)

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages