From 799044b9ad0bf07c98767c8937afa7e702f4257e Mon Sep 17 00:00:00 2001 From: Jan200101 Date: Thu, 20 Oct 2022 08:02:32 +0200 Subject: add on join and leave events --- BerryClient/events.py | 53 ++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 46 insertions(+), 7 deletions(-) diff --git a/BerryClient/events.py b/BerryClient/events.py index c01b6ee..041a852 100644 --- a/BerryClient/events.py +++ b/BerryClient/events.py @@ -35,8 +35,30 @@ def on_player_movement(): return decorator +PLAYER_JOIN_CALLBACKS = [] +def on_player_join(): + def decorator(func): + def wrapper(core: "BerryCore", playerId: int) -> bool: + return func(core, playerId) + + PLAYER_JOIN_CALLBACKS.append(wrapper) + + return decorator + +PLAYER_LEAVE_CALLBACKS = [] +def on_player_leave(): + def decorator(func): + def wrapper(core: "BerryCore", playerId: int) -> bool: + return func(core, playerId) + + PLAYER_LEAVE_CALLBACKS.append(wrapper) + + return decorator + +KNOWN_PLAYERS = [] PLAYER_POSITIONS = {} def process_events(core: "BerryCore"): + global KNOWN_PLAYERS for hit in core.events.pollBlockHits(): for callback in BLOCK_CALLBACKS: @@ -55,12 +77,29 @@ def process_events(core: "BerryCore"): playerEntityIds = [] for playerId in playerEntityIds: - PLAYER_POSITIONS[playerId] = core.entity.getPos(playerId) + try: + PLAYER_POSITIONS[playerId] = core.entity.getPos(playerId) + except RequestError: + # player ID is no longer valid, move on + continue + + if playerId in KNOWN_PLAYERS: + if OLD_POSITIONS[playerId] != PLAYER_POSITIONS[playerId]: + for callback in PLAYER_MOVEMENT_CALLBACKS: + if callback(core, playerId, + OLD_POSITIONS[playerId], PLAYER_POSITIONS[playerId]): + break + + else: + for callback in PLAYER_JOIN_CALLBACKS: + if callback(core, playerId): + break + + for playerLeft in [pId for pId in KNOWN_PLAYERS if pId not in playerEntityIds]: + for callback in PLAYER_LEAVE_CALLBACKS: + if callback(core, playerLeft): + break + + KNOWN_PLAYERS = playerEntityIds - if (playerId in OLD_POSITIONS - and OLD_POSITIONS[playerId] != PLAYER_POSITIONS[playerId]): - for callback in PLAYER_MOVEMENT_CALLBACKS: - if callback(core, playerId, - OLD_POSITIONS[playerId], PLAYER_POSITIONS[playerId]): - break -- cgit v1.2.3