interfaces utils - wxyz-abcd/node-haxball GitHub Wiki

Utils

This object consists of several helper utility functions for developers.

1. Functions

  • generateAuth(): Promise([authKey: string, authObj: Auth])

    Generates a new player_auth_key along with its companion auth object(auhObj) to be used as parameters to the function Room.join. We should store the auth key and use it later if we want to be recognized in Haxball rooms. Any internal error will result in a rejected promise.

    Parameters: None.

    Return value: Promise([authKey: string, authObj: Auth]).

    Example:

    function joinRoomWithNewAuth(roomId, playerName, playerAvatar){
      Utils.generateAuth().then(([authKey, authObj])=>{
        Room.join({
          id: roomId,
        }, {
          storage: {
            player_name: playerName,
            avatar: playerAvatar,
            player_auth_key: authKey,
            // ...
          }, 
          authObj: authObj,
          /*
          ...
          other parameters here
          ...
          */
        });
      }
    }
  • authFromKey(authKey: string): Promise(Auth)

    Recreates the auth object from the given authKey. The returned object is only to be used as parameter to the function Room.join.

    • Bad inputs or any internal error will result in a rejected promise.

    Parameters:

    • authKey: string: A simplified string that represents an auth object.

    Return value: The Auth object that was generated from the given authKey.

    Example:

    function joinRoomWithOldAuth(roomId, authKey, playerName, playerAvatar){
      Utils.authFromKey(authKey).then((authObj)=>{
        Room.join({
          id: roomId,
        }, {
          storage: {
            player_name: playerName,
            avatar: playerAvatar,
            player_auth_key: authKey,
            // ...
          }, 
          authObj: authObj,
          /*
          ...
          other parameters here
          ...
          */
        });
      }, (error)=>{
        console.error("Wrong auth key.");
      });
    }
  • getRoomList(): Promise(roomListArray: RoomData[])

    Connects to Haxball's backend server, retrieves the current room list and returns it.

    Parameters: None.

    Return value: A promise that returns the current list of open rooms returned from the Haxball's backend server.

    Example:

    Utils.getRoomList().then((list)=>{
      list.forEach((room)=>{
        console.log(room);
      });
    });
  • calculateAllRoomDistances(geo: GeoLocation, roomList: RoomData[]): void

    Calculates the distances to the given GeoLocation geo of all rooms in given roomList and stores them inside each room's dist property.

    Parameters:

    • geo: GeoLocation: The location to calculate the distances to.
    • roomList: RoomData[]: The room list to update.

    Return value: void.

    Example:

    function getRoomListSortedByDistanceToGeoLocation(geoLocation){
      return Utils.getRoomList().then((list)=>{
        calculateAllRoomDistances(geoLocation, list);
        list.sort((a, b) => (a.dist - b.dist));
        return list;
      });
    }
  • numberToColor(number: int): string

    Returns the html color string (rgba representation) of the given number. This function is mostly intended to be used in renderers and map editors. Bad inputs will return a bad string output.

    Parameters:

    • number: int: A number in the range [0, 16777215].

    Return value: The rgba representation of the color that was generated from the given number.

    Example:

    function drawTextWithColor(canvas, x, y, text, color){
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = Utils.numberToColor(color);
      ctx.fillText(text, x, y);
      return canvas;
    }
  • colorToNumber(color: string): int

    Returns the number representation of the given html color string. (rgba representation) This function is mostly intended to be used in renderers and map editors.

    • Bad inputs will return undefined.
    • Alpha value of the input color is not used. (The game engine currently assigns 255 to all alpha values by default.)

    Parameters:

    • color: string: The rgba representation of a color.

    Return value: An integer that represents the given color.

    Example:

    function createCustomSegment(x1, y1, x2, y2, curve, rgbColor){
      return room.state.createSegmentFromObj({
        v0: room.state.createVertex({x: x1, y: y1}),
        v1: room.state.createVertex({x: x2, y: y2}),
        curve: curve, 
        color: Utils.colorToNumber(rgbColor)
      });
    }
  • ipToNumber(ip: string): NumericIPv4 | NumericIPv6 | null

    Returns the numeric representation of the given ip address. Returns null if the input string is ill-formatted.

    Parameters:

    • ip: string: The ip address to be converted.

    Return value: An integer for ipv4 string, a BigInt for ipv6 string.

    Example:

    console.log(Utils.ipToNumber("8.8.8.8"));
    console.log(Utils.ipToNumber("2001:0000:130f::09c0:876a:130b"));
  • numberToIp(ip: NumericIPv4 | NumericIPv6): string | null

    Returns the ip address string of a given numeric representation. Returns null if the input number is invalid.

    Parameters:

    • ip: NumericIPv4 | NumericIPv6: The numeric representation of an ip address to be converted.

    Return value: A formatted ip string.

    Example:

    console.log(Utils.numberToIp(Utils.ipToNumber("8.8.8.8")));
    console.log(Utils.numberToIp(Utils.ipToNumber("2001:0000:130f::09c0:876a:130b")));
  • authToNumber(auth: string): BigInt

    Returns the numeric representation of the given auth string. Returns null if the length of the auth string is not 43.

    Parameters:

    • auth: string: The auth value to be converted.

    Return value: A BigInt.

    Example:

    console.log(Utils.authToNumber("abcabcabcabcabcabcabcabcabcabcabcabcabcabca"));
  • numberToAuth(auth: BigInt): string

    Returns the auth string for the numeric representation of it. Returns null if the input number is invalid.

    Parameters:

    • auth: The numeric representation of an auth string to be converted.

    Return value: An auth string.

    Example:

    console.log(Utils.numberToAuth(Utils.authToNumber("abcabcabcabcabcabcabcabcabcabcabcabcabcabca")));
  • compareBits(value1: NumericIPv4 | NumericIPv6, value2: NumericIPv4 | NumericIPv6, bitMask: NumericIPv4 | NumericIPv6): boolean

    Compares the bits of value1 and value2 at the exact positions that are 1 in the given bitMask.

    The types of value1, value2 and bitMask must be the same.

    Parameters:

    • value1: The first value to be compared.
    • value2: The second value to be compared.
    • bitMask: The bit mask that represents which bits to compare.

    Return value: A boolean whose value is true if all bits that are compared are equal.

    Example:

    console.log(Utils.compareBits(10, 6, 2));
    console.log(Utils.compareBits(10, 5, 2));
  • keyState(dirX: int, dirY: int, kick: boolean): int

    Returns an integer key state value, only to be used with Room.setKeyState.

    Parameters:

    • dirX: int: Desired x direction. One of [-1:left, 0:still, 1:right].
    • dirY: int: Desired y direction. One of [-1:up, 0:still, 1:down].
    • kick: boolean: Desired pressed state of the kick button.

    Return value: An integer in the range [0, 31].

    Example:

    // This will be interpreted as pressing left direction key and kick key, and releasing all other keys.
    room.setKeyState(Utils.keyState(-1, 0, true));
  • reverseKeyState(state: int): object

    Returns the explanation of the given key state.

    Parameters:

    • state: int: An integer in the range [0, 31].

    Return value:

    An object that has the following keys:

    • dirX: int: X direction. One of [-1:left, 0:still, 1:right].
    • dirY: int: Y direction. One of [-1:up, 0:still, 1:down].
    • kick: boolean: State of the kick button.

    Example:

    console.log(Utils.reverseKeyState(3));
  • runAfterGameTick(state: int): object

    Runs a callback function after ticks game ticks.

    Parameters:

    • callback: Function<void>: The function to run.
    • ticks: int: Number of ticks to wait before running the callback function. Defaults to 1.

    Return value: void.

    Example:

    Utils.runAfterGameTick(()=>{
      console.log("This code will run after 3 game ticks.");
    }, 3);
  • getGeo(): Promise(GeoLocation)

    Connects to Haxball's backend server, retrieves your location based on IP address using backend's geolocation API and returns it.

    • Might throw errors.

    Parameters: None.

    Return value: A promise that returns a GeoLocation object that has your location data retrieved from the backend server.

    Example:

    function joinRoomWithNewAuthAndBackendGeo(roomId, playerName, playerAvatar){
      Utils.getGeo().then((geo)=>{
        Utils.generateAuth().then(([authKey, authObj])=>{
          Room.join({
            id: roomId,
          }, {
            storage: {
              player_name: playerName,
              avatar: playerAvatar,
              player_auth_key: authKey,
              geo: geo,
              // ...
            }, 
            authObj: authObj,
            /*
            ...
            other parameters here
            ...
            */
          });
        }
      }).catch((ex)=>{
        console.error("Error:", ex);
      });
    }
  • getDefaultStadiums(): Stadium[]

    Returns the default stadium array.

    Parameters: None.

    Return value: All of the default stadiums as an array.

  • exportStadium(stadium: Stadium): string

    Generate and return text content from a stadium object that can be directly written in a .hbs file.

    Return value: string.

    Example:

    function exportDefaultStadium(index){
      var allDefaultStadiums = Utils.getDefaultStadiums();
      return Utils.exportStadium(allDefaultStadiums[index]);
    }
  • parseStadium(textDataFromHbsFile: string): Stadium

    Parses a string as a Stadium object. Exception might be thrown if an error occurs.

    Parameters:

    textDataFromHbsFile: string: The string representation of a Stadium object.

    Return value: The generated Stadium object.

    Example:

    function changeStadium(room, fileObj){
      var fr = new FileReader();
      fr.onload = function(){
        try{
          room.setCurrentStadium(Utils.parseStadium(fr.result));
        }
        catch(ex){
          console.log(ex.toString());
        }
      };
      fr.readAsText(fileObj);
    }
  • parseHexInt(str: string): int

    Parses a string that contains decimal or hexadecimal digits as an integer.

    Parameters:

    • str: string: The string to be converted into an integer.

    Return value: The converted integer value or null if conversion failed.

  • numberToHexString(number: int, minLength?: int): string

    Converts an integer into hexadecimal format.

    Parameters:

    • number: int: The integer to be converted into hexadecimal format.

    Return value: The string that contains the hexadecimal format of the given number. If minLength is given, its length will be at least minLength characters.

  • parseGeo(geoStr?: object|string, fallback?: object, retNull?: boolean): GeoLocation | null

    Parses the given string or json object as a GeoLocation object and returns it.

    Parameters:

    • geoStr?: object|string: An (optionally stringified) object that may have the following keys:
      • lat: Latitude value.
      • lon: Longitude value.
      • flag: Country code.
    • fallback?: object: An object whose keys will be used as fallback if the first parameter does not have any of the requested key(s). It should have lat, lon, flag as well.
    • retNull?: boolean: Whether to return null if geoStr is null. Defaults to true.

    Return value: A GeoLocation object.

  • promiseWithTimeout(promise: Promise, msec: int32): Promise

    Returns a new promise that executes the given promise until msec milliseconds have passed. If timeout is reached, the promise is rejected.

    Parameters:

    • promise: Promise: A Promise that has to be executed with a time limit.
    • msec: int32: The time limit.

    Return value: The new promise with time limit.

  • hexStrToNumber(str: string): string

    Converts the playerObject.conn values to readable ip address string.

    Parameters:

    • str: string: The string to be converted.

    Return value: The converted ip address string.

  • byteArrayToIp(data: Uint8Array): string

    Converts a Uint8Array that was read from basro's backend into a readable ip address string.

    Parameters:

    • data: Uint8Array: The data to be converted.

    Return value: The recovered ip address string.

  • refreshRoomToken(params: object): Promise<{code: int, value: string|Error}>

    Generates a new room token from an old room token OR a rcr(recaptcha response) value.

    Parameters:

    • params: object: An object that may contain the following keys:
      • token: string: The old room token. (Default value is "")
      • rcr: string: The recaptcha response value received from Google Recaptcha v2 API. (Default value is "")

    Return value: A Promise that resolves to an object that contains code and value keys. code can be 0, 1 or 2. Possible scenarios are as follows:

    • If code = 0; The token value was accepted and value contains the new room token.
    • If code = 1; The token value was rejected and value contains the sitekey value that is required by Google Recaptcha v2 API to show recaptcha inside a website.
    • If code = 2; An error occurred while sending request or receiving response and value contains the error.
  • generateRoomId(params: object): Promise<{roomId: string, newToken: string}>

    Generates and returns the room id corresponding to the given room token. This function also refreshes the room token and returns the new token.

    Parameters:

    • params: object: An object that may contain the following keys:
      • token: string: The room token.
      • proxyAgent: object: A custom proxy agent to use for the connection. This method does not work in browsers. (Default value is null)

    Return value: A Promise that resolves to an object that contains roomId and newToken keys. The promise is rejected if an error occurs.

⚠️ **GitHub.com Fallback** ⚠️