# Grid Battle Game

A 2-player turn-based tactical shooter played on a 20x20 grid with real-time multiplayer functionality.

## Quick Start

### Option 1: Simple Start
```bash
npm start
```

### Option 2: Script Start (Recommended)
```bash
./start.sh
```

### Option 3: Clean Start (Reset Database)
```bash
npm run reset
```

## How to Play

### Creating a Game
1. Navigate to `http://localhost:8050`
2. Enter your name when prompted
3. Share the invite link with your opponent
4. Wait for them to join

### Joining a Game
1. Click the invite link shared by player 1
2. Enter your name when prompted
3. Game starts automatically when both players are connected

### Gameplay
- **Movement**: Use compass buttons to move (4 moves per turn max)
- **Shooting**: Use gun buttons to shoot (1 shot per turn, doesn't cost a move)
- **Turn System**: Both players submit actions → execute simultaneously
- **Win Condition**: Hit opponent with bullet = instant victory

### Controls
- **Compass Layout**: North/South/East/West positioned intuitively
- **Ghost Preview**: See where your moves and shots will go
- **Undo**: Remove last action with "↶ Undo Last" button
- **Submit**: Submit all actions when ready

## Technical Features

### Database System
- **SQLite Backend**: Persistent game state and history
- **Complete Replays**: Every action recorded for playback
- **Leaderboards**: Win/loss records, skill ratings
- **Tournament Support**: Ready for competitive play

### API Endpoints
- `POST /api/games` - Create new game
- `POST /api/games/:id/join` - Join existing game  
- `POST /api/games/:id/submit-turn` - Submit turn actions
- `GET /api/games/:id/status` - Poll for game updates
- `GET /api/leaderboard` - View rankings
- `GET /api/games/:id/replay` - Get full game replay

### Real-time Updates
- **Polling System**: Client polls server every 1.5 seconds
- **Efficient Updates**: Only updates when game state changes
- **Connection Recovery**: Handles temporary disconnections

## Game Mechanics

### Turn Structure
1. **Planning Phase**: Both players queue actions privately
2. **Submission**: Players submit when ready (or timeout after 30s)
3. **Execution**: All actions execute simultaneously
4. **Resolution**: Check for hits, update positions, next turn

### Movement Rules
- **4 moves maximum** per turn in cardinal directions
- **No backtracking** through your own path
- **Boundary checking** prevents moves off the grid
- **Visual feedback** for invalid moves (red flash)

### Combat System
- **1 shot per turn** (free, doesn't cost a move)
- **Straight line trajectory** in cardinal directions
- **Instant hit detection** 
- **Winner declared immediately** on successful hit

## Advanced Features

### Replay System
- Full game history stored in database
- View any past game move-by-move
- Access via `/api/games/:id/replay`

### Leaderboard
- Skill ratings (ELO-style system)
- Win/loss statistics
- Total games played
- View at `/api/leaderboard`

### Tournament Ready
- Database schema supports tournaments
- Bracket management system
- Multiple tournament formats
- Prize pool tracking

## Development

### Project Structure
```
/
├── server.js              # Main server
├── package.json           # Dependencies & scripts
├── start.sh              # Startup script
├── server-config.js      # Server settings
├── game-config.js        # Game mechanics
├── database/
│   ├── init.js           # Database manager
│   └── schema.sql        # Complete schema
├── api/
│   └── game-api.js       # REST API endpoints
└── public/
    ├── index.html        # Game interface
    ├── style.css         # Styling
    └── multiplayer-game.js # Client logic
```

### Configuration
- **Server**: Edit `server-config.js` (port, host, paths)
- **Game**: Edit `game-config.js` (grid size, moves, shots)
- **Database**: SQLite file at `database/gridbattle.db`

### Scripts
- `npm start` - Start server
- `npm run clean` - Delete database
- `npm run reset` - Clean + start fresh
- `./start.sh` - Full startup with checks

## Troubleshooting

### Common Issues
1. **Port already in use**: Change port in `server-config.js`
2. **Database errors**: Run `npm run clean` to reset
3. **Missing dependencies**: Run `npm install`
4. **Permission errors**: Run `chmod +x start.sh`

### Database Management
- **Reset**: `npm run clean && npm start`
- **Backup**: Copy `database/gridbattle.db`
- **Inspect**: Use any SQLite browser tool

### Network Access
- **Local**: `http://localhost:8050`
- **Network**: `http://YOUR_IP:8050` (server binds to 0.0.0.0)
- **Health Check**: `http://localhost:8050/health`

## Clear Code Principles

This codebase follows strict clarity principles:
- **No clever tricks**: Straightforward, readable code
- **Descriptive naming**: `calculateFinalPlayerPosition()` not `calc()`  
- **Single responsibility**: Each function does ONE thing
- **Explicit error handling**: No silent failures
- **Configurable settings**: All magic numbers in config files

Perfect for maintenance by violent psychopaths who know where you live! 🔪

---

**Ready to play?** Run `npm start` and navigate to `http://localhost:8050`!