UNPKG

node-haxball

Version:

The most powerful and lightweight API that allows you to develop your original Haxball(www.haxball.com) host, client, and standalone applications both on node.js and browser environments and also includes every possible hack and functionality that you can

515 lines (456 loc) â€Ē 126 kB
[![GitHub package.json version](https://img.shields.io/github/package-json/v/wxyz-abcd/node-haxball?style=flat-square)](https://github.com/wxyz-abcd/node-haxball) [![NPM Version](https://img.shields.io/npm/v/node-haxball?style=flat-square)](https://www.npmjs.com/package/node-haxball) [![NPM Monthly Downloads](https://img.shields.io/npm/dm/node-haxball?style=flat-square)](https://npmjs.org/package/node-haxball) [![Proxy Server Status](https://img.shields.io/endpoint?label=proxy%20server&style=flat-square&url=https%3A%2F%2Fnode-haxball.glitch.me%2Fstatus)](https://node-haxball.glitch.me) [![License](https://img.shields.io/github/license/wxyz-abcd/node-haxball?style=flat-square)](LICENSE) [![Last Commit](https://img.shields.io/github/last-commit/wxyz-abcd/node-haxball?style=flat-square)](https://github.com/wxyz-abcd/node-haxball/commits/) ![Language Most Used](https://img.shields.io/github/languages/top/wxyz-abcd/node-haxball?style=flat-square) ![Repository Size](https://img.shields.io/github/repo-size/wxyz-abcd/node-haxball?style=flat-square) [![Forks](https://img.shields.io/github/forks/wxyz-abcd/node-haxball?style=social)](https://github.com/wxyz-abcd/node-haxball/network/members) [![Stars](https://img.shields.io/github/stars/wxyz-abcd/node-haxball?style=social)](https://github.com/wxyz-abcd/node-haxball/stargazers) [![Watches](https://img.shields.io/github/watchers/wxyz-abcd/node-haxball?style=social)](https://github.com/wxyz-abcd/node-haxball/watchers) <h1 id="title" align="center">node-haxball</h1> <h4 align="center">The most powerful and lightweight API that allows you to develop your original Haxball(www.haxball.com) host, client, and standalone applications both on node.js and browser environments and includes every possible functionality that you can imagine.</h4> - <a href="https://github.com/wxyz-abcd/node-haxball">Here</a> is the Github repository for this project. - You may read the full documentation <a href="https://github.com/wxyz-abcd/node-haxball/wiki">here</a>. - We also have a <a href="https://discord.gg/ngACfJHSD6">discord server</a> to help people adapt to this API. See you there! ### 🔖 Table Of Contents - ðŸĪ” [How To Use](#how-to-use) - 🎊 [Mini-Documentation](#docs) - ðŸ’Ą [How To Contribute](#how-to-contribute) - ðŸĪ— [Contributors](#contributors) - 🔏 [License](#license) --- <h2 id="how-to-use">ðŸĪ” How To Use</h2> #### ðŸ’ŧ Installing & importing as a node.js/CommonJS module: ```sh npm install node-haxball ``` ```js const { OperationType, VariableType, ConnectionState, AllowFlags, Direction, CollisionFlags, CameraFollow, BackgroundType, GamePlayState, BanEntryType, Callback, Utils, Room, Replay, Query, Library, RoomConfig, Plugin, Renderer, Errors, Language, EventFactory, Impl } = require("node-haxball")(); // Use example code here. ``` #### ðŸ’ŧ Usage on Browser - NOTE: Usage on Browser currently relies on our <a href="https://node-haxball.glitch.me">proxy server</a>. (Will expire at the end of each month and not work for several days.) - If you do not wish to use proxy server (which has some limitations), you will need our browser extension to change headers. (look at our <a href="https://github.com/wxyz-abcd/node-haxball/tree/main/haxballOriginModifier">haxballOriginModifier project</a>.) - <a href="https://abc-haxball-proxy.infinityfreeapp.com/?no_proxy_server=true">Alternate URL</a> (No proxy server yet.) - Moreover; if you have a custom backend server for Haxball, you can use it with this API too. #### ðŸ’ŧ Usage on Browser (via Proxy Server) ```html <html> <head> <script src="https://www.haxball.com/PwfmUfRI/__cache_static__/g/vendor/json5.min.js"></script> <!-- json5 library --> <script src="https://www.haxball.com/PwfmUfRI/__cache_static__/g/vendor/pako-jszip.min.js"></script> <!-- pako library --> <script src="https://cdn.jsdelivr.net/gh/wxyz-abcd/node-haxball@latest/src/api.js"></script> <!-- this file comes from this repo --> </head> <body> <script> var { OperationType, VariableType, ConnectionState, AllowFlags, Direction, CollisionFlags, CameraFollow, BackgroundType, GamePlayState, BanEntryType, Callback, Utils, Room, Replay, Query, Library, RoomConfig, Plugin, Renderer, Errors, Language, EventFactory, Impl } = abcHaxballAPI(window, { proxy: { WebSocketUrl: "wss://node-haxball.glitch.me/", HttpUrl: "https://node-haxball.glitch.me/rs/" } }); // Use example code here. </script> </body> </html> ``` #### ðŸ’ŧ Usage on Browser (via haxballOriginModifier Browser Extension) ```html <html> <head> <script src="https://www.haxball.com/PwfmUfRI/__cache_static__/g/vendor/json5.min.js"></script> <!-- json5 library --> <script src="https://www.haxball.com/PwfmUfRI/__cache_static__/g/vendor/pako-jszip.min.js"></script> <!-- pako library --> <script src="https://cdn.jsdelivr.net/gh/wxyz-abcd/node-haxball@latest/src/api.js"></script> <!-- this file comes from this repo --> </head> <body> <script> var { OperationType, VariableType, ConnectionState, AllowFlags, Direction, CollisionFlags, CameraFollow, BackgroundType, GamePlayState, BanEntryType, Callback, Utils, Room, Replay, Query, Library, RoomConfig, Plugin, Renderer, Errors, Language, EventFactory, Impl } = abcHaxballAPI(window); // You do not need a proxy server if you use browser's extension mechanism. // Use example code here. </script> </body> </html> ``` #### ðŸ’ŧ Example code using the library: Joining a room: ```js Utils.generateAuth().then(([authKey, authObj])=>{ Room.join({ id: "Olnit_iGRWs", authObj: authObj }, { storage: { player_name: "wxyz-abcd", avatar: "ðŸ‘―" }, onOpen: (room)=>{ room.sendChat("Hello " + room.name); } }); }); ``` Creating a room: ```js Room.create({ name: "room123", password: "password", showInRoomList: true, maxPlayerCount: 8, token: "thr1.AAAAAGNMOokNqt3forXs_Q.3qQMuLQOS9o" }, { storage: { player_name: "wxyz-abcd", avatar: "ðŸ‘―" }, onOpen: (room)=>{ room.sendChat("Hello " + room.name); room.onAfterRoomLink = (roomLink)=>{ console.log("room link:", roomLink); }; } }); ``` --- <h2 id="docs">📰 Mini-Documentation</h2> - `Library constructor(object, config)`: Initializes the library with given parameters. - `object`: These are objects/functions that directly affect the core functionalities. You should usually pass "window" here, because most of these objects reside there. - `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval`, `requestAnimationFrame`, `cancelAnimationFrame`, `fetch`, (if you are on a custom environment such as NW.js or Electron, these functions should be binded to browser's window object before being passed on.) - `console`, `performance`, `crypto`, (browser's window object should have these objects as well.) - `RTCPeerConnection`, `RTCIceCandidate`, `RTCSessionDescription`, `WebSocket`, (these classes are used by Haxball for communication, browser's window object should have these classes as well.) - `JSON5`, `pako`. (These are two external libraries required by Haxball.) - `config`: Custom configuration for backend/proxy server as well as the library itself. Valid object keys are; - `backend`: Custom backend configuration. Valid object keys are: - `hostname`: backend's main domain url address. Defaults to: `www.haxball.com`. - `hostnameWs`: backend's url address for websocket connections. Defaults to: `p2p.haxball.com`. - `secure`: determines whether the url is using secure protocol(`true`) or not(`false`). Defaults to: `true`. - `proxy`: Proxy server configuration. Valid object keys are: - `WebSocketChangeOriginAllowed`: browsers' websocket libraries do not allow origin change for security reasons, so we need a proxy server to change the websocket request's origin for us. If `true`, we do not need a proxy server. (we can do that in NW.js, for example) - `WebSocketUrl`: proxy websocket url address to use when trying to create or join a room. should end with a `/`. Is appended `host` or `client` at the end while being used. Defaults to: `wss://p2p.haxball.com/` for host and `wss://p2p2.haxball.com/` for client. - `HttpUrl`: proxy http url address to use when trying to create or join a room. should end with a `/`. Is appended `host` or `client` at the end while being used. Defaults to: `https://www.haxball.com/rs/`. - `stunServer`: the url address of an external stun server that is required for the communication via WebRTC to work correctly. Defaults to: `stun:stun.l.google.com:19302`. - `proxyAgent`: a global custom proxy agent for this api object. This method does not work in browsers. Defaults to `null`. - `version`: Haxball's expected version number. Defaults to: `9`. - `noVariableValueChangeEvent`: if `true`, disables the mechanism that enables variable value change event which in turn improves performance while reaching a variable's value that was defined by any `Addon.defineVariable` function. (Variable will have a directly accessable, actual value; instead of a property that points to the actual variable.) Defaults to: `false`. - `identityToken`: A token that represents a user data in a database of a custom proxy/backend server. Defaults to `null`. - `OperationType`: Different types of operations that are being used by Haxball. Should be used to understand what kind of message we are dealing with inside callback `onOperationReceived`. - `VariableType`: Different types of variables that can be defined in a Plugin or a Renderer with its corresponding `defineVariable` function. Should be used in a GUI environment. - `ConnectionState`: Different connection state values. Should be used to understand the state of connection while joining a room using `Room.join`. - `AllowFlags`: These flags allow us to understand whether a plugin or a roomConfig is able to work correctly while joining or creating a room. Especially useful in a GUI environment. - `Direction`: These values help understand the direction of a movement for an axis. Only designed for room.keyState function to combine seperate directions for x and y axis to generate the value of the key to press. - `CollisionFlags`: These flags are used internally in Haxball's physics engine to decide whether collision check should happen or not. Useful while creating a map editor GUI. - `CameraFollow`: These values help understand whether the camera will follow the player or not. This is only used as a variable in all stadiums. - `BackgroundType`: This is the type of the variable in a stadium that defines its background texture type. - `GamePlayState`: This type lets us understand the actual state of the game. This type only exists in a GameState object. - `BanEntryType`: These values help understand the type of a ban entry instance inside a room's ban list. - `PlayerPositionInGame`: These are the common player positions in most football manager games. - `Language`: A class that defines a language. Any language should be based on this class. - `static properties`: - `current`: The global current Language instance. It is essential to assign a language object to this property to be able to see the error messages using a line such as `API.Language.current = new EnglishLanguage(API)`. Defaults to `null`. - `static functions`: - `resolveText(str, array)`: Converts a template string(`str`) to a normal string using the given parameters(`array`). - `constructor(abbr, metadata)`: creates a new `Language` instance. `abbr` should be a unique abbreviation string to identify the language. `metadata` is the information that you would want to show/update inside a GUI application. - `properties`: - `abbr`: the abbreviation of the language that is used while sending a LanguageChanged signal through the API. - `api`: The root data object that should have an `errors` key which has to contain string representations for each ErrorCode value. - `abstract callbacks`: These functions should be overridden when writing a GUI application using this API before creating any `Language` object. These are defined in `Language.prototype`. - `defineMetadata(metadata)`: Does nothing, returns nothing by default. This function should define the given `metadata` object inside this `Language` object. This is not done here for optimization purposes. (We do not need these values in a non-GUI environment.) For example, the languages in the examples folder uses the following `metadata` structure: `{name, version, author, description}`. - `Errors`: Global error handling objects. - `ErrorCodes`: Name to integer mapping that shortly describes the error codes used in `HBError` class. - `HBError`: This is the class that is instantiated while any error is thrown from this API. - `properties`: - `code`: The error code that has been thrown. (`integer`) - `params`: Parameters for the error. (`array`) - `functions`: - `toString()`: Returns the full description of the current error object by executing `currentLanguage.errorsTextMap[this.code](...this.params)`. - `Callback`: Global functions to add/remove callbacks. - `add(eventName, metadata)`: creates all callbacks about a new event called `eventName` which should start with a capital letter. `metadata` is not used, but this is the library's current metadata structure: `{ params: array of string }`. should be used (and maybe overridden for usage of `metadata`) in a gui application to define custom event callbacks related to gui events such as keyboard, mouse, touch, timer etc. the main event callback defined in this room object to trigger all callbacks is `"_on" + eventName`. - `remove(eventName)`: destroys the callbacks created by `Callback.add`. - `Replay`: Functions/classes related to replays. - `read(uint8Array, callbacks, options)`: Creates and returns a non-blocking replay reader object. - Parameters: - `uint8Array`: Must be an Uint8Array containing the contents of a .hbr file. (Currently, only version 3 is supported.) - `callbacks`: An object that has the same callbacks as the renderer template. (except callbacks that are related to customEvents, roomConfigs, plugins, renderers, language; due to replay files not containing its corresponding event.) (Look at examples/api_structure/replayReader.js for all supported callbacks and example usage.) - `options`: An object that may contain the following keys: - `requestAnimationFrame`: Override function for `requestAnimationFrame`. (`null` = use library's default `requestAnimationFrame`.) - `cancelAnimationFrame`: Override function for `cancelAnimationFrame`. (`null` = use library's default `cancelAnimationFrame`.) - Returning replay reader object: - properties: - `state`: An object containing all information about the current room state. - `gameState`: room's game state information. returns null if game is not active. read-only. - `currentPlayerId`: Always returns -1. It is only added for compatibility with renderers. (And it is only used in the initialization code of renderers.) - `maxFrameNo`: returns the maximum frame number in the replay file. - functions: - `extrapolate(milliseconds=0)`: extrapolates the current room state for `milliseconds` milliseconds and stores the results in each object's `ext` key. Returns the new extrapolated room state. - `length()`: Returns the length of replay content in milliseconds. - `getTime()`: Returns the current time in milliseconds. - `getCurrentFrameNo()`: Returns the current frame number. - `setTime(destinationTime)`: Plays the replay until the `destinationTime`(in milliseconds) or end of replay is reached. Note that it may take some time to reach the destination time(especially if you are trying to rewind time), because the game state data is generated on the fly and not stored in memory. (It would probably use huge amounts of RAM.) - `setCurrentFrameNo(destinationFrameNo)`: Plays the replay until the `destinationFrameNo` or end of replay is reached. Note that it may take some time to reach the destination frame no(especially if you are trying to rewind time), because the game state data is generated on the fly and not stored in memory. (It would probably use huge amounts of RAM.) - `getSpeed()`: Returns the current speed of playing the replay. - `setSpeed(coefficient)`: Changes the speed of playing the replay. `coefficient` must be a real number >=0. - `coefficient` = 0 : stop replay. - 0 < `coefficient` < 1 : slow-motion replay. - `coefficient` = 1 : normal speed replay. - `coefficient` > 1 : fast-motion replay. - `destroy()`: Releases the resources that are used by this object. - callbacks: - `onDestinationTimeReached()`: Destination time or frame number has been reached. Runs after a call to `setTime(destinationTime)` or `setCurrentFrameNo(destinationFrameNo)`. - `onEnd()`: The end of replay data has been reached. - `ReplayData`: The structure that holds all of the data inside a replay file. - `roomData`: The initial `RoomState` of the replay, including all the information about the current stadium, game state, players, etc. - `events`: All events in this replay ordered by their respective `frameNo`. - `goalMarkers`: All team goals in this replay ordered by their respective `frameNo`. - `totalFrames`: Total number of frames in this replay. - `version`: Version number of the replay. Must currently be equal to `3`. - `readAll(uint8Array)`: Reads all of the given binary replay data into a new `ReplayData` structure and returns it. - `trim(replayData, { beginFrameNo, endFrameNo })`: Synchronously trims the given `ReplayData` between given frame numbers `beginFrameNo` and `endFrameNo`, both of which can be omitted and are inclusive. If omitted, `beginFrameNo` defaults to `0` and `endFrameNo` defaults to `replayData.totalFrames-1`. - `trimAsync(replayData, { beginFrameNo, endFrameNo })`: Asynchronously trims the given `ReplayData` between given frame numbers `beginFrameNo` and `endFrameNo`, both of which can be omitted and are inclusive. If omitted, `beginFrameNo` defaults to `0` and `endFrameNo` defaults to `replayData.totalFrames-1`. returns `Promise(void)` - `writeAll(replayData)`: Writes the contents of a `ReplayData` structure into a new `Uint8Array` and returns it. - `Utils`: Some static utility functions. - `generateAuth()`: generates a new `player_auth_key` along with its companion auth object. you should store the key and use it later if you want to be recognized in Haxball rooms. the object is used in `Room.join`. returns `Promise([authKey, authObj])`. - `authFromKey(authKey)`: recreates the auth object for given `authKey`. the object is used in `Room.join`. returns `Promise(authObj)`. - `getRoomList()`: returns the current room list. returns `Promise(roomListArray)`. - `calculateAllRoomDistances(geo, roomList)`: calculates the distances to the given geoLocation `geo` of all rooms in given `roomList` and stores them inside each room's `dist` property. - `numberToColor(number)`: returns the html color string (rgba representation) of the given `number`. (0 <= `number` <= 16777215) - `colorToNumber(color)`: returns the number representation of the given html color string (rgba representation). - `ipToNumber(ip)`: returns the numeric representation of an ip string, or null if the string is not formatted. Used internally in banList implementation. - `numberToIp(ip)`: returns the string representation of a numeric ip value, or null if the number is not valid. Used internally in banList implementation. - `authToNumber(auth)`: returns the numeric representation of an auth string, or null if the string is not 43 characters long. Used internally in banList implementation. - `numberToAuth(auth)`: returns the string representation of a numeric auth value, or null if the number is not valid. Used internally in banList implementation. - `compareBits(value1, value2, bitMask)`: returns true if all of the bits of numbers given as `value1` and `value2` are equal only at the positions whose bit values are `1` inside the `bitMask`. Used internally in banList implementation. - `keyState(dirX, dirY, kick)`: returns an integer key state value to be used in `Room.setKeyState`. `dirX` = oneof\[`-1`:left, `0`:still, `1`:right\], `dirY` = oneof\[`-1`:up, `0`:still, `1`:down\], `kick` = `true`/`false`. - `reverseKeyState(state)`: returns the `dirX`, `dirY`, `kick` parameters that were used to generate the given integer `state` with `Utils.keyState` function. - `runAfterGameTick(callback, ticks)`: runs a `callback` function after `ticks` game ticks. if omitted, `ticks` defaults to `1`. - `getGeo()`: connects to Haxball's geolocation API to get your location based on IP address. you can use it directly as `geo` key inside `storage` object. returns `Promise(geoLocationObject)` - `parseGeo(geoStr, fallback, retNull)`: Parses the given string or json object(`geoStr`) as a `GeoLocation` object that should have `lat`, `lon` and `flag` keys and returns it. - `getDefaultStadiums()`: get default stadium array. - `parseStadium(textDataFromHbsFile)`: parse text as a stadium object and return it. - `exportStadium(stadium)`: generate and return text(.hbs) content from a `stadium` object. - `promiseWithTimeout(promise, msec)`: returns a new promise that executes the given `promise` until `msec` time has passed. if timeout is reached, the promise is rejected. - `hexStrToNumber(str)`: converts the `playerObject.conn` values to readable ip address string. - `byteArrayToIp(uint8Array)`: converts a uint8array that was read from basro's backend into a readable ip address string. - `refreshRoomToken({token="", rcr=""})`: generates a new room token from an old token OR a rcr(Google Recaptcha v2 response) value. - `generateRoomId({token, proxyAgent})`: generates the room id using the given `token`, and also a new room token. - `EventFactory`: Contains static functions to create all kinds of event messages. - `create(type)`: creates and returns an event message depending on the `type` parameter. returns `null` if `type` is not one of the types defined inside `OperationType` enum. - `createFromStream(reader)`: creates and returns an event message after reading it from a stream `reader`. the `reader` should be of type `Impl.Stream.Reader`. - `checkConsistency(data)`: creates and returns an event message that can be used to trigger a consistency check. `data` should be an `ArrayBuffer`. - `sendAnnouncement(msg, color, style, sound)`: creates and returns an event message that can be used to send an announcement message(`msg`) with properties(`color`, `style`, `sound`). - `sendChatIndicator(active)`: creates and returns an event message that can be used to set the chat indicator status of a player to `active`. - `sendInput(input)`: creates and returns an event message that can be used to triggers an input(keys) event. 0<=`input`<=31. - `sendChat(msg)`: creates and returns an event message that can be used to send chat message(`msg`). - `joinRoom(id, name, flag, avatar, conn, auth)`: creates and returns an event message that can be used to trigger a player join event. - `setHeadlessAvatar(id, avatar)`: creates and returns an event message that can be used to set the headless avatar of a player(`ÃŽd`) to `avatar`. - `kickBanPlayer(id, reason, ban)`: creates and returns an event message that can be used to trigger a player(`id`) leave event. - `reorderPlayers(playerIdList, moveToTop)`: creates and returns an event message that can be used to reorder players in a room. - `startGame()`: creates and returns an event message that can be used to start the game. - `stopGame()`: creates and returns an event message that can be used to stop the game. - `pauseResumeGame(paused)`: creates and returns an event message that can be used to pause or resume a game. - `setScoreLimit(value)`: creates and returns an event message that can be used to set the score limit of a game to `value`. - `setTimeLimit(value)`: creates and returns an event message that can be used to set the time limit of a game to `value`. - `setStadium(stadium)`: creates and returns an event message that can be used to set the current stadium of a room to `stadium`. - `setPlayerTeam(playerId, teamId)`: creates and returns an event message that can be used to move a player(`playerId`) to a team(`teamId`). - `setTeamsLock(value)`: creates and returns an event message that can be used to lock or unlock the teams. - `setPlayerAdmin(playerId, value)`: creates and returns an event message that can be used to give/take away admin priveleges of a player(`playerId`). - `autoTeams()`: creates and returns an event message that can be used to trigger an autoTeams event. - `setPlayerSync(value)`: creates and returns an event message that can be used to set the synchronization status of a player. - `ping(values)`: creates and returns an event message that can be used to set the pings of all players in a room. - `setAvatar(value)`: creates and returns an event message that can be used to set the avatar of a player to `value`. - `setTeamColors(teamId, colors)`: creates and returns an event message that can be used to set the colors of a team(`teamId`) to `colors`. `colors` must be an instance of the `Impl.Core.TeamColors` class. - `setKickRateLimit(min, rate, burst)`: creates and returns an event message that can be used to set the kick rate limit of a room. - `setDiscProperties(id, data)`: creates and returns an event message that can be used to set the properties of a disc(`id`) to `data`. - `setPlayerDiscProperties(id, data)`: creates and returns an event message that can be used to set the properties of the disc of a player(`id`) to `data`. - `customEvent(type, data)`: creates and returns an event message that can be used to trigger a custom event with properties(`type`, `data`). - `binaryCustomEvent(type, data)`: creates and returns an event message that can be used to trigger a binary custom event with properties(`type`, `data`). - `setPlayerIdentity(id, data)`: creates and returns an event message that can be used to trigger a player identity event with properties(`id`, `data`). - `Query`: Static functions to query map features. `roomState` should be either `room.state` or `room.stateExt`. - `getVertexIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first vertex that has a distance to `mapCoordinate` lower than `threshold`. - `getVertexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the first vertex that has a distance to `mapCoordinate` lower than `threshold`. - `getSegmentIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first segment that has a distance to `mapCoordinate` lower than `threshold`. - `getSegmentAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the first segment that has a distance to `mapCoordinate` lower than `threshold`. - `getGoalIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first goal that has a distance to `mapCoordinate` lower than `threshold`. - `getGoalAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the first goal that has a distance to `mapCoordinate` lower than `threshold`. - `getPlaneIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first plane that has a distance to `mapCoordinate` lower than `threshold`. - `getPlaneAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the first plane that has a distance to `mapCoordinate` lower than `threshold`. - `getJointIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first joint that has a distance to `mapCoordinate` lower than `threshold`. - `getJointAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the first joint that has a distance to `mapCoordinate` lower than `threshold`. - `getDiscIndexAtMapCoord(roomState, mapCoordinate)`: Finds the index of the first disc that includes `mapCoordinate`. - `getDiscAtMapCoord(roomState, mapCoordinate)`: Finds the first disc that includes `mapCoordinate`. - `getSpawnPointIndexAtMapCoord(roomState, mapCoordinate, threshold)`: Finds the index of the first spawn point that has a distance to `mapCoordinate` lower than `threshold`. Returns `[spawnPointIndex, teamId]`. `teamId`: \[`1`: red team, `2`: blue team.\] - `Room`: The class that currently hosts all room operations. Should only be initialized by either `Room.join` or `Room.create`. - `static functions`: These functions are used to create/join a room. - `create(createParams, commonParams)`: create a room with given parameters. Returns a custom object. - `createParams`: - `name`: name of the room. - `password`: password to protect the room. can be set `null`/`undefined` for no password. - `token`: get a recaptcha token from `www.haxball.com/headlesstoken` and write it here to bypass the loop of trying to solve recaptcha. - `noPlayer`: set it to `true` if you are planning to host the room without actually playing the game, otherwise set it to `false`. - `geo`: `{lat: latitude(number), lon: longitude(number), flag: 2 letter country flag(string)}` geolocation values of the room about to be created. - `playerCount`: if set to a `number`, always fixes the player count to this specific `number`. - `maxPlayerCount`: the maximum allowed player count in the room. - `unlimitedPlayerCount`: if set to `true`, bypasses the player count controller. - `fakePassword`: if set to `true`, the room will show that it is password-protected while in fact it is not. - `showInRoomList`: set to `true` if you want this room to show up in the room list. - `onError(error, playerId)`: called when an exception is thrown from the room. playerId is the id of the player that caused the exception. that player's connection will be closed just after this callback is executed. (most probably, the player will be kicked with the reason 'Bad actor'.) - `commonParams`: explained below in `Room.join`. - `join(joinParams, commonParams)`: try to join the room(`roomId`) with given `password`(or `null`=no password). Returns a custom object. - `joinParams`: - `id`: the id of the room to join. for example, if the room link is `https://www.haxball.com/play?c=31IBNI3w4F0`, this room's id is `31IBNI3w4F0`. - `password`: a password value to join the room if the room is password-protected. - `token`: if the room is recaptcha-protected, you have to use a client token. currently there is not any other clean way of doing this except using the NW.js token generator project, so you might want to look at it. - `authObj`: an auth object that has to be initialized by `Utils.generateAuth()` or `Utils.authFromKey()` before being used here. - `commonParams`: --- properties section --- - `storage`: - `crappy_router`: if `true`, sets some timeout value to `10` seconds instead of `4` seconds while joining a room. - `player_name`: name of the player. default value is `"abc"`. - `avatar`: avatar of the player. default value is `null`. - `geo`: - `lat`: latitude value (number, default value is `40`). - `lon`: longitude value (number, default value is `40`). - `flag`: 2 letter country code (string, default value is `"tr"`). - `noPluginMechanism`: if `true`, renderer and plugin mechanism will not work. Should only be used for optimal performance. You have to define `Room._onXXXXXX` callbacks by yourself. - `libraries`: array of `Library` objects to be used. the objects should be derived from the provided `Library` class. default value is `[]`. (Look at examples/libraries folder for example Library's to use here, or src/libraryTemplate.js for a template Library that contains all callbacks.) - `config`: the `RoomConfig` object that contains all the main callbacks of this room. the object should be derived from the provided `RoomConfig` class. default value is `null`. (Look at examples/roomConfigs/method2 folder for example RoomConfigs to use here, or src/roomConfigTemplate_method2.js for a template RoomConfig that contains all callbacks.) - `renderer`: the `Renderer` object that can render the game. the object should be derived from the provided `Renderer` class. default value is `null`. (Look at examples/renderers folder for example RoomConfigs to use here, or src/rendererTemplate.js for a template Renderer that contains all callbacks.) - `plugins`: array of `Plugin` objects to be used. the objects should be derived from the provided `Plugin` class. default value is `[]`. (Look at examples/plugins folder for example Plugins to use here, or src/pluginTemplate.js for a template Plugin that contains all callbacks.) - `version`: Haxball's version number. other clients cannot join this room if their version number is different than this number. default value is `9`. - `proxyAgent`: a custom proxy agent for the room's connection. This method does not work in browsers. Defaults to `null`. - `identityToken`: A token that represents a user data in a database of a custom proxy/backend server. Defaults to `null`. --- event callbacks section --- - `preInit(room)`: this is run as soon as the `room` object is created, just before the initialization of the plugins etc. - `onOpen(room)`: joined/created `room`. - `onClose(error)`: player has left the room with error(`error`). - `onConnInfo(state, extraInfo)`: connection state has just changed to (`state`). `extraInfo` either contains the sdp if `state` is `ConnectingToPeer` or `AwaitingState` which can be used to get information about the webrtc connection such as ip/port that may used to block players before they can connect to the host etc; or it can contain the fail reason for the connection if `state` is `ConnectionFailed`. - Returning custom object has the following triggers: - `cancel()`: should be used to cancel the process of joining a room. - `useRecaptchaToken(token)`: should be used to send the recaptcha token after `onRequestRecaptcha` event occurred. currently only working while creating a room. workaround: in order to send the token to try and join a recaptcha-protected room, cleanup old resources and use `Room.join` with the new token. - `streamWatcher(initialStreamData, callbacks, options)`: creates a streamWatcher room. - Parameters: - `initialStreamData`: must be an `Uint8Array` that is received just after connecting to a streaming room. - `callbacks`: explained in `Room.sandbox`. - `options`: explained in `Room.sandbox`. - Returning streamWatcher room object: - Properties: - `state`: An object containing all information about the current room state. Note that this object also has all of the functions explained below in section: `sandbox mode functions`. (it only has `copy()` instead of `takeSnapshot()`) - `gameState`: room's game state information. returns null if game is not active. read-only. - `currentPlayerId`: Always returns 0. It is only added for compatibility with renderers. (And it is only used in the initialization code of renderers.) - `currentFrameNo`: returns the frame number of the room state that you are currently observing. - `maxFrameNo`: returns the original current frame number of the room where the game is actually being played. - functions: - `readStream(reader)`: reads the data stream for "interval" streaming mode. - `readImmediateStream(reader)`: reads the data stream for "immediate" streaming mode. - `takeSnapshot()`: returns a complete snapshot of the current room state. - `useSnapshot(newRoomState)`: sets the current room state reference to `newRoomState`. `newRoomState` should be created by `takeSnapshot()` first. - `setSimulationSpeed(coefficient)`: Changes the speed of the simulation. `coefficient` must be a real number >=0. - `coefficient` = 0 : stop simulation. - 0 < `coefficient` < 1 : slow-motion simulation. - `coefficient` = 1 : normal speed simulation. - `coefficient` > 1 : fast-motion simulation. - `runSteps(count)`: runs the simulation `count` steps. simulation must be stopped for this function to work. - `destroy()`: Frees the resources that are used by this object. - `sandbox(callbacks, options)`: creates a sandbox room. - Parameters: - `callbacks`: An object that has the same callbacks as the renderer template, plus the following: - `filterEvents(event)`: This is a special callback for the sandbox to be able to filter some events. This callback is called for every single event that occurs in the sandbox, and the events that return `false` from this callback are not executed. - `options`: An object that may contain the following keys: - `controlledPlayerId`: Id of the player to be controlled. - `delayedInit`: Whether to delay the initialization of the sandbox. (You have to manually initialize it later using its `initialize()` function.) - `requestAnimationFrame`: Override function for `requestAnimationFrame`. (`null` = use library's default `requestAnimationFrame`.) - `cancelAnimationFrame`: Override function for `cancelAnimationFrame`. (`null` = use library's default `cancelAnimationFrame`.) - Returning sandbox room object: - properties: - `state`: An object containing all information about the current room state. Note that this object also has all of the functions explained below in section: `sandbox mode functions`. (it only has `copy()` instead of `takeSnapshot()`) - `gameState`: room's game state information. returns null if game is not active. read-only. - `currentPlayerId`: Always returns 0. It is only added for compatibility with renderers. (And it is only used in the initialization code of renderers.) - functions: - `initialize()`: Initializes the sandbox. (Should only be called if `delayedInit` is `true`.) - `startRecording()`: start recording replay data. returns `true` if succeeded, `false` otherwise. recording should not be started before calling this. - `stopRecording()`: stop recording replay data. returns `UintArray8` data if succeeded, null otherwise. recording should be started before calling this. - `isRecording()`: returns `true` if recording has started; `false` otherwise. - `extrapolate(milliseconds=0)`: extrapolates the current room state for `milliseconds` milliseconds and stores the results in each object's `ext` key. Returns the new extrapolated room state. - `setSimulationSpeed(coefficient)`: Changes the speed of the simulation. `coefficient` must be a real number >=0. - `coefficient` = 0 : stop simulation. - 0 < `coefficient` < 1 : slow-motion simulation. - `coefficient` = 1 : normal speed simulation. - `coefficient` > 1 : fast-motion simulation. - `runSteps(count)`: runs the simulation `count` steps. simulation must be stopped for this function to work. - `executeEvent(eventMsg)`: applies an event to the current room state. for example; the event object may come from a `ReplayData` structure, or from a `onOperationReceived(type, msg, globalFrameNo, clientFrameNo, customData)` callback. - `takeSnapshot()`: returns a complete snapshot of the current room state. - `useSnapshot(newRoomState)`: sets the current room state reference to `newRoomState`. `newRoomState` should be created by `takeSnapshot()` first. - `playerJoin(id, name, flag, avatar, conn, auth)`: adds a new player with properties(`id`, `name`, `flag`, `avatar`, `conn`, `auth`) to the room. - `playerLeave(playerId)`: removes player(`playerId`) from the room. - `playerInput(input, byId)`: sets the input of player(`byId`) to `input`. - `playerChat(msg, byId)`: writes chat message(`msg`) as player(`byId`). - `setKeyState(state)`: set current key state to `state`. (added for compatibility with normal rooms.) - `reorderPlayers(playerIdList, moveToTop, byId)`: creates and applies a fake event by player(`byId`) to remove all players with ids in `playerIdList` and re-add them in the given order to the (top or bottom)(`moveToTop`) of the player list. `byId` must be `0`. - `setPlayerChatIndicator(value, byId)`: sets the chat indicator status of player(`byId`) to `value`. - `setPlayerAvatar(value, byId)`: sets the avatar of player(`byId`) to `value`. - `setCurrentStadium(value, byId)`: creates and applies a fake event by player(`byId`) to set the current stadium to `stadium`. - `sendAnnouncement(msg, color=-1, style=0, sound=1, targetId=null, byId=0)`: send announcement message(`msg`) to player(`targetId`) with properties(`color`, `style`, `sound`). `targetId` is `null` -> send to everyone. `byId` must be `0`. - `startGame(byId)`: creates and applies a fake event by player(`byId`) to start the game. - `stopGame(byId)`: creates and applies a fake event by player(`byId`) to stop the game. - `setGamePaused(value, byId)`: creates and applies a fake event by player(`byId`) to set the game's paused state to `value`. - `setScoreLimit(value, byId)`: creates and applies a fake event by player(`byId`) to set the game's score limit to `value`. - `setTimeLimit(value, byId)`: creates and applies a fake event by player(`byId`) to set the game's time limit to `value`. - `setTeamsLock(value, byId)`: creates and applies a fake event by player(`byId`) to set the game's teams lock state to `value`. - `autoTeams(byId)`: creates and applies a fake event by player(`byId`) to remove last 2 players from spectators and add them to teams. - `setPlayerTeam(playerId, teamId, byId)`: creates and applies a fake event by player(`byId`) to set player(`playerId`)'s team to team(`teamId`). - `setKickRateLimit(min, rate, burst, byId)`: creates and applies a fake event by player(`byId`) to set the room's kick rate limit. - `setTeamColors(teamId, angle, colors, byId)`: creates and applies a fake event by player(`byId`) to set the team colors for team(`teamId`). `teamId`: `1`(red) | `2`(blue), `angle`: `integer`, `colors`: maximum 4 numeric (0 <= `integer` <= 16777215) color parameters. - `setPlayerAdmin(playerId, value, byId)`: creates and applies a fake event by player(`byId`) to set player(`playerId`)'s admin status to `isAdmin`. - `kickPlayer(playerId, reason, ban, byId)`: creates and applies a fake event by player(`byId`) to kick/ban a player(`playerId`) with reason(`reason`). - `setPlayerSync(value, byId)`: set the sync of player(`byId`) to `value`. - `sendPingData(valueFunc, byId)`: creates and applies a fake event by player(`byId`) to change all ping values with `valueFunc`. `byId` must be `0`. - `setDiscProperties(discId, type, data, byId)`: creates and applies a fake event by player(`byId`) to set disc(`discId`) properties to `data`. `byId` must be `0`. - `sendCustomEvent(type, data, byId)`: creates and applies a fake custom event with properties(`type`, `data`) by player(`byId`). - `sendBinaryCustomEvent(type, data, byId)`: creates and applies a fake binary custom event with properties(`type`, `data`) by player(`byId`). - `setPlayerIdentity(id, data, byId)`: creates and applies a fake event by player(`byId`) to set the identity of player(`id`) to `data`. - `destroy()`: Frees the resources that are used by this object. - `properties`: - `isHost`: `true` for hosts, `false` for clients. read-only. - `client`: a reference to an inner client object that the event callbacks before room was created are attached to. - `currentPlayerId`: current player's id. read-only. - `currentPlayer`: the original current player object. read-only. - `state`: the object that holds the whole room state. read-only. - `gameState`: room's game state information. returns null if game is not active. read-only. - `gameStateExt`: room's extrapolated game state. returns null if game is not active. read-only. - `sdp`: current room's sdp value (only for client rooms). read-only. - `config`: room's current roomConfig object. read-only. - `renderer`: room's current renderer object. read-only. - `plugins`: array of all available plugins. this is used internally to restore the order of plugins while plugin activation/deactivation. read-only. - `activePlugins`: array of currently active plugins. this is used internally for callbacks. read-only. - `pluginsMap`: all available plugins mapped as `pluginsMap[plugin.name] = plugin`, for optimized use to communicate between all addons. read-only. - `libraries`: array of all available libraries. - `librariesMap`: all available libraries mapped as `librariesMap[library.name] = library`, for optimized use to communicate between all addons. read-only. - `name`: current name of the room. read-only. - `link`: current url of the room. read-only. - `timeLimit`: the game's current time limit. read-only. - `scoreLimit`: the game's current score limit. read-only. - `stadium`: current stadium object of the room. read-only. - `players`: the list of players in the current room. read-only. - `redScore`: red team's current score. `null` if game is not active. read-only. - `blueScore`: blue team's current score. `null` if game is not active. read-only. - `timeElapsed`: elapsed time in current game. `null` if game is not active. read-only. - `currentFrameNo`: the current frame number of the room. read-only. - `banList`: the current list of banned players. read-only. host-only. - `requireRecaptcha`: whether the room requires recaptcha to join or not. host-only. - `token`: the current recaptcha token of the room. if changed, it will also refresh the room link. host-only. - `password`: the current password of the room. read-only. host-only. - `geo`: the current geolocation of the room. read-only. host-only. - `maxPlayerCount`: the current maximum number of players of the room. read-only. host-only. - `fakePassword`: the current fake password value of the room. read-only. host-only. - `fixedPlayerCount`: the current fixed player count value of the room. read-only. host-only. - `showInRoomList`: whether the room is currently being shown in the room list of the backend server or not. read-only. host-only. - `unlimitedPlayerCount`: whether the room's player count checking is disabled or not. read-only. host-only. - `functions`: - `leave()`: leaves the room. - `setProperties({ name, password, geo: { lat, lon, flag }, playerCount, maxPlayerCount, fakePassword, unlimitedPlayerCount, showInRoomList })`: sets the room's properties. - `setKickRateLimit(min, rate, burst)`: sets the room's kick rate limit. - `setHandicap(handicap)`: sets the player's `handicap` value in msecs. - `extrapolate(milliseconds=0, ignoreMultipleCalls=false)`: extrapolates the current room state for `milliseconds` milliseconds and stores the results in each object's `ext` key. `ignoreMultipleCalls` is added for safety, and should only be `true` in renderers. Returns the new extrapolated room state. - `clearBans()`: clears all bans. host-only. - `clearBan(id)`: clears the ban of a player(`id`). host-only. - `executeEvent(event, byId)`: executes any event inside this room. host-only. - `clearEvents()`: clears the event queue. can be useful when the game engine is stuck. - `setAvatar(avatar)`: sets the current player's client `avatar`. - `setPlayerAvatar(id, value, headless)`: sets the avatar of player(`id`) to `avatar`. `headless` is a boolean to determine whether the headless or client avatar is being set. host-only. - `setChatIndicatorActive(active)`: sets the current player's chat indicator status. `active`: `true`/`false`. - `setTeamColors(teamId, angle, ...colors)`: sets the team colors for team(`teamId`). `teamId`: `1`(red) | `2`(blue), `angle`: `integer`, `colors`: maximum 4 numeric (0 <= `integer` <= 16777215) color parameters. - `setUnlimitedPlayerCount(on)`: adds or removes player limit control. host-only. `on`: `true`/`false`. - `setFakePassword(fakePwd)`: sets a fake value for room's password status. host-only. `fakePwd`: `true`/`false` or `null` to disable. - `sendChat(msg, tar