FF1: fix printjson

This commit is contained in:
Fabian Dill 2022-09-09 21:28:24 +02:00 committed by Fabian Dill
parent 99d2caa57d
commit 88a225764a
5 changed files with 34 additions and 35 deletions

View File

@ -5,6 +5,7 @@ import urllib.parse
import sys import sys
import typing import typing
import time import time
import functools
import ModuleUpdate import ModuleUpdate
ModuleUpdate.update() ModuleUpdate.update()
@ -17,7 +18,8 @@ if __name__ == "__main__":
Utils.init_logging("TextClient", exception_logger="Client") Utils.init_logging("TextClient", exception_logger="Client")
from MultiServer import CommandProcessor from MultiServer import CommandProcessor
from NetUtils import Endpoint, decode, NetworkItem, encode, JSONtoTextParser, ClientStatus, Permission, NetworkSlot from NetUtils import Endpoint, decode, NetworkItem, encode, JSONtoTextParser, \
ClientStatus, Permission, NetworkSlot, RawJSONtoTextParser
from Utils import Version, stream_input from Utils import Version, stream_input
from worlds import network_data_package, AutoWorldRegister from worlds import network_data_package, AutoWorldRegister
import os import os
@ -204,6 +206,10 @@ class CommonContext:
# execution # execution
self.keep_alive_task = asyncio.create_task(keep_alive(self), name="Bouncy") self.keep_alive_task = asyncio.create_task(keep_alive(self), name="Bouncy")
@functools.cached_property
def raw_text_parser(self) -> RawJSONtoTextParser:
return RawJSONtoTextParser(self)
@property @property
def total_locations(self) -> typing.Optional[int]: def total_locations(self) -> typing.Optional[int]:
"""Will return None until connected.""" """Will return None until connected."""

View File

@ -1,4 +1,5 @@
import asyncio import asyncio
import copy
import json import json
import time import time
from asyncio import StreamReader, StreamWriter from asyncio import StreamReader, StreamWriter
@ -6,7 +7,7 @@ from typing import List
import Utils import Utils
from CommonClient import CommonContext, server_loop, gui_enabled, console_loop, ClientCommandProcessor, logger, \ from CommonClient import CommonContext, server_loop, gui_enabled, ClientCommandProcessor, logger, \
get_base_parser get_base_parser
SYSTEM_MESSAGE_ID = 0 SYSTEM_MESSAGE_ID = 0
@ -64,7 +65,7 @@ class FF1Context(CommonContext):
def _set_message(self, msg: str, msg_id: int): def _set_message(self, msg: str, msg_id: int):
if DISPLAY_MSGS: if DISPLAY_MSGS:
self.messages[(time.time(), msg_id)] = msg self.messages[time.time(), msg_id] = msg
def on_package(self, cmd: str, args: dict): def on_package(self, cmd: str, args: dict):
if cmd == 'Connected': if cmd == 'Connected':
@ -76,29 +77,23 @@ class FF1Context(CommonContext):
elif cmd == "ReceivedItems": elif cmd == "ReceivedItems":
msg = f"Received {', '.join([self.item_names[item.item] for item in args['items']])}" msg = f"Received {', '.join([self.item_names[item.item] for item in args['items']])}"
self._set_message(msg, SYSTEM_MESSAGE_ID) self._set_message(msg, SYSTEM_MESSAGE_ID)
elif cmd == 'PrintJSON':
print_type = args['type'] def on_print_json(self, args: dict):
item = args['item'] relevant = args.get("type", None) in {"Hint", "ItemSend"}
receiving_player_id = args['receiving'] if relevant:
receiving_player_name = self.player_names[receiving_player_id] item = args["item"]
sending_player_id = item.player # goes to this world
sending_player_name = self.player_names[item.player] if self.slot_concerns_self(args["receiving"]):
if print_type == 'Hint': relevant = True
msg = f"Hint: Your {self.item_names[item.item]} is at" \ # found in this world
f" {self.player_names[item.player]}'s {self.location_names[item.location]}" elif self.slot_concerns_self(item.player):
self._set_message(msg, item.item) relevant = True
elif print_type == 'ItemSend' and receiving_player_id != self.slot: # not related
if sending_player_id == self.slot:
if receiving_player_id == self.slot:
msg = f"You found your own {self.item_names[item.item]}"
else: else:
msg = f"You sent {self.item_names[item.item]} to {receiving_player_name}" relevant = False
else: if relevant:
if receiving_player_id == sending_player_id: item = args["item"]
msg = f"{sending_player_name} found their {self.item_names[item.item]}" msg = self.raw_text_parser(copy.deepcopy(args["data"]))
else:
msg = f"{sending_player_name} sent {self.item_names[item.item]} to " \
f"{receiving_player_name}"
self._set_message(msg, item.item) self._set_message(msg, item.item)
def run_gui(self): def run_gui(self):

