Repository files navigation # 🎮 Tic Tac Toe Multiplayer - Full Stack Next.js Application
A comprehensive full-stack multiplayer Tic Tac Toe game built with **Next.js 14+** and **MongoDB Atlas**. This project demonstrates all four Next.js rendering strategies (SSR, CSR, SSG, ISR) along with complete game functionality, player statistics, and game replay features.
## 🚀 Features
### Core Gameplay
- ✅ **Two-player multiplayer** - Create or join games with unique usernames
- ✅ **Real-time gameplay** - Turn-based game with live updates
- ✅ **Game validation** - Automatic win/draw detection
- ✅ **Move history** - Complete tracking of all moves with timestamps
### Pages & Rendering Strategies
- 🏠 **Home Page (SSG)** - Static site generation for game instructions and interface
- 🎯 **Game Board (CSR)** - Client-side rendering for real-time gameplay
- 🏆 **Leaderboard (SSR)** - Server-side rendering for fresh rankings on every request
- 📜 **History Page (ISR)** - Incremental static regeneration for player game history
- 🎬 **Game Replay** - Step-by-step replay of completed games
### Additional Features
- 📊 Player statistics (wins, losses, draws, win rate)
- 🔄 Game replay with play/pause controls
- 🌙 Dark mode support
- 📱 Responsive design with Tailwind CSS
- 🎨 Modern UI with smooth transitions
## 🛠️ Tech Stack
- **Framework:** Next.js 14+ (App Router)
- **Database:** MongoDB Atlas
- **ORM:** Mongoose
- **Language:** JavaScript/JSX
- **Styling:** Tailwind CSS
- **Deployment:** Vercel-ready
## 📁 Project Structure
```
tic_tac_toe/
├── src/
│ ├── app/
│ │ ├── api/
│ │ │ ├── players/ # Player management API
│ │ │ ├── games/ # Game management API
│ │ │ │ ├── [gameId]/ # Game-specific endpoints
│ │ │ │ │ ├── join/ # Join game endpoint
│ │ │ │ │ ├── move/ # Make move endpoint
│ │ │ │ │ └── moves/ # Get moves for replay
│ │ │ │ └── open/ # Get open games
│ │ │ └── history/ # Player history API
│ │ ├── game/[gameId]/ # Game board page (CSR)
│ │ ├── leaderboard/ # Leaderboard page (SSR)
│ │ ├── history/ # History page (ISR)
│ │ │ └── [gameId]/ # Game replay page
│ │ ├── layout.tsx # Root layout with metadata
│ │ └── page.tsx # Home page (SSG)
│ ├── components/
│ │ └── HomeClient.jsx # Client component for home page
│ ├── lib/
│ │ ├── mongodb.js # MongoDB connection
│ │ └── gameLogic.js # Game logic utilities
│ └── models/
│ ├── Player.js # Player schema
│ ├── Game.js # Game schema
│ └── Move.js # Move schema
├── public/ # Static assets
└── package.json
```
## 📊 Database Schema
### Players Collection
```javascript
{
username: String (unique),
wins: Number,
losses: Number,
draws: Number,
timestamps: true
}
```
### Games Collection
```javascript
{
player1: ObjectId (ref: 'players'),
player2: ObjectId (ref: 'players'),
status: String ('open' | 'active' | 'finished'),
winner: ObjectId (ref: 'players'),
currentTurn: ObjectId (ref: 'players'),
board: [String] (9 elements),
isDraw: Boolean,
endedAt: Date,
timestamps: true
}
```
### Moves Collection
```javascript
{
gameId: ObjectId (ref: 'Games'),
playerId: ObjectId (ref: 'players'),
position: Number (0-8),
symbol: String ('X' | 'O'),
timestamp: Date,
timestamps: true
}
```
## 🔧 Setup Instructions
### Prerequisites
- Node.js 18+ installed
- MongoDB Atlas account (or local MongoDB)
- npm or yarn package manager
### Installation
1. **Clone the repository**
```bash
cd tic_tac_toe
```
2. **Install dependencies**
```bash
npm install
```
3. **Configure environment variables**
Create a `.env.local` file in the root directory:
```env
MONGODB_URI=mongodb+srv://krishna:krishna1234@cluster0.i7ftluu.mongodb.net/tictactoe?retryWrites=true&w=majority
```
**Note:** The MongoDB URI is already configured in the code, but you can override it with the environment variable.
4. **Verify MongoDB Collections**
Ensure your MongoDB Atlas database has these collections:
- `players` (lowercase 'p')
- `Games` (uppercase 'G')
- `Moves` (uppercase 'M')
5. **Run the development server**
```bash
npm run dev
```
6. **Open your browser**
Navigate to [http://localhost:3000](http://localhost:3000)
## 🎮 How to Play
1. **Enter Username** - Choose a unique username to identify yourself
2. **Create or Join Game** - Start a new game or join an existing open game
3. **Play** - Take turns placing X or O on the board
4. **Win** - Get three in a row (horizontal, vertical, or diagonal) to win!
5. **View Stats** - Check the leaderboard and your game history
## 🎯 Rendering Strategies Explained
### 1. Static Site Generation (SSG) - Home Page (`/`)
- **How it works:** Page is generated at build time
- **Why:** Static content like instructions doesn't change frequently
- **Benefits:** Fastest page load, great for SEO
### 2. Client-Side Rendering (CSR) - Game Board (`/game/[gameId]`)
- **How it works:** Data fetched on the client after page load
- **Why:** Real-time gameplay requires frequent updates
- **Benefits:** Interactive, dynamic updates without page refresh
### 3. Server-Side Rendering (SSR) - Leaderboard (`/leaderboard`)
- **How it works:** Fresh data fetched on every request
- **Why:** Leaderboard needs to show current rankings
- **Benefits:** Always up-to-date data, good for SEO
### 4. Incremental Static Regeneration (ISR) - History (`/history`)
- **How it works:** Static page regenerated periodically
- **Why:** Balance between static and dynamic content
- **Benefits:** Fast load times with periodic updates
## 🔌 API Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/api/players` | GET | Fetch all players for leaderboard |
| `/api/players` | POST | Create new player (unique username) |
| `/api/games` | POST | Create a new game |
| `/api/games/open` | GET | Fetch list of open games |
| `/api/games/[gameId]` | GET | Fetch details of one game |
| `/api/games/[gameId]/join` | POST | Join an open game |
| `/api/games/[gameId]/move` | POST | Submit a move |
| `/api/games/[gameId]/moves` | GET | Get all moves for replay |
| `/api/history/[playerId]` | GET | Fetch a player's full game history |
## 🎨 UI Features
- **Modern Design** - Clean, professional interface with Tailwind CSS
- **Dark Mode** - Automatic dark mode support
- **Responsive** - Works on desktop, tablet, and mobile
- **Animations** - Smooth transitions and loading states
- **Accessibility** - Semantic HTML and proper ARIA labels
## 🚀 Deployment
### Deploy to Vercel
1. Push your code to GitHub
2. Import project in Vercel
3. Add environment variable: `MONGODB_URI`
4. Deploy!
```bash
npm run build
npm start
```
## 📝 SEO & Metadata
Each page includes proper metadata:
- Title tags
- Meta descriptions
- Open Graph tags
- Semantic HTML structure
## 🧪 Testing the Application
1. **Create two players** - Open two browser windows/tabs
2. **Player 1:** Enter username and create a game
3. **Player 2:** Enter different username and join the game
4. **Play the game** - Take turns making moves
5. **Check leaderboard** - View updated rankings
6. **View history** - See past games and replay them
## 🐛 Troubleshooting
### MongoDB Connection Issues
- Verify your IP is whitelisted in MongoDB Atlas
- Check the connection string format
- Ensure database user has proper permissions
### Build Errors
- Clear `.next` folder: `rm -rf .next`
- Reinstall dependencies: `rm -rf node_modules && npm install`
- Check Node.js version: `node --version` (should be 18+)
## 📚 Learning Outcomes
This project demonstrates:
- ✅ Next.js App Router architecture
- ✅ All four rendering strategies (SSG, SSR, CSR, ISR)
- ✅ MongoDB integration with Mongoose
- ✅ RESTful API design
- ✅ Real-time game logic
- ✅ State management in React
- ✅ Responsive UI with Tailwind CSS
- ✅ SEO best practices
## 👨💻 Author
**CodingGita**
- Built with Next.js 14+ and MongoDB Atlas
- © 2025 All rights reserved
## 📄 License
This project is created for educational purposes as part of a full-stack development assignment.
---
**Happy Gaming! 🎮**
# tic-tac
About
No description, website, or topics provided.
Resources
Stars
Watchers
Forks
You can’t perform that action at this time.