Skip to content

2xBuild/NextWord-Server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Word Chain Game - Backend

A real-time WebSocket server for a multiplayer word chain game where players take turns creating words that start with the last letter of the previous word.

Features

  • Real-time Multiplayer: WebSocket-based communication for instant game updates
  • Turn-based Gameplay: Automated turn management with configurable time limits
  • Word Validation: Dictionary-based word verification
  • Flexible Scoring: Configurable point systems (fixed or length-based)
  • Room Management: Create and join game rooms with custom configurations
  • Player Management: Automatic handling of disconnections and eliminations
  • Progressive Difficulty: Optional time decrease and difficulty increase per turn

Tech Stack

  • Runtime: Node.js
  • Language: TypeScript
  • WebSocket: ws library
  • Build Tool: TypeScript Compiler (tsc)

Getting Started

Prerequisites

  • Node.js (v16 or higher)
  • npm or yarn

Installation

# Install dependencies
npm install

# Run development server
npm run dev

The WebSocket server will start on ws://localhost:8080

Folder Structure

backend/
├── src/
│   ├── app.ts                    # WebSocket server entry point
│   ├── db/                       # In-memory data stores
│   │   ├── rooms.ts             # Active game rooms
│   │   └── users.ts             # Connected users
│   ├── func/
│   │   ├── GameManager.ts       # Core game logic and turn management
│   │   ├── routeMessage.ts      # WebSocket message router
│   │   ├── routeHandler/        # Message handlers
│   │   │   ├── createRoom.ts    # Room creation logic
│   │   │   ├── joinRoom.ts      # Room joining logic
│   │   │   ├── startGame.ts     # Game initialization
│   │   │   ├── playGame.ts      # Word submission handler
│   │   │   └── sendChatMessage.ts # Chat functionality
│   │   ├── userFunc/            # User management
│   │   │   └── removeUser.ts    # Handle disconnections
│   │   └── utils/               # Utility functions
│   │       ├── generateUniqueRoomId.ts
│   │       ├── isValidWord.ts   # Word validation
│   │       ├── jsonParser.ts    # Message parsing
│   │       └── validateUsername.ts
│   └── interfaces/              # TypeScript interfaces
├── dist/                        # Compiled JavaScript (generated)
├── package.json
├── tsconfig.json
└── readme.md

Architecture

WebSocket Message Flow

  1. Client connects → WebSocket connection established
  2. Client sends messagejsonParser parses JSON
  3. Message routedrouteMessage directs to appropriate handler
  4. Handler processes → Business logic executed
  5. Response sent → Results broadcast to relevant clients

Game Flow

  1. Room Creation: Host creates room with custom configuration
  2. Players Join: Other players join using room ID
  3. Game Start: Host starts game when ready
  4. Turn Management: GameManager handles turns automatically
  5. Word Submission: Players submit words during their turn
  6. Validation: Words checked for validity and game rules
  7. Scoring: Points awarded based on configuration
  8. Game End: Last remaining player wins

WebSocket API

Message Format

All messages follow this structure:

{
  "type": "MESSAGE_TYPE",
  "payload": { /* message-specific data */ }
}

Message Types

  • CREATE_ROOM: Create a new game room
  • JOIN_ROOM: Join an existing room
  • START_GAME: Begin the game (host only)
  • PLAY_GAME: Submit a word during your turn
  • CHAT_MESSAGE: Send a chat message

For detailed API documentation, see api_docs.md

Game Configuration

When creating a room, you can configure:

  • max_players: Maximum number of players (2-8)
  • init_time_per_turn: Initial time limit per turn (seconds)
  • min_word_len: Minimum word length (3-5)
  • diff: Difficulty level (easy/medium/hard)
  • prg_time_dcr: Progressive time decrease (boolean)
  • prg_diff_incr: Progressive difficulty increase (boolean)
  • reward_by_word_length: Award points based on word length (boolean)

Contributing

Code Style

  • Use TypeScript for all new code
  • Follow existing naming conventions
  • Add comments for complex logic
  • Keep functions focused and single-purpose

Adding New Features

  1. Create a new route handler in src/func/routeHandler/
  2. Register the handler in src/func/routeMessage.ts
  3. Update interfaces if needed in src/interfaces/
  4. Test thoroughly with multiple clients

Adding New Message Types

  1. Define the message type in routeMessage.ts
  2. Create handler function in routeHandler/
  3. Add payload interface if needed
  4. Document in api_docs.md

Testing

  1. Start the dev server: npm run dev
  2. Connect with a WebSocket client
  3. Test all message types and edge cases
  4. Verify error handling and disconnection scenarios

Common Tasks

Add a new utility function:

  • Create file in src/func/utils/
  • Export the function
  • Import where needed

Modify game rules:

  • Edit src/func/GameManager.ts
  • Update validation logic in validateWord()
  • Adjust scoring in calculatePoints()

Change data structures:

  • Update interfaces in src/db/rooms.ts or src/db/users.ts
  • Update all references throughout the codebase

License

ISC

Support

For issues or questions, please open an issue on the repository.

About

Ws server for NextWord game

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published