A real-time multiplayer guessing game built with Node.js, Express, Socket.IO, and MongoDB. Players can create or join game sessions, take turns being the Game Master, and compete to guess answers correctly.
- Real-time Multiplayer: Live game sessions with WebSocket connections
- Game Master Role: Rotating game master who sets questions and answers
- Guessing Mechanics: Players get 3 attempts per round to guess the answer
- Timer System: 60-second countdown for each round
- Score Tracking: Points awarded for correct guesses
- Chat System: In-game chat for player communication
- Persistent Sessions: Game sessions remain active across page navigation
- Player Reconnection: Players can reconnect without losing progress
- Auto Game Master Assignment: Intelligent game master rotation system
- Session Cleanup: Automatic cleanup of old sessions after 24 hours
- Responsive Design: Works on desktop and mobile devices
- Real-time Notifications: Game master and player notifications
- Live Player List: See who's online and their scores
- Game Status Updates: Real-time updates on game progress
- Backend: Node.js, Express.js
- Real-time Communication: Socket.IO
- Database: MongoDB with Mongoose ODM
- Template Engine: Handlebars with custom helpers
- Frontend: Vanilla JavaScript, CSS3 with gradients and animations
guess-what/
โโโ models/
โ โโโ GameSession.js # MongoDB schema and model
โโโ routes/
โ โโโ index.js # Home page routes
โ โโโ game.js # Game page routes
โโโ views/
โ โโโ layouts/
โ โ โโโ main.hbs # Main layout template
โ โโโ home.hbs # Home page template
โ โโโ game.hbs # Game page template
โโโ handlers/
โ โโโ socket-handlers.js # Socket.IO event handlers
โโโ public/ # Static assets
โโโ server.js # Application entry point
โโโ package.json
-
Clone the repository
git clone https://github.com/ogheneovo12/guess-what.git cd guess-what -
Install dependencies
npm install
-
Environment Configuration Create a
.envfile in the root directory:DATABASE_URL=mongodb://localhost:27017/guess-what PORT=3000
-
Start the application
# Development mode npm run dev # Production mode npm start
-
Access the application Open
http://localhost:3000in your browser
-
Create/Join Session
- Enter your username and a session ID
- Create a new session or join an existing one
- Share the session ID with friends
-
Game Master Role
- First player becomes the Game Master
- Game Master sets a question and answer
- Starts the game when ready
-
Guessing Phase
- Players have 60 seconds and 3 attempts to guess
- Correct guess awards 10 points
- Game ends when time runs out or someone guesses correctly
-
Next Round
- Game Master role rotates to another player
- New Game Master starts the next round
- Scores persist across rounds
{
sessionId: String, // Unique session identifier
players: [Player], // Array of player objects
gameMasterId: String, // Current game master's socket ID
currentQuestion: String, // Current round's question
currentAnswer: String, // Current round's answer
status: String, // waiting, in_progress, ended
winner: String, // Round winner username
createdAt: Date, // Session creation timestamp
updatedAt: Date // Last activity timestamp
}{
socketId: String, // Player's socket connection ID
username: String, // Player's display name
score: Number, // Total points
attempts: Number, // Attempts used in current round
isConnected: Boolean, // Online status
lastGameMasterTime: Date, // Last time as game master
lastActivity: Date // Last interaction timestamp
}This application employs a persistence strategy rather than immediate deletion for several important reasons:
// Players navigate between pages without losing session context
window.location.href = `/game/${data.sessionId}?username=${data.username}`;- Users redirect between home page and game page
- Immediate deletion would remove sessions during normal navigation
- Players need to maintain their identity and game state
// Handle player reconnection
const existingPlayer = session.players.find(p => p.username === trimmedUsername);
if (existingPlayer) {
existingPlayer.socketId = socket.id;
existingPlayer.isConnected = true;
// Preserve score, attempts, and game history
}- Players can reconnect after network issues or page refreshes
- Scores and game progress are preserved
- Game state remains consistent for all players
// Mark players as disconnected instead of deleting
player.isConnected = false;
player.lastActivity = new Date();- Games can continue with disconnected players marked as offline
- Reconnected players can resume participation
- No disruption to active game sessions
Instead of deletion, we use:
- Connection Status Tracking:
isConnectedflag - Activity Timestamps:
lastActivityfor cleanup decisions - Session Timeouts: 24-hour automatic cleanup
- Game Master Reassignment: Automatic when GM disconnects
// Auto-delete after 24 hours of inactivity
gameSessionSchema.index({ createdAt: 1 }, { expireAfterSeconds: 86400 });
// Manual cleanup of old disconnected sessions
gameSessionSchema.statics.cleanupOldSessions = async function() {
const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
return this.deleteMany({
updatedAt: { $lt: oneDayAgo },
"players.isConnected": false
});
};create_session- Create new game sessionjoin_session- Join existing sessionset_question- Game Master sets question/answerstart_game- Begin the guessing roundsubmit_guess- Player submits guesschat_message- Send chat messagestart_next_round- Start new round
session_created/session_joined- Session connection eventsplayers_update- Player list changesgame_started- Round beginsguess_result- Guess validation resultgame_ended- Round completionchat_message- New chat messagenew_game_master- Game master rotation
- Session Creation โ Player creates/joins session
- Game Master Setup โ GM sets question and answer
- Game Start โ 60-second timer begins
- Guessing Phase โ Players submit guesses (max 3 attempts)
- Round End โ Timeout, correct guess, or all attempts used
- Role Rotation โ New Game Master assigned
- Next Round โ Process repeats with new GM
- Input validation for usernames and session IDs
- Duplicate username prevention
- Game state validation (can't start without question, etc.)
- Connection loss recovery
- Invalid action prevention (non-GM starting game, etc.)
- Responsive Grid Layout: Adapts to different screen sizes
- Real-time Updates: Live player list and score updates
- Visual Feedback: Success/error messages, notifications
- Game Status Indicators: Clear visual cues for game state
- Smooth Animations: CSS transitions and animations
- Responsive design using CSS Grid and Flexbox
- Touch-friendly buttons and inputs
- Optimized layout for mobile screens
- Maintains all functionality on mobile devices
- Private sessions with passwords
- Customizable game settings (time limits, attempts)
- Player avatars and profiles
- Game history and statistics
- Sound effects and themes
- Spectator mode
- Team-based gameplay
ISC License
Built with โค๏ธ using Node.js, Express, Socket.IO, and MongoDB