feat: version 2.0.0

This commit is contained in:
AURUMVORXX
2025-04-15 12:20:31 +03:00
parent dfcf695f24
commit 988f901dc8
44 changed files with 3143 additions and 1378 deletions

626
include/events.nut Normal file
View File

@@ -0,0 +1,626 @@
addEventHandler("onPlayerUseCheat", function(playerid, type)
{
local data = {
event = "onPlayerUseCheat",
args = {
playerid = playerid,
type = type
}
}
_PyG2O_Send(data);
});
addEventHandler("onBan", function(banInfo)
{
local data = {
event = "onBan",
args = {
ban = {
mac = "mac" in banInfo ? banInfo["mac"] : "-1",
ip = "ip" in banInfo ? banInfo["ip"] : "-1",
serial = "serial" in banInfo ? banInfo["serial"] : "-1",
name = "name" in banInfo ? banInfo["name"] : "-1",
timestamp = "timestamp" in banInfo ? banInfo["timestamp"] : -1
}
}
}
_PyG2O_Send(data);
});
addEventHandler("onInit", function()
{
local data = {
event = "onInit",
args = {}
}
_PyG2O_Send(data);
});
addEventHandler("onExit", function()
{
local data = {
event = "onExit",
args = {}
}
_PyG2O_Send(data);
});
addEventHandler("onTick", function()
{
local data = {
event = "onTick",
args = {}
}
_PyG2O_Send(data);
});
addEventHandler("onTime", function(day, hour, min)
{
local data = {
event = "onTime",
args = {
day = day,
hour = hour,
min = min,
}
}
_PyG2O_Send(data);
});
addEventHandler("onUnban", function(banInfo)
{
local data = {
event = "onUnban",
args = {
ban = {
mac = "mac" in banInfo ? banInfo["mac"] : "-1",
ip = "ip" in banInfo ? banInfo["ip"] : "-1",
serial = "serial" in banInfo ? banInfo["serial"] : "-1",
name = "name" in banInfo ? banInfo["name"] : "-1",
timestamp = "timestamp" in banInfo ? banInfo["timestamp"] : -1
}
}
}
_PyG2O_Send(data);
});
addEventHandler("onNpcActionFinished", function(npc_id, action_type, action_id, result)
{
local data = {
event = "onNpcActionFinished",
args = {
npc_id = npc_id,
action_type = action_type,
action_id = action_id,
result = result
}
}
_PyG2O_Send(data);
});
addEventHandler("onNpcActionSent", function(npc_id, action_type, action_id)
{
local data = {
event = "onNpcActionSent",
args = {
npc_id = npc_id,
action_type = action_type,
action_id = action_id,
}
}
_PyG2O_Send(data);
});
addEventHandler("onNpcChangeHostPlayer", function(npc_id, current_id, previous_id)
{
local data = {
event = "onNpcChangeHostPlayer",
args = {
npc_id = npc_id,
current_id = current_id,
previous_id = previous_id
}
}
_PyG2O_Send(data);
});
addEventHandler("onNpcCreated", function(npc_id)
{
local data = {
event = "onNpcCreated",
args = {
npc_id = npc_id
}
}
_PyG2O_Send(data);
});
addEventHandler("onNpcDestroyed", function(npc_id)
{
local data = {
event = "onNpcDestroyed",
args = {
npc_id = npc_id
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeColor", function(playerid, r, g, b)
{
local data = {
event = "onPlayerChangeColor",
args = {
playerid = playerid,
r = r,
g = g,
b = b
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeFocus", function(playerid, oldFocusId, newFocusId)
{
local data = {
event = "onPlayerChangeFocus",
args = {
playerid = playerid,
oldFocusId = oldFocusId,
newFocusId = newFocusId
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeHealth", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeHealth",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeMana", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeMana",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeMaxHealth", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeMaxHealth",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeMaxMana", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeMaxMana",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeWeaponMode", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeWeaponMode",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerChangeWorld", function(playerid, previous, current)
{
local data = {
event = "onPlayerChangeWorld",
args = {
playerid = playerid,
previous = previous,
current = current
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerCommand", function(playerid, command, params)
{
local data = {
event = "onPlayerCommand",
args = {
playerid = playerid,
command = command,
params = params
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerDamage", function(playerid, killerid, description)
{
local data = {
event = "onPlayerDamage",
args = {
playerid = playerid,
killerid = killerid,
obj_DamageDescription = {
name = "desc",
data = _PyG2O_Serialize(description)
}
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerDead", function(playerid, killerid)
{
local data = {
event = "onPlayerDead",
args = {
playerid = playerid,
killerid = killerid
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerDisconnect", function(playerid, reason)
{
local data = {
event = "onPlayerDisconnect",
args = {
playerid = playerid,
reason = reason
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerDropItem", function(playerid, itemGround)
{
local data = {
event = "onPlayerDropItem",
args = {
playerid = playerid,
obj_ItemGround = {
name = "itemGround",
data = _PyG2O_Serialize(itemGround)
}
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEnterWorld", function(playerid, world)
{
local data = {
event = "onPlayerEnterWorld",
args = {
playerid = playerid,
world = world
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipAmulet", function(playerid, instance)
{
local data = {
event = "onPlayerEquipAmulet",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipArmor", function(playerid, instance)
{
local data = {
event = "onPlayerEquipArmor",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipBelt", function(playerid, instance)
{
local data = {
event = "onPlayerEquipBelt",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipHandItem", function(playerid, hand, instance)
{
local data = {
event = "onPlayerEquipHandItem",
args = {
playerid = playerid,
hand = hand,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipHelmet", function(playerid, instance)
{
local data = {
event = "onPlayerEquipHelmet",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipMeleeWeapon", function(playerid, instance)
{
local data = {
event = "onPlayerEquipMeleeWeapon",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipRangedWeapon", function(playerid, instance)
{
local data = {
event = "onPlayerEquipRangedWeapon",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipRing", function(playerid, handId, instance)
{
local data = {
event = "onPlayerEquipRing",
args = {
playerid = playerid,
handId = handId,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipShield", function(playerid, instance)
{
local data = {
event = "onPlayerEquipShield",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerEquipSpell", function(playerid, slotId, instance)
{
local data = {
event = "onPlayerEquipSpell",
args = {
playerid = playerid,
slotId = slotId,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerJoin", function(playerid)
{
local data = {
event = "onPlayerJoin",
args = {
playerid = playerid
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerMessage", function(playerid, message)
{
local data = {
event = "onPlayerMessage",
args = {
playerid = playerid,
message = message
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerMobInteract", function(playerid, from, to)
{
local data = {
event = "onPlayerMobInteract",
args = {
playerid = playerid,
from = from,
to = to
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerRespawn", function(playerid)
{
local data = {
event = "onPlayerRespawn",
args = {
playerid = playerid
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerShoot", function(playerid, munition)
{
local data = {
event = "onPlayerShoot",
args = {
playerid = playerid,
munition = munition
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerSpellCast", function(playerid, instance, spellLevel)
{
local data = {
event = "onPlayerSpellCast",
args = {
playerid = playerid,
instance = instance,
spellLevel = spellLevel
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerSpellSetup", function(playerid, instance)
{
local data = {
event = "onPlayerSpellSetup",
args = {
playerid = playerid,
instance = instance
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerTakeItem", function(playerid, itemGround)
{
local data = {
event = "onPlayerTakeItem",
args = {
playerid = playerid,
obj_ItemGround = {
name = "itemGround",
data = _PyG2O_Serialize(itemGround)
}
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerTeleport", function(playerid, vobName)
{
local data = {
event = "onPlayerTeleport",
args = {
playerid = playerid,
vobName = vobName
}
}
_PyG2O_Send(data);
});
addEventHandler("onPlayerToggleFaceAni", function(playerid, aniName, toggle)
{
local data = {
event = "onPlayerToggleFaceAni",
args = {
playerid = playerid,
aniName = aniName,
toggle = toggle
}
}
_PyG2O_Send(data);
});

128
include/main.nut Normal file
View File

@@ -0,0 +1,128 @@
local _pyg2o_server_connection = -1;
local _silent = false;
local _url = -1
local _reconnect = false;
function PyG2O_Start(url, reconnect = false, silent = false)
{
_silent = silent;
_url = url;
_reconnect = reconnect;
_pyg2o_server_connection = WebsocketClient();
_pyg2o_server_connection.silent = true;
_pyg2o_server_connection.setUrl("ws://localhost:8080");
_pyg2o_server_connection.start();
if (!_silent)
print("[PyG2O] Initializing connection on " + url)
}
function _PyG2O_Send(data)
{
if (_pyg2o_server_connection == -1)
return;
_pyg2o_server_connection.send(JSON.dump_ansi(data));
}
function _PyG2O_InitializeConstants()
{
local const_data = {
"type": "const_init",
"args": getconsttable()
};
_PyG2O_Send(const_data);
}
function _PyG2O_GetClassName(object)
{
if (object instanceof DamageDescription)
return "DamageDescription";
else if (object instanceof ItemGround)
return "ItemGround";
return null;
}
function _PyG2O_Serialize(object)
{
local cls = object.getclass();
local tab = {};
if (object instanceof DamageDescription)
{
tab["_flags"] <- object.flags;
tab["_damage"] <- object.damage;
tab["_item_instance"] <- object.item_instance;
tab["_distance"] <- object.distance;
tab["_spell_id"] <- object.spell_id;
tab["_spell_level"] <- object.spell_level;
tab["_node"] <- object.node;
}
else if (object instanceof ItemGround)
{
tab["_id"] <- object.id;
tab["_instance"] <- object.instance;
tab["_amount"] <- object.amount;
tab["_world"] <- object.world;
tab["_virtualWorld"] <- object.virtualWorld;
tab["_position"] <- object.getPosition();
tab["_rotation"] <- object.getRotation();
}
return tab;
}
addEventHandler("onWebsocketConnect", function(socket, url)
{
if (socket != _pyg2o_server_connection)
return;
if (!_silent)
{
print("[PyG2O] Successfully connected to " + url);
_PyG2O_InitializeConstants();
}
});
addEventHandler("onWebsocketDisconnect", function(socket, url)
{
if (socket != _pyg2o_server_connection || _reconnect)
return;
_pyg2o_server_connection = -1;
});
addEventHandler("onWebsocketMessage", function(socket, url, message)
{
if (socket != _pyg2o_server_connection)
return;
local request = JSON.parse_ansi(message);
if ("uuid" in request)
{
local result = compilestring(request["args"])();
local className = _PyG2O_GetClassName(result);
if (className != null)
{
className = format("obj_%s", className)
request["args"] = {};
request["args"].rawset(className, {});
local objTab = request["args"].rawget(className);
objTab["name"] <- "result";
objTab["data"] <- _PyG2O_Serialize(result);
}
else
{
request["args"] =
{
"result": result
};
}
_pyg2o_server_connection.send(JSON.dump_ansi(request, 2));
}
});

4
include/pyg2o.xml Normal file
View File

@@ -0,0 +1,4 @@
<server>
<script src="main.nut" type="server" />
<script src="events.nut" type="server" />
</server>

View File

View File

@@ -1,5 +1,5 @@
[build-systems] [build-systems]
requires = ["setuptools>=42"] requires = ["setuptools>=42", "websockets>=15"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project] [project]

View File

@@ -1,155 +0,0 @@
from g2o.functions.event import addEvent
from g2o.functions.event import callEvent
from g2o.functions.event import event
from g2o.functions.event import removeEventHandler
from g2o.functions.event import toggleEvent
from g2o.functions.event import removeEvent
from g2o.classes.packets import Packet
from g2o.classes.damage import DamageDescription
from g2o.classes.items import ItemGround
from g2o.classes.items import ItemsGround
from g2o.classes.daedalus import Daedalus
from g2o.classes.sky import Sky
from g2o.classes.mds import Mds
from g2o.classes.way import Way
from g2o.functions.chat import sendMessageToAll
from g2o.functions.chat import sendMessageToPlayer
from g2o.functions.chat import sendPlayerMessageToAll
from g2o.functions.chat import sendPlayerMessageToPlayer
from g2o.functions.math import getDistance2d
from g2o.functions.math import getDistance3d
from g2o.functions.math import getVectorAngle
from g2o.functions.game import getHostname
from g2o.functions.game import getMaxSlots
from g2o.functions.game import getPlayersCount
from g2o.functions.game import exit
from g2o.functions.game import getDayLength
from g2o.functions.game import getServerDescription
from g2o.functions.game import getServerWorld
from g2o.functions.game import getTime
from g2o.functions.game import serverLog
from g2o.functions.game import setDayLength
from g2o.functions.game import setServerDescription
from g2o.functions.game import setServerWorld
from g2o.functions.game import setTime
from g2o.functions.npc import clearNpcActions
from g2o.functions.npc import createNpc
from g2o.functions.npc import destroyNpc
from g2o.functions.npc import getNpcAction
from g2o.functions.npc import getNpcActions
from g2o.functions.npc import getNpcActionsCount
from g2o.functions.npc import getNpcHostPlayer
from g2o.functions.npc import getNpcLastActionId
from g2o.functions.npc import isNpc
from g2o.functions.npc import isNpcActionFinished
from g2o.functions.npc import npcAttackMelee
from g2o.functions.npc import npcAttackRanged
from g2o.functions.npc import npcSpellCast
from g2o.functions.npc import npcUseClosestMob
from g2o.functions.npc import setNpcHostPlayer
from g2o.functions.player import addBan
from g2o.functions.player import applyPlayerOverlay
from g2o.functions.player import ban
from g2o.functions.player import drawWeapon
from g2o.functions.player import equipItem
from g2o.functions.player import getPlayerAmulet
from g2o.functions.player import getPlayerAngle
from g2o.functions.player import getPlayerAni
from g2o.functions.player import getPlayerArmor
from g2o.functions.player import getPlayerAtVector
from g2o.functions.player import getPlayerBelt
from g2o.functions.player import getPlayerCameraPosition
from g2o.functions.player import getPlayerCollision
from g2o.functions.player import getPlayerColor
from g2o.functions.player import getPlayerContext
from g2o.functions.player import getPlayerDexterity
from g2o.functions.player import getPlayerFaceAnis
from g2o.functions.player import getPlayerFatness
from g2o.functions.player import getPlayerFocus
from g2o.functions.player import getPlayerHealth
from g2o.functions.player import getPlayerHelmet
from g2o.functions.player import getPlayerIP
from g2o.functions.player import getPlayerInstance
from g2o.functions.player import getPlayerInvisible
from g2o.functions.player import getPlayerMacAddr
from g2o.functions.player import getPlayerMana
from g2o.functions.player import getPlayerMaxHealth
from g2o.functions.player import getPlayerMaxMana
from g2o.functions.player import getPlayerMeleeWeapon
from g2o.functions.player import getPlayerName
from g2o.functions.player import getPlayerPing
from g2o.functions.player import getPlayerPosition
from g2o.functions.player import getPlayerRangedWeapon
from g2o.functions.player import getPlayerRespawnTime
from g2o.functions.player import getPlayerRing
from g2o.functions.player import getPlayerScale
from g2o.functions.player import getPlayerSerial
from g2o.functions.player import getPlayerShield
from g2o.functions.player import getPlayerSkillWeapon
from g2o.functions.player import getPlayerSpell
from g2o.functions.player import getPlayerStrength
from g2o.functions.player import getPlayerTalent
from g2o.functions.player import getPlayerVirtualWorld
from g2o.functions.player import getPlayerVisual
from g2o.functions.player import getPlayerWeaponMode
from g2o.functions.player import getPlayerWorld
from g2o.functions.player import giveItem
from g2o.functions.player import hitPlayer
from g2o.functions.player import isPlayerConnected
from g2o.functions.player import isPlayerDead
from g2o.functions.player import isPlayerSpawned
from g2o.functions.player import isPlayerUnconscious
from g2o.functions.player import kick
from g2o.functions.player import playAni
from g2o.functions.player import playFaceAni
from g2o.functions.player import readySpell
from g2o.functions.player import removeItem
from g2o.functions.player import removePlayerOverlay
from g2o.functions.player import removeWeapon
from g2o.functions.player import setPlayerAngle
from g2o.functions.player import setPlayerCollision
from g2o.functions.player import setPlayerColor
from g2o.functions.player import setPlayerContext
from g2o.functions.player import setPlayerDexterity
from g2o.functions.player import setPlayerFatness
from g2o.functions.player import setPlayerHealth
from g2o.functions.player import setPlayerInstance
from g2o.functions.player import setPlayerInvisible
from g2o.functions.player import setPlayerMana
from g2o.functions.player import setPlayerMaxHealth
from g2o.functions.player import setPlayerMaxMana
from g2o.functions.player import setPlayerName
from g2o.functions.player import setPlayerPosition
from g2o.functions.player import setPlayerRespawnTime
from g2o.functions.player import setPlayerScale
from g2o.functions.player import setPlayerSkillWeapon
from g2o.functions.player import setPlayerStrength
from g2o.functions.player import setPlayerTalent
from g2o.functions.player import setPlayerVirtualWorld
from g2o.functions.player import setPlayerVisual
from g2o.functions.player import setPlayerWeaponMode
from g2o.functions.player import setPlayerWorld
from g2o.functions.player import spawnPlayer
from g2o.functions.player import stopAni
from g2o.functions.player import stopFaceAni
from g2o.functions.player import unequipItem
from g2o.functions.player import unreadySpell
from g2o.functions.player import unspawnPlayer
from g2o.functions.player import useItem
from g2o.functions.player import useItemToState
from g2o.functions.streamer import findNearbyPlayers
from g2o.functions.streamer import getStreamedPlayersByPlayer
from g2o.functions.streamer import getSpawnedPlayersForPlayer
from g2o.functions.waypoint import getNearestWaypoint
from g2o.functions.waypoint import getWaypoint
from g2o.constants import *

View File

@@ -1,196 +0,0 @@
import sqg2o
class Packet(sqg2o.Packet):
"""
This class represents data packet that gets send over the network.
Original: [Packet](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/network/Packet/)
## `int` bitsUsed *(read-only)*
Represents the total number of bits used by the script packet data.
## `int` bytesUsed *(read-only)*
Represents the total number of bytes used by the script packet data.
"""
def __init__(self):
return super().__init__()
def reset(self):
"""
This method will clear the packet data, making it empty.
"""
return super().reset()
def send(self, playerid : int, reliability : int):
"""
This method will send the packet data to the specified player.
**Parameters:**
* `int` **playerid**: the id of the player to whom you want to send the packet.
* `int` **reliability**: the reliability type, for more information see [Reliability](../../constants/reliability.md).
"""
return super().send(playerid, reliability)
def sendToAll(self, reliability : int):
"""
This method will send the packet data to the specified player.
**Parameters:**
* `int` **reliability**: the reliability type, for more information see [Reliability](../../constants/reliability.md).
"""
return super().send(playerid, reliability)
def writeInt8(self, value : int):
"""
This method will append signed int8 value to the packet. (1 byte)
**Parameters:**
* `int` **value**: the number value in range -128 to 127.
"""
return super().writeInt8(value)
def writeUInt8(self, value : int):
"""
This method will append unsigned int8 value to the packet. (1 byte)
**Parameters:**
* `int` **value**: the number value in range 0 to 255.
"""
return super().writeInt8(value)
def writeInt16(self, value : int):
"""
This method will append signed int16 value to the packet. (2 bytes)
**Parameters:**
* `int` **value**: the number value in range -32768 to 32767.
"""
return super().writeInt16(value)
def writeUInt16(self, value : int):
"""
This method will append unsigned int16 value to the packet. (2 bytes)
**Parameters:**
* `int` **value**: the number value in range 0 to 65535.
"""
return super().writeInt16(value)
def writeInt32(self, value : int):
"""
This method will append signed int32 value to the packet. (4 bytes)
**Parameters:**
* `int` **value**: the number value in range -2147483648 to 2147483647.
"""
return super().writeInt32(value)
def writeUInt32(self, value : int):
"""
!!! note
By default squirrel uses int32 values, which means that this method behaves exactly the same as [writeInt32](Packet.md#g2o.classes.packets.Packet.writeInt32) in scripts.
This method will append unsigned int32 value to the packet. (4 bytes)
**Parameters:**
* `int` **value**: the number value in range 0 to 4294967295.
"""
return super().writeInt32(value)
def writeBool(self, value : bool):
"""
This method will append boolean value to the packet. (1 bit)
**Parameters:**
* `bool` **value**: the boolean value.
"""
return super().writeBool(value)
def writeFloat(self, value : float):
"""
This method will append float value to the packet. (4 bytes)
**Parameters:**
* `float` **value**: the number value.
"""
return super().writeFloat(value)
def writeString(self, value : str):
"""
!!! note
The amount of bytes appended to the packet depends on the length of string, 1 byte = 1 char.
This method will append string value to the packet.
**Parameters:**
* `str` **value**: the text value.
"""
return super().writeString(value)
def readInt8(self,) -> int:
"""
This method will get signed int8 value from the packet. (1 byte)
**Returns `int`:**
the number value in range -128 to 127.
"""
return super().readInt8()
def readUInt8(self,) -> int:
"""
This method will get unsigned int8 value from the packet. (1 byte)
**Returns `int`:**
the number value in range 0 to 255.
"""
return super().readInt8()
def readInt16(self) -> int:
"""
This method will get signed int16 value from the packet. (2 bytes)
**Returns `int`:**
the number value in range -32768 to 32767.
"""
return super().readInt16()
def readUInt16(self) -> int:
"""
This method will get unsigned int16 value from the packet. (2 bytes)
**Returns `int`:**
the number value in range 0 to 65535.
"""
return super().readInt16()
def readInt32(self) -> int:
"""
This method will get signed int32 value from the packet. (4 bytes)
**Returns `int`:**
the number value in range -2147483648 to 2147483647.
"""
return super().readInt32()
def readUInt32(self) -> int:
"""
This method will get unsigned int32 value from the packet. (4 bytes)
**Returns `int`:**
the number value in range 0 to 4294967295.
"""
return super().readInt32()
def readBool(self) -> bool:
"""
This method will get signed int8 value from the packet. (1 byte)
**Returns `bool`:**
the boolean value.
"""
return super().readBool()
def readFloat(self) -> float:
"""
This method will get float value from the packet. (4 bytes)
**Returns `float`:**
the number value.
"""
return super().readFloat()
def readString(self) -> str:
"""
!!! note
The amount of bytes appended to the packet depends on the length of string, 1 byte = 1 char.
This method will get string value from the packet.
**Returns `str`:**
the text value.
"""
return super().readString()
@property
def bitsUsed(self):
return super().bitsUsed
@property
def bytesUsed(self):
return super().bytesUsed

View File

@@ -1,106 +0,0 @@
import sqg2o
class SkyMeta(type):
@property
def weather(self):
return sqg2o.Sky.weather
@weather.setter
def weather(self, value):
sqg2o.Sky.weather
@property
def raining(self):
return sqg2o.Sky.raining
@raining.setter
def raining(self, value):
sqg2o.Sky.raining = value
@property
def renderLightning(self):
return sqg2o.Sky.renderLightning
@renderLightning.setter
def renderLightning(self, value):
sqg2o.Sky.renderLightning = value
@property
def windScale(self):
return sqg2o.Sky.windScale
@windScale.setter
def windScale(self, value):
sqg2o.Sky.windScale = value
@property
def dontRain(self):
return sqg2o.Sky.dontRain
@dontRain.setter
def dontRain(self, value):
sqg2o.Sky.dontRain = value
class Sky(metaclass=SkyMeta):
"""
This class represents data packet that gets send over the network.
Original: [Sky](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Sky/)
## `int` weather
Represents the sky weather. For more information see [Weather Constants](../../constants/weather.md)
## `bool` raining
Represents the raining/snowing state.
## `bool` renderLightning
Represents the lightning feature during raining state.
Lightning will only be rendered during raining and when weatherWeight is larger than 0.5
## `float` windScale
Represents the sky wind scale used during raining/snowing.
## `bool` dontRain
Represents the sky dontRain feature.
When it's enabled, the rain/snow won't fall.
"""
@staticmethod
def setRainStartTime(hour : int, minute : int):
"""
This method will set the sky weather time when it starts raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
sqg2o.Sky.setRainStartTime(hour, minute)
@staticmethod
def setRainStopTime(hour : int, minute : int):
"""
This method will set the sky weather time when it stops raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
sqg2o.Sky.setRainStopTime(hour, minute)
@staticmethod
def getRainStartTime() -> dict:
"""
This method will get the sky weather time when it starts raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
return sqg2o.Sky.getRainStartTime()
@staticmethod
def getRainStopTime() -> dict:
"""
This method will get the sky weather time when it stops raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
return sqg2o.Sky.getRainStopTime()

View File

@@ -1,48 +0,0 @@
import sqg2o
class Way(sqg2o.Way):
"""
This class represents Way constructed from waypoints.
Original: [Way](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/waypoint/Way/)
## `str` start *(read-only)*
Represents the start waypoint for Way.
## `str` end *(read-only)*
Represents the end waypoint for Way.
"""
def __init__(self, world : str, startWp : str, endWp : str):
"""
## Parameters
`str` **world**: the name of the world from config.xml.
`str` **startWp**: the name of the start waypoint.
`str` **endWp**: the name of the end waypoint.
"""
return super().__init__(world, startWp, endWp)
def getWaypoints(self) -> list:
"""
This method will get the all waypoints between startWp & endWp.
## Returns
`list [str]`: the list containing the names of all of the Way waypoints.
"""
return super().getWaypoints()
def getCountWaypoints(self):
"""
This method will get the number of waypoints between start waypoint & end waypoint.
## Returns
`int`: the number of waypoints.
"""
return super().getCountWaypoints()
@property
def start(self):
return super().start
@property
def end(self):
return super().end

View File

@@ -1,13 +0,0 @@
from .anticheat import *
from .context import *
from .damage import *
from .general import *
from .hand import *
from .item import *
from .network import *
from .npc import *
from .reliability import *
from .skillweapon import *
from .talent import *
from .weaponmode import *
from .weather import *

View File

@@ -1,3 +0,0 @@
import sqg2oconst
AC_SPEED_HACK = sqg2oconst.AC_SPEED_HACK

View File

@@ -1,4 +0,0 @@
import sqg2oconst
DAMAGE_CTX = sqg2oconst.DAMAGE_CTX
EQUIPMENT_CTX = sqg2oconst.EQUIPMENT_CTX

View File

@@ -1,11 +0,0 @@
import sqg2oconst
DAMAGE_UNKNOWN = sqg2oconst.DAMAGE_UNKNOWN
DAMAGE_BARRIER = sqg2oconst.DAMAGE_BARRIER
DAMAGE_BLUNT = sqg2oconst.DAMAGE_BLUNT
DAMAGE_EDGE = sqg2oconst.DAMAGE_EDGE
DAMAGE_FIRE = sqg2oconst.DAMAGE_FIRE
DAMAGE_FLY = sqg2oconst.DAMAGE_FLY
DAMAGE_MAGIC = sqg2oconst.DAMAGE_MAGIC
DAMAGE_POINT = sqg2oconst.DAMAGE_POINT
DAMAGE_FALL = sqg2oconst.DAMAGE_FALL

View File

@@ -1,5 +0,0 @@
import sqg2oconst
DEBUG_MODE = sqg2oconst.DEBUG_MODE
CLIENT_SIDE = sqg2oconst.CLIENT_SIDE
SERVER_SIDE = sqg2oconst.SERVER_SIDE

View File

@@ -1,4 +0,0 @@
import sqg2oconst
HAND_LEFT = sqg2oconst.HAND_LEFT
HAND_RIGHT = sqg2oconst.HAND_RIGHT

View File

@@ -1,38 +0,0 @@
import sqg2oconst
ITEM_CAT_NONE = sqg2oconst.ITEM_CAT_NONE
ITEM_CAT_NF = sqg2oconst.ITEM_CAT_NF
ITEM_CAT_FF = sqg2oconst.ITEM_CAT_FF
ITEM_CAT_MUN = sqg2oconst.ITEM_CAT_MUN
ITEM_CAT_ARMOR = sqg2oconst.ITEM_CAT_ARMOR
ITEM_CAT_FOOD = sqg2oconst.ITEM_CAT_FOOD
ITEM_CAT_DOCS = sqg2oconst.ITEM_CAT_DOCS
ITEM_CAT_POTION = sqg2oconst.ITEM_CAT_POTION
ITEM_CAT_LIGHT = sqg2oconst.ITEM_CAT_LIGHT
ITEM_CAT_RUNE = sqg2oconst.ITEM_CAT_RUNE
ITEM_CAT_MAGIC = sqg2oconst.ITEM_CAT_MAGIC
ITEM_FLAG_DAG = sqg2oconst.ITEM_FLAG_DAG
ITEM_FLAG_SWD = sqg2oconst.ITEM_FLAG_SWD
ITEM_FLAG_AXE = sqg2oconst.ITEM_FLAG_AXE
ITEM_FLAG_2HD_SWD = sqg2oconst.ITEM_FLAG_2HD_SWD
ITEM_FLAG_2HD_AXE = sqg2oconst.ITEM_FLAG_2HD_AXE
ITEM_FLAG_SHIELD = sqg2oconst.ITEM_FLAG_SHIELD
ITEM_FLAG_BOW = sqg2oconst.ITEM_FLAG_BOW
ITEM_FLAG_CROSSBOW = sqg2oconst.ITEM_FLAG_CROSSBOW
ITEM_FLAG_RING = sqg2oconst.ITEM_FLAG_RING
ITEM_FLAG_AMULET = sqg2oconst.ITEM_FLAG_AMULET
ITEM_FLAG_BELT = sqg2oconst.ITEM_FLAG_BELT
ITEM_FLAG_DROPPED = sqg2oconst.ITEM_FLAG_DROPPED
ITEM_FLAG_MI = sqg2oconst.ITEM_FLAG_MI
ITEM_FLAG_MULTI = sqg2oconst.ITEM_FLAG_MULTI
ITEM_FLAG_NFOCUS = sqg2oconst.ITEM_FLAG_NFOCUS
ITEM_FLAG_CREATEAMMO = sqg2oconst.ITEM_FLAG_CREATEAMMO
ITEM_FLAG_NSPLIT = sqg2oconst.ITEM_FLAG_NSPLIT
ITEM_FLAG_DRINK = sqg2oconst.ITEM_FLAG_DRINK
ITEM_FLAG_TORCH = sqg2oconst.ITEM_FLAG_TORCH
ITEM_FLAG_THROW = sqg2oconst.ITEM_FLAG_THROW
ITEM_FLAG_ACTIVE = sqg2oconst.ITEM_FLAG_ACTIVE
ITEM_WEAR_NO = sqg2oconst.ITEM_WEAR_NO
ITEM_WEAR_TORSO = sqg2oconst.ITEM_WEAR_TORSO
ITEM_WEAR_HEAD = sqg2oconst.ITEM_WEAR_HEAD
ITEM_WEAR_LIGHT = sqg2oconst.ITEM_WEAR_LIGHT

View File

@@ -1,5 +0,0 @@
import sqg2oconst
DISCONNECTED = sqg2oconst.DISCONNECTED
LOST_CONNECTION = sqg2oconst.LOST_CONNECTION
HAS_CRASHED = sqg2oconst.HAS_CRASHED

View File

@@ -1,28 +0,0 @@
import sqg2oconst
ATTACK_RUN = sqg2oconst.ATTACK_RUN
ATTACK_FORWARD = sqg2oconst.ATTACK_FORWARD
ATTACK_LEFT = sqg2oconst.ATTACK_LEFT
ATTACK_RIGHT = sqg2oconst.ATTACK_RIGHT
ACTION_CLEAR_QUEUE = sqg2oconst.ACTION_CLEAR_QUEUE
ACTION_APPLY_OVERLAY = sqg2oconst.ACTION_APPLY_OVERLAY
ACTION_REMOVE_OVERLAY = sqg2oconst.ACTION_REMOVE_OVERLAY
ACTION_PLAY_ANI = sqg2oconst.ACTION_PLAY_ANI
ACTION_STOP_ANI = sqg2oconst.ACTION_STOP_ANI
ACTION_EQUIP_ITEM = sqg2oconst.ACTION_EQUIP_ITEM
ACTION_UNEQUIP_ITEM = sqg2oconst.ACTION_UNEQUIP_ITEM
ACTION_WEAPON_MODE = sqg2oconst.ACTION_WEAPON_MODE
ACTION_DRAW_WEAPON = sqg2oconst.ACTION_DRAW_WEAPON
ACTION_REMOVE_WEAPON = sqg2oconst.ACTION_REMOVE_WEAPON
ACTION_USE_ITEM = sqg2oconst.ACTION_USE_ITEM
ACTION_USE_ITEM_TO_STATE = sqg2oconst.ACTION_USE_ITEM_TO_STATE
ACTION_READY_SPELL = sqg2oconst.ACTION_READY_SPELL
ACTION_UNREADY_SPELL = sqg2oconst.ACTION_UNREADY_SPELL
ACTION_ATTACK_MELEE_WEAPON = sqg2oconst.ACTION_ATTACK_MELEE_WEAPON
ACTION_ATTACK_RANGED_WEAPON = sqg2oconst.ACTION_ATTACK_RANGED_WEAPON
ACTION_SPELL_CAST = sqg2oconst.ACTION_SPELL_CAST
ACTION_USE_MOB_SCHEME = sqg2oconst.ACTION_USE_MOB_SCHEME
ACTION_SHOOT_AT = sqg2oconst.ACTION_SHOOT_AT
ACTION_START_AIM_AT = sqg2oconst.ACTION_START_AIM_AT
ACTION_STOP_AIM_AT = sqg2oconst.ACTION_STOP_AIM_AT
ACTION_SCRIPT = sqg2oconst.ACTION_SCRIPT

View File

@@ -1,7 +0,0 @@
import sqg2oconst
UNRELIABLE = sqg2oconst.UNRELIABLE
UNRELIABLE_SEQUENCED = sqg2oconst.UNRELIABLE_SEQUENCED
RELIABLE = sqg2oconst.RELIABLE
RELIABLE_ORDERED = sqg2oconst.RELIABLE_ORDERED
RELIABLE_SEQUENCED = sqg2oconst.RELIABLE_SEQUENCED

View File

@@ -1,6 +0,0 @@
import sqg2oconst
WEAPON_1H = sqg2oconst.WEAPON_1H
WEAPON_2H = sqg2oconst.WEAPON_2H
WEAPON_BOW = sqg2oconst.WEAPON_BOW
WEAPON_CBOW = sqg2oconst.WEAPON_CBOW

View File

@@ -1,24 +0,0 @@
import sqg2oconst
TALENT_1H = sqg2oconst.TALENT_1H
TALENT_2H = sqg2oconst.TALENT_2H
TALENT_BOW = sqg2oconst.TALENT_BOW
TALENT_CROSSBOW = sqg2oconst.TALENT_CROSSBOW
TALENT_PICK_LOCKS = sqg2oconst.TALENT_PICK_LOCKS
TALENT_PICKPOCKET = sqg2oconst.TALENT_PICKPOCKET
TALENT_MAGE = sqg2oconst.TALENT_MAGE
TALENT_SNEAK = sqg2oconst.TALENT_SNEAK
TALENT_REGENERATE = sqg2oconst.TALENT_REGENERATE
TALENT_FIREMASTER = sqg2oconst.TALENT_FIREMASTER
TALENT_ACROBATIC = sqg2oconst.TALENT_ACROBATIC
TALENT_PICKPOCKET_UNUSED = sqg2oconst.TALENT_PICKPOCKET_UNUSED
TALENT_SMITH = sqg2oconst.TALENT_SMITH
TALENT_RUNES = sqg2oconst.TALENT_RUNES
TALENT_ALCHEMY = sqg2oconst.TALENT_ALCHEMY
TALENT_THROPHY = sqg2oconst.TALENT_THROPHY
TALENT_A = sqg2oconst.TALENT_A
TALENT_B = sqg2oconst.TALENT_B
TALENT_C = sqg2oconst.TALENT_C
TALENT_D = sqg2oconst.TALENT_D
TALENT_E = sqg2oconst.TALENT_E
TALENT_MAX = sqg2oconst.TALENT_MAX

View File

@@ -1,11 +0,0 @@
import sqg2oconst
WEAPONMODE_NONE = sqg2oconst.WEAPONMODE_NONE
WEAPONMODE_FIST = sqg2oconst.WEAPONMODE_FIST
WEAPONMODE_DAG = sqg2oconst.WEAPONMODE_DAG
WEAPONMODE_1HS = sqg2oconst.WEAPONMODE_1HS
WEAPONMODE_2HS = sqg2oconst.WEAPONMODE_2HS
WEAPONMODE_BOW = sqg2oconst.WEAPONMODE_BOW
WEAPONMODE_CBOW = sqg2oconst.WEAPONMODE_CBOW
WEAPONMODE_MAG = sqg2oconst.WEAPONMODE_MAG
WEAPONMODE_MAX = sqg2oconst.WEAPONMODE_MAX

View File

@@ -1,4 +0,0 @@
import sqg2oconst
WEATHER_SNOW = sqg2oconst.WEATHER_SNOW
WEATHER_RAIN = sqg2oconst.WEATHER_RAIN

View File

@@ -1,248 +0,0 @@
eventList = {}
disabledEventList = []
def callEvent(evtName : str, **kwargs : dict):
"""
This function will notify (call) every handler bound to specified event.
Original: [callEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/callEvent/)
## Declaration
```python
def callEvent(evtName : str, **kwargs : dict)
```
## Parameters
* `str` **name**: the name of the event
* `**dict` **kwargs**: the variable number of arguments.
## Usage
```python
import g2o
g2o.addEvent('testEvt')
@g2o.event('testEvt')
def onTestEvent(**kwargs):
print(f'{kwargs['name']} called my beautiful test event')
g2o.callEvent('testEvt', name = 'Diego')
```
"""
isEventCancelled = False
if evtName in eventList and evtName not in disabledEventList:
for event in eventList[evtName]:
event['function'].eventName = evtName
event['function'].cancelled = isEventCancelled
result = event['function'](**kwargs)
if result != None:
isEventCancelled = not result
return isEventCancelled
def addEvent(name : str):
"""
This function will register a new event with specified name.
Events can be used to notify function(s) when something will happen, like player joins the server, etc.
Original: [addEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/addEvent/)
## Declaration
```python
def addEvent(name)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
g2o.addEvent('testEvt')
```
"""
if not name in eventList:
eventList[name] = []
def event(name : str, priority : int = 9999):
"""
This function will bind function to specified event.
Original: [addEventHandler](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/addEventHandler/)
## Declaration
```python
def event(name : str, priority : int = 9999)
```
## Parameters
* `str` **name**: the name of the event
* `int` **priority**: the function priority. The lower the value, the sooner the function/handler will be called.
## Usage
```python
import g2o
@g2o.event('onInit')
def onInitEventHandler(**kwargs):
print('Called onInit event')
```
"""
def inlineEvt(func):
if name not in eventList:
return None
eventList[name].append({'function': func, 'priority': priority})
eventList[name].sort(key = lambda x: x['priority'])
return func
return inlineEvt
def removeEventHandler(name : str, func : object):
"""
This function will unbind function from specified event.
Original: [removeEventHandler](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEventHandler/)
## Declaration
```python
def removeEventHandler(name : str, func : object)
```
## Parameters
* `str` **name**: the name of the event
* `object` **func**: the reference to a function which is currently bound to specified event.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEventHandler('onTime', onTimeEvt)
```
"""
if not name in eventList:
pass
for index, item in enumerate(eventList[name]):
if item['function'] == func:
del eventList[name][index]
def toggleEvent(name : str, toggle : bool):
'''
!!! note
By default every event is toggled `on` (enabled).
This function will toggle event (enable or disable it globally). By toggling event off, you can completely disable certain event from calling it's handlers.
Original: [toggleEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/toggleEvent/)
## Declaration
```python
def toggleEvent(name : str, toggle : bool)
```
## Parameters
* `str` **name**: the name of the event
* `bool` **toggle**: `false` if you want to disable the event, otherwise true.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.toggleEvent('onTime', false)
```
'''
if not toggle and name not in disabledEventList:
disabledEventList.append(name)
elif toggle and name in disabledEventList:
disabledEventList.remove(name)
def removeEvent(name : str):
'''
!!! warning
Removing an event also cause all event handlers to unregister.
This function will unregister an event with specified name.
Original: [removeEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEvent/)
## Declaration
```python
def removeEvent(name : str)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEvent('onTime')
```
'''
if name in eventList:
eventList.pop(name)
## registering default events
addEvent('onInit')
addEvent('onExit')
addEvent('onTick')
addEvent('onTime')
addEvent('onBan')
addEvent('onUnban')
addEvent('onPlayerChangeColor')
addEvent('onPlayerChangeFocus')
addEvent('onPlayerChangeHealth')
addEvent('onPlayerChangeMana')
addEvent('onPlayerChangeMaxHealth')
addEvent('onPlayerChangeMaxMana')
addEvent('onPlayerChangeWeaponMode')
addEvent('onPlayerChangeWorld')
addEvent('onPlayerCommand')
addEvent('onPlayerDamage')
addEvent('onPlayerDead')
addEvent('onPlayerDisconnect')
addEvent('onPlayerDropItem')
addEvent('onPlayerEnterWorld')
addEvent('onPlayerJoin')
addEvent('onPlayerMessage')
addEvent('onPlayerMobInteract')
addEvent('onPlayerRespawn')
addEvent('onPlayerShoot')
addEvent('onPlayerSpellCast')
addEvent('onPlayerSpellSetup')
addEvent('onPlayerTakeItem')
addEvent('onPlayerTeleport')
addEvent('onPlayerToggleFaceAni')
addEvent('onPlayerEquipAmulet')
addEvent('onPlayerEquipArmor')
addEvent('onPlayerEquipBelt')
addEvent('onPlayerEquipHandItem')
addEvent('onPlayerEquipHelmet')
addEvent('onPlayerEquipMeleeWeapon')
addEvent('onPlayerEquipRangedWeapon')
addEvent('onPlayerEquipRing')
addEvent('onPlayerEquipShield')
addEvent('onPlayerEquipSpell')
addEvent('onPacket')
addEvent('onPlayerUseCheat')
addEvent('onNpcActionFinished')
addEvent('onNpcActionSent')
addEvent('onNpcChangeHostPlayer')
addEvent('onNpcCreated')
addEvent('onNpcDestroyed')

View File

@@ -1 +1,159 @@
print('Hello') __version__ = '2.0.0'
from .server import PythonWebsocketServer
from .functions.chat import sendMessageToAll
from .functions.chat import sendMessageToPlayer
from .functions.chat import sendPlayerMessageToAll
from .functions.chat import sendPlayerMessageToPlayer
from .functions.math import getDistance2d
from .functions.math import getDistance3d
from .functions.math import getVectorAngle
from .functions.game import getHostname
from .functions.game import getMaxSlots
from .functions.game import getPlayersCount
from .functions.game import exit
from .functions.game import getDayLength
from .functions.game import getServerDescription
from .functions.game import getServerWorld
from .functions.game import getTime
from .functions.game import serverLog
from .functions.game import setDayLength
from .functions.game import setServerDescription
from .functions.game import setServerWorld
from .functions.game import setTime
from .functions.npc import clearNpcActions
from .functions.npc import createNpc
from .functions.npc import destroyNpc
from .functions.npc import getNpcAction
from .functions.npc import getNpcActions
from .functions.npc import getNpcActionsCount
from .functions.npc import getNpcHostPlayer
from .functions.npc import getNpcLastActionId
from .functions.npc import isNpc
from .functions.npc import isNpcActionFinished
from .functions.npc import npcAttackMelee
from .functions.npc import npcAttackRanged
from .functions.npc import npcSpellCast
from .functions.npc import npcUseClosestMob
from .functions.npc import setNpcHostPlayer
from .functions.player import addBan
from .functions.player import applyPlayerOverlay
from .functions.player import ban
from .functions.player import drawWeapon
from .functions.player import equipItem
from .functions.player import getPlayerAmulet
from .functions.player import getPlayerAngle
from .functions.player import getPlayerAni
from .functions.player import getPlayerArmor
from .functions.player import getPlayerAtVector
from .functions.player import getPlayerBelt
from .functions.player import getPlayerCameraPosition
from .functions.player import getPlayerCollision
from .functions.player import getPlayerColor
from .functions.player import getPlayerContext
from .functions.player import getPlayerDexterity
from .functions.player import getPlayerFaceAnis
from .functions.player import getPlayerFatness
from .functions.player import getPlayerFocus
from .functions.player import getPlayerHealth
from .functions.player import getPlayerHelmet
from .functions.player import getPlayerIP
from .functions.player import getPlayerInstance
from .functions.player import getPlayerInvisible
from .functions.player import getPlayerMacAddr
from .functions.player import getPlayerMana
from .functions.player import getPlayerMaxHealth
from .functions.player import getPlayerMaxMana
from .functions.player import getPlayerMeleeWeapon
from .functions.player import getPlayerName
from .functions.player import getPlayerPing
from .functions.player import getPlayerPosition
from .functions.player import getPlayerRangedWeapon
from .functions.player import getPlayerRespawnTime
from .functions.player import getPlayerRing
from .functions.player import getPlayerScale
from .functions.player import getPlayerSerial
from .functions.player import getPlayerShield
from .functions.player import getPlayerSkillWeapon
from .functions.player import getPlayerSpell
from .functions.player import getPlayerStrength
from .functions.player import getPlayerTalent
from .functions.player import getPlayerVirtualWorld
from .functions.player import getPlayerVisual
from .functions.player import getPlayerWeaponMode
from .functions.player import getPlayerWorld
from .functions.player import giveItem
from .functions.player import hitPlayer
from .functions.player import isPlayerConnected
from .functions.player import isPlayerDead
from .functions.player import isPlayerSpawned
from .functions.player import isPlayerUnconscious
from .functions.player import kick
from .functions.player import playAni
from .functions.player import playFaceAni
from .functions.player import readySpell
from .functions.player import removeItem
from .functions.player import removePlayerOverlay
from .functions.player import removeWeapon
from .functions.player import setPlayerAngle
from .functions.player import setPlayerCollision
from .functions.player import setPlayerColor
from .functions.player import setPlayerContext
from .functions.player import setPlayerDexterity
from .functions.player import setPlayerFatness
from .functions.player import setPlayerHealth
from .functions.player import setPlayerInstance
from .functions.player import setPlayerInvisible
from .functions.player import setPlayerMana
from .functions.player import setPlayerMaxHealth
from .functions.player import setPlayerMaxMana
from .functions.player import setPlayerName
from .functions.player import setPlayerPosition
from .functions.player import setPlayerRespawnTime
from .functions.player import setPlayerScale
from .functions.player import setPlayerSkillWeapon
from .functions.player import setPlayerStrength
from .functions.player import setPlayerTalent
from .functions.player import setPlayerVirtualWorld
from .functions.player import setPlayerVisual
from .functions.player import setPlayerWeaponMode
from .functions.player import setPlayerWorld
from .functions.player import spawnPlayer
from .functions.player import stopAni
from .functions.player import stopFaceAni
from .functions.player import unequipItem
from .functions.player import unreadySpell
from .functions.player import unspawnPlayer
from .functions.player import useItem
from .functions.player import useItemToState
from .functions.streamer import findNearbyPlayers
from .functions.streamer import getStreamedPlayersByPlayer
from .functions.streamer import getSpawnedPlayersForPlayer
from .functions.waypoint import getNearestWaypoint
from .functions.waypoint import getWaypoint
from .functions.event import addEvent
from .functions.event import callEvent
from .functions.event import event
from .functions.event import removeEventHandler
from .functions.event import toggleEvent
from .functions.event import removeEvent
from .constants import Constant
from .classes.daedalus import Daedalus
from .classes.damage import DamageDescription
from .classes.items import ItemGround
from .classes.items import ItemsGround
from .classes.mds import Mds
from .classes.sky import Sky
# from exception import set_default_logger
# from exception import handle_exception

14
src/pyg2o/call_repr.py Normal file
View File

@@ -0,0 +1,14 @@
import inspect
def get_call_repr():
frame = inspect.currentframe().f_back
func_name = frame.f_code.co_name
args_info = inspect.getargvalues(frame)
# Формируем аргументы в виде строки
args_str = []
for arg in args_info.args:
val = args_info.locals[arg]
args_str.append(f"{val!r}" if not isinstance(val, str) else f"'{val}'")
return f"{func_name}({', '.join(args_str)})"

View File

@@ -1,4 +1,4 @@
import sqg2o from ..server import PythonWebsocketServer
class Daedalus: class Daedalus:
""" """
@@ -6,7 +6,7 @@ class Daedalus:
Original: [Daedalus](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Daedalus/) Original: [Daedalus](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Daedalus/)
""" """
@staticmethod @staticmethod
def index(value : str) -> int: async def index(value : str) -> int:
""" """
This method will get the daedalus symbol index by its name. This method will get the daedalus symbol index by its name.
**Parameters:** **Parameters:**
@@ -15,10 +15,14 @@ class Daedalus:
**Returns `int`:** **Returns `int`:**
the daedalus symbol index number. the daedalus symbol index number.
""" """
return sqg2o.Daedalus.index(value) data = f'return Daedalus.index({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod @staticmethod
def symbol(value : str) -> dict: async def symbol(value : str) -> dict:
""" """
This method will get the daedalus symbol by its name. This method will get the daedalus symbol by its name.
**Parameters:** **Parameters:**
@@ -27,10 +31,14 @@ class Daedalus:
**Returns `dict`:** **Returns `dict`:**
the daedalus symbol (empty if there's no symbol with given name) the daedalus symbol (empty if there's no symbol with given name)
""" """
return sqg2o.Daedalus.symbol(value) data = f'return Daedalus.symbol({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod @staticmethod
def instance(value : str) -> dict: async def instance(value : str) -> dict:
""" """
This method will get the all of the daedalus instance variables. This method will get the all of the daedalus instance variables.
**Parameters:** **Parameters:**
@@ -39,4 +47,8 @@ class Daedalus:
**Returns `dict`:** **Returns `dict`:**
the object containing all of the daedalus instance variables. the object containing all of the daedalus instance variables.
""" """
return sqg2o.Daedalus.instance(value) data = f'return Daedalus.instance({value})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -1,6 +1,5 @@
import sqg2o
class DamageDescription(sqg2o.DamageDescription): class DamageDescription():
""" """
This class represents damage information. This class represents damage information.
Original: [DamageDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/DamageDescription//) Original: [DamageDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/DamageDescription//)
@@ -31,56 +30,65 @@ class DamageDescription(sqg2o.DamageDescription):
Represents the name of the node hit by a point projectile. Represents the name of the node hit by a point projectile.
""" """
def __init__(self): def __init__(self):
return super().__init__() self._flags : int = 0
self._damage : int = 0
self._item_instance : str = ''
self._distance : int = 0
self._spell_id : int = 0
self._spell_level : int = 0
self._node : str = 0
def _initialize(self, **kwargs):
self.__dict__.update(kwargs)
@property @property
def item_instance(self): def flags(self) -> int:
return super().item_instance return self._flags
@property
def flags(self):
return super().flags
@flags.setter @flags.setter
def flags(self, value): def flags(self, value):
super().flags = value self._flags = value
@property @property
def damage(self): def damage(self) -> int:
return super().damage return self._damage
@damage.setter @damage.setter
def damage(self, value): def damage(self, value):
super().damage = value self._damage = value
@property @property
def distance(self): def item_instance(self) -> str:
return super().distance return self._item_instance
@property
def distance(self) -> int:
return self._distance
@distance.setter @distance.setter
def distance(self, value): def distance(self, value):
super().distance = value self._distance = value
@property @property
def spell_id(self): def spell_id(self) -> int:
return super().spell_id return self._spell_id
@spell_id.setter @spell_id.setter
def spell_id(self, value): def spell_id(self, value):
super().spell_id = value self._spell_id = value
@property @property
def spell_level(self): def spell_level(self) -> int:
return super().spell_level return self._spell_level
@spell_level.setter @spell_level.setter
def spell_level(self, value): def spell_level(self, value):
super().spell_level = value self._spell_level = value
@property @property
def node(self): def node(self) -> str:
return super().node return self._node
@node.setter @node.setter
def node(self, value): def node(self, value):
super().node = value self._node = value

View File

@@ -1,4 +1,4 @@
import sqg2o from ..server import PythonWebsocketServer
class ItemsGround: class ItemsGround:
""" """
@@ -6,7 +6,7 @@ class ItemsGround:
Original: [ItemsGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemsGround/) Original: [ItemsGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemsGround/)
""" """
@staticmethod @staticmethod
def getById(id : int): async def getById(id : int):
""" """
This method will retrieve the item ground object by its unique id. This method will retrieve the item ground object by its unique id.
@@ -16,10 +16,15 @@ class ItemsGround:
**Returns `ItemGround`:** **Returns `ItemGround`:**
the item ground object or `throws an exception` if the object cannot be found. the item ground object or `throws an exception` if the object cannot be found.
""" """
return sqg2o.ItemsGround.getById(id) data = f'return ItemsGround.getById({id})'
# TODO: Добавить десериализацию ItemGround
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod @staticmethod
def create(data : dict) -> int: async def create(data : dict) -> int:
""" """
This method will create the item ground. This method will create the item ground.
@@ -35,18 +40,26 @@ class ItemsGround:
**Returns `int`:** **Returns `int`:**
the item ground id. the item ground id.
""" """
return sqg2o.ItemsGround.create(data) data = f'return ItemsGround.create({data})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod @staticmethod
def destroy(id : int): async def destroy(id : int):
""" """
This method will destroy the item ground by it's unique id. This method will destroy the item ground by it's unique id.
**Parameters:** **Parameters:**
* `int` **itemGroundId**: the item ground unique id. * `int` **itemGroundId**: the item ground unique id.
""" """
sqg2o.ItemsGround.destroy(id) data = f'return ItemsGround.destroy({id})'
class ItemGround(sqg2o.ItemGround): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
class ItemGround:
""" """
This class represents item on the ground. This class represents item on the ground.
Original: [ItemGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemGround//) Original: [ItemGround](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/item/ItemGround//)
@@ -67,44 +80,53 @@ class ItemGround(sqg2o.ItemGround):
Represents the virtual world of item ground. Represents the virtual world of item ground.
""" """
def __init__(self): def __init__(self):
return super().__init__() self._id = -1
self._instance = ''
self._amount = -1
self._world = -1
self._virtualWorld = -1
self._position = -1
self._rotation = -1
def getPosition() -> tuple: def getPosition(self) -> dict:
""" """
This method will get the item ground position on the world. This method will get the item ground position on the world.
**Returns `tuple(float, float, float)`:** **Returns `tuple(float, float, float)`:**
`X-Y-Z` item ground position on the world. `X-Y-Z` item ground position on the world.
""" """
return super().getPosition() return self._position
def getRotation() -> tuple: def getRotation(self) -> dict:
""" """
This method will get the item ground rotation on the world. This method will get the item ground rotation on the world.
**Returns `tuple(float, float, float)`:** **Returns `tuple(float, float, float)`:**
`X-Y-Z` item ground roration on the world. `X-Y-Z` item ground roration on the world.
""" """
return super().getRotation() return self._rotation
@property @property
def id(self): def id(self) -> int:
return super().id return self._id
@property @property
def instance(self): def instance(self) -> str:
return super().instance return self._instance
@property @property
def amount(self): def amount(self) -> int:
return super().amount return self._amount
@property @property
def world(self): def world(self) -> str:
return super().world return self._world
@property @property
def virtualWorld(self): def virtualWorld(self) -> int:
return super().virtualWorld return self._virtualWorld
@virtualWorld.setter @virtualWorld.setter
def virtualWorld(self, value): def virtualWorld(self, value):
super().virtualWorld = value self._virtualWorld = value
def _initialize(self, **kwargs):
self.__dict__.update(kwargs)

View File

@@ -1,4 +1,4 @@
import sqg2o from ..server import PythonWebsocketServer
class Mds: class Mds:
""" """
@@ -6,7 +6,7 @@ class Mds:
Original: [Mds](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-classes/mds/Mds/) Original: [Mds](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-classes/mds/Mds/)
""" """
@staticmethod @staticmethod
def id(mdsName : str) -> int: async def id(mdsName : str) -> int:
""" """
This method will convert the mds name to mds id. This method will convert the mds name to mds id.
**Parameters:** **Parameters:**
@@ -15,10 +15,14 @@ class Mds:
**Returns `int`:** **Returns `int`:**
the unique mds id. the unique mds id.
""" """
return sqg2o.Mds.id(mdsName) data = f'return Mds.id({mdsName})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod @staticmethod
def name(mdsId : int) -> str: async def name(mdsId : int) -> str:
""" """
This method will convert the mds id to mds name. This method will convert the mds id to mds name.
**Parameters:** **Parameters:**
@@ -27,4 +31,8 @@ class Mds:
**Returns `str`:** **Returns `str`:**
the mds name, e.g: `"HumanS_Sprint.mds"`. the mds name, e.g: `"HumanS_Sprint.mds"`.
""" """
return sqg2o.Mds.name(mdsId) data = f'return Mds.id({mdsId})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

161
src/pyg2o/classes/sky.py Normal file
View File

@@ -0,0 +1,161 @@
from ..server import PythonWebsocketServer
class Sky:
"""
This class represents data packet that gets send over the network.
Original: [Sky](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-classes/game/Sky/)
## `int` weather
Represents the sky weather. For more information see [Weather Constants](../../constants/weather.md)
## `bool` raining
Represents the raining/snowing state.
## `bool` renderLightning
Represents the lightning feature during raining state.
Lightning will only be rendered during raining and when weatherWeight is larger than 0.5
## `float` windScale
Represents the sky wind scale used during raining/snowing.
## `bool` dontRain
Represents the sky dontRain feature.
When it's enabled, the rain/snow won't fall.
"""
@staticmethod
async def get_weather():
data = 'return Sky.weather'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_weather(value):
data = 'return Sky.weather = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_raining():
data = 'return Sky.raining'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_raining(value):
data = 'return Sky.raining = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_renderLightning():
data = 'return Sky.renderLightning'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_renderLightning(value):
data = 'return Sky.renderLightning = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_windScale():
data = 'return Sky.windScale'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_windScale(value):
data = 'return Sky.windScale = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def get_dontRain():
data = 'return Sky.dontRain'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def set_dontRain(value):
data = 'return Sky.dontRain = value'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def setRainStartTime(hour : int, minute : int):
"""
This method will set the sky weather time when it starts raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
data = f'return Sky.setRainStartTime({hour}, {minute})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def setRainStopTime(hour : int, minute : int):
"""
This method will set the sky weather time when it stops raining/snowing.
**Parameters:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
data = f'return Sky.setRainStopTime({hour}, {minute})'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def getRainStartTime() -> dict:
"""
This method will get the sky weather time when it starts raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining start hour.
* `int` **minute**: the sky weather raining start min.
"""
data = 'return Sky.getRainStartTime()'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
@staticmethod
async def getRainStopTime() -> dict:
"""
This method will get the sky weather time when it stops raining/snowing.
**Returns `dict`:**
* `int` **hour**: the sky weather raining stop hour.
* `int` **minute**: the sky weather raining stop min.
"""
data = 'return Sky.getRainStopTime()'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,129 @@
import inspect
class Constant:
AC_SPEED_HACK = None
DAMAGE_CTX = None
EQUIPMENT_CTX = None
DAMAGE_UNKNOWN = None
DAMAGE_BARRIER = None
DAMAGE_BLUNT = None
DAMAGE_EDGE = None
DAMAGE_FIRE = None
DAMAGE_FLY = None
DAMAGE_MAGIC = None
DAMAGE_POINT = None
DAMAGE_FALL = None
DEBUG_MODE = None
CLIENT_SIDE = None
SERVER_SIDE = None
HAND_LEFT = None
HAND_RIGHT = None
ITEM_CAT_NONE = None
ITEM_CAT_NF = None
ITEM_CAT_FF = None
ITEM_CAT_MUN = None
ITEM_CAT_ARMOR = None
ITEM_CAT_FOOD = None
ITEM_CAT_DOCS = None
ITEM_CAT_POTION = None
ITEM_CAT_LIGHT = None
ITEM_CAT_RUNE = None
ITEM_CAT_MAGIC = None
ITEM_FLAG_DAG = None
ITEM_FLAG_SWD = None
ITEM_FLAG_AXE = None
ITEM_FLAG_2HD_SWD = None
ITEM_FLAG_2HD_AXE = None
ITEM_FLAG_SHIELD = None
ITEM_FLAG_BOW = None
ITEM_FLAG_CROSSBOW = None
ITEM_FLAG_RING = None
ITEM_FLAG_AMULET = None
ITEM_FLAG_BELT = None
ITEM_FLAG_DROPPED = None
ITEM_FLAG_MI = None
ITEM_FLAG_MULTI = None
ITEM_FLAG_NFOCUS = None
ITEM_FLAG_CREATEAMMO = None
ITEM_FLAG_NSPLIT = None
ITEM_FLAG_DRINK = None
ITEM_FLAG_TORCH = None
ITEM_FLAG_THROW = None
ITEM_FLAG_ACTIVE = None
ITEM_WEAR_NO = None
ITEM_WEAR_TORSO = None
ITEM_WEAR_HEAD = None
ITEM_WEAR_LIGHT = None
DISCONNECTED = None
LOST_CONNECTION = None
HAS_CRASHED = None
ATTACK_RUN = None
ATTACK_FORWARD = None
ATTACK_LEFT = None
ATTACK_RIGHT = None
ACTION_CLEAR_QUEUE = None
ACTION_APPLY_OVERLAY = None
ACTION_REMOVE_OVERLAY = None
ACTION_PLAY_ANI = None
ACTION_STOP_ANI = None
ACTION_EQUIP_ITEM = None
ACTION_UNEQUIP_ITEM = None
ACTION_WEAPON_MODE = None
ACTION_DRAW_WEAPON = None
ACTION_REMOVE_WEAPON = None
ACTION_USE_ITEM = None
ACTION_USE_ITEM_TO_STATE = None
ACTION_READY_SPELL = None
ACTION_UNREADY_SPELL = None
ACTION_ATTACK_MELEE_WEAPON = None
ACTION_ATTACK_RANGED_WEAPON = None
ACTION_SPELL_CAST = None
ACTION_USE_MOB_SCHEME = None
ACTION_SHOOT_AT = None
ACTION_START_AIM_AT = None
ACTION_STOP_AIM_AT = None
ACTION_SCRIPT = None
WEAPON_1H = None
WEAPON_2H = None
WEAPON_BOW = None
WEAPON_CBOW = None
TALENT_1H = None
TALENT_2H = None
TALENT_BOW = None
TALENT_CROSSBOW = None
TALENT_PICK_LOCKS = None
TALENT_PICKPOCKET = None
TALENT_MAGE = None
TALENT_SNEAK = None
TALENT_REGENERATE = None
TALENT_FIREMASTER = None
TALENT_ACROBATIC = None
TALENT_PICKPOCKET_UNUSED = None
TALENT_SMITH = None
TALENT_RUNES = None
TALENT_ALCHEMY = None
TALENT_THROPHY = None
TALENT_A = None
TALENT_B = None
TALENT_C = None
TALENT_D = None
TALENT_E = None
TALENT_MAX = None
WEAPONMODE_NONE = None
WEAPONMODE_FIST = None
WEAPONMODE_DAG = None
WEAPONMODE_1HS = None
WEAPONMODE_2HS = None
WEAPONMODE_BOW = None
WEAPONMODE_CBOW = None
WEAPONMODE_MAG = None
WEAPONMODE_MAX = None
WEATHER_SNOW = None
WEATHER_RAIN = None
@classmethod
def _update(cls, constants):
existing_vars = [name for name, _ in inspect.getmembers(cls) if not name.startswith('_') and not inspect.ismodule(_)]
for key, val in constants.items():
if key in existing_vars:
setattr(cls, key, val)

View File

@@ -1,6 +1,7 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def sendMessageToAll(r : int, g : int, b : int, text : str): async def sendMessageToAll(r : int, g : int, b : int, text : str):
""" """
This function will send a chat message to every connected player. This function will send a chat message to every connected player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`. Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`.
@@ -8,7 +9,7 @@ def sendMessageToAll(r : int, g : int, b : int, text : str):
## Declaration ## Declaration
```python ```python
def sendMessageToAll(r : int, g : int, b : int, text : str) async def sendMessageToAll(r : int, g : int, b : int, text : str)
``` ```
## Parameters ## Parameters
@@ -17,9 +18,13 @@ def sendMessageToAll(r : int, g : int, b : int, text : str):
* `int` **b**: the blue color component in RGB model. * `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send. * `str` **text**: that will be send.
""" """
return sqg2o.sendMessageToAll(r, g, b, text) data = f'return {get_call_repr()}'
def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str):
""" """
This function will send a chat message to specific player. This function will send a chat message to specific player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`. Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as `-1`.
@@ -27,7 +32,7 @@ def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str):
## Declaration ## Declaration
```python ```python
def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str) async def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str)
``` ```
## Parameters ## Parameters
@@ -37,9 +42,13 @@ def sendMessageToPlayer(playerid : int, r : int, g : int, b : int, text : str):
* `int` **b**: the blue color component in RGB model. * `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send. * `str` **text**: that will be send.
""" """
return sqg2o.sendMessageToPlayer(playerid, r, g, b, text) data = f'return {get_call_repr()}'
def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str):
""" """
This function will send a chat message from one player to every player. Sending a message This function will send a chat message from one player to every player. Sending a message
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**. Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**.
@@ -47,7 +56,7 @@ def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str
## Declaration ## Declaration
```python ```python
def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str) async def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str)
``` ```
## Parameters ## Parameters
@@ -57,9 +66,13 @@ def sendPlayerMessageToAll(senderid : int, r : int, g : int, b : int, text : str
* `int` **b**: the blue color component in RGB model. * `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send. * `str` **text**: that will be send.
""" """
return sqg2o.sendPlayerMessageToAll(senderid, r, g, b, text) data = f'return {get_call_repr()}'
def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str):
""" """
This function will send a chat message from one player to another player. This function will send a chat message from one player to another player.
Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**. Sending a message triggers client side event [onPlayerMessage](../../defaultEvents/player/onPlayerMessage.md) with playerid set as **senderid**.
@@ -67,7 +80,7 @@ def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int
## Declaration ## Declaration
```python ```python
sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str) async def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int, b : int, text : str)
``` ```
## Parameters ## Parameters
@@ -78,4 +91,8 @@ def sendPlayerMessageToPlayer(senderid : int, receiverid : int, r : int, g : int
* `int` **b**: the blue color component in RGB model. * `int` **b**: the blue color component in RGB model.
* `str` **text**: that will be send. * `str` **text**: that will be send.
""" """
return sqg2o.sendPlayerMessageToAll(senderid, receiverid, r, g, b, text) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -0,0 +1,737 @@
from typing import Literal, overload
from functools import wraps
from ..serialize import _deserialize
eventList = {}
disabledEventList = []
async def callEvent(evtName : str, **kwargs : list):
"""
This function will notify (call) every handler bound to specified event.
Original: [callEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/callEvent/)
## Declaration
```python
def callEvent(evtName : str, **kwargs : list)
```
## Parameters
* `str` **name**: the name of the event
* `**dict` **kwargs**: the variable number of arguments.
## Usage
```python
import g2o
g2o.addEvent('testEvt')
@g2o.event('testEvt')
def onTestEvent(**kwargs):
print(f'{kwargs['name']} called my beautiful test event')
g2o.callEvent('testEvt', name = 'Diego')
```
"""
isEventCancelled = False
if evtName in eventList and evtName not in disabledEventList:
for event in eventList[evtName]:
event['function'].eventName = evtName
event['function'].cancelled = isEventCancelled
result = await event['function'](**kwargs)
if result != None:
isEventCancelled = not result
return isEventCancelled
def addEvent(name : str):
"""
This function will register a new event with specified name.
Events can be used to notify function(s) when something will happen, like player joins the server, etc.
Original: [addEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/addEvent/)
## Declaration
```python
def addEvent(name)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
g2o.addEvent('testEvt')
```
"""
if not name in eventList:
eventList[name] = []
@overload
def event(event_name: Literal['onPlayerUseCheat'], priority: int = 9999) -> None:
'''
!!! note
Detecting some type of forbidden tools may take, even a few minutes. Server need time to analyze player data.
## Parameters:
* **playerid**: str - the id of the player who used some type of trainer/cheat.
* **type**: int - the type of used trainer/cheat. For more information see AntiCheat constants.
'''
...
@overload
def event(event_name: Literal['onBan'], priority: int = 9999) -> None:
'''
!!! note
If serial/mac/ip/name indexes doesn't exist, then the parameters has not been specified when ban was added.
This event is triggered when new ban is being added.
## Parameters:
* **banInfo**: dict
* **mac**: str - MAC address of the banned player.
* **ip**: str - IP address of the banned player.
* **serial**: str - serial of the banned player.
* **name**: str - nickname of the banned player.
* **timestamp**: int - timestamp when the ban expires.
'''
...
@overload
def event(event_name: Literal['onExit'], priority: int = 9999) -> None:
'''
This event is triggered when server is going to shut down.
You can use it, to save some data before closing up, or do something else.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onInit'], priority: int = 9999) -> None:
'''
This event is triggered when server successfully starts up.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onTick'], priority: int = 9999) -> None:
'''
This event is triggered in every server main loop iteration.
## Parameters:
No parameters.
'''
...
@overload
def event(event_name: Literal['onTime'], priority: int = 9999) -> None:
'''
This event is triggered each time when game time minute passes.
## Parameters:
* **day**: int - the current ingame day.
* **hour**: int - the current ingame hour.
* **min**: int - the current ingame minutes.
'''
...
@overload
def event(event_name: Literal['onUnban'], priority: int = 9999) -> None:
'''
!!! note
If serial/mac/ip/name indexes doesn't exist, then the parameters has not been specified when ban was added.
This event is triggered when ban with specified info is being removed.
## Parameters:
* **banInfo**: dict
* **mac**: str - MAC address of the banned player.
* **ip**: str - IP address of the banned player.
* **serial**: str - serial of the banned player.
* **name**: str - nickname of the banned player.
* **timestamp**: int - timestamp when the ban expires.
'''
...
@overload
def event(event_name: Literal['onNpcActionFinished'], priority: int = 9999) -> None:
'''
This event is triggered when NPC action was finished.
## Parameters:
* **npc_id**: int - the npc identifier.
* **action_type**: int - the action type.
* **action_id**: int - the unique action identifier.
* **result**: bool - the result of finished action.
'''
...
@overload
def event(event_name: Literal['onNpcActionSent'], priority: int = 9999) -> None:
'''
This event is triggered when server sends NPC action to streamed players.
## Parameters:
* **npc_id**: int - the npc identifier.
* **action_type**: int - the action type.
* **action_id**: int - the unique action identifier.
'''
...
@overload
def event(event_name: Literal['onNpcChangeHostPlayer'], priority: int = 9999) -> None:
'''
This event is triggered when NPC host is changed. Every remote NPC is hosted by one of spawned players in order to get valid position of NPC.
## Parameters:
* **npc_id**: int - the npc identifier.
* **current_id**: int - the id of the current host, can be -1 if there is no current host.
* **previous_id**: int - the id of the previous host, can be -1 if there was no previous host.
'''
...
@overload
def event(event_name: Literal['onNpcCreated'], priority: int = 9999) -> None:
'''
This event is triggered when remote NPC is created.
## Parameters:
* **npc_id**: int - the id of the newly created remote npc.
'''
...
@overload
def event(event_name: Literal['onNpcDestroyed'], priority: int = 9999) -> None:
'''
This event is triggered when remote NPC is destroyed.
## Parameters:
* **npc_id**: int - the id of the destroyed remote npc.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeColor'], priority: int = 9999) -> None:
'''
This event is triggered when player nickname color was changed for all players.
## Parameters:
* **playerid**: int - the id of the player whose nickname color was changed.
* **r**: int - the amount of red in the nickname color ``(0 - 255)``.
* **g**: int - the amount of green in the nickname color ``(0 - 255)``.
* **b**: int - the amount of blue in the nickname color ``(0 - 255)``.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeFocus'], priority: int = 9999) -> None:
'''
This event is triggered when player targets another player.
## Parameters:
* **playerid**: int - the id of the player which changes the focus.
* **oldFocusId**: int - the old playerid targeted by the player. Can be ``-1`` if player wasn't targeting other player.
* **newFocusId**: int - the new playerid targeted by the player. Can be ``-1`` if player doesn't target anyone.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeHealth'], priority: int = 9999) -> None:
'''
This event is triggered when player health changes.
## Parameters:
* **playerid**: int - the id of the player whose health points gets changed.
* **previous**: int - the previous health points of the player.
* **current**: int - the current health points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMana'], priority: int = 9999) -> None:
'''
This event is triggered when player mana changes.
## Parameters:
* **playerid**: int - the id of the player whose mana points gets changed.
* **previous**: int - the previous mana points of the player.
* **current**: int - the current mana points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMaxHealth'], priority: int = 9999) -> None:
'''
This event is triggered when player maximum health changes.
## Parameters:
* **playerid**: int - the id of the player whose maximum health points gets changed.
* **previous**: int - the previous maximum health points of the player.
* **current**: int - the current maximum health points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeMaxMana'], priority: int = 9999) -> None:
'''
This event is triggered when player maximum mana changes.
## Parameters:
* **playerid**: int - the id of the player whose maximum mana points gets changed.
* **previous**: int - the previous maximum mana points of the player.
* **current**: int - the current maximum mana points of the player.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeWeaponMode'], priority: int = 9999) -> None:
'''
This event is triggered when player changes the weapon mode.
## Parameters:
* **playerid**: int - the id of the player which changes the weapon mode.
* **previous**: int - the old weapon mode which was used by the player. For more information see Weapon mode constants.
* **current**: int - the new weapon mode in which player is currently using. For more information see Weapon mode constants.
'''
...
@overload
def event(event_name: Literal['onPlayerChangeWorld'], priority: int = 9999) -> None:
'''
This event is triggered when player tries to change his currently played world (ZEN).
## Parameters:
* **playerid**: int - the id of the player who tries to change the played world.
* **world**: str - a filename name of the world.
* **waypoint**: str - a name of the waypoint that the player will be teleported to.
'''
...
@overload
def event(event_name: Literal['onPlayerCommand'], priority: int = 9999) -> None:
'''
This event is triggered when a player uses command on the chat.
Command always begins with forward slash ``/``.
## Parameters:
* **playerid**: int - the id of the player who typed the command.
* **command**: str - used command name on the chat.
* **params**: str - command parameters divided by space.
'''
...
@overload
def event(event_name: Literal['onPlayerDamage'], priority: int = 9999) -> None:
'''
This event is triggered when one player hits another player.
## Parameters:
* **playerid**: int - the id of the player who was hit.
* **killerid**: int - the id of the killer. If killerid is set to ``-1``, it means that there was no killer. In this particular case damage source can be fall from a tall object or scripts.
* **description**: DamageDescription - a structure containing damage information. For more information see DamageDescription
'''
...
@overload
def event(event_name: Literal['onPlayerDead'], priority: int = 9999) -> None:
'''
This event is triggered when one player kills another player.
## Parameters:
* **playerid**: int - the id of the player who died.
* **killerid**: int - the id of the player who killed other player. If killerid is set to -1, it means that there was no killer.
'''
...
@overload
def event(event_name: Literal['onPlayerDisconnect'], priority: int = 9999) -> None:
'''
This event is triggered when a player gets disconnected with the server.
## Parameters:
* **playerid**: int - the id of the player who joined the server.
* **reason**: int - the reason why player got disconnected. For more information see Network constants.
'''
...
# TODO: Отмена ивента
@overload
def event(event_name: Literal['onPlayerDropItem'], priority: int = 9999) -> None:
'''
!!! note
Cancelling this event will delete the dropped item from the world.
This event is triggered when player drops an item from his inventory to the ground.
## Parameters:
* **playerid**: int - the id of the player who tries to drop the item on the ground.
* **itemGround**: ItemGround - the ground item object which represents the dropped item by the player.
'''
...
@overload
def event(event_name: Literal['onPlayerEnterWorld'], priority: int = 9999) -> None:
'''
This event is triggered when player entered the world (ZEN) and was successfully spawned in it.
## Parameters:
* **playerid**: int - the id of the player who entered the world.
* **world**: str - a filename name of the world.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipAmulet'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips amulet. When item is unequiped, ``None`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips an amulet.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipArmor'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips armor. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips an armor.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipBelt'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips belt. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a belt.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipHandItem'], priority: int = 9999) -> None:
'''
This event is triggered when game adds item to player hand, e.g: when player opens or consumes any item. When item is removed from hand, ``null is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a hand item.
* **hand**: int - the id of the hand in which player holds item. For more information see Hand constants.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipHelmet'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips helmet. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a helmet.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipMeleeWeapon'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips melee weapon. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips melee weapon.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipRangedWeapon'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips ranged weapon. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips ranged weapon.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipRing'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips ring. When item is unequiped, ``null`` item id is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a ring.
* **handId**: int - the hand id that the player is putting the ring on.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipShield'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips shield. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: int - the id of the player who equips a shield.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerEquipSpell'], priority: int = 9999) -> None:
'''
This event is triggered when player equips or unequips scroll or rune. When item is unequiped, ``null`` is returned instead.
## Parameters:
* **playerid**: the id of the player who equips a spell.
* **slotId**: int - the slot id that the player puts the spell on in range <0, 6>.
* **instance**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerJoin'], priority: int = 9999) -> None:
'''
This event is triggered when a player successfully joined the server.
## Parameters:
* **playerid**: int - the id of the player who joined the server.
'''
...
@overload
def event(event_name: Literal['onPlayerMessage'], priority: int = 9999) -> None:
'''
This event is triggered when a player types the message on the chat.
## Parameters:
* **playerid**: int - the id of the player who typed the message.
'''
...
@overload
def event(event_name: Literal['onPlayerMobInteract'], priority: int = 9999) -> None:
'''
This event is triggered when player interacts with any kind of mob object in the world. In Gothic, mobs are special vobs on the map, that hero can interact with. For example bed, door, chest etc.
## Parameters:
* **playerid**: int - the id of the player who interacts with mob.
* **from**: int - represents previous state of mob. If value is ``1``, then mob was used, in any other case value is ``0``.
* **to**: int - represents current state of mob. If value is ``1``, then mob is used, in any other case value is ``0``.
'''
...
@overload
def event(event_name: Literal['onPlayerRespawn'], priority: int = 9999) -> None:
'''
This event is triggered when a player respawns after death.
## Parameters:
* **playerid**: int - the id of the player who respawned after death.
'''
...
@overload
def event(event_name: Literal['onPlayerShoot'], priority: int = 9999) -> None:
'''
This event is triggered when player shoot using ranged weapon.
## Parameters:
* **playerid**: int - the id of the player who just shot.
* **munition**: str|None - the item instance from Daedalus scripts.
'''
...
@overload
def event(event_name: Literal['onPlayerSpellCast'], priority: int = 9999) -> None:
'''
!!! note
Right now transformation and summon spells are not supported, despite this event will be triggered for them. Cancelling this event willl prevent this action to be synced to other players.
This event is triggered when player is casting some spell.
## Parameters:
* **playerid**: int - the id of the player who casts the spell.
* **munition**: str|None - the item instance from Daedalus scripts.
* **spellLevel**: int - the level of charged spell
'''
...
@overload
def event(event_name: Literal['onPlayerSpellSetup'], priority: int = 9999) -> None:
'''
This event is triggered when player prepares the spell.
## Parameters:
* **playerid**: int - the id of the player who prepares the spell.
* **munition**: str|None - the item instance from Daedalus scripts.
'''
...
# TODO: Отмена ивента
@overload
def event(event_name: Literal['onPlayerTakeItem'], priority: int = 9999) -> None:
'''
!!! note
Even if this event is triggered it doesn't mean, that player will get item to his inventory. It only means, that the player tried to get the item from the ground. Server is the last decide if the item can be taken from the ground. Canceling this event will prevent the item to be taken from the ground.
This event is triggered when player takes an item from the ground.
## Parameters:
* **playerid**: int - the id of the player who tries to take the ground item.
* **itemGround**: ItemGround - the ground item object which player tried to to take.
'''
...
@overload
def event(event_name: Literal['onPlayerTeleport'], priority: int = 9999) -> None:
'''
This event is triggered when player gets teleported by the game to the specified vob.
## Parameters:
* **playerid**: int - the id of the player who gets teleported by the game.
* **vobName**: str - represents the name of the vob that player gets teleported to.
'''
...
@overload
def event(event_name: Literal['onPlayerToggleFaceAni'], priority: int = 9999) -> None:
'''
This event is triggered when player face animation is toggled (played or stopped), due to eating or other activities.
## Parameters:
* **playerid**: int - the id of the player which toggled face animation.
* **aniName**: str - the face animation name.
* **toggle**: bool - ``True`` when player is started playing face animation, otherwise ``False``.
'''
...
def event(event_name: str, priority: int = 9999) -> None:
def inlineEvt(func):
if event_name not in eventList:
return None
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
eventList[event_name].append({'function': wrapper, 'priority': priority})
eventList[event_name].sort(key = lambda x: x['priority'])
return wrapper
return inlineEvt
def removeEventHandler(name : str, func : object):
"""
This function will unbind function from specified event.
Original: [removeEventHandler](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEventHandler/)
## Declaration
```python
def removeEventHandler(name : str, func : object)
```
## Parameters
* `str` **name**: the name of the event
* `object` **func**: the reference to a function which is currently bound to specified event.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEventHandler('onTime', onTimeEvt)
```
"""
if not name in eventList:
pass
for index, item in enumerate(eventList[name]):
if item['function'] == func:
del eventList[name][index]
def toggleEvent(name : str, toggle : bool):
'''
!!! note
By default every event is toggled `on` (enabled).
This function will toggle event (enable or disable it globally). By toggling event off, you can completely disable certain event from calling it's handlers.
Original: [toggleEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/toggleEvent/)
## Declaration
```python
def toggleEvent(name : str, toggle : bool)
```
## Parameters
* `str` **name**: the name of the event
* `bool` **toggle**: `false` if you want to disable the event, otherwise true.
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.toggleEvent('onTime', false)
```
'''
if not toggle and name not in disabledEventList:
disabledEventList.append(name)
elif toggle and name in disabledEventList:
disabledEventList.remove(name)
def removeEvent(name : str):
'''
!!! warning
Removing an event also cause all event handlers to unregister.
This function will unregister an event with specified name.
Original: [removeEvent](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/event/removeEvent/)
## Declaration
```python
def removeEvent(name : str)
```
## Parameters
* `str` **name**: the name of the event
## Usage
```python
import g2o
@g2o.event('onTime')
def onTimeEvt(**kwargs):
print('Calling only once')
g2o.removeEvent('onTime')
```
'''
if name in eventList:
eventList.pop(name)
## registering default events
addEvent('onInit')
addEvent('onExit')
addEvent('onTick')
addEvent('onTime')
addEvent('onBan')
addEvent('onUnban')
addEvent('onPlayerChangeColor')
addEvent('onPlayerChangeFocus')
addEvent('onPlayerChangeHealth')
addEvent('onPlayerChangeMana')
addEvent('onPlayerChangeMaxHealth')
addEvent('onPlayerChangeMaxMana')
addEvent('onPlayerChangeWeaponMode')
addEvent('onPlayerChangeWorld')
addEvent('onPlayerCommand')
addEvent('onPlayerDamage')
addEvent('onPlayerDead')
addEvent('onPlayerDisconnect')
addEvent('onPlayerDropItem')
addEvent('onPlayerEnterWorld')
addEvent('onPlayerJoin')
addEvent('onPlayerMessage')
addEvent('onPlayerMobInteract')
addEvent('onPlayerRespawn')
addEvent('onPlayerShoot')
addEvent('onPlayerSpellCast')
addEvent('onPlayerSpellSetup')
addEvent('onPlayerTakeItem')
addEvent('onPlayerTeleport')
addEvent('onPlayerToggleFaceAni')
addEvent('onPlayerEquipAmulet')
addEvent('onPlayerEquipArmor')
addEvent('onPlayerEquipBelt')
addEvent('onPlayerEquipHandItem')
addEvent('onPlayerEquipHelmet')
addEvent('onPlayerEquipMeleeWeapon')
addEvent('onPlayerEquipRangedWeapon')
addEvent('onPlayerEquipRing')
addEvent('onPlayerEquipShield')
addEvent('onPlayerEquipSpell')
addEvent('onPacket')
addEvent('onPlayerUseCheat')
addEvent('onNpcActionFinished')
addEvent('onNpcActionSent')
addEvent('onNpcChangeHostPlayer')
addEvent('onNpcCreated')
addEvent('onNpcDestroyed')
addEvent('onWebsocketConnect')
addEvent('onWebsocketDisconnect')

View File

@@ -1,13 +1,14 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def getHostname() -> str: async def getHostname() -> str:
""" """
This function will get the hostname of the server. This function will get the hostname of the server.
Original: [getHostname](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getHostname/) Original: [getHostname](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getHostname/)
## Declaration ## Declaration
```python ```python
def getHostname() -> str async def getHostname() -> str
``` ```
## Returns ## Returns
`str`: Server hostname. `str`: Server hostname.
@@ -21,16 +22,23 @@ def getHostname() -> str:
print('Server hostname:', g2o.getHostname()) print('Server hostname:', g2o.getHostname())
``` ```
""" """
return sqg2o.getHostname()
def getMaxSlots() -> int: data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getMaxSlots() -> int:
""" """
This function will get the max number of slots available on the server. This function will get the max number of slots available on the server.
Original: [getMaxSlots](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getMaxSlots/) Original: [getMaxSlots](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getMaxSlots/)
## Declaration ## Declaration
```python ```python
def getMaxSlots() -> int async def getMaxSlots() -> int
``` ```
## Returns ## Returns
`int`: Max slots number on the server. `int`: Max slots number on the server.
@@ -44,16 +52,20 @@ def getMaxSlots() -> int:
print('Server max slots:', g2o.getMaxSlots()) print('Server max slots:', g2o.getMaxSlots())
``` ```
""" """
return sqg2o.getMaxSlots() data = f'return {get_call_repr()}'
def getPlayersCount() -> int: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getPlayersCount() -> int:
""" """
This function will get the max number of slots available on the server. This function will get the max number of slots available on the server.
Original: [getPlayersCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getPlayersCount/) Original: [getPlayersCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/game/getPlayersCount/)
## Declaration ## Declaration
```python ```python
def getPlayersCount() -> int async def getPlayersCount() -> int
``` ```
## Returns ## Returns
`int`: Number of players on the server. `int`: Number of players on the server.
@@ -67,93 +79,121 @@ def getPlayersCount() -> int:
print('Players online:', g2o.getPlayersCount()) print('Players online:', g2o.getPlayersCount())
``` ```
""" """
return sqg2o.getPlayersCount() data = f'return {get_call_repr()}'
def exit(exitCode : int = 0): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def exit(exitCode : int = 0):
""" """
This function will close the server with specified exit code. This function will close the server with specified exit code.
Original: [exit](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/exit/) Original: [exit](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/exit/)
## Declaration ## Declaration
```python ```python
def exit(exitCode : int = 0) async def exit(exitCode : int = 0)
``` ```
## Parameters ## Parameters
* `int` **exitCode**: exit status for g2o server. * `int` **exitCode**: exit status for g2o server.
""" """
return sqg2o.exit(exitCode) data = f'return {get_call_repr()}'
def getDayLength() -> float: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getDayLength() -> float:
""" """
The function is used to get the day length in miliseconds. The function is used to get the day length in miliseconds.
Original: [getDayLength](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getDayLength/) Original: [getDayLength](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getDayLength/)
## Declaration ## Declaration
```python ```python
def getDayLength() -> float async def getDayLength() -> float
``` ```
## Returns ## Returns
`float`: the current day length in miliseconds. `float`: the current day length in miliseconds.
""" """
return sqg2o.getDayLength() data = f'return {get_call_repr()}'
def getServerDescription() -> str: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getServerDescription() -> str:
""" """
This function will get the description of the server. This function will get the description of the server.
Original: [getServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerDescription/) Original: [getServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerDescription/)
## Declaration ## Declaration
```python ```python
def getServerDescription() -> str async def getServerDescription() -> str
``` ```
## Returns ## Returns
`str`: Server description. `str`: Server description.
""" """
return sqg2o.getServerDescription() data = f'return {get_call_repr()}'
def getServerWorld() -> str: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getServerWorld() -> str:
""" """
The function is used to get the path of the default world on the server. The function is used to get the path of the default world on the server.
Original: [getServerWorld](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerWorld/) Original: [getServerWorld](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getServerWorld/)
## Declaration ## Declaration
```python ```python
def getServerWorld() -> str async def getServerWorld() -> str
``` ```
## Returns ## Returns
`str`: The world path name. `str`: The world path name.
""" """
return sqg2o.getServerWorld() data = f'return {get_call_repr()}'
def getTime() -> dict: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getTime() -> dict:
""" """
The function is used to get the path of the default world on the server. The function is used to get the path of the default world on the server.
Original: [getTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getTime/) Original: [getTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/getTime/)
## Declaration ## Declaration
```python ```python
def getTime() -> dict async def getTime() -> dict
``` ```
## Returns ## Returns
`dict {day, hour, min}`: The current time in the game. `dict {day, hour, min}`: The current time in the game.
""" """
return sqg2o.getTime() data = f'return {get_call_repr()}'
def serverLog(text : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def serverLog(text : str):
""" """
This function will log the text into server.log file. This function will log the text into server.log file.
Original: [serverLog](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/serverLog/) Original: [serverLog](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/serverLog/)
## Declaration ## Declaration
```python ```python
def serverLog(text : str) async def serverLog(text : str)
``` ```
## Parameters ## Parameters
`str` **text**: the text message that you want to append to server.log file. `str` **text**: the text message that you want to append to server.log file.
""" """
return sqg2o.serverLog(text) data = f'return {get_call_repr()}'
def setDayLength(miliseconds : float): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setDayLength(miliseconds : float):
""" """
!!! note !!! note
Day length can't be smaller than 10 000 miliseconds. Day length can't be smaller than 10 000 miliseconds.
@@ -163,30 +203,38 @@ def setDayLength(miliseconds : float):
## Declaration ## Declaration
```python ```python
def setDayLength(miliseconds : float) async def setDayLength(miliseconds : float)
``` ```
## Parameters ## Parameters
`float` **miliseconds**: day length in miliseconds. `float` **miliseconds**: day length in miliseconds.
""" """
return sqg2o.setDayLength(miliseconds) data = f'return {get_call_repr()}'
def setServerDescription(description : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setServerDescription(description : str):
""" """
This function will set the description of the server. This function will set the description of the server.
Original: [setServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setServerDescription/) Original: [setServerDescription](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setServerDescription/)
## Declaration ## Declaration
```python ```python
def setServerDescription(description : str) async def setServerDescription(description : str)
``` ```
## Parameters ## Parameters
`str` **description**: the server description. `str` **description**: the server description.
## Returns ## Returns
`bool`: `true` if server description was set successfully, otherwise `false`. `bool`: `true` if server description was set successfully, otherwise `false`.
""" """
return sqg2o.setServerDescription(description) data = f'return {get_call_repr()}'
def setServerWorld(world : str): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setServerWorld(world : str):
""" """
!!! note !!! note
The server world limit is set to 32 characters. The server world limit is set to 32 characters.
@@ -199,25 +247,34 @@ def setServerWorld(world : str):
## Declaration ## Declaration
```python ```python
def setServerWorld(world : str) async def setServerWorld(world : str)
``` ```
## Parameters ## Parameters
`str` **world**: the path to the target world. `str` **world**: the path to the target world.
""" """
return sqg2o.setServerWorld(world) data = f'return {get_call_repr()}'
def setTime(hour : int, min : int, day : int = 0): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setTime(hour : int, min : int, day : int = 0):
""" """
This function will set the current time in the game to the given time, for all the players. This function will set the current time in the game to the given time, for all the players.
Original: [setTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setTime/) Original: [setTime](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/game/setTime/)
## Declaration ## Declaration
```python ```python
def setTime(hour : int, min : int, day : int = 0) async def setTime(hour : int, min : int, day : int = 0)
``` ```
## Parameters ## Parameters
`int` **hour**: the hour of new time (in the range between 0-23). `int` **hour**: the hour of new time (in the range between 0-23).
`int` **min**: the minute of new time (in the range between 0-59). `int` **min**: the minute of new time (in the range between 0-59).
`int` **day**: the day of new time. `int` **day**: the day of new time.
""" """
return sqg2o.setTime(hour, min, day) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -1,13 +1,14 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float: async def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float:
""" """
This function will get the 2d distance between two points. This function will get the 2d distance between two points.
Original: [getDistance2d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance2d/) Original: [getDistance2d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance2d/)
## Declaration ## Declaration
```python ```python
def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float async def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float
``` ```
## Parameters ## Parameters
@@ -18,16 +19,20 @@ def getDistance2d(x1 : float, y1: float, x2 : float, y2 : float) -> float:
## Returns ## Returns
`float`: Returns the calculated 2d distance between two points as floating point number. `float`: Returns the calculated 2d distance between two points as floating point number.
""" """
return sqg2o.getDistance2d(x1, y1, x2, y2) data = f'return {get_call_repr()}'
def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float:
""" """
This function will get the 3d distance between two points. This function will get the 3d distance between two points.
Original: [getDistance3d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance3d/) Original: [getDistance3d](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getDistance3d/)
## Declaration ## Declaration
```python ```python
def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float async def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2 : float) -> float
``` ```
## Parameters ## Parameters
@@ -40,16 +45,20 @@ def getDistance3d(x1 : float, y1: float, z1 : float, x2 : float, y2 : float, z2
## Returns ## Returns
`float`: Returns the calculated 3d distance between two points as floating point number. `float`: Returns the calculated 3d distance between two points as floating point number.
""" """
return sqg2o.getDistance3d(x1, y1, z1, x2, y2, z2) data = f'return {get_call_repr()}'
def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float:
""" """
This function will get angle on Y axis directed towards the second point. This function will get angle on Y axis directed towards the second point.
Original: [getVectorAngle](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getVectorAngle/) Original: [getVectorAngle](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/shared-functions/math/getVectorAngle/)
## Declaration ## Declaration
```python ```python
def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float async def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float
``` ```
## Parameters ## Parameters
@@ -60,4 +69,8 @@ def getVectorAngle(x1 : float, y1: float, x2 : float, y2 : float) -> float:
## Returns ## Returns
`float`: Returns the angle on Y axis directed towards the second point. `float`: Returns the angle on Y axis directed towards the second point.
""" """
return sqg2o.getVectorAngle(x1, y1, x2, y2) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -1,20 +1,25 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def clearNpcActions(npc_id : int): async def clearNpcActions(npc_id : int):
""" """
This function clears remote NPC actions queue. Remote NPCs uses actions queue to execute thier tasks. This function clears remote NPC actions queue. Remote NPCs uses actions queue to execute thier tasks.
Original: [clearNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/clearNpcActions/) Original: [clearNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/clearNpcActions/)
## Declaration ## Declaration
```python ```python
clearNpcActions(npc_id : int) async def clearNpcActions(npc_id : int)
``` ```
## Parameters ## Parameters
`int` **npc_id**: the npc identifier. `int` **npc_id**: the npc identifier.
""" """
return sqg2o.clearNpcActions(npc_id) data = f'return {get_call_repr()}'
def createNpc(name : str, instance : str = 'PC_HERO') -> int: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def createNpc(name : str, instance : str = 'PC_HERO') -> int:
""" """
!!! note !!! note
By default npcs won't be added to world. In order to do that, you have to call [spawnPlayer](../player/spawnPlayer.md). By default npcs won't be added to world. In order to do that, you have to call [spawnPlayer](../player/spawnPlayer.md).
@@ -25,38 +30,46 @@ def createNpc(name : str, instance : str = 'PC_HERO') -> int:
## Declaration ## Declaration
```python ```python
def createNpc(name : str, instance : str = 'PC_HERO') -> int async def createNpc(name : str, instance : str = 'PC_HERO') -> int
``` ```
## Parameters ## Parameters
`str` **name**: the displayed name of the npc. `str` **name**: the displayed name of the npc.
`str` **instance**: the instance name of for the npc. `str` **instance**: the instance name of for the npc.
""" """
return sqg2o.createNpc(name, instance) data = f'return {get_call_repr()}'
def destroyNpc(npc_id : int) -> bool: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def destroyNpc(npc_id : int) -> bool:
""" """
This function destroys remote NPC. This function destroys remote NPC.
Original: [destroyNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/destroyNpc/) Original: [destroyNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/destroyNpc/)
## Declaration ## Declaration
```python ```python
def destroyNpc(npc_id : int) -> bool async def destroyNpc(npc_id : int) -> bool
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`bool`: `true` when npc was successfully destroyed, otherwise false`. `bool`: `true` when npc was successfully destroyed, otherwise false`.
""" """
return sqg2o.destroyNpc(npc_id) data = f'return {get_call_repr()}'
def getNpcAction(npc_id : int, index : int) -> dict: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcAction(npc_id : int, index : int) -> dict:
""" """
This function gets information about element on specified index in NPC action queue. This function gets information about element on specified index in NPC action queue.
Original: [getNpcAction](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcAction/) Original: [getNpcAction](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcAction/)
## Declaration ## Declaration
```python ```python
getNpcAction(npc_id : int, index : int) -> dict async def getNpcAction(npc_id : int, index : int) -> dict
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
@@ -64,96 +77,120 @@ def getNpcAction(npc_id : int, index : int) -> dict:
## Returns ## Returns
`dict {type, id, status}`: The table containing information about selected element. `dict {type, id, status}`: The table containing information about selected element.
""" """
return sqg2o.getNpcAction(npc_id, index) data = f'return {get_call_repr()}'
def getNpcActions(npc_id : int) -> list: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcActions(npc_id : int) -> list:
""" """
This function gets informations about elements in NPC action queue. This function gets informations about elements in NPC action queue.
Original: [getNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActions/) Original: [getNpcActions](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActions/)
## Declaration ## Declaration
```python ```python
def getNpcActions(npc_id : int) -> list async def getNpcActions(npc_id : int) -> list
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`list [{type, id}]`: The array containing information about queue elements. `list [{type, id}]`: The array containing information about queue elements.
""" """
return sqg2o.getNpcActions(npc_id) data = f'return {get_call_repr()}'
def getNpcActionsCount(npc_id : int) -> int: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcActionsCount(npc_id : int) -> int:
""" """
This function gets elements count in NPC action queue. This function gets elements count in NPC action queue.
Original: [getNpcActionsCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActionsCount/) Original: [getNpcActionsCount](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcActionsCount/)
## Declaration ## Declaration
```python ```python
def getNpcActionsCount(npc_id : int) -> int async def getNpcActionsCount(npc_id : int) -> int
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`int`: The count of elements inside queue, otherwise `-1`. `int`: The count of elements inside queue, otherwise `-1`.
""" """
return sqg2o.getNpcActionsCount(npc_id) data = f'return {get_call_repr()}'
def getNpcHostPlayer(npc_id : int) -> int: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcHostPlayer(npc_id : int) -> int:
""" """
This function gets NPC host player id. This function gets NPC host player id.
Original: [getNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcHostPlayer/) Original: [getNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcHostPlayer/)
## Declaration ## Declaration
```python ```python
getNpcHostPlayer(npc_id : int) -> int async def getNpcHostPlayer(npc_id : int) -> int
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`int`: the host player identifier. If there is no host player `-1` is returned instead. `int`: the host player identifier. If there is no host player `-1` is returned instead.
""" """
return sqg2o.getNpcHostPlayer(npc_id) data = f'return {get_call_repr()}'
def getNpcLastActionId(npc_id : int) -> int: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getNpcLastActionId(npc_id : int) -> int:
""" """
This function gets last action identifier, that was enqued to the NPC action queue. Every action in queue has associated unique id, by which can be identified. This function gets last action identifier, that was enqued to the NPC action queue. Every action in queue has associated unique id, by which can be identified.
Original: [getNpcLastActionId](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcLastActionId/) Original: [getNpcLastActionId](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/getNpcLastActionId/)
## Declaration ## Declaration
```python ```python
getNpcLastActionId(npc_id : int) -> int async def getNpcLastActionId(npc_id : int) -> int
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`int`: The last finished action identifier, otherwise `-1`. `int`: The last finished action identifier, otherwise `-1`.
""" """
return sqg2o.getNpcLastActionId(npc_id) data = f'return {get_call_repr()}'
def isNpc(npc_id : int) -> bool: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def isNpc(npc_id : int) -> bool:
""" """
This function checks whether id related to given object is remote NPC. This function checks whether id related to given object is remote NPC.
Original: [isNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpc/) Original: [isNpc](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpc/)
## Declaration ## Declaration
```python ```python
def isNpc(npc_id : int) -> bool async def isNpc(npc_id : int) -> bool
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
## Returns ## Returns
`bool`: `true` when object is NPC, otherwise `false`. `bool`: `true` when object is NPC, otherwise `false`.
""" """
return sqg2o.isNpc(npc_id) data = f'return {get_call_repr()}'
def isNpcActionFinished(npc_id : int, action_id : int) -> bool: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def isNpcActionFinished(npc_id : int, action_id : int) -> bool:
""" """
This function checks whether specified NPC action was finished. This function checks whether specified NPC action was finished.
Original: [isNpcActionFinished](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpcActionFinished/) Original: [isNpcActionFinished](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/isNpcActionFinished/)
## Declaration ## Declaration
```python ```python
def isNpcActionFinished(npc_id : int, action_id : int) -> bool async def isNpcActionFinished(npc_id : int, action_id : int) -> bool
``` ```
## Parameters ## Parameters
`int` **npc_id**: the identifier of npc. `int` **npc_id**: the identifier of npc.
@@ -161,9 +198,13 @@ def isNpcActionFinished(npc_id : int, action_id : int) -> bool:
## Returns ## Returns
`bool`: `true` if specified action identifier was already finished, otherwise `false`. `bool`: `true` if specified action identifier was already finished, otherwise `false`.
""" """
return sqg2o.isNpcActionFinished(npc_id, action_id) data = f'return {get_call_repr()}'
def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int):
""" """
!!! note !!! note
Combo is internal Gothic value. Its behaviour can be sometimes undefined. For example -1 value doesn't work for not humanoid NPCs. Combo is internal Gothic value. Its behaviour can be sometimes undefined. For example -1 value doesn't work for not humanoid NPCs.
@@ -173,7 +214,7 @@ def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo :
## Declaration ## Declaration
```python ```python
def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int) async def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo : int)
``` ```
## Parameters ## Parameters
`int` **attacker_id**: the remote npc id. `int` **attacker_id**: the remote npc id.
@@ -181,62 +222,78 @@ def npcAttackMelee(attacker_id : int, enemy_id : int, attack_type : int, combo :
`int` **attack_type**: the type of attack. `int` **attack_type**: the type of attack.
`int` **combol**: the combo sequence. For `-1` execute next command immediately. `int` **combol**: the combo sequence. For `-1` execute next command immediately.
""" """
return sqg2o.npcAttackMelee(attacker_id, enemy_id, attack_type, combo) data = f'return {get_call_repr()}'
def npcAttackRanged(attacker_id : int, enemy_id : int): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcAttackRanged(attacker_id : int, enemy_id : int):
""" """
This function enqueues attack ranged action to the remote NPC action queue. This function enqueues attack ranged action to the remote NPC action queue.
Original: [npcAttackRanged](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcAttackRanged/) Original: [npcAttackRanged](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcAttackRanged/)
## Declaration ## Declaration
```python ```python
def npcAttackRanged(attacker_id : int, enemy_id : int) async def npcAttackRanged(attacker_id : int, enemy_id : int)
``` ```
## Parameters ## Parameters
`int` **attacker_id**: the remote npc id. `int` **attacker_id**: the remote npc id.
`int` **enemy_id**: the remote npc or player id. `int` **enemy_id**: the remote npc or player id.
""" """
return sqg2o.npcAttackRanged(attacker_id, enemy_id) data = f'return {get_call_repr()}'
def npcSpellCast(attacker_id : int, enemy_id : int): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcSpellCast(attacker_id : int, enemy_id : int):
""" """
This function enqueues spell cast action to the remote NPC action queue. This function enqueues spell cast action to the remote NPC action queue.
Original: [npcSpellCast](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcSpellCast/) Original: [npcSpellCast](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcSpellCast/)
## Declaration ## Declaration
```python ```python
def npcSpellCast(attacker_id : int, enemy_id : int) async def npcSpellCast(attacker_id : int, enemy_id : int)
``` ```
## Parameters ## Parameters
`int` **attacker_id**: the remote npc id. `int` **attacker_id**: the remote npc id.
`int` **enemy_id**: the remote npc or player id. `int` **enemy_id**: the remote npc or player id.
""" """
return sqg2o.npcSpellCast(attacker_id, enemy_id) data = f'return {get_call_repr()}'
def npcUseClosestMob(npc_id : int, sceme : str, target_state : int): server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def npcUseClosestMob(npc_id : int, sceme : str, target_state : int):
""" """
This function enqueues use closest mob action to the remote NPC action queue. This function enqueues use closest mob action to the remote NPC action queue.
Original: [npcUseClosestMob](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcUseClosestMob/) Original: [npcUseClosestMob](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/npcUseClosestMob/)
## Declaration ## Declaration
```python ```python
def npcUseClosestMob(npc_id : int, sceme : str, target_state : int) async def npcUseClosestMob(npc_id : int, sceme : str, target_state : int)
``` ```
## Parameters ## Parameters
`int` **npc_id**: the npc identifier. `int` **npc_id**: the npc identifier.
`str` **sceme**: the animation sceme name, e.g: `"BENCH"` when you want to interact with bench. `str` **sceme**: the animation sceme name, e.g: `"BENCH"` when you want to interact with bench.
`int` **target_state**: the target state, use `1` if you want to start interaction and `-1` to end it. `int` **target_state**: the target state, use `1` if you want to start interaction and `-1` to end it.
""" """
return sqg2o.npcUseClosestMob(npc_id, sceme, target_state) data = f'return {get_call_repr()}'
def setNpcHostPlayer(npc_id : int, host_id : int) -> bool: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def setNpcHostPlayer(npc_id : int, host_id : int) -> bool:
""" """
This function sets new NPC host player. This function sets new NPC host player.
Original: [setNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/setNpcHostPlayer/) Original: [setNpcHostPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/npc/setNpcHostPlayer/)
## Declaration ## Declaration
```python ```python
def setNpcHostPlayer(npc_id : int, host_id : int) -> bool async def setNpcHostPlayer(npc_id : int, host_id : int) -> bool
``` ```
## Parameters ## Parameters
`int` **npc_id**: the npc identifier. `int` **npc_id**: the npc identifier.
@@ -244,4 +301,8 @@ def setNpcHostPlayer(npc_id : int, host_id : int) -> bool:
## Returns ## Returns
`bool`: `true` if host was successfully changed, otherwise `false`. `bool`: `true` if host was successfully changed, otherwise `false`.
""" """
return sqg2o.setNpcHostPlayer(npc_id, host_id) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -1,13 +1,14 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list: async def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list:
""" """
This function will search for nearest players, that matches given query arguments. This function will search for nearest players, that matches given query arguments.
Original: [findNearbyPlayers](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/findNearbyPlayers/) Original: [findNearbyPlayers](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/findNearbyPlayers/)
## Declaration ## Declaration
```python ```python
def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list async def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world : int = 0) -> list
``` ```
## Parameters ## Parameters
`dict {x, y, z}` **position**: the centroid position. `dict {x, y, z}` **position**: the centroid position.
@@ -17,36 +18,48 @@ def findNearbyPlayers(position : dict, radius : int, world : str, virtual_world
## Returns ## Returns
`list [int]`: ids of nearby players. `list [int]`: ids of nearby players.
""" """
return sqg2o.findNearbyPlayers(position, radius, world, virtual_world) data = f'return {get_call_repr()}'
def getSpawnedPlayersForPlayer(id : int) -> list: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getSpawnedPlayersForPlayer(id : int) -> list:
""" """
This function is used to retrieve currently spawned players for given player. This function is used to retrieve currently spawned players for given player.
Original: [getSpawnedPlayersForPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getSpawnedPlayersForPlayer/) Original: [getSpawnedPlayersForPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getSpawnedPlayersForPlayer/)
## Declaration ## Declaration
```python ```python
def getSpawnedPlayersForPlayer(id : int) -> list async def getSpawnedPlayersForPlayer(id : int) -> list
``` ```
## Parameters ## Parameters
`int` **id**: the player id. `int` **id**: the player id.
## Returns ## Returns
`list [int]`: ids of spawned players. `list [int]`: ids of spawned players.
""" """
return sqg2o.getSpawnedPlayersForPlayer(id) data = f'return {get_call_repr()}'
def getStreamedPlayersByPlayer(id : int) -> list: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getStreamedPlayersByPlayer(id : int) -> list:
""" """
This function is used to retrieve currently streamed players by given player. More details: Streamed players are basically clients, that has spawned given player in their game. Please notice, that player can be spawned only one way. Which means that there are situation were player 1 is spawned for player 2, but not the other way arount. Simple examples: - Invisible players cannot be seen, but they can see everyone nearby. - Flying around world using camera. This function is used to retrieve currently streamed players by given player. More details: Streamed players are basically clients, that has spawned given player in their game. Please notice, that player can be spawned only one way. Which means that there are situation were player 1 is spawned for player 2, but not the other way arount. Simple examples: - Invisible players cannot be seen, but they can see everyone nearby. - Flying around world using camera.
Original: [getStreamedPlayersByPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getStreamedPlayersByPlayer/) Original: [getStreamedPlayersByPlayer](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/streamer/getStreamedPlayersByPlayer/)
## Declaration ## Declaration
```python ```python
def getStreamedPlayersByPlayer(id : int) -> list async def getStreamedPlayersByPlayer(id : int) -> list
``` ```
## Parameters ## Parameters
`int` **id**: the player id. `int` **id**: the player id.
## Returns ## Returns
`list [int]`: ids of streamed players. `list [int]`: ids of streamed players.
""" """
return sqg2o.getStreamedPlayersByPlayer(id) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

View File

@@ -1,13 +1,14 @@
import sqg2o from ..server import PythonWebsocketServer
from ..call_repr import get_call_repr
def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict: async def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict:
""" """
This function is used to retrieve the information about nearest waypoint from the specified position. This function is used to retrieve the information about nearest waypoint from the specified position.
Original: [getNearestWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getNearestWaypoint/) Original: [getNearestWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getNearestWaypoint/)
## Declaration ## Declaration
```python ```python
def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict async def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict
``` ```
## Parameters ## Parameters
`str` **world**: the world name in which the waypoint exists. `str` **world**: the world name in which the waypoint exists.
@@ -17,16 +18,20 @@ def getNearestWaypoint(world : str, x : int, y : int, z : int) -> dict:
## Returns ## Returns
`dict {name, x, y, z}`: Waypoint information. `dict {name, x, y, z}`: Waypoint information.
""" """
return sqg2o.getNearestWaypoint(world, x, y, z) data = f'return {get_call_repr()}'
def getWaypoint(world : str, name : str) -> dict: server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result
async def getWaypoint(world : str, name : str) -> dict:
""" """
This function is used to retrieve the position of specified waypoint. This function is used to retrieve the position of specified waypoint.
Original: [getWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getWaypoint/) Original: [getWaypoint](https://gothicmultiplayerteam.gitlab.io/docs/0.3.0/script-reference/server-functions/waypoint/getWaypoint/)
## Declaration ## Declaration
```python ```python
def getWaypoint(world : str, name : str) -> dict async def getWaypoint(world : str, name : str) -> dict
``` ```
## Parameters ## Parameters
`str` **world**: the world name in which the waypoint exists. `str` **world**: the world name in which the waypoint exists.
@@ -34,4 +39,8 @@ def getWaypoint(world : str, name : str) -> dict:
## Returns ## Returns
`dict {x, y, z}`: The position of waypoint. `dict {x, y, z}`: The position of waypoint.
""" """
return sqg2o.getWaypoint(world, name) data = f'return {get_call_repr()}'
server = await PythonWebsocketServer.get_server()
result = await server.make_request(data)
return result

14
src/pyg2o/serialize.py Normal file
View File

@@ -0,0 +1,14 @@
def _deserialize(className, data):
from .classes.damage import DamageDescription
from .classes.items import ItemGround
className = className[4:]
new_cls = None
if className == 'DamageDescription':
new_cls = DamageDescription()
elif className == 'ItemGround':
new_cls = ItemGround()
new_cls._initialize(**data)
return new_cls

126
src/pyg2o/server.py Normal file
View File

@@ -0,0 +1,126 @@
import websockets
import asyncio
import logging
import json
import uuid
from typing import Optional
from .constants import Constant
from .functions.event import callEvent
from .serialize import _deserialize
class PythonWebsocketServer:
_current_server = None
def __init__(self, host: str, port: int, whitelist: list[str], ping_interval: int = 30, silent: bool = False):
self.host: str = host
self.port: int = port
self.ping_interval: int = ping_interval
self.whitelist = whitelist
self.silent = silent
self.requests_list: dict[str, asyncio.Future] = dict()
self._stop_event: asyncio.Event = asyncio.Event()
self.connected_socket: Optional[websockets.ClientConnection] = None
@classmethod
async def get_server(cls):
return cls._current_server
async def start(self):
async with websockets.serve(
self.handle_connection,
host=self.host,
port=self.port,
ping_interval=self.ping_interval,
):
logging.info(f'[PyG2O] Server is started at ws://{self.host}:{self.port}')
PythonWebsocketServer._current_server = self
await self._stop_event.wait()
async def stop(self):
PythonWebsocketServer._current_server = None
self.connected_socket = None
self._stop_event.set()
async def make_request(self, data: str):
if (self.connected_socket is None):
return None
request_id = str(uuid.uuid4())
self.requests_list[request_id] = asyncio.get_running_loop().create_future()
request = {
'uuid': request_id,
'args': data,
}
request = json.dumps(request)
formatted_request = request.replace("'", '\\"')
formatted_request = formatted_request.replace("False", 'false')
formatted_request = formatted_request.replace("True", 'true')
await self.connected_socket.send(formatted_request)
result = await asyncio.wait_for(
self.requests_list[request_id],
timeout=30
)
return result
async def handle_connection(self, websocket: websockets.ClientConnection):
if (websocket.remote_address[0] not in self.whitelist or self.connected_socket is not None):
await websocket.close(4000, 'Connection denied')
return
self.connected_socket = websocket
self.is_connected = websocket
if (not self.silent):
logging.info(f'Client connected: {websocket.remote_address}')
asyncio.create_task(callEvent('onWebsocketConnect', **{}))
try:
async for message in websocket:
message_json = json.loads(message)
# Deserializing objects
if ('args' in message_json):
formatted_args = dict()
for key, value in message_json['args'].items():
if not key.startswith('obj_'):
formatted_args[key] = value
continue
formatted_args[value['name']] = _deserialize(key, value['data'])
message_json['args'] = formatted_args
# Processing events
if ('event' in message_json):
asyncio.create_task(callEvent(message_json['event'], **formatted_args))
continue
# Processing requests from Squirrel side
if ('type' in message_json):
Constant._update(message_json['args'])
continue
# Processing made requests
if (
'uuid' in message_json and
message_json['uuid'] in self.requests_list.keys()
):
self.requests_list[message_json['uuid']].set_result(next(iter(message_json['args'].values())))
except json.JSONDecodeError as e:
logging.exception(f'[PyG2O] JSON Exception: {e}')
except Exception as e:
logging.exception(f'[PyG2O] Exception: {e}')
finally:
if (not self.silent):
logging.info('Client disconnected')
self.is_connected = None
self.connected_socket = None
asyncio.create_task(callEvent('onWebsocketDisconnect', **{}))