node-haxball
v1.5.0
Published
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
Downloads
147
Maintainers
Readme
- Here is the Github repository for this project.
- You may read the full documentation here.
- We also have a discord server to help people adapt to this API. See you there!
🔖 Table Of Contents
💻 Installing & importing as a node.js/CommonJS module:
npm install node-haxball
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 proxy server. (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 haxballOriginModifier project.)
- Alternate URL (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>
<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>
<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:
Utils.generateAuth().then(([authKey, authObj])=>{
Room.join({
id: "Olnit_iGRWs",
authObj: authObj
}, {
storage: {
player_name: "wxyz-abcd",
avatar: "👽"
},
onSuccess: (room)=>{
room.sendChat("Hello " + room.name);
}
});
});
Creating a room:
Room.create({
name: "room123",
password: "password",
showInRoomList: true,
maxPlayerCount: 8,
token: "thr1.AAAAAGNMOokNqt3forXs_Q.3qQMuLQOS9o"
}, {
storage: {
player_name: "wxyz-abcd",
avatar: "👽"
},
onSuccess: (room)=>{
room.sendChat("Hello " + room.name);
room.onAfterRoomLink = (roomLink)=>{
console.log("room link:", roomLink);
};
}
});
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
, (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
,XMLHttpRequest
, (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. Iftrue
, 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 appendedhost
orclient
at the end while being used. Defaults to:wss://p2p.haxball.com/
for host andwss://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 appendedhost
orclient
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 tonull
.version
: Haxball's expected version number. Defaults to:9
.noVariableValueChangeEvent
: iftrue
, disables the mechanism that enables variable value change event which in turn improves performance while reaching a variable's value that was defined by anyAddon.defineVariable
function. (Variable will have a directly accessable, actual value; instead of a property that points to the actual variable.) Defaults to:false
.noWebRTC
: Iftrue
, skips the WebRTC initialization. Needed to be able to use the API functions that are not related to networking in environments without WebRTC support. Defaults to:false
.identityToken
: A token that represents a user data in a database of a custom proxy/backend server. Defaults tonull
.
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 callbackonOperationReceived
.VariableType
: Different types of variables that can be defined in a Plugin or a Renderer with its correspondingdefineVariable
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 usingRoom.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 asAPI.Language.current = new EnglishLanguage(API)
. Defaults tonull
.
static functions
:resolveText(str, array)
: Converts a template string(str
) to a normal string using the given parameters(array
).
constructor(abbr, metadata)
: creates a newLanguage
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 anerrors
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 anyLanguage
object. These are defined inLanguage.prototype
.defineMetadata(metadata)
: Does nothing, returns nothing by default. This function should define the givenmetadata
object inside thisLanguage
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 followingmetadata
structure:{name, version, author, description}
.
Errors
: Global error handling objects.ErrorCodes
: Name to integer mapping that shortly describes the error codes used inHBError
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 executingcurrentLanguage.errorsTextMap[this.code](...this.params)
.
Callback
: Global functions to add/remove callbacks.add(eventName, metadata)
: creates all callbacks about a new event calledeventName
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 ofmetadata
) 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 byCallback.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 forrequestAnimationFrame
. (null
= use library's defaultrequestAnimationFrame
.)cancelAnimationFrame
: Override function forcancelAnimationFrame
. (null
= use library's defaultcancelAnimationFrame
.)
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.)
- functions:
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 thedestinationTime
(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 thedestinationFrameNo
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 tosetTime(destinationTime)
orsetCurrentFrameNo(destinationFrameNo)
.onEnd()
: The end of replay data has been reached.
- properties:
ReplayData
: The structure that holds all of the data inside a replay file.roomData
: The initialRoomState
of the replay, including all the information about the current stadium, game state, players, etc.events
: All events in this replay ordered by their respectiveframeNo
.goalMarkers
: All team goals in this replay ordered by their respectiveframeNo
.totalFrames
: Total number of frames in this replay.version
: Version number of the replay. Must currently be equal to3
.
readAll(uint8Array)
: Reads all of the given binary replay data into a newReplayData
structure and returns it.trim(replayData, { beginFrameNo, endFrameNo })
: Synchronously trims the givenReplayData
between given frame numbersbeginFrameNo
andendFrameNo
, both of which can be omitted and are inclusive. If omitted,beginFrameNo
defaults to0
andendFrameNo
defaults toreplayData.totalFrames-1
.trimAsync(replayData, { beginFrameNo, endFrameNo })
: Asynchronously trims the givenReplayData
between given frame numbersbeginFrameNo
andendFrameNo
, both of which can be omitted and are inclusive. If omitted,beginFrameNo
defaults to0
andendFrameNo
defaults toreplayData.totalFrames-1
. returnsPromise(void)
writeAll(replayData)
: Writes the contents of aReplayData
structure into a newUint8Array
and returns it.
Utils
: Some static utility functions.generateAuth()
: generates a newplayer_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 inRoom.join
. returnsPromise([authKey, authObj])
.authFromKey(authKey)
: recreates the auth object for givenauthKey
. the object is used inRoom.join
. returnsPromise(authObj)
.getRoomList()
: returns the current room list. returnsPromise(roomListArray)
.calculateAllRoomDistances(geo, roomList)
: calculates the distances to the given geoLocationgeo
of all rooms in givenroomList
and stores them inside each room'sdist
property.numberToColor(number)
: returns the html color string (rgba representation) of the givennumber
. (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 asvalue1
andvalue2
are equal only at the positions whose bit values are1
inside thebitMask
. Used internally in banList implementation.keyState(dirX, dirY, kick)
: returns an integer key state value to be used inRoom.setKeyState
.dirX
= oneof[-1
:left,0
:still,1
:right],dirY
= oneof[-1
:up,0
:still,1
:down],kick
=true
/false
.reverseKeyState(state)
: returns thedirX
,dirY
,kick
parameters that were used to generate the given integerstate
withUtils.keyState
function.runAfterGameTick(callback, ticks)
: runs acallback
function afterticks
game ticks. if omitted,ticks
defaults to1
.getGeo()
: connects to Haxball's geolocation API to get your location based on IP address. you can use it directly asgeo
key insidestorage
object. returnsPromise(geoLocationObject)
parseGeo(geoStr, fallback, retNull)
: Parses the given string or json object(geoStr
) as aGeoLocation
object that should havelat
,lon
andflag
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 astadium
object.promiseWithTimeout(promise, msec)
: returns a new promise that executes the givenpromise
untilmsec
time has passed. if timeout is reached, the promise is rejected.hexStrToNumber(str)
: converts theplayerObject.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.
EventFactory
: Contains static functions to create all kinds of event messages.create(type)
: creates and returns an event message depending on thetype
parameter. returnsnull
iftype
is not one of the types defined insideOperationType
enum.createFromStream(reader)
: creates and returns an event message after reading it from a streamreader
. thereader
should be of typeImpl.Stream.F
.checkConsistency(data)
: creates and returns an event message that can be used to trigger a consistency check.data
should be anArrayBuffer
.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 toactive
.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
) toavatar
.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 tovalue
.setTimeLimit(value)
: creates and returns an event message that can be used to set the time limit of a game tovalue
.setStadium(stadium)
: creates and returns an event message that can be used to set the current stadium of a room tostadium
.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 tovalue
.setTeamColors(teamId, colors)
: creates and returns an event message that can be used to set the colors of a team(teamId
) tocolors
.colors
must be an instance of theImpl.Core.ka
(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
) todata
.setPlayerDiscProperties(id, data)
: creates and returns an event message that can be used to set the properties of the disc of a player(id
) todata
.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 eitherroom.state
orroom.stateExt
.getVertexIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first vertex that has a distance tomapCoordinate
lower thanthreshold
.getVertexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the first vertex that has a distance tomapCoordinate
lower thanthreshold
.getSegmentIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first segment that has a distance tomapCoordinate
lower thanthreshold
.getSegmentAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the first segment that has a distance tomapCoordinate
lower thanthreshold
.getGoalIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first goal that has a distance tomapCoordinate
lower thanthreshold
.getGoalAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the first goal that has a distance tomapCoordinate
lower thanthreshold
.getPlaneIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first plane that has a distance tomapCoordinate
lower thanthreshold
.getPlaneAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the first plane that has a distance tomapCoordinate
lower thanthreshold
.getJointIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first joint that has a distance tomapCoordinate
lower thanthreshold
.getJointAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the first joint that has a distance tomapCoordinate
lower thanthreshold
.getDiscIndexAtMapCoord(roomState, mapCoordinate)
: Finds the index of the first disc that includesmapCoordinate
.getDiscAtMapCoord(roomState, mapCoordinate)
: Finds the first disc that includesmapCoordinate
.getSpawnPointIndexAtMapCoord(roomState, mapCoordinate, threshold)
: Finds the index of the first spawn point that has a distance tomapCoordinate
lower thanthreshold
. Returns[spawnPointIndex, teamId]
.teamId
: [1
: red team,2
: blue team.]
Room
: The class that currently hosts all room operations. Should only be initialized by eitherRoom.join
orRoom.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 setnull
/undefined
for no password.token
: get a recaptcha token fromwww.haxball.com/headlesstoken
and write it here to bypass the loop of trying to solve recaptcha.noPlayer
: set it totrue
if you are planning to host the room without actually playing the game, otherwise set it tofalse
.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 anumber
, always fixes the player count to this specificnumber
.maxPlayerCount
: the maximum allowed player count in the room.unlimitedPlayerCount
: if set totrue
, bypasses the player count controller.fakePassword
: if set totrue
, the room will show that it is password-protected while in fact it is not.showInRoomList
: set totrue
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. the connection will be closed just after this callback is executed.
commonParams
: explained below inRoom.join
.
join(joinParams, commonParams)
: try to join the room(roomId
) with givenpassword
(ornull
=no password). Returns a custom object.joinParams
:id
: the id of the room to join. for example, if the room link ishttps://www.haxball.com/play?c=31IBNI3w4F0
, this room's id is31IBNI3w4F0
.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 byUtils.generateAuth()
orUtils.authFromKey()
before being used here.
commonParams
: --- properties section ---storage
:crappy_router
: iftrue
, sets some timeout value to10
seconds instead of4
seconds while joining a room.player_name
: name of the player. default value is"abc"
.avatar
: avatar of the player. default value isnull
.geo
:lat
: latitude value (number, default value is40
).lon
: longitude value (number, default value is40
).flag
: 2 letter country code (string, default value is"tr"
).
onValueSet(key, value)
: a callback function that is called just after the value of a key of this object has been changed by this library. default value isnull
.
noPluginMechanism
: iftrue
, renderer and plugin mechanism will not work. Should only be used for optimal performance. You have to defineRoom._onXXXXXX
callbacks by yourself.libraries
: array ofLibrary
objects to be used. the objects should be derived from the providedLibrary
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
: theRoomConfig
object that contains all the main callbacks of this room. the object should be derived from the providedRoomConfig
class. default value isnull
. (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
: theRenderer
object that can render the game. the object should be derived from the providedRenderer
class. default value isnull
. (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 ofPlugin
objects to be used. the objects should be derived from the providedPlugin
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 is9
.kickTimeout
: when you kick the ball, it causes you to release kick button by default. this library changes it so that it causes a timeout that makes you automatically press kick button again. you may assign a negative value to disable this feature. default value is-1
(msec).proxyAgent
: a custom proxy agent for the room's connection. This method does not work in browsers. Defaults tonull
.identityToken
: A token that represents a user data in a database of a custom proxy/backend server. Defaults tonull
.
--- event callbacks section ---
preInit(room)
: this is run as soon as theroom
object is created, just before the initialization of the plugins etc.onSuccess(room)
: joined/createdroom
.onFailure(error)
: join room failed with error(error
).onLeave(msg)
: triggered while leaving the room with reason(msg
).onConnectionStateChange(state, sdp)
: connection state has just changed to (state
).sdp
value can be used to get all the information about the webrtc connection whenstate
is1
or2
. you may use this to block players before they can connect the host, etc.onReverseConnection()
: trying reverse connection while joining a room.onRequestRecaptcha()
: recaptcha is required while joining or creating a room.
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 afteronRequestRecaptcha
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 useRoom.join
with the new token.
streamWatcher(initialStreamData, callbacks, options)
: creates a streamWatcher room.Parameters:
initialStreamData
: must be anUint8Array
that is received just after connecting to a streaming room.callbacks
: explained inRoom.sandbox
.options
: explained inRoom.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 hascopy()
instead oftakeSnapshot()
)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 tonewRoomState
.newRoomState
should be created bytakeSnapshot()
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 simulationcount
steps. simulation must be stopped for this function to work.destroy()
: Frees the resources that are used by this object.
- Properties:
sandbox(callbacks, options)
: creates a sandbox room.- Parameters:
callbacks
: An object that has the same callbacks as the renderer template.options
: An object that may contain the following keys:controlledPlayerId
: Id of the player to be controlled.requestAnimationFrame
: Override function forrequestAnimationFrame
. (null
= use library's defaultrequestAnimationFrame
.)cancelAnimationFrame
: Override function forcancelAnimationFrame
. (null
= use library's defaultcancelAnimationFrame
.)
- 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 hascopy()
instead oftakeSnapshot()
)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:
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 simulationcount
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 aReplayData
structure, or from aonOperationReceived(type, msg, globalFrameNo, clientFrameNo, customData)
callback.takeSnapshot()
: returns a complete snapshot of the current room state.useSnapshot(newRoomState)
: sets the current room state reference tonewRoomState
.newRoomState
should be created bytakeSnapshot()
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
) toinput
.playerChat(msg, byId)
: writes chat message(msg
) as player(byId
).setKeyState(state)
: set current key state tostate
. (added for compatibility with normal rooms.)setPlayerChatIndicator(value, byId)
: sets the chat indicator status of player(byId
) tovalue
.setPlayerAvatar(value, byId)
: sets the avatar of player(byId
) tovalue
.setCurrentStadium(value, byId)
: creates and applies a fake event by player(byId
) to set the current stadium tostadium
.sendAnnouncement(msg, color=-1, style=0, sound=1, targetId, byId)
: send announcement message(msg
) to player(targetId
) with properties(color
,style
,sound
).targetId
isnull
-> send to everyone.byId
must be0
.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 tovalue
.setScoreLimit(value, byId)
: creates and applies a fake event by player(byId
) to set the game's score limit tovalue
.setTimeLimit(value, byId)
: creates and applies a fake event by player(byId
) to set the game's time limit tovalue
.setTeamsLock(value, byId)
: creates and applies a fake event by player(byId
) to set the game's teams lock state tovalue
.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 parseable(hex-rgb) color parameters.setPlayerAdmin(playerId, value, byId)
: creates and applies a fake event by player(byId
) to set player(playerId
)'s admin status toisAdmin
.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
) tovalue
.sendPingData(valueFunc, byId)
: creates and applies a fake event by player(byId
) to change all ping values withvalueFunc
.byId
must be0
.setDiscProperties(discId, type, data, byId)
: creates and applies a fake event by player(byId
) to set disc(discId
) properties todata
.byId
must be0
.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
) todata
.destroy()
: Frees the resources that are used by this object.
- properties:
- Parameters:
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.kickTimeout
: time between releasing and re-pressing the kick key (in milliseconds, defaults to-1
). 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 aspluginsMap[plugin.name] = plugin
, for optimized use to communicate between all addons. read-only.libraries
: array of all available libraries.librariesMap
: all available libraries mapped aslibrariesMap[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'shandicap
value in msecs.extrapolate(milliseconds)
: extrapolates the current room state formilliseconds
milliseconds and stores the results in each object'sext
key.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 clientavatar
.setPlayerAvatar(id, value, headless)
: sets the avatar of player(id
) toavatar
.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 parseable(hex-rgb) 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
ornull
to disable.sendChat(msg, targetId)
: send chat message(msg
) to player(targetId
).targetId
isnull
-> send to everyone.targetId
is host-only.sendAnnouncement(msg, targetId, color, style, sound)
: send announcement message(msg
) to player(targetId
) with properties(color
,style
,sound
).targetId
isnull
-> send to everyone. host-only.setDiscProperties(discId, properties)
: set disc(discId
)properties
. host-only.setPlayerDiscProperties(playerId, properties)
: set player(playerId
)'s discproperties
. host-only.reorderPlayers(playerIdList, moveToTop)
: remove all players with ids inplayerIdList
and re-add them in the given order to the (top or bottom)(moveToTop
) of the player list. host-only.sendCustomEvent(type, data, targetId)
: sends aCustomEvent(type, data)
that can only be received by the users of this modified client. iftargetId
(host-only) is specified, the event is only sent to player(targetId
).sendBinaryCustomEvent(type, data, targetId)
: sends aBinaryCustomEvent(type, data)
that can only be received by the users of this modified client. iftargetId
(host-only) is specified, the event is only sent to player(targetId
).setPlayerIdentity(id, data, targetId)
: sends aSetPlayerIdentityEvent(type, data)
to set the identity data(playerObject.identity
) of player(id
) todata
. that can only be received by the users of this modified client. iftargetId
(host-only) is specified, the event is only sent to player(targetId
).getKeyState()
: get current key state.setKeyState(state)
: set current key state tostate
.startGame()
: start game.stopGame()
: stop game.pauseGame()
: toggle pause/resume game.isGamePaused()
: returnstrue
if game is paused.autoTeams()
: remove last 2 players from spectators and add them to teams.lockTeams()
: toggle lock/unlock the ability to change teams.resetTeams()
: move everyone to spectators.randTeams()
: remove random 2 players from spectators and add them to teams.resetTeam(teamId)
: move everyone on team(teamId
) to spectators.setSync(value)
: set synchronized status tovalue
which must betrue
orfalse
. host-only.setCurrentStadium(stadium)
: set current map(stadium
).setTimeLimit(value)
: set time limit(value
).setScoreLimit(value)
: set score limit(value
).changeTeam(teamId)
: set current player's team(teamId
).setPlayerTeam(playerId, teamId)
: set player(playerId
)'s team to team(teamId
).setPlayerAdmin(playerId, isAdmin)
: set player(playerId
)'s admin status toisAdmin
.kickPlayer(playerId, reason, isBanning)
: kick/ban a player(playerId
) with reason(reason
).getPlayer(id)
: get the original player data object for player(id
).getBall(extrapolated = true)
: get the original ball object.getDiscs(extrapolated = true)
: get the original disc object for disc(discId
).getDisc(discId, extrapolated = true)
: get the original disc object for disc(discId
).getPlayerDisc(playerId, extrapolated = true)
: get the original disc object for player(playerId
).getPlayerDisc_exp(playerId)
: get the original disc object for player(playerId
). faster thangetPlayerDisc
, but experimental. use at your own risk.addPlayerBan(playerId)
: bans a player(playerId
) from joining the room. host-only.addIpBan(...ips)
: bans all given ip(range)(s) from joining the room. host-only.addAuthBan(...auths)
: bans all given auth(s) from joining the room. host-only.removeBan(id)
: removes the ban entry(id). host-only.setPluginActive(name, active)
: activate/deactivate the plugin(name
).startRecording()
: start recording replay data. returnstrue
if succeeded,false
otherwise. recording should not be started before calling this.stopRecording()
: stop recording replay data. returnsUIntArray8
data if succeeded, null otherwise. recording should be started before calling this.startStreaming({immediate = true, onClientCount, emitData})
: start streaming the game. currently, recording and streaming cannot be run simultaneously. returns{onSuccess: ()=>void, onDataReceived: (data)=>void, interval: ()=>void}
.stopStreaming()
: stop streaming the game.isRecording()
: returnstrue
if recording/streaming has started;false
otherwise.setConfig(roomConfig)
: sets theRoomConfig
object that contains all the main callbacks of this room. theroomConfig
object should be derived from the providedRoomConfig
class.mixConfig(newRoomConfig)
: adds all callbacks innewRoomConfig
into the room's current RoomConfig object. if there are callbacks with the same name, a new callback is created that calls both of them. (current callback is called first.)updatePlugin(pluginIndex, newPluginObj)
: sets thePlugin
at the specifiedpluginIndex
to thenewPluginObj
object, initialization and activation are automatic. plugin names must be the same. the plugin object should be derived from the providedPlugin
class.setRenderer(renderer)
: sets theRenderer
object that will render the game. therenderer
object should be derived from the providedRenderer
class.updateLibrary(libraryIndex, newLibraryObj)
: sets theLibrary
at the specifiedlibraryIndex
to thenewLibraryObj
object, initialization and activation are automatic. library names must be the same. the library object should be derived from the providedLibrary
class.
sandbox mode functions
: these functions are not supported by the original Haxball client. you would need to createCustomEvent
s to use them within a synchronized(network) environment. the game must NOT be stopped for these functions to work.takeSnapshot()
: returns a snapshot of the current game state. you can load this object directly into sandbox using itsuseSnapshot(newRoomState)
function.exportStadium()
: returns all current game objects in hbs format.createVertex(data)
: creates a vertex object in memory.data
:{ x: number, y: number, bCoef: number, cMask: array of string, cGroup: array of string }
createSegment(data)
: creates a segment object in memory using vertex indices.data
:{ v0: number, v1: number, color: ("transparent" || string || [r: number, g: number, b: number]), bias: number, (curve: number || curveF: number), vis: boolean, bCoef: number, cMask: array of string, cGroup: array of string }
createSegmentFromObj(data)
: creates a segment object in memory using vertex objects.data
:{ v0: vertexObj, v1: vertexObj, color: ("transparent" || string || [r: number, g: number, b: number]), bias: number, (curve: number || curveF: number), vis: boolean, bCoef: number, cMask: array of string, cGroup: array of string }
createGoal(data)
: creates a goal object in memory.data
:{ p0: [x: number, y: number], p1: [x: number, y: number], team: ("red" || "blue") }
createPlane(data)
: creates a plane object in memory.data
:{ normal: [x: number, y: number], dist: number, bCoef: number, cMask: array of string, cGroup: array of string }
createDisc(data)
: creates a disc object in memory.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, color: ("transparent" || string || [r: number, g: number, b: number]), bCoef: number, cMask: array of string, cGroup: array of string }
createJoint(data)
: creates a joint object in memory using disc indices.data
:{ d0: number, d1: number, color: ("transparent" || string || [r: number, g: number, b: number]), strength: "rigid" || number, length: null || number || [min: number, max: number] }
createJointFromObj(data)
: creates a joint object in memory using disc objects.data
:{ d0: discObj, d1: discObj, color: ("transparent" || string || [r: number, g: number, b: number]), strength: "rigid" || number, length: null || number || [min: number, max: number] }
addVertex(data)
: creates a vertex object and adds it to the current stadium.data
:{ x: number, y: number, bCoef: number, cMask: array of string, cGroup: array of string }
addSegment(data)
: creates a segment object and adds it to the current stadium.data
:{ v0: number, v1: number, color: ("transparent" || string || [r: number, g: number, b: number]), bias: number, (curve: number || curveF: number), vis: boolean, bCoef: number, cMask: array of string, cGroup: array of string }
addGoal(data)
: creates a goal object and adds it to the current stadium.data
:{ p0: [x: number, y: number], p1: [x: number, y: number], team: ("red" || "blue") }
addPlane(data)
: creates a plane object and adds it to the current stadium.data
:{ normal: [x: number, y: number], dist: number, bCoef: number, cMask: array of string, cGroup: array of string }
addDisc(data)
: creates a disc object and adds it to the current stadium.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, color: ("transparent" || string || [r: number, g: number, b: number]), bCoef: number, cMask: array of string, cGroup: array of string }
addJoint(data)
: creates a joint object and adds it to the current stadium.data
:{ d0: number, d1: number, color: ("transparent" || string || [r: number, g: number, b: number]), strength: "rigid" || number, length: null || number || [min: number, max: number] }
addSpawnPoint(data)
: adds a spawn point with given properties to the current stadium.data
:{ x: number, y: number, team: ("red" || "blue") }
addPlayer(data)
: adds a player with given properties to the current stadium.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, bCoef: number, cMask: array of string, cGroup: array of string, id: integer, name: string, avatar: string, flag: string, team: ("spec" || "red" || "blue") }
. these keys must exist:team
,id
,name
,avatar
,flag
.findVertexIndicesOfSegmentObj(segmentObj)
: finds the indices of vertices that form the given segment object(segmentObj
). return format:[index1, index2]
.findVertexIndicesOfSegment(segmentIndex)
: finds the indices of vertices that form thesegmentIndex
th segment object. return format[index1, index2]
.updateVertex(idx, data)
: updates theidx
th vertex's only the given values.data
:{ x: number, y: number, bCoef: number, cMask: array of string, cGroup: array of string }
updateSegment(idx, data)
: updates theidx
th segment's only the given values.data
:{ v0: number, v1: number, color: ("transparent" || string || [r: number, g: number, b: number]), bias: number, (curve: number || curveF: number), vis: boolean, bCoef: number, cMask: array of string, cGroup: array of string }
updateGoal(idx, data)
: updates theidx
th goal's only the given values.data
:{ p0: [x: number, y: number], p1: [x: number, y: number], team: ("red" || "blue") }
updatePlane(idx, data)
: updates theidx
th plane's only the given values.data
:{ normal: [x: number, y: number], dist: number, bCoef: number, cMask: array of string, cGroup: array of string }
updateDisc(idx, data)
: updates theidx
th disc's only the given values.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, color: ("transparent" || string || [r: number, g: number, b: number]), bCoef: number, cMask: array of string, cGroup: array of string }
updateDiscObj(discObj, data)
: updates the given disc object(discObj
)'s only the given values.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, color: ("transparent" || string || [r: number, g: number, b: number]), bCoef: number, cMask: array of string, cGroup: array of string }
updateJoint(idx, data)
: updates theidx
th joint's only the given values.data
:{ d0: number, d1: number, color: ("transparent" || string || [r: number, g: number, b: number]), strength: "rigid" || number, length: null || number || [min: number, max: number] }
updateSpawnPoint(idx, team, data)
: updates theidx
th spawn point in team(team
) using only the given values.data
:{ x: number, y: number, team: ("red" || "blue") }
updatePlayer(playerId, data)
: updates the player(playerId
)'s only the given values.data
:{ pos: [x: number, y: number], speed: [x: number, y: number], gravity: [x: number, y: number], radius: number, invMass: number, damping: number, bCoef: number, cMask: array of string, cGroup: array of string, name: string, avatar: string, flag: string, team: ("spec" || "red" || "blue") }
removeVertex(idx)
: removes theidx
th vertex from the current stadium.removeSegment(idx)
: removes theidx
th segment from the current stadium.removeGoal(idx)
: removes theidx
th goal from the current stadium.removePlane(idx)
: removes theidx
th plane from the current stadium.removeDisc(idx)
: removes theidx
th disc from the current stadium.removeJoint(idx)
: removes theidx
th joint from the current stadium.removeSpawnPoint(idx, team)
: removes theidx
th spawn point of team(team
) from the current stadium.team
:"red" || "blue"
removePlayer(playerId)
: removes the player(playerId
) from the current stadium.updateStadiumPlayerPhysics(data)
: updates the current stadium's only the given player physics values.data
:{ radius: number, gravity: [x: number, y: number], invMass: number, bCoef: number, cGroup: array of string, damping: number, kickingDamping: number, acceleration: number, kickingAcceleration: number, kickStrength: number, kickback: number }
updateStadiumBg(data)
: updates the current stadium's only the given background values.data
:{ type: 0("none") || 1("grass") || 2("hockey"), width: number, height: number, kickOffRadius: number, cornerRadius: number, color: ("transparent" || string || [r: number, g: number, b: number]), goalLine: number }
updateStadiumGeneral(data)
: updates the current stadium's only the given general values.data
:{ name: string, width: number, height: number, maxViewWidth: number, cameraFollow: 0("") || 1("player"), spawnDistance: number, kickOffReset: true("full") || false("partial"), canBeStored: boolean }
fake event triggers
: these functions are intended to be used in host mode to create/control in-memory bot players that will run much more efficiently than standard networking bot players. they also work for normal player objects, and can be used to create some events belonging to a player that did not originate from that player. most of these fake events also trigger anonOperationReceived
call before being sent to clients.fakePlayerJoin(id, name, flag, avatar, conn, auth)
: triggers a fake join room event; which in turn creates a new in-memory player object. If there was a player before with this id, old resources are automatically reassigned to this new player object, and that player will wake up. 0 <=id
<= 65535, all the other parameters must be a string.fakePlayerLeave(id)
: triggers a fake leave room event. returns the player's properties so that you may pass them tofakePlayerJoin
at a later time to wake that player. passingid
= 0 causes desync on clients (because there's a special check for the caseid
= 0 in original clients). the player, although seemingly leaving the room, still watches the room, waiting for a fake player join event. all parameters exceptid
may be different in the newfakePlayerJoin
call, which allows player'sname
,flag
,avatar
,conn
andauth
to change without the player entirely leaving the room.fakeSendPlayerInput(input, byId)
: triggers a fake input(keys) event that apparently came fromplayer(byId)
. 0<=input
<=31.fakeSendPlayerChat(msg, targetId, byId)
: triggers a fake chat event that apparently came fromplayer(byId)
.msg
must be a string.targetId
is the id of the player who will receive this event message. IftargetId