### Start Development Server Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Start the development server to begin working on the project. ```bash bun run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Install all project dependencies using Bun. ```bash bun install ``` -------------------------------- ### Install haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/README.md Install the haxball.js package using npm. This is the first step to using the library. ```sh npm install haxball.js ``` -------------------------------- ### Basic Module Usage Example Source: https://github.com/mertushka/haxball.js/blob/main/README.md A fundamental example demonstrating how to initialize haxball.js and configure a basic Haxball room. This includes setting room name, player limits, and score/time limits. ```js import HaxballJS from 'haxball.js'; HaxballJS().then((HBInit) => { // Same as in Haxball Headless Host Documentation const room = HBInit({ roomName: 'Haxball.JS', maxPlayers: 16, public: true, noPlayer: true, token: 'YOUR_TOKEN_HERE', // Required }); room.setDefaultStadium('Big'); room.setScoreLimit(5); room.setTimeLimit(0); room.onRoomLink = function (link) { console.log(link); }; // If there are no admins left in the room give admin to one of the remaining players. function updateAdmins() { // Get all players var players = room.getPlayerList(); if (players.length == 0) return; // No players left, do nothing. if (players.find((player) => player.admin) != null) return; // There's an admin left so do nothing. room.setPlayerAdmin(players[0].id, true); // Give admin to the first non admin player in the list } room.onPlayerJoin = function (player) { updateAdmins(); }; room.onPlayerLeave = function (player) { updateAdmins(); }; }); ``` -------------------------------- ### Start Game Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Initiates the game. Use this after configuring room settings. ```typescript startGame(): (): void ``` -------------------------------- ### Get Room Link Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md An example of how to get the room URL when it becomes available. ```javascript room.onRoomLink = (url) => { console.log(`Room available at: ${url}`); }; ``` -------------------------------- ### startGame Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Starts the game. If a game is already in progress, this method does nothing. ```APIDOC ## startGame() ### Description Starts the game. If a game is already in progress this method does nothing. ### Method (Implicitly a method call on a Room object, e.g., `room.startGame(...)`) ### Parameters (No parameters) ### Request Example ```javascript room.startGame(); ``` ### Response #### Success Response (void return type, no specific success response) #### Response Example (No explicit response example for void methods) ``` -------------------------------- ### Start the Game Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet demonstrates how to initiate the game. Call this method when the room is ready and players have joined. ```javascript room.startGame(); ``` -------------------------------- ### Install haxball.js with Bun Source: https://github.com/mertushka/haxball.js/blob/main/README.md Install the haxball.js package using Bun. It also includes a command to trust the 'node-datachannel' dependency, which is experimental. ```bash bun install haxball.js bun pm trust node-datachannel bun index.ts ``` -------------------------------- ### Start Recording Replay Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Begins recording the current game session for replay purposes. ```typescript startRecording(): (): void ``` -------------------------------- ### Basic Usage Example Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Demonstrates initializing haxball.js, creating a room, configuring game settings, and listening to player join and team goal events. ```javascript import HaxballJS from 'haxball.js'; // Initialize HaxballJS().then((HBInit) => { // Create room const room = HBInit({ roomName: 'My Room', maxPlayers: 16, noPlayer: true, token: 'YOUR_TOKEN' }); // Configure game room.setDefaultStadium('Big'); room.setScoreLimit(5); room.setTimeLimit(0); // Listen to events room.onPlayerJoin = (player) => { console.log(`${player.name} joined`); room.sendAnnouncement(`Welcome ${player.name}!`); }; room.onTeamGoal = (team) => { console.log(`Team ${team} scored!`); }; }); ``` -------------------------------- ### Initialize and Create Room Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Example of initializing Haxball.js and creating a new room with specified settings. Ensure the HAXBALL_TOKEN environment variable is set. ```javascript import HaxballJS from 'haxball.js'; HaxballJS({ debug: true }).then((HBInit) => { const room = HBInit({ roomName: 'Test Room', token: process.env.HAXBALL_TOKEN, noPlayer: true }); }); ``` -------------------------------- ### Handle Game Start Event Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Logs the name of the player who started the game. This event is triggered when a new game begins. ```javascript room.onGameStart = (byPlayer) => { if (byPlayer) console.log(`Started by ${byPlayer.name}`); }; ``` -------------------------------- ### Start and Stop Game Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Control the game's lifecycle by starting and stopping it. Use these functions to manage when the game is active. ```javascript // Start/stop game room.startGame(); room.stopGame(); ``` -------------------------------- ### Recording Methods Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Methods for starting and stopping game recording for replays. ```APIDOC ## Recording Methods ### startRecording #### Description Starts recording the current game for a replay. #### Method `startRecording(): void` ### stopRecording #### Description Stops recording and returns the recorded replay data. #### Method `stopRecording(): Uint8Array | null` ``` -------------------------------- ### Starting Replay Recording in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Initiate replay recording with startRecording. Remember to call stopRecording afterwards to prevent memory leaks. ```typescript startRecording(): void ``` ```javascript room.startRecording(); // ... game happens ... const replayData = room.stopRecording(); ``` -------------------------------- ### Minimal Room Initialization Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md Initializes a Haxball room with only the required token. Use this for basic setup. ```javascript const room = HBInit({ token: 'YOUR_TOKEN_HERE' }); ``` -------------------------------- ### Start and Stop Recording Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Initiate game recording to capture replay data. Stop recording to retrieve the data and save it. ```javascript // Start recording room.startRecording(); // ... game plays ... // Stop and save replay const replayData = room.stopRecording(); if (replayData) { fs.writeFileSync('replay.hbr', replayData); } ``` -------------------------------- ### onGameStart Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Handles the event when a game begins. It can identify if a specific player initiated the game start. ```APIDOC ## onGameStart ### Description Event called when a game starts. ### Method Event Handler ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **byPlayer** (`PlayerObject | null`) - Required - The player who caused the event (can be null if not caused by a player). ``` -------------------------------- ### Standard Competitive Game Room Setup Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Configures a public room for competitive play with a specified name, player limit, and game settings. 'noPlayer: true' is recommended for headless bots. ```javascript const room = HBInit({ roomName: 'Competitive 5v5', maxPlayers: 10, public: true, noPlayer: true, token: process.env.HAXBALL_TOKEN }); room.setDefaultStadium('Big'); room.setScoreLimit(5); room.setTimeLimit(90); ``` -------------------------------- ### Initialize HaxballJS and Create a Room Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet shows the basic setup for initializing the HaxballJS library and creating a new room with essential configuration. It returns a Promise that resolves to the HBInit function, which is then used to create the room object. ```javascript HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'My Room', noPlayer: true, token: 'TOKEN' }); }); ``` -------------------------------- ### Game Event Handlers Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Set up listeners for core game events including start, tick, pause, and position resets. ```javascript // Game events room.onGameStart = (byPlayer) => { /* ... */ }; room.onGameTick = () => { /* ... */ }; room.onGamePause = (byPlayer) => { /* ... */ }; room.onPositionsReset = () => { /* ... */ }; ``` -------------------------------- ### Game State Methods Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Methods for controlling the game state, including starting, stopping, and pausing the game. ```APIDOC ## Game State Methods ### startGame #### Description Starts the game. #### Method `startGame(): void` ### stopGame #### Description Stops the game. #### Method `stopGame(): void` ### pauseGame #### Description Pauses or resumes the game. #### Method `pauseGame(pauseState: boolean): void` ``` -------------------------------- ### Handle Player Join Event Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Example of handling the `onPlayerJoin` event to log player information and send a welcome announcement. This snippet assumes a `room` object is already initialized. ```javascript room.onPlayerJoin = (player) => { console.log(`${player.name} (${player.id}) joined`); room.sendAnnouncement(`Welcome ${player.name}!`); }; ``` -------------------------------- ### Get All Players Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Retrieves a list of all players currently in the room. ```typescript getPlayerList(): (): PlayerObject[] ``` -------------------------------- ### Physics & Discs Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Methods for interacting with discs in Haxball.js, including getting and setting their properties. ```APIDOC ## Physics & Discs ### `getDiscCount()` #### Description Get the total number of discs in the game. #### Returns - `number`: The total disc count. ### `getDiscProperties(discIndex: number)` #### Description Retrieve the properties of a specific disc. #### Parameters ##### Path Parameters - **discIndex** (number) - Required - The index of the disc to query. #### Returns - `DiscPropertiesObject | null`: An object containing the disc's properties, or null if the index is invalid. ### `setDiscProperties(discIndex: number, properties: Partial)` #### Description Update the properties of a specific disc. #### Parameters ##### Path Parameters - **discIndex** (number) - Required - The index of the disc to modify. ##### Request Body - **properties** (Partial) - Required - An object containing the properties to update. #### Returns - `void` ### `getPlayerDiscProperties(playerId: number)` #### Description Get the properties of the disc controlled by a specific player. #### Parameters ##### Path Parameters - **playerId** (number) - Required - The ID of the player whose disc properties to retrieve. #### Returns - `DiscPropertiesObject | null`: An object containing the player's disc properties, or null if the player or disc is not found. ### `setPlayerDiscProperties(playerId: number, properties: Partial)` #### Description Set the properties of the disc controlled by a specific player. #### Parameters ##### Path Parameters - **playerId** (number) - Required - The ID of the player whose disc properties to set. ##### Request Body - **properties** (Partial) - Required - An object containing the properties to set. #### Returns - `void` ``` -------------------------------- ### Player Management Examples Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Common patterns for managing players within a Haxball room using the RoomObject API. This includes kicking, banning, unbanning, setting admin status, and moving players between teams. ```APIDOC ## Player Management ### Kick a player ```javascript room.kickPlayer(playerId, 'Reason', false); ``` ### Ban a player ```javascript room.kickPlayer(playerId, 'Permanent ban', true); ``` ### Unban a player ```javascript room.clearBan(playerId); ``` ### Make admin ```javascript room.setPlayerAdmin(playerId, true); ``` ### Move to team ```javascript // Red team room.setPlayerTeam(playerId, 1); // Blue team room.setPlayerTeam(playerId, 0); // None team room.setPlayerTeam(playerId, 2); ``` ``` -------------------------------- ### Get Disc Properties Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Retrieve the physics properties of a specific disc, identified by its index. This includes position and velocity. ```javascript // Get disc properties const ballProps = room.getDiscProperties(0); const playerDisc = room.getPlayerDiscProperties(playerId); ``` -------------------------------- ### Get Player Information Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Retrieves information about a specific player by their ID. Returns null if the player is not found. ```typescript getPlayer(): (playerId: number) ``` -------------------------------- ### Get Player List Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet shows how to retrieve a list of all players currently in the room. This method is useful for iterating over players or checking their status. ```javascript const players = room.getPlayerList(); ``` -------------------------------- ### Get Game Scores Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Retrieves the current game scores and timing information. Returns null if the game has not started or is not active. ```typescript getScores(): (): ScoresObject | null ``` -------------------------------- ### Build the Project Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Build the project for production or distribution. ```bash bun run build ``` -------------------------------- ### Get Ball Position Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet shows how to get the current position of the ball in the game world. This can be used for various game mechanics or tracking the ball's movement. ```javascript const ballPos = room.getBallPosition(); ``` -------------------------------- ### startRecording Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Initiates the recording of a Haxball replay. Remember to stop it to avoid memory leaks. ```APIDOC ## startRecording() ### Description Starts recording of a haxball replay. ### Method ```typescript startRecording(): void ``` ### Warning Don't forget to call stopRecording or it will cause a memory leak. ### Request Example ```javascript room.startRecording(); // ... game happens ... const replayData = room.stopRecording(); ``` ``` -------------------------------- ### getBallPosition Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Gets the current position of the ball on the field. ```APIDOC ## getBallPosition() ### Description Returns the ball's position in the field. ### Method ```typescript getBallPosition(): { x: number; y: number } | null ``` ### Returns The ball's position as {x, y} or null if no game is in progress. ### Request Example ```javascript const ballPos = room.getBallPosition(); if (ballPos) { console.log(`Ball position: (${ballPos.x}, ${ballPos.y})`); } ``` ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Change your current directory to the cloned haxball.js project folder. ```bash cd haxball.js ``` -------------------------------- ### Production Room Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Set up a public production room with competitive settings. Includes default stadium, score limit, and team settings. ```javascript HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'Official Server', maxPlayers: 12, public: true, noPlayer: true, token: process.env.HAXBALL_TOKEN }); // Set up room with competitive settings room.setDefaultStadium('Big'); room.setScoreLimit(3); room.setTimeLimit(0); // No time limit room.setTeamsLock(false); }); ``` -------------------------------- ### CommonJS HaxballJS Initialization Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Demonstrates how to initialize HaxballJS using CommonJS module syntax. The promise resolves to the HBInit function for room creation. ```javascript const HaxballJS = require('haxball.js').default; HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'CommonJS Room', token: 'YOUR_TOKEN_HERE' }); }); ``` -------------------------------- ### Basic HaxballJS Initialization Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Initializes HaxballJS without any specific configuration. The promise resolves to the HBInit function, which is then used to set up a new room with basic parameters. ```javascript import HaxballJS from 'haxball.js'; HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'My Haxball Room', maxPlayers: 16, public: true, noPlayer: true, token: 'YOUR_TOKEN_HERE' }); }); ``` -------------------------------- ### Get Disc Properties Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Retrieves the properties of a specific disc by its index. Returns null if the index is out of bounds. ```typescript getDiscProperties(discIndex: number): DiscPropertiesObject | null ``` ```javascript const ballProps = room.getDiscProperties(0); if (ballProps) { console.log(`Ball position: (${ballProps.x}, ${ballProps.y}) `); console.log(`Ball speed: (${ballProps.xspeed}, ${ballProps.yspeed}) `); } ``` -------------------------------- ### Get Ball Position Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Retrieves the current position of the ball in the game. Returns null if the game is not active. ```typescript getBallPosition(): (): { x: number; y: number } | null ``` -------------------------------- ### Run Project Tests Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Execute the project's test suite to ensure code quality. ```bash bun run test ``` -------------------------------- ### HBInit Function Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md Initializes a Haxball headless room with the specified configuration. It returns a RoomObject for further control. ```APIDOC ## HBInit Function ### Description Initializes a Haxball headless room with the specified configuration. ### Method `HBInit(roomConfig: RoomConfigObject): RoomObject` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### `roomConfig` (`RoomConfigObject`) - Required Configuration object for the room. All properties are optional. - **roomName** (`string`) - Optional - The name for the room displayed in the room list. Defaults to "Unnamed". - **playerName** (`string`) - Optional - The name for the host player. Ignored if noPlayer is true. Defaults to "Host". - **password** (`string`) - Optional - The password for the room. If omitted, no password is set. - **maxPlayers** (`number`) - Optional - Maximum number of players the room accepts. Must be greater than 0. Defaults to 20. - **public** (`boolean`) - Optional - If true the room will appear in the room list and be publicly joinable. Defaults to true. - **geo** (`object`) - Optional - GeoLocation override for the room. Must have properties: code (string), lat (number), lon (number). - **token** (`string`) - Required - Token obtained from https://www.haxball.com/headlesstoken to skip recaptcha. These tokens expire after a few minutes. - **noPlayer** (`boolean`) - Optional - If true, the room player list will be empty and playerName is ignored. Recommended to set to true. When true, events will have null as the byPlayer argument when caused by the host. Defaults to false. ### Request Example ```javascript const room = HBInit({ token: 'YOUR_TOKEN_HERE', roomName: 'My Game Room', maxPlayers: 10, public: false }); ``` ### Response #### Success Response (200) - **RoomObject** - An object used to control the room and listen to room events. ``` -------------------------------- ### Room Initialization Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Configure room settings during initialization, including name, player name, password, player count, and token. ```typescript HBInit({ roomName: 'My Room', playerName: 'Host', password: 'optional', maxPlayers: 16, public: true, noPlayer: true, // Recommended: no host player geo: { code: 'US', lat: 40, lon: -74 }, token: 'REQUIRED' }); ``` -------------------------------- ### Get Player Disc Properties Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Fetches the properties of a player's disc using their player ID. Returns null if the player does not exist. ```typescript getPlayerDiscProperties(playerId: number): DiscPropertiesObject | null ``` ```javascript const playerDisc = room.getPlayerDiscProperties(3); if (playerDisc) { console.log(`Player position: (${playerDisc.x}, ${playerDisc.y}) `); } ``` -------------------------------- ### Minimal Room Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Creates a room with only the essential 'token' parameter. The room will have default settings for other options. ```javascript const room = HBInit({ token: 'YOUR_HEADLESS_TOKEN' }); ``` -------------------------------- ### HaxballJS Initialization Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md The main entry point for initializing Haxball.js. It takes an optional configuration object and returns a promise that resolves with the HBInit function. ```typescript import HaxballJS from 'haxball.js'; // HaxballJS is the main entry point HaxballJS(config?: HaxballJSConfig): Promise ``` -------------------------------- ### Getting the List of Connected Players in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Obtain an array of all currently connected PlayerObjects using getPlayerList. Useful for iterating through players and accessing their properties. ```typescript getPlayerList(): PlayerObject[] ``` ```javascript const players = room.getPlayerList(); players.forEach(p => { console.log(`${p.name} (ID: ${p.id}) on team ${p.team}`); }); ``` -------------------------------- ### Project Structure Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md The project is organized into src, test, and dist directories, with the main entry point at src/index.ts and type definitions in src/types.ts. ```tree haxball.js/ ├── src/ │ ├── index.ts # Main entry point, HaxballJS function │ └── types.ts # Type definitions and interfaces ├── test/ # Test suite ├── dist/ # Compiled output (CommonJS and ESM) └── package.json # Project metadata and dependencies ``` -------------------------------- ### Get Room Scores Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet demonstrates how to fetch the current scores for both teams in the room. This is essential for displaying game status or implementing score-based logic. ```javascript const scores = room.getScores(); ``` -------------------------------- ### Getting the Ball's Position in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Find the ball's current position on the field using getBallPosition. Returns an object with x and y coordinates, or null if no game is active. ```typescript getBallPosition(): { x: number; y: number } | null ``` ```javascript const ballPos = room.getBallPosition(); if (ballPos) { console.log(`Ball position: (${ballPos.x}, ${ballPos.y})`); } ``` -------------------------------- ### Standard Room Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md Sets up a room with a name, player limit, public visibility, and no host player. Also configures game settings like stadium, score, and time limits. ```javascript const room = HBInit({ roomName: 'My Football Game', maxPlayers: 16, public: true, noPlayer: true, token: process.env.HAXBALL_TOKEN }); room.setDefaultStadium('Big'); room.setScoreLimit(5); room.setTimeLimit(90); ``` -------------------------------- ### Stopping Replay Recording and Getting Data in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Stop recording and retrieve replay data using stopRecording. Returns the replay file contents as a Uint8Array or null if recording was not active. ```typescript stopRecording(): Uint8Array | null ``` ```javascript const replayData = room.stopRecording(); if (replayData) { fs.writeFileSync('replay.hbr', replayData); } ``` -------------------------------- ### Data Flow Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Illustrates the data flow from HaxballJS initialization to RoomObject control and event handling. ```mermaid graph TD HaxballJS(config) ↓ Promise ↓ HBInit(roomConfig) ↓ RoomObject ├─→ Control Methods (sync, async effects) ├─→ Query Methods (getPlayerList, getScores, etc.) └─→ Event Handlers (onPlayerJoin, onGameStart, etc.) ``` -------------------------------- ### HaxballJS Initialization Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/MANIFEST.txt Initializes the HaxballJS library, allowing for optional configuration and support for custom WebRTC implementations and proxy configurations. ```APIDOC ## HaxballJS Function ### Description Initializes the HaxballJS library with optional configuration. ### Method ``` (config?: HaxballJSConfig) ``` ### Parameters #### Request Body - **config** (HaxballJSConfig) - Optional - Configuration object for HaxballJS. ### Request Example ```json { "example": "HaxballJS({ token: 'YOUR_TOKEN' })" } ``` ### Response #### Success Response (void) Initializes the library. ### Notes - Supports custom WebRTC implementations. - Supports proxy configuration for multiple rooms. ``` -------------------------------- ### Getting a Player Object by ID in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Retrieve a specific player's object using getPlayer, providing the player's ID. Returns the PlayerObject or null if the player is not found. ```typescript getPlayer(playerId: number): PlayerObject | null ``` ```javascript const player = room.getPlayer(5); if (player) { console.log(player.name, player.team, player.admin); } ``` -------------------------------- ### Log Kick Rate Limit Settings Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Logs the parameters when the kick rate limit is set. Displays the minimum frames, rate, and burst values. ```javascript room.onKickRateLimitSet = (min, rate, burst, byPlayer) => { console.log(`Kick rate limit set: min=${min}, rate=${rate}, burst=${burst}`); }; ``` -------------------------------- ### Retrieving Game Scores in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Get current game scores using getScores. Returns a ScoresObject containing red and blue scores, time, and time limit, or null if no game is in progress. ```typescript getScores(): ScoresObject | null ``` ```javascript const scores = room.getScores(); if (scores) { console.log(`Red: ${scores.red}, Blue: ${scores.blue}`); console.log(`Time: ${scores.time}s, Limit: ${scores.timeLimit}min`); } ``` -------------------------------- ### Initialize Haxball.js with CommonJS Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Import and initialize the Haxball.js library using CommonJS modules. Ensure you import the default export. ```javascript const HaxballJS = require('haxball.js').default; HaxballJS().then((HBInit) => { const room = HBInit({ token: 'TOKEN' }); }); ``` -------------------------------- ### Common Usage Patterns Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Illustrates common patterns for using the Haxball.js API, such as initializing the library and handling player join events. ```APIDOC ## Common Usage Patterns ### Initialize and Create Room ```javascript import HaxballJS from 'haxball.js'; HaxballJS({ debug: true }).then((HBInit) => { const room = HBInit({ roomName: 'Test Room', token: process.env.HAXBALL_TOKEN, noPlayer: true }); }); ``` ### Handle Player Join ```javascript room.onPlayerJoin = (player) => { console.log(`${player.name} (${player.id}) joined`); room.sendAnnouncement(`Welcome ${player.name}!`); }; ``` ``` -------------------------------- ### HaxballJS Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Configuration options for initializing Haxball.js, including proxy settings, debug logging, and custom WebRTC implementation. ```typescript { proxy?: string; debug?: boolean; webrtc?: CustomWebRTC; } ``` -------------------------------- ### Getting the Total Number of Discs in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Query the total number of discs in the game, including the ball and player discs, using getDiscCount. This typically includes the ball plus one disc per player. ```typescript getDiscCount(): number ``` ```javascript const discCount = room.getDiscCount(); console.log(`Total discs: ${discCount}`); // Usually 1 (ball) + number of players ``` -------------------------------- ### RoomObject Methods Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/MANIFEST.txt Provides a collection of methods for controlling and managing a Haxball room, including player management, game state, and stadium configuration. ```APIDOC ## RoomObject Methods ### Description These methods allow direct control over the Haxball room, its players, and game state. ### Methods #### Player Management - **sendChat(message: string): void** - Sends a chat message to all players in the room. - Example: `room.sendChat('Welcome to the room!')` - **kickPlayer(player: PlayerObject, reason?: string): void** - Kicks a player from the room. - Example: `room.kickPlayer(player, 'No reason given')` - **setAdmin(player: PlayerObject, admin: boolean): void** - Sets or unsets a player as an administrator. - Example: `room.setAdmin(player, true)` #### Game Control - **start(): void** - Starts the game. - Example: `room.start()` - **stop(): void** - Stops the game. - Example: `room.stop()` - **pause(): void** - Pauses the game. - Example: `room.pause()` #### Stadium Configuration - **setStadium(stadium: StadiumObject): void** - Sets the stadium for the room. - Example: `room.setStadium(myCustomStadium)` ### Notes - For a complete list of `RoomObject` methods and their parameters, refer to `api-reference/room-object.md`. ``` -------------------------------- ### Clone the Repository Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Clone your fork of the haxball.js repository to your local machine. ```bash git clone https://github.com/mertushka/haxball.js.git ``` -------------------------------- ### Multiple Rooms Behind One IP Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Configure multiple rooms using different proxy servers to bypass IP limitations. Ensure each room uses a unique token. ```javascript HaxballJS({ proxy: 'http://proxy.example.com:8080' }).then((HBInit) => { // Create up to 2 rooms per IP through different proxies const room1 = HBInit({ roomName: 'Room 1', token: process.env.TOKEN_1 }); const room2 = HBInit({ roomName: 'Room 2', token: process.env.TOKEN_2 }); }); ``` -------------------------------- ### Private Tournament Room Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Sets up a private room for a tournament, requiring a password and not appearing in public lists. 'noPlayer: true' is suitable for automated tournaments. ```javascript const room = HBInit({ roomName: 'Tournament Finals', maxPlayers: 8, password: 'tournament2024', public: false, noPlayer: true, token: process.env.HAXBALL_TOKEN }); ``` -------------------------------- ### HaxballJS Initialization with Proxy Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Initializes HaxballJS with a specified HTTP proxy URL for WebSocket connections. This is useful for managing multiple rooms behind a single IP address. ```javascript HaxballJS({ proxy: "http://proxy.example.com:8080" }).then((HBInit) => { const room = HBInit({ roomName: 'Proxied Room', maxPlayers: 12, token: 'YOUR_TOKEN_HERE' }); }); ``` -------------------------------- ### HaxballJS Initialization Options Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Configure Haxball.js during initialization with options like proxy, debug mode, or custom WebRTC implementation. ```typescript HaxballJS({ proxy: 'http://proxy:8080', // Optional: for multiple rooms per IP debug: true, // Optional: enable debug logging webrtc: CustomWebRTCImpl // Optional: use custom WebRTC }).then((HBInit) => { /* ... */ }); ``` -------------------------------- ### Initialize Haxball.js Room Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Initializes a Haxball.js room with a name and token, and logs the room link upon successful connection. Ensure you replace 'YOUR_TOKEN' with your actual room token. ```javascript import HaxballJS from 'haxball.js'; HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'My Haxball Room', token: 'YOUR_TOKEN' }); room.onRoomLink = (link) => console.log(link); }); ``` -------------------------------- ### High-Performance Environment Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Optimize a room for high performance with increased player capacity and adjusted kick rates. This configuration is suitable for demanding environments. ```javascript HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'Performance Room', maxPlayers: 20, noPlayer: true, token: process.env.HAXBALL_TOKEN }); // Optimize kick rates room.setKickRateLimit(1, 5, 3); // Allow faster, more fluid gameplay }); ``` -------------------------------- ### HaxballJS Initialization with Custom WebRTC Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Initializes HaxballJS using a custom WebRTC implementation. This allows overriding the default node-datachannel library with a different implementation. ```javascript import HaxballJS from 'haxball.js'; import CustomWebRTC from 'custom-webrtc'; HaxballJS({ webrtc: CustomWebRTC }).then((HBInit) => { const room = HBInit({ roomName: 'Custom WebRTC Room', token: 'YOUR_TOKEN_HERE' }); }); ``` -------------------------------- ### Default Export Signature Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md The main entry point function signature. It accepts optional configuration and returns a promise that resolves to the HBInit function. ```typescript export default function HaxballJS(config?: HaxballJSConfig): Promise ``` -------------------------------- ### Storing Haxball Token in .env Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Store your Haxball headless token securely in an environment file. ```bash # .env file HAXBALL_TOKEN=your_token_here ``` -------------------------------- ### Stadium & Settings Methods Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/quick-reference.md Methods for configuring the stadium, score limit, time limit, password, and recaptcha requirements. ```APIDOC ## Stadium & Settings Methods ### setDefaultStadium #### Description Sets the default stadium for the room. #### Method `setDefaultStadium(stadiumName: string): void` ### setCustomStadium #### Description Loads a custom stadium from file contents. #### Method `setCustomStadium(stadiumFileContents: string): void` ### setScoreLimit #### Description Sets the score limit for the game. #### Method `setScoreLimit(limit: number): void` ### setTimeLimit #### Description Sets the time limit for the game in minutes. #### Method `setTimeLimit(limitInMinutes: number): void` ### setPassword #### Description Sets or removes the room password. #### Method `setPassword(pass: string | null): void` ### setRequireRecaptcha #### Description Enables or disables the requirement for recaptcha to join. #### Method `setRequireRecaptcha(required: boolean): void` ``` -------------------------------- ### Configuring Kick Rate Limits in Haxball.js Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Manage kick rate limits with setKickRateLimit to control how frequently players can be kicked. Adjust min, rate, and burst parameters to fine-tune the limits. ```typescript setKickRateLimit(min: number, rate: number, burst: number): void ``` ```javascript room.setKickRateLimit(2, 0, 0); // Default: slow kicks room.setKickRateLimit(1, 5, 3); // Fast kicks with burst ``` -------------------------------- ### HaxballJS Function Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Initializes the Haxball environment and returns a promise that resolves to the HBInit function. This is the primary entry point for using the haxball.js library. ```APIDOC ## HaxballJS Function ### Description The `HaxballJS` function is the main entry point for the haxball.js library. It initializes the Haxball environment with optional configuration and returns a promise that resolves to the `HBInit` function. ### Function Signature ```typescript function HaxballJS(config?: HaxballJSConfig): Promise ``` ### Parameters #### config (`HaxballJSConfig`) - **Type**: `HaxballJSConfig` - **Default**: `undefined` - **Description**: Optional configuration object for HaxballJS. ##### HaxballJSConfig Interface ```typescript interface HaxballJSConfig { proxy?: string; debug?: boolean; webrtc?: { RTCPeerConnection: typeof globalThis.RTCPeerConnection; RTCIceCandidate: typeof globalThis.RTCIceCandidate; RTCSessionDescription: typeof globalThis.RTCSessionDescription; }; } ``` ###### Configuration Properties - **proxy** (`string`): Optional HTTP proxy URL for WebSocket connections (e.g., "http://1.1.1.1:80"). Required if connecting from an IP that already has 2 rooms. Haxball limits 2 rooms per IP address. - **debug** (`boolean`): Enable debug mode for verbose logging. - **webrtc** (`object`): Custom WebRTC implementation providing RTCPeerConnection, RTCIceCandidate, and RTCSessionDescription. Use this to override the default node-datachannel library. ### Return Type - **Type**: `Promise` - **Description**: Returns a `Promise` that resolves to the [HBInit function](room-object.md#hbinit-function), which can be used to create and control Haxball rooms. ### Usage Examples #### Basic Usage ```javascript import HaxballJS from 'haxball.js'; HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'My Haxball Room', maxPlayers: 16, public: true, noPlayer: true, token: 'YOUR_TOKEN_HERE' }); }); ``` #### With Proxy Configuration ```javascript HaxballJS({ proxy: "http://proxy.example.com:8080" }).then((HBInit) => { const room = HBInit({ roomName: 'Proxied Room', maxPlayers: 12, token: 'YOUR_TOKEN_HERE' }); }); ``` #### With Custom WebRTC Implementation ```javascript import HaxballJS from 'haxball.js'; import CustomWebRTC from 'custom-webrtc'; HaxballJS({ webrtc: CustomWebRTC }).then((HBInit) => { const room = HBInit({ roomName: 'Custom WebRTC Room', token: 'YOUR_TOKEN_HERE' }); }); ``` #### With Debug Enabled ```javascript HaxballJS({ debug: true }).then((HBInit) => { // Debug output will be logged to console const room = HBInit({ roomName: 'Debug Room', token: 'YOUR_TOKEN_HERE' }); }); ``` #### CommonJS Usage ```javascript const HaxballJS = require('haxball.js').default; HaxballJS().then((HBInit) => { const room = HBInit({ roomName: 'CommonJS Room', token: 'YOUR_TOKEN_HERE' }); }); ``` ``` -------------------------------- ### Room Configuration with Custom Host Player Name Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Configures a room with a specific host player name. 'noPlayer: false' ensures the host player joins the room, which is not typical for bots. ```javascript const room = HBInit({ roomName: 'Game Server', playerName: 'GameAdmin', maxPlayers: 16, public: true, noPlayer: false, // Host player will join token: process.env.HAXBALL_TOKEN }); ``` -------------------------------- ### HBInit Function Signature Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md The HBInit function initializes a Haxball headless room. It takes a RoomConfigObject and returns a RoomObject. ```typescript function HBInit(roomConfig: RoomConfigObject): RoomObject ``` -------------------------------- ### Set Game Limits Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Configure the score limit and time limit for the game. Time limit is in minutes. ```javascript // Set game parameters room.setScoreLimit(3); room.setTimeLimit(30); // 30 minutes ``` -------------------------------- ### Development Room Configuration Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/configuration.md Configure a private development room with debugging enabled. Keep rooms private during development. ```javascript HaxballJS({ debug: true }).then((HBInit) => { const room = HBInit({ roomName: '[DEV] Test Room', maxPlayers: 4, public: false, // Keep private during development noPlayer: true, token: process.env.HAXBALL_TOKEN }); }); ``` -------------------------------- ### Room with Custom Player Name Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md Sets up a public room with a custom host player name. This is useful for identifying the bot or administrator. ```javascript const room = HBInit({ roomName: 'Game Server', playerName: 'GameAdmin', maxPlayers: 12, public: true, token: 'YOUR_TOKEN_HERE' }); ``` -------------------------------- ### Proxy Configuration Source: https://github.com/mertushka/haxball.js/blob/main/README.md Configure haxball.js to use a proxy server. This is necessary to bypass Haxball's limit of 2 rooms per IP address. ```js HaxballJS({ proxy: "http://1.1.1.1:80", }).then((HBInit) => {...}); ``` -------------------------------- ### HaxballJS Function Signature Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md The main entry point for the haxball.js library. It initializes the necessary connections and returns a promise that resolves to the HBInit function, which is used to create and manage Haxball rooms. ```APIDOC ## Default Export ```typescript export default function HaxballJS(config?: HaxballJSConfig): Promise ``` The main entry point. Returns a promise that resolves to the HBInit function. ``` -------------------------------- ### Handle Player Join Event Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Callback function executed when a new player joins the room. Provides player details. ```typescript onPlayerJoin(player: PlayerJoinObject): void ``` ```javascript room.onPlayerJoin = (player) => { console.log(`${player.name} joined. Auth: ${player.auth}, Connection: ${player.conn}`); }; ``` -------------------------------- ### Handle Player Join Event Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/INDEX.md This snippet demonstrates how to register a callback function for the player join event. The function will be executed whenever a new player joins the room. ```javascript room.onPlayerJoin = (player) => { /* ... */ }; ``` -------------------------------- ### Room with Geolocation Override Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-configuration.md Initializes a room with a custom geolocation, which can influence player latency perception. The room is configured to not have a host player. ```javascript const room = HBInit({ roomName: 'European Server', geo: { code: 'FR', lat: 48.8566, lon: 2.3522 }, noPlayer: true, token: 'YOUR_TOKEN_HERE' }); ``` -------------------------------- ### getPlayerList Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Fetches a list of all currently connected players in the room. ```APIDOC ## getPlayerList() ### Description Returns the current list of players. ### Method ```typescript getPlayerList(): PlayerObject[] ``` ### Returns Array of all currently connected PlayerObjects. ### Request Example ```javascript const players = room.getPlayerList(); players.forEach(p => { console.log(`${p.name} (ID: ${p.id}) on team ${p.team}`); }); ``` ``` -------------------------------- ### HaxballJS Initialization with Debug Enabled Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/haxballjs-function.md Initializes HaxballJS with the debug mode enabled, which provides verbose logging to the console. This is helpful for troubleshooting. ```javascript HaxballJS({ debug: true }).then((HBInit) => { // Debug output will be logged to console const room = HBInit({ roomName: 'Debug Room', token: 'YOUR_TOKEN_HERE' }); }); ``` -------------------------------- ### Fix Code Style and Formatting Source: https://github.com/mertushka/haxball.js/blob/main/CONTRIBUTING.md Automatically fix code style and formatting issues using the provided script. ```bash bun run lint:fix ``` -------------------------------- ### RoomObject Event Handlers Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/MANIFEST.txt Documents the various event handlers available for the RoomObject, allowing developers to react to in-game events such as player joins, goals, and game state changes. ```APIDOC ## RoomObject Event Handlers ### Description These handlers allow you to respond to various events occurring within the Haxball room. ### Events #### Player Events - **onPlayerJoin(player: PlayerObject): void** - Called when a player joins the room. - Example: `room.onPlayerJoin = (player) => { console.log(player.name + ' joined'); }` - **onPlayerLeave(player: PlayerObject): void** - Called when a player leaves the room. - Example: `room.onPlayerLeave = (player) => { console.log(player.name + ' left'); }` - **onPlayerChat(player: PlayerObject, message: string): void** - Called when a player sends a chat message. - Example: `room.onPlayerChat = (player, message) => { console.log(player.name + ': ' + message); }` #### Game Events - **onGameStart(): void** - Called when the game starts. - Example: `room.onGameStart = () => { console.log('Game started!'); }` - **onGameStop(): void** - Called when the game stops. - Example: `room.onGameStop = () => { console.log('Game stopped.'); }` - **onGameTick(): void** - Called on every game tick. - Example: `room.onGameTick = () => { /* update game logic */ }` #### Team Events - **onTeamGoal(teamId: 0 | 1, score: number): void** - Called when a team scores a goal. - Example: `room.onTeamGoal = (teamId, score) => { console.log('Team ' + teamId + ' scored! Score: ' + score); }` ### Notes - For a complete list of event handlers and their signatures, refer to `api-reference/room-object.md`. ``` -------------------------------- ### Set Disc Properties Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/README.md Manually set the position and velocity of a disc. Use with caution as it overrides physics. ```javascript // Set disc position and velocity room.setDiscProperties(0, { x: 0, y: 0, xspeed: 10, yspeed: 5 }); ``` -------------------------------- ### setCustomStadium Source: https://github.com/mertushka/haxball.js/blob/main/_autodocs/api-reference/room-object.md Parses the provided string as a .hbs stadium file and sets it as the selected stadium. This method does nothing if a game is in progress. ```APIDOC ## setCustomStadium(stadiumFileContents) ### Description Parses the stadiumFileContents as a .hbs stadium file and sets it as the selected stadium. There must not be a game in progress. ### Method (Implicitly a method call on a Room object, e.g., `room.setCustomStadium(...)`) ### Parameters #### Parameters - **stadiumFileContents** (string) - Yes - The contents of the .hbs stadium file as a string ### Request Example ```javascript const stadiumJson = `{ "name": "Custom Stadium", "width": 200, "height": 130, "bg": { "type": "grass" } }`; room.setCustomStadium(stadiumJson); ``` ### Response #### Success Response (void return type, no specific success response) #### Response Example (No explicit response example for void methods) ```