View File

@ -743,6 +743,7 @@ async def countdown(ctx: Context, timer: int):
broadcast_countdown(ctx, 0, f"[Server]: GO") broadcast_countdown(ctx, 0, f"[Server]: GO")
ctx.countdown_timer = 0 ctx.countdown_timer = 0
def broadcast_text_all(ctx: Context, text: str, additional_arguments: dict = {}): def broadcast_text_all(ctx: Context, text: str, additional_arguments: dict = {}):
old_clients, new_clients = [], [] old_clients, new_clients = [], []
@ -755,9 +756,11 @@ def broadcast_text_all(ctx: Context, text: str, additional_arguments: dict = {})
ctx.broadcast(old_clients, [{"cmd": "Print", "text": text }]) ctx.broadcast(old_clients, [{"cmd": "Print", "text": text }])
ctx.broadcast(new_clients, [{**{"cmd": "PrintJSON", "data": [{ "text": text }]}, **additional_arguments}]) ctx.broadcast(new_clients, [{**{"cmd": "PrintJSON", "data": [{ "text": text }]}, **additional_arguments}])
def broadcast_countdown(ctx: Context, timer: int, message: str): def broadcast_countdown(ctx: Context, timer: int, message: str):
broadcast_text_all(ctx, message, {"type": "Countdown", "countdown": timer}) broadcast_text_all(ctx, message, {"type": "Countdown", "countdown": timer})
def get_players_string(ctx: Context): def get_players_string(ctx: Context):
auth_clients = {(c.team, c.slot) for c in ctx.endpoints if c.auth} auth_clients = {(c.team, c.slot) for c in ctx.endpoints if c.auth}

View File

@ -15,9 +15,6 @@ import typing
from json import loads, dumps from json import loads, dumps
import ModuleUpdate
ModuleUpdate.update()
from Utils import init_logging, messagebox from Utils import init_logging, messagebox
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -135,11 +135,6 @@ class SC2Context(CommonContext):
last_loc_list = None last_loc_list = None
difficulty_override = -1 difficulty_override = -1
mission_id_to_location_ids: typing.Dict[int, typing.List[int]] = {} mission_id_to_location_ids: typing.Dict[int, typing.List[int]] = {}
raw_text_parser: RawJSONtoTextParser
def __init__(self, *args, **kwargs):
super(SC2Context, self).__init__(*args, **kwargs)
self.raw_text_parser = RawJSONtoTextParser(self)
async def server_auth(self, password_requested: bool = False): async def server_auth(self, password_requested: bool = False):
if password_requested and not self.password: if password_requested and not self.password:
@ -164,10 +159,13 @@ class SC2Context(CommonContext):
check_mod_install() check_mod_install()
def on_print_json(self, args: dict): def on_print_json(self, args: dict):
# goes to this world
if "receiving" in args and self.slot_concerns_self(args["receiving"]): if "receiving" in args and self.slot_concerns_self(args["receiving"]):
relevant = True relevant = True
# found in this world
elif "item" in args and self.slot_concerns_self(args["item"].player): elif "item" in args and self.slot_concerns_self(args["item"].player):
relevant = True relevant = True
# not related
else: else:
relevant = False relevant = False