Compare commits
10
Commits
9a3851f802
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ac5630ae9 | ||
|
|
ede991de51 | ||
|
|
eae3f376a7 | ||
|
|
bf6abfb2fa | ||
|
|
710d3ec041 | ||
|
|
51a28417ad | ||
|
|
d9225b9ad0 | ||
|
|
c0a88d5137 | ||
|
|
6d6df751dd | ||
|
|
14516a878f |
No files matched your search
@@ -2,8 +2,8 @@ import json
|
|||||||
|
|
||||||
from websockets.asyncio.server import ServerConnection
|
from websockets.asyncio.server import ServerConnection
|
||||||
|
|
||||||
from autobeerpong.types.raw import MessageRaw_T, ClientRaw_T, PlayerRaw_T
|
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
|
from autobeerpong.types.raw import ClientRaw_T, MessageRaw_T, PlayerRaw_T
|
||||||
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
@@ -37,6 +37,7 @@ class Client:
|
|||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
self.state = ClientState.DISCONNECTED
|
self.state = ClientState.DISCONNECTED
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
|
self.ready = False
|
||||||
|
|
||||||
async def send(self, msg_dict: MessageRaw_T) -> None:
|
async def send(self, msg_dict: MessageRaw_T) -> None:
|
||||||
assert self.websocket is not None
|
assert self.websocket is not None
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
import tomllib
|
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import tomllib
|
||||||
|
|
||||||
CONFIG_FILE = Path(f"{Path(__file__).parent.parent}") / "config.toml"
|
CONFIG_FILE = Path(f"{Path(__file__).parent.parent}") / "config.toml"
|
||||||
|
|
||||||
with open(CONFIG_FILE, "rb") as fp:
|
with open(CONFIG_FILE, "rb") as fp:
|
||||||
config_raw = tomllib.load(fp)
|
config_raw = tomllib.load(fp)
|
||||||
|
|
||||||
SCHEMA_DIR = Path(__file__).parent.parent.parent / "schema"
|
SRC_DIR = Path(__file__).parent.parent.parent
|
||||||
|
CONSTANTS_DIR = SRC_DIR / "constants"
|
||||||
|
SCHEMA_DIR = SRC_DIR / "schema"
|
||||||
SERVER_PORT = int(config_raw["server_port"])
|
SERVER_PORT = int(config_raw["server_port"])
|
||||||
SERVER_HOST = str(config_raw["server_host"])
|
SERVER_HOST = str(config_raw["server_host"])
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
|
from autobeerpong import config
|
||||||
|
|
||||||
|
with open(config.CONSTANTS_DIR / "constants.json", "r") as fp:
|
||||||
|
constants = json.load(fp)
|
||||||
|
|
||||||
|
GRAVITATIONAL_CONSTANT = float(constants["gravitationalConstant"])
|
||||||
|
TABLE_CONFIG_WIDTH = float(constants["tableConfiguration"]["width"])
|
||||||
|
TABLE_CONFIG_HALF_WIDTH = float(TABLE_CONFIG_WIDTH / 2.0)
|
||||||
|
TABLE_CONFIG_HEIGHT = float(constants["tableConfiguration"]["height"])
|
||||||
|
TABLE_CONFIG_THICKNESS = float(constants["tableConfiguration"]["thickness"])
|
||||||
|
TABLE_CONFIG_LEG_OFFSET = float(constants["tableConfiguration"]["legOffset"])
|
||||||
|
TABLE_CONFIG_LET_THICKNESS = float(constants["tableConfiguration"]["legThickness"])
|
||||||
|
CUP_CONFIG_HEIGHT = float(constants["cupConfiguration"]["height"])
|
||||||
|
CUP_CONFIG_WIDTH_RIM = float(constants["cupConfiguration"]["widthRim"])
|
||||||
|
BALL_RADIUS = float(constants["ballRadius"])
|
||||||
|
GROUND_HEIGHT = float(constants["groundHeight"])
|
||||||
|
CHAMPION_DISTANCE_FROM_TABLE = float(constants["championDistanceFromTable"])
|
||||||
|
CHAMPION_GAP = float(constants["championGap"])
|
||||||
|
CUP_OFFSETS = [float(offset) for offset in constants["cupOffsets"]]
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
|
import json
|
||||||
|
|
||||||
from websockets.asyncio.server import ServerConnection
|
from websockets.asyncio.server import ServerConnection
|
||||||
|
|
||||||
|
from autobeerpong.types.raw import MessageRaw_T
|
||||||
|
|
||||||
|
|
||||||
class ClientContext:
|
class ClientContext:
|
||||||
def __init__(self, websocket: ServerConnection) -> None:
|
def __init__(self, websocket: ServerConnection) -> None:
|
||||||
@@ -11,3 +15,6 @@ class ClientContext:
|
|||||||
def get_client_id(self) -> int:
|
def get_client_id(self) -> int:
|
||||||
assert self.client_id is not None
|
assert self.client_id is not None
|
||||||
return self.client_id
|
return self.client_id
|
||||||
|
|
||||||
|
async def send(self, msg_dict: MessageRaw_T) -> None:
|
||||||
|
await self.websocket.send(json.dumps(msg_dict))
|
||||||
@@ -1,10 +1,9 @@
|
|||||||
from itertools import count
|
from itertools import count
|
||||||
|
|
||||||
|
|
||||||
from autobeerpong.states.server import ServerState
|
|
||||||
from autobeerpong.contexts.lobby import LobbyContext
|
|
||||||
from autobeerpong.types.client_map import ClientMap_T
|
|
||||||
from autobeerpong.client import Client
|
from autobeerpong.client import Client
|
||||||
|
from autobeerpong.contexts.lobby import LobbyContext
|
||||||
|
from autobeerpong.states.server import ServerState
|
||||||
|
from autobeerpong.types.client_map import ClientMap_T
|
||||||
|
|
||||||
|
|
||||||
class ServerContext:
|
class ServerContext:
|
||||||
@@ -26,3 +25,6 @@ class ServerContext:
|
|||||||
def get_client(self, client_id: int) -> Client:
|
def get_client(self, client_id: int) -> Client:
|
||||||
assert client_id in self.clients
|
assert client_id in self.clients
|
||||||
return self.clients[client_id]
|
return self.clients[client_id]
|
||||||
|
|
||||||
|
def has_client(self, client_id: int) -> bool:
|
||||||
|
return client_id in self.clients
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
class NoMessageTypeException(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UnknownMessageTypeException(Exception):
|
||||||
|
pass
|
||||||
@@ -1,10 +1,86 @@
|
|||||||
|
import random
|
||||||
|
|
||||||
|
from autobeerpong import constants
|
||||||
from autobeerpong.types.raw import MessageRaw_T
|
from autobeerpong.types.raw import MessageRaw_T
|
||||||
|
|
||||||
|
champions = ["berset", "lucas"]
|
||||||
|
|
||||||
|
|
||||||
|
def randomChampion() -> str:
|
||||||
|
return random.choice(champions)
|
||||||
|
|
||||||
|
|
||||||
|
class Vec2D:
|
||||||
|
def __init__(self, x: float, y: float) -> None:
|
||||||
|
self.x = x
|
||||||
|
self.y = y
|
||||||
|
|
||||||
|
|
||||||
|
class Target(Vec2D):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Cup:
|
||||||
|
def __init__(self, pos: Vec2D) -> None:
|
||||||
|
self.is_hit = False
|
||||||
|
self.pos = pos
|
||||||
|
self.height = constants.CUP_CONFIG_HEIGHT
|
||||||
|
self.width_rim = constants.CUP_CONFIG_WIDTH_RIM
|
||||||
|
|
||||||
|
def __bool__(self) -> bool:
|
||||||
|
return self.is_hit
|
||||||
|
|
||||||
|
def get_hit_target(self) -> Target:
|
||||||
|
return Target(self.pos.x, self.pos.y)
|
||||||
|
|
||||||
|
def get_targets(self) -> list[Target]:
|
||||||
|
if self.is_hit:
|
||||||
|
return [
|
||||||
|
Target(self.pos.x - self.width_rim / 2, self.pos.y),
|
||||||
|
Target(self.pos.x, self.pos.y),
|
||||||
|
Target(self.pos.x + self.width_rim / 2, self.pos.y),
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
return [
|
||||||
|
Target(self.pos.x - self.width_rim / 2, self.pos.y + self.height),
|
||||||
|
Target(self.pos.x + self.width_rim / 2, self.pos.y + self.height),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
class Team:
|
class Team:
|
||||||
def __init__(self) -> None:
|
def __init__(self, opposite: bool = False) -> None:
|
||||||
self.formation = [1, 2, 3]
|
self.formation = [randomChampion(), randomChampion(), randomChampion()]
|
||||||
self.cups = [True, True, True]
|
self.cups: list[Cup] = []
|
||||||
|
|
||||||
|
for cup_index, cup_pos in enumerate(constants.CUP_OFFSETS):
|
||||||
|
x_pos = (
|
||||||
|
constants.TABLE_CONFIG_HALF_WIDTH - cup_pos
|
||||||
|
if opposite
|
||||||
|
else -constants.TABLE_CONFIG_HALF_WIDTH + cup_pos
|
||||||
|
)
|
||||||
|
y_pos = constants.TABLE_CONFIG_HEIGHT
|
||||||
|
|
||||||
|
self.cups.append(Cup(Vec2D(x_pos, y_pos)))
|
||||||
|
|
||||||
|
self.shooter_pos = Vec2D(
|
||||||
|
constants.TABLE_CONFIG_HALF_WIDTH, 2.5 * constants.TABLE_CONFIG_HEIGHT * -1
|
||||||
|
)
|
||||||
|
self.shooting_range_from = 0 if opposite else -constants.TABLE_CONFIG_HALF_WIDTH
|
||||||
|
self.shooting_range_to = constants.TABLE_CONFIG_HALF_WIDTH if opposite else 0
|
||||||
|
|
||||||
|
if not opposite:
|
||||||
|
self.shooter_pos.x *= -1
|
||||||
|
|
||||||
|
def get_active_cups(self) -> list[Cup]:
|
||||||
|
return list(filter(lambda cup: not cup.is_hit, self.cups))
|
||||||
|
|
||||||
|
def get_no_hit_targets(self) -> list[Target]:
|
||||||
|
targets: list[Target] = []
|
||||||
|
|
||||||
|
for cup in self.cups:
|
||||||
|
targets.extend(cup.get_targets())
|
||||||
|
|
||||||
|
return targets
|
||||||
|
|
||||||
def rotate(self) -> None:
|
def rotate(self) -> None:
|
||||||
self.formation.insert(0, self.formation.pop())
|
self.formation.insert(0, self.formation.pop())
|
||||||
@@ -18,52 +94,90 @@ class Match:
|
|||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.turn = True
|
self.turn = True
|
||||||
self.team_a = Team()
|
self.team_a = Team()
|
||||||
self.team_b = Team()
|
self.team_b = Team(opposite=True)
|
||||||
self.history: list[MessageRaw_T] = []
|
self.history: list[MessageRaw_T] = []
|
||||||
|
|
||||||
def get_table_state(self) -> MessageRaw_T:
|
def get_table_state(self) -> MessageRaw_T:
|
||||||
return {
|
return {
|
||||||
"cupsA": self.team_a.cups.copy(),
|
"cupsA": [not cup.is_hit for cup in self.team_a.cups],
|
||||||
"cupsB": self.team_b.cups.copy(),
|
"cupsB": [not cup.is_hit for cup in self.team_b.cups],
|
||||||
"teamA": self.team_a.formation.copy(),
|
"teamA": self.team_a.formation.copy(),
|
||||||
"teamB": self.team_b.formation.copy(),
|
"teamB": self.team_b.formation.copy(),
|
||||||
}
|
}
|
||||||
|
|
||||||
def get_action(self) -> MessageRaw_T:
|
def calculate_relative_end_position(
|
||||||
turn = "a" if self.turn else "b"
|
self, start_pos: Vec2D, end_pos: Vec2D
|
||||||
x_pos = -150 if self.turn else 150
|
) -> Vec2D:
|
||||||
x_vel = 250 if self.turn else -250
|
return Vec2D(
|
||||||
|
abs(start_pos.x - end_pos.x),
|
||||||
|
-abs(start_pos.y + end_pos.y),
|
||||||
|
)
|
||||||
|
|
||||||
# determine if hit
|
def calculate_relative_start_velocity(
|
||||||
# is_hit = True if random.random() >= 0.5 else False
|
self, r_end_pos: Vec2D, stop_time: float
|
||||||
|
) -> Vec2D:
|
||||||
|
r_vel_x = r_end_pos.x / stop_time
|
||||||
|
|
||||||
return {
|
if not self.turn:
|
||||||
"turn": turn,
|
r_vel_x *= -1
|
||||||
"parabola": {
|
|
||||||
"startPosition": [x_pos, -200],
|
|
||||||
"startVelocity": [x_vel, -300],
|
|
||||||
"stopTime": 900,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
def match_not_over(self) -> bool:
|
r_vel_y = (
|
||||||
return any(self.team_a.cups) and any(self.team_b.cups)
|
r_end_pos.y / stop_time + constants.GRAVITATIONAL_CONSTANT * stop_time * 0.5
|
||||||
|
)
|
||||||
|
|
||||||
|
return Vec2D(r_vel_x, -r_vel_y)
|
||||||
|
|
||||||
|
def get_actions(self, active_team: Team, opposite_team: Team) -> list[MessageRaw_T]:
|
||||||
|
actions: list[MessageRaw_T] = []
|
||||||
|
|
||||||
|
# stupidity_factor = -1
|
||||||
|
start_pos = active_team.shooter_pos
|
||||||
|
|
||||||
|
# determine if hit or not
|
||||||
|
is_hit = random.random() < 0.5
|
||||||
|
|
||||||
|
if is_hit:
|
||||||
|
cup = random.choice(opposite_team.get_active_cups())
|
||||||
|
target = cup.get_hit_target()
|
||||||
|
|
||||||
|
cup.is_hit = True
|
||||||
|
|
||||||
|
else:
|
||||||
|
target = random.choice(opposite_team.get_no_hit_targets())
|
||||||
|
|
||||||
|
r_end_pos = self.calculate_relative_end_position(start_pos, target)
|
||||||
|
stop_time = r_end_pos.x - 1.0
|
||||||
|
r_start_vel = self.calculate_relative_start_velocity(r_end_pos, stop_time)
|
||||||
|
|
||||||
|
actions.append(
|
||||||
|
{
|
||||||
|
"turn": "a" if self.turn else "b",
|
||||||
|
"parabola": {
|
||||||
|
"startPosition": [
|
||||||
|
start_pos.x,
|
||||||
|
start_pos.y,
|
||||||
|
],
|
||||||
|
"startVelocity": [r_start_vel.x, r_start_vel.y],
|
||||||
|
"stopTime": stop_time,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return actions
|
||||||
|
|
||||||
|
def match_over(self) -> bool:
|
||||||
|
return all(self.team_a.cups) or all(self.team_b.cups)
|
||||||
|
|
||||||
def resolve(self) -> None:
|
def resolve(self) -> None:
|
||||||
# first send table state
|
# first send table state
|
||||||
self.history.append(self.get_table_state())
|
self.history.append(self.get_table_state())
|
||||||
|
|
||||||
while self.match_not_over():
|
while not self.match_over():
|
||||||
# action
|
# action
|
||||||
active_team = self.team_a if self.turn else self.team_b
|
active_team = self.team_a if self.turn else self.team_b
|
||||||
other_team = self.team_a if not self.turn else self.team_b
|
opposite_team = self.team_a if not self.turn else self.team_b
|
||||||
|
|
||||||
self.history.append(self.get_action())
|
self.history.extend(self.get_actions(active_team, opposite_team))
|
||||||
|
|
||||||
for i in range(len(other_team.cups)):
|
|
||||||
if other_team.cups[i]:
|
|
||||||
other_team.cups[i] = False
|
|
||||||
break
|
|
||||||
|
|
||||||
active_team.rotate()
|
active_team.rotate()
|
||||||
# table state
|
# table state
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from autobeerpong.contexts.client import ClientContext
|
||||||
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.messages.lobby.can_rejoin_response import CanRejoinResponseMessage
|
||||||
|
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||||
|
from autobeerpong.states.client import ClientState
|
||||||
|
|
||||||
|
|
||||||
|
class CanRejoinMessage(Message):
|
||||||
|
has_direct_response = True
|
||||||
|
triggers_broadcast = False
|
||||||
|
|
||||||
|
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||||
|
self.id = int(message_raw["messageContent"]["id"])
|
||||||
|
|
||||||
|
def to_raw(self) -> MessageRaw_T:
|
||||||
|
msg_raw = super().to_raw()
|
||||||
|
msg_raw["messageContent"].update({"id": self.id})
|
||||||
|
|
||||||
|
self.validate(msg_raw)
|
||||||
|
|
||||||
|
return msg_raw
|
||||||
|
|
||||||
|
async def execute(
|
||||||
|
self, server_context: ServerContext, client_context: ClientContext
|
||||||
|
) -> None:
|
||||||
|
assert client_context.has_joined is False
|
||||||
|
|
||||||
|
canRejoin = self._canRejoin(server_context)
|
||||||
|
|
||||||
|
can_rejoin_response_raw = CanRejoinResponseMessage(
|
||||||
|
{
|
||||||
|
"messageType": "canRejoinResponse",
|
||||||
|
"messageContent": {"canRejoin": canRejoin},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
await client_context.send(can_rejoin_response_raw.to_raw())
|
||||||
|
|
||||||
|
def _canRejoin(self, server_context: ServerContext) -> bool:
|
||||||
|
client_exists = server_context.has_client(self.id)
|
||||||
|
|
||||||
|
if not client_exists:
|
||||||
|
return False
|
||||||
|
|
||||||
|
client = server_context.get_client(self.id)
|
||||||
|
return client.state is ClientState.DISCONNECTED
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from autobeerpong.messages.message import Message
|
||||||
|
from autobeerpong.types.raw import ClientRaw_T, MessageRaw_T
|
||||||
|
|
||||||
|
|
||||||
|
class CanRejoinResponseMessage(Message):
|
||||||
|
has_direct_response = False
|
||||||
|
|
||||||
|
def _contents_from_raw(self, message_raw: MessageRaw_T):
|
||||||
|
self.can_rejoin: ClientRaw_T = message_raw["messageContent"]["canRejoin"]
|
||||||
|
|
||||||
|
def to_raw(self) -> MessageRaw_T:
|
||||||
|
msg_raw = super().to_raw()
|
||||||
|
msg_raw["messageContent"].update({"canRejoin": self.can_rejoin})
|
||||||
|
|
||||||
|
self.validate(msg_raw)
|
||||||
|
|
||||||
|
return msg_raw
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
from autobeerpong.messages.message import Message
|
|
||||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
|
||||||
from autobeerpong.types.raw import MessageRaw_T
|
|
||||||
from autobeerpong.client import Client
|
from autobeerpong.client import Client
|
||||||
from autobeerpong.contexts.server import ServerContext
|
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.contexts.client import ClientContext
|
||||||
from autobeerpong.states.server import ServerState
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||||
|
from autobeerpong.messages.message import Message
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
|
from autobeerpong.states.server import ServerState
|
||||||
|
from autobeerpong.types.raw import MessageRaw_T
|
||||||
|
|
||||||
|
|
||||||
class JoinMessage(Message):
|
class JoinMessage(Message):
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from autobeerpong.messages.message import Message
|
from autobeerpong.messages.message import Message
|
||||||
from autobeerpong.types.raw import MessageRaw_T, ClientRaw_T
|
from autobeerpong.types.raw import ClientRaw_T, MessageRaw_T
|
||||||
|
|
||||||
|
|
||||||
class JoinResponseMessage(Message):
|
class JoinResponseMessage(Message):
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
|
||||||
from autobeerpong.contexts.server import ServerContext
|
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.contexts.client import ClientContext
|
||||||
from autobeerpong.states.server import ServerState
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
|
|
||||||
|
|
||||||
@@ -23,9 +22,14 @@ class RejoinMessage(Message):
|
|||||||
self, server_context: ServerContext, client_context: ClientContext
|
self, server_context: ServerContext, client_context: ClientContext
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|
||||||
assert server_context.state is ServerState.LOBBY
|
|
||||||
assert client_context.has_joined is False
|
assert client_context.has_joined is False
|
||||||
|
|
||||||
|
if not server_context.has_client(self.id):
|
||||||
|
print(
|
||||||
|
f"A client wanted to rejoin with id {self.id}, but no matching id found in disconnected clients."
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
client = server_context.get_client(self.id)
|
client = server_context.get_client(self.id)
|
||||||
client.websocket = client_context.websocket
|
client.websocket = client_context.websocket
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
|
||||||
from autobeerpong.contexts.server import ServerContext
|
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.contexts.client import ClientContext
|
||||||
from autobeerpong.states.server import ServerState
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
|
from autobeerpong.states.server import ServerState
|
||||||
|
|
||||||
|
|
||||||
class ToggleReadyMessage(Message):
|
class ToggleReadyMessage(Message):
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
|
||||||
from autobeerpong.contexts.server import ServerContext
|
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.contexts.client import ClientContext
|
||||||
from autobeerpong.states.server import ServerState
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
|
from autobeerpong.states.server import ServerState
|
||||||
|
|
||||||
|
|
||||||
class ToggleRoleMessage(Message):
|
class ToggleRoleMessage(Message):
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import jsonschema
|
import jsonschema
|
||||||
import jsonschema.protocols
|
import jsonschema.protocols
|
||||||
|
|
||||||
from pathlib import Path
|
|
||||||
from referencing import Registry, Resource
|
from referencing import Registry, Resource
|
||||||
from referencing.jsonschema import DRAFT202012
|
from referencing.jsonschema import DRAFT202012
|
||||||
|
|
||||||
import autobeerpong.config as config
|
from autobeerpong import config
|
||||||
from autobeerpong.contexts.server import ServerContext
|
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.contexts.client import ClientContext
|
||||||
|
from autobeerpong.contexts.server import ServerContext
|
||||||
from autobeerpong.types.raw import MessageRaw_T
|
from autobeerpong.types.raw import MessageRaw_T
|
||||||
|
|
||||||
|
|
||||||
@@ -24,6 +24,7 @@ def _retrieve_from_filesystem(uri: str):
|
|||||||
|
|
||||||
class Message:
|
class Message:
|
||||||
has_direct_response = False
|
has_direct_response = False
|
||||||
|
triggers_broadcast = True
|
||||||
registry = Registry(retrieve=_retrieve_from_filesystem)
|
registry = Registry(retrieve=_retrieve_from_filesystem)
|
||||||
validator: jsonschema.protocols.Validator = jsonschema.Draft202012Validator(
|
validator: jsonschema.protocols.Validator = jsonschema.Draft202012Validator(
|
||||||
json.loads((config.SCHEMA_DIR / Path("message.json")).read_text()),
|
json.loads((config.SCHEMA_DIR / Path("message.json")).read_text()),
|
||||||
|
|||||||
@@ -1,32 +1,39 @@
|
|||||||
import json
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import json
|
||||||
|
from typing import ClassVar
|
||||||
|
|
||||||
|
from websockets import Data
|
||||||
from websockets.asyncio.server import ServerConnection, serve
|
from websockets.asyncio.server import ServerConnection, serve
|
||||||
from websockets.exceptions import ConnectionClosedOK
|
from websockets.exceptions import ConnectionClosedOK
|
||||||
|
|
||||||
import autobeerpong.config as config
|
from autobeerpong import config
|
||||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
from autobeerpong.contexts.client import ClientContext
|
||||||
|
from autobeerpong.contexts.server import ServerContext
|
||||||
|
from autobeerpong.exceptions import NoMessageTypeException, UnknownMessageTypeException
|
||||||
|
from autobeerpong.match import Match
|
||||||
|
from autobeerpong.messages.lobby.can_rejoin import CanRejoinMessage
|
||||||
|
from autobeerpong.messages.lobby.can_rejoin_response import CanRejoinResponseMessage
|
||||||
from autobeerpong.messages.lobby.join import JoinMessage
|
from autobeerpong.messages.lobby.join import JoinMessage
|
||||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||||
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
||||||
|
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
||||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||||
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
||||||
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
|
||||||
from autobeerpong.messages.match.start_match import StartMatchMessage
|
|
||||||
from autobeerpong.messages.match.match_state import MatchStateMessage
|
from autobeerpong.messages.match.match_state import MatchStateMessage
|
||||||
from autobeerpong.contexts.server import ServerContext
|
from autobeerpong.messages.match.start_match import StartMatchMessage
|
||||||
from autobeerpong.contexts.client import ClientContext
|
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||||
from autobeerpong.states.client import ClientState
|
from autobeerpong.states.client import ClientState
|
||||||
from autobeerpong.states.server import ServerState
|
from autobeerpong.states.server import ServerState
|
||||||
from autobeerpong.match import Match
|
|
||||||
|
|
||||||
|
|
||||||
class AutobeerpongServer:
|
class AutobeerpongServer:
|
||||||
message_map: dict[str, type[Message]] = {
|
message_map: ClassVar[dict[str, type[Message]]] = {
|
||||||
# LOBBY
|
# LOBBY
|
||||||
"join": JoinMessage,
|
"join": JoinMessage,
|
||||||
"joinResponse": JoinResponseMessage,
|
"joinResponse": JoinResponseMessage,
|
||||||
"rejoin": RejoinMessage,
|
"rejoin": RejoinMessage,
|
||||||
|
"canRejoin": CanRejoinMessage,
|
||||||
|
"canRejoinResponse": CanRejoinResponseMessage,
|
||||||
"toggleReady": ToggleReadyMessage,
|
"toggleReady": ToggleReadyMessage,
|
||||||
"toggleRole": ToggleRoleMessage,
|
"toggleRole": ToggleRoleMessage,
|
||||||
"lobbyState": LobbyStateMessage,
|
"lobbyState": LobbyStateMessage,
|
||||||
@@ -50,7 +57,8 @@ class AutobeerpongServer:
|
|||||||
await client.send(msg_raw)
|
await client.send(msg_raw)
|
||||||
|
|
||||||
async def update_server_state(self) -> None:
|
async def update_server_state(self) -> None:
|
||||||
if self.context.state is ServerState.LOBBY:
|
state = self.context.state
|
||||||
|
if state is ServerState.LOBBY:
|
||||||
players = list(
|
players = list(
|
||||||
filter(
|
filter(
|
||||||
lambda x: x.state is ClientState.PLAYER,
|
lambda x: x.state is ClientState.PLAYER,
|
||||||
@@ -58,25 +66,17 @@ class AutobeerpongServer:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
if all([player.ready for player in players]):
|
if self.context.lobby.is_players_full() and all(
|
||||||
|
player.ready for player in players
|
||||||
|
):
|
||||||
# all players are ready, advance server state to match
|
# all players are ready, advance server state to match
|
||||||
self.context.state = ServerState.MATCH
|
await self.transition_to_match()
|
||||||
# send match start message to all connected clients
|
|
||||||
start_match = StartMatchMessage(
|
|
||||||
{"messageType": "startMatch", "messageContent": {}}
|
|
||||||
)
|
|
||||||
|
|
||||||
await self.broadcast(start_match.to_raw())
|
elif state is ServerState.MATCH:
|
||||||
|
if not self.context.lobby.is_players_full():
|
||||||
|
await self.transition_to_lobby()
|
||||||
|
|
||||||
match = Match()
|
async def broadcast_lobby_state(self):
|
||||||
match.resolve()
|
|
||||||
|
|
||||||
await self.broadcast(match.to_raw())
|
|
||||||
|
|
||||||
elif self.context.state is ServerState.MATCH:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def get_lobby_state(self) -> LobbyStateMessage:
|
|
||||||
players = list(
|
players = list(
|
||||||
filter(
|
filter(
|
||||||
lambda x: x.state is ClientState.PLAYER,
|
lambda x: x.state is ClientState.PLAYER,
|
||||||
@@ -90,7 +90,7 @@ class AutobeerpongServer:
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
return LobbyStateMessage(
|
lobby_message = LobbyStateMessage(
|
||||||
{
|
{
|
||||||
"messageType": "lobbyState",
|
"messageType": "lobbyState",
|
||||||
"messageContent": {
|
"messageContent": {
|
||||||
@@ -100,37 +100,71 @@ class AutobeerpongServer:
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
await self.broadcast(lobby_message.to_raw())
|
||||||
|
|
||||||
|
async def transition_to_match(self):
|
||||||
|
self.context.state = ServerState.MATCH
|
||||||
|
# send match start message to all connected clients
|
||||||
|
start_match = StartMatchMessage(
|
||||||
|
{"messageType": "startMatch", "messageContent": {}}
|
||||||
|
)
|
||||||
|
|
||||||
|
await self.broadcast(start_match.to_raw())
|
||||||
|
|
||||||
|
match = Match()
|
||||||
|
match.resolve()
|
||||||
|
|
||||||
|
await self.broadcast(match.to_raw())
|
||||||
|
|
||||||
|
async def transition_to_lobby(self):
|
||||||
|
self.context.state = ServerState.LOBBY
|
||||||
|
players = filter(
|
||||||
|
lambda x: x.state is ClientState.PLAYER,
|
||||||
|
self.context.lobby._clients.values(),
|
||||||
|
)
|
||||||
|
for player in players:
|
||||||
|
player.ready = False
|
||||||
|
|
||||||
|
await self.broadcast_lobby_state()
|
||||||
|
|
||||||
async def handler(self, websocket: ServerConnection) -> None:
|
async def handler(self, websocket: ServerConnection) -> None:
|
||||||
client_context = ClientContext(websocket)
|
client_context = ClientContext(websocket)
|
||||||
|
|
||||||
async for msg in websocket:
|
async for msg in websocket:
|
||||||
message_raw: MessageRaw_T = json.loads(msg)
|
message = self.to_message(msg)
|
||||||
message_type = str(message_raw.get("messageType"))
|
|
||||||
|
|
||||||
if message_type is None:
|
|
||||||
raise Exception("Message has no messageType property.")
|
|
||||||
|
|
||||||
MessageClass = self.message_map.get(message_type)
|
|
||||||
|
|
||||||
if MessageClass is None:
|
|
||||||
raise Exception(f"Unknown messageType: {message_type}.")
|
|
||||||
|
|
||||||
message = MessageClass(message_raw)
|
|
||||||
|
|
||||||
await message.execute(
|
await message.execute(
|
||||||
server_context=self.context,
|
server_context=self.context,
|
||||||
client_context=client_context,
|
client_context=client_context,
|
||||||
)
|
)
|
||||||
|
|
||||||
await self.broadcast(self.get_lobby_state().to_raw())
|
if message.triggers_broadcast:
|
||||||
|
await self.broadcast_lobby_state()
|
||||||
|
|
||||||
await self.update_server_state()
|
await self.update_server_state()
|
||||||
|
|
||||||
if client_context.has_joined:
|
if client_context.has_joined:
|
||||||
self.context.clients[client_context.get_client_id()].disconnect()
|
self.context.clients[client_context.get_client_id()].disconnect()
|
||||||
try:
|
try:
|
||||||
await self.broadcast(self.get_lobby_state().to_raw())
|
await self.broadcast_lobby_state()
|
||||||
except ConnectionClosedOK:
|
except ConnectionClosedOK:
|
||||||
pass
|
pass
|
||||||
|
finally:
|
||||||
|
await self.update_server_state()
|
||||||
|
|
||||||
|
def to_message(self, data: Data) -> Message:
|
||||||
|
message_raw: MessageRaw_T = json.loads(data)
|
||||||
|
message_type = str(message_raw.get("messageType"))
|
||||||
|
|
||||||
|
if message_type is None:
|
||||||
|
raise NoMessageTypeException("Message has no messageType property.")
|
||||||
|
|
||||||
|
MessageClass = self.message_map.get(message_type)
|
||||||
|
|
||||||
|
if MessageClass is None:
|
||||||
|
raise UnknownMessageTypeException(f"Unknown messageType: {message_type}.")
|
||||||
|
|
||||||
|
return MessageClass(message_raw)
|
||||||
|
|
||||||
async def _start(self) -> None:
|
async def _start(self) -> None:
|
||||||
async with serve(
|
async with serve(
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from unittest import IsolatedAsyncioTestCase
|
|||||||
from autobeerpong.messages.lobby.join import JoinMessage
|
from autobeerpong.messages.lobby.join import JoinMessage
|
||||||
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
from autobeerpong.messages.lobby.join_response import JoinResponseMessage
|
||||||
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
from autobeerpong.messages.lobby.rejoin import RejoinMessage
|
||||||
|
from autobeerpong.messages.lobby.can_rejoin import CanRejoinMessage
|
||||||
|
from autobeerpong.messages.lobby.can_rejoin_response import CanRejoinResponseMessage
|
||||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||||
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
from autobeerpong.messages.lobby.toggle_role import ToggleRoleMessage
|
||||||
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
from autobeerpong.messages.lobby.state import LobbyStateMessage
|
||||||
@@ -299,3 +301,44 @@ class TestLobby(IsolatedAsyncioTestCase):
|
|||||||
|
|
||||||
client_a.shutdown()
|
client_a.shutdown()
|
||||||
client_b.shutdown()
|
client_b.shutdown()
|
||||||
|
|
||||||
|
@manage_server
|
||||||
|
async def test_can_rejoin_true(self):
|
||||||
|
client = TestClient()
|
||||||
|
|
||||||
|
client_responses = await client.send_messages(
|
||||||
|
[JoinMessage({"messageType": "join", "messageContent": {"name": "Ruedi"}})]
|
||||||
|
)
|
||||||
|
join_response = client_responses[0]
|
||||||
|
assert type(join_response) is JoinResponseMessage
|
||||||
|
|
||||||
|
joined_id = join_response.client_raw["id"]
|
||||||
|
|
||||||
|
client.shutdown()
|
||||||
|
|
||||||
|
restarted_client = TestClient()
|
||||||
|
restarted_client_responses = await restarted_client.send_messages(
|
||||||
|
[CanRejoinMessage({"messageType": "canRejoin", "messageContent": {"id": joined_id}})]
|
||||||
|
)
|
||||||
|
|
||||||
|
can_rejoin_response = restarted_client_responses[0]
|
||||||
|
assert type(can_rejoin_response) is CanRejoinResponseMessage
|
||||||
|
self.assertTrue(can_rejoin_response.can_rejoin)
|
||||||
|
|
||||||
|
restarted_client.shutdown();
|
||||||
|
|
||||||
|
@manage_server
|
||||||
|
async def test_can_rejoin_false(self):
|
||||||
|
client = TestClient()
|
||||||
|
cannot_rejoin_responses = await client.send_messages(
|
||||||
|
[CanRejoinMessage({"messageType": "canRejoin", "messageContent": {"id": 0}})]
|
||||||
|
)
|
||||||
|
|
||||||
|
cannot_rejoin_response = cannot_rejoin_responses[-1]
|
||||||
|
print(cannot_rejoin_response)
|
||||||
|
assert type(cannot_rejoin_response) is CanRejoinResponseMessage
|
||||||
|
self.assertFalse(cannot_rejoin_response.can_rejoin)
|
||||||
|
|
||||||
|
client.shutdown()
|
||||||
|
|
||||||
|
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
from unittest import IsolatedAsyncioTestCase
|
from unittest import IsolatedAsyncioTestCase
|
||||||
|
|
||||||
from autobeerpong.messages.message import Message
|
|
||||||
from autobeerpong.messages.lobby.join import JoinMessage
|
from autobeerpong.messages.lobby.join import JoinMessage
|
||||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||||
from tests.utils.server import manage_server
|
from autobeerpong.messages.message import Message
|
||||||
|
|
||||||
from tests.utils.client import TestClient
|
from tests.utils.client import TestClient
|
||||||
from tests.utils.manager import TestClientManager
|
from tests.utils.manager import TestClientManager
|
||||||
|
from tests.utils.server import manage_server
|
||||||
|
|
||||||
|
|
||||||
def get_two_players_join_and_ready(
|
def get_two_players_join_and_ready(
|
||||||
|
|||||||
@@ -71,10 +71,7 @@ class TestClient:
|
|||||||
for message in messages:
|
for message in messages:
|
||||||
await self.send_message(message)
|
await self.send_message(message)
|
||||||
|
|
||||||
if message.has_direct_response:
|
num_responses = (1 if message.has_direct_response else 0) + (1 if message.triggers_broadcast else 0)
|
||||||
num_responses = 2
|
|
||||||
else:
|
|
||||||
num_responses = 1
|
|
||||||
|
|
||||||
for _ in range(num_responses):
|
for _ in range(num_responses):
|
||||||
responses.append(await self.get_response())
|
responses.append(await self.get_response())
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"gravitationalConstant": 9.81,
|
||||||
|
"tableConfiguration": {
|
||||||
|
"width": 2.44,
|
||||||
|
"height": 0.7,
|
||||||
|
"thickness": 0.15,
|
||||||
|
"legOffset": 0.15,
|
||||||
|
"legThickness": 0.15
|
||||||
|
},
|
||||||
|
"cupConfiguration" : {
|
||||||
|
"height": 0.2,
|
||||||
|
"widthRim": 0.18
|
||||||
|
},
|
||||||
|
"ballRadius": 0.05,
|
||||||
|
"groundHeight": 0.0,
|
||||||
|
"championDistanceFromTable": 0.5,
|
||||||
|
"championGap": 0.8,
|
||||||
|
"cupOffsets": [0.54, 0.32, 0.1]
|
||||||
|
}
|
||||||
@@ -10,7 +10,12 @@ import { MatchState } from "./MatchState";
|
|||||||
import { BaseSocket, MessageEvent } from "./sockets/BaseSocket";
|
import { BaseSocket, MessageEvent } from "./sockets/BaseSocket";
|
||||||
import { Socket } from "./sockets/Socket";
|
import { Socket } from "./sockets/Socket";
|
||||||
|
|
||||||
type MessageType = "join" | "rejoin" | "toggleRole" | "toggleReady";
|
type MessageType =
|
||||||
|
| "join"
|
||||||
|
| "rejoin"
|
||||||
|
| "canRejoin"
|
||||||
|
| "toggleRole"
|
||||||
|
| "toggleReady";
|
||||||
|
|
||||||
interface Request {
|
interface Request {
|
||||||
messageType: MessageType;
|
messageType: MessageType;
|
||||||
@@ -30,6 +35,13 @@ interface RejoinRequest {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CanRejoinRequest {
|
||||||
|
messageType: "canRejoin";
|
||||||
|
messageContent: {
|
||||||
|
id: Id;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface ToggleRoleRequest {
|
interface ToggleRoleRequest {
|
||||||
messageType: "toggleRole";
|
messageType: "toggleRole";
|
||||||
messageContent: Record<string, never>;
|
messageContent: Record<string, never>;
|
||||||
@@ -75,12 +87,17 @@ export class Connection extends Evented<typeof ConnectionEvents> {
|
|||||||
private _wasConnected = false;
|
private _wasConnected = false;
|
||||||
|
|
||||||
private _waitForJoin = false;
|
private _waitForJoin = false;
|
||||||
|
private _joined = false;
|
||||||
private _client: Client | null = null;
|
private _client: Client | null = null;
|
||||||
|
|
||||||
get connected(): boolean {
|
get connected(): boolean {
|
||||||
return this._socket?.connected ?? false;
|
return this._socket?.connected ?? false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
get joined(): boolean {
|
||||||
|
return this._joined;
|
||||||
|
}
|
||||||
|
|
||||||
connect(mock?: BaseSocket): void {
|
connect(mock?: BaseSocket): void {
|
||||||
this._socket?.offAll();
|
this._socket?.offAll();
|
||||||
this._socket = mock ?? new Socket();
|
this._socket = mock ?? new Socket();
|
||||||
@@ -97,7 +114,7 @@ export class Connection extends Evented<typeof ConnectionEvents> {
|
|||||||
// TODO: Print error if not valid json.
|
// TODO: Print error if not valid json.
|
||||||
const messageObject = JSON.parse(message.json);
|
const messageObject = JSON.parse(message.json);
|
||||||
|
|
||||||
if (this._waitForJoin) {
|
if (this._waitForJoin && messageObject.messageType === "joinResponse") {
|
||||||
const client = messageObject.messageContent.client;
|
const client = messageObject.messageContent.client;
|
||||||
if (!validateClientSchema(client)) {
|
if (!validateClientSchema(client)) {
|
||||||
return;
|
return;
|
||||||
@@ -107,6 +124,7 @@ export class Connection extends Evented<typeof ConnectionEvents> {
|
|||||||
storeClient(this._client);
|
storeClient(this._client);
|
||||||
|
|
||||||
this._waitForJoin = false;
|
this._waitForJoin = false;
|
||||||
|
this._joined = true;
|
||||||
this.emit("joined", new JoinedEvent());
|
this.emit("joined", new JoinedEvent());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -146,6 +164,8 @@ export class Connection extends Evented<typeof ConnectionEvents> {
|
|||||||
private _onDisconnect(): void {
|
private _onDisconnect(): void {
|
||||||
log("Connection", "disconnected");
|
log("Connection", "disconnected");
|
||||||
|
|
||||||
|
this._joined = false;
|
||||||
|
|
||||||
// The socket close event is also invoked when a connection attempt fails.
|
// The socket close event is also invoked when a connection attempt fails.
|
||||||
// Only emit the disconnect event when we actually had a connection.
|
// Only emit the disconnect event when we actually had a connection.
|
||||||
if (this._wasConnected) {
|
if (this._wasConnected) {
|
||||||
@@ -193,6 +213,32 @@ export class Connection extends Evented<typeof ConnectionEvents> {
|
|||||||
this._send(rejoinRequest);
|
this._send(rejoinRequest);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
canRejoin(id: Id): Promise<boolean> {
|
||||||
|
const canRejoinRequest = {
|
||||||
|
messageType: "canRejoin",
|
||||||
|
messageContent: { id },
|
||||||
|
} as CanRejoinRequest;
|
||||||
|
|
||||||
|
this._waitForJoin = true;
|
||||||
|
this._send(canRejoinRequest);
|
||||||
|
|
||||||
|
let resolver: (canRejoin: boolean) => void;
|
||||||
|
const promise = new Promise<boolean>((resolve) => {
|
||||||
|
resolver = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const handler = (message: MessageEvent) => {
|
||||||
|
const messageObject = JSON.parse(message.json);
|
||||||
|
if (messageObject.messageType === "canRejoinResponse") {
|
||||||
|
resolver(messageObject.messageContent.canRejoin);
|
||||||
|
this._socket?.off("message", handler);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
this._socket?.on("message", handler);
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
}
|
||||||
|
|
||||||
toggleRole(): void {
|
toggleRole(): void {
|
||||||
const toggleRoleRequest = {
|
const toggleRoleRequest = {
|
||||||
messageType: "toggleRole",
|
messageType: "toggleRole",
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export class Ball extends BaseActor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onInitialize(engine: Engine): void {
|
onInitialize(engine: Engine): void {
|
||||||
|
this.z = -1; // Place the ball behind other actors.
|
||||||
const { configuration } = this;
|
const { configuration } = this;
|
||||||
const { radius } = configuration;
|
const { radius } = configuration;
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { Clock } from "../Timers/Clock";
|
|||||||
export class BaseActor extends Actor {
|
export class BaseActor extends Actor {
|
||||||
private _clocks: Clock[] = [];
|
private _clocks: Clock[] = [];
|
||||||
|
|
||||||
override update(engine: Engine, elapsed: number): void {
|
override update(engine: Engine, elapsedMS: number): void {
|
||||||
super.update(engine, elapsed);
|
super.update(engine, elapsedMS);
|
||||||
this._clocks.forEach((clock) => clock.update(elapsed));
|
this._clocks.forEach((clock) => clock.update(elapsedMS));
|
||||||
}
|
}
|
||||||
|
|
||||||
protected addClock(timer: Clock): void {
|
protected addClock(timer: Clock): void {
|
||||||
|
|||||||
@@ -4,15 +4,16 @@ import { randomInteger } from "../utils/randomUtils";
|
|||||||
import { getImage } from "../imageLoader";
|
import { getImage } from "../imageLoader";
|
||||||
import { Clock } from "../Timers/Clock";
|
import { Clock } from "../Timers/Clock";
|
||||||
import { BaseActor } from "./BaseActor";
|
import { BaseActor } from "./BaseActor";
|
||||||
import { ChampionName, champions } from "./champions";
|
import { champions } from "./champions";
|
||||||
|
import { ChampionId } from "../jsonTypes";
|
||||||
|
|
||||||
type Facing = "left" | "right";
|
type Facing = "left" | "right";
|
||||||
|
|
||||||
export class Champion extends BaseActor {
|
export class Champion extends BaseActor {
|
||||||
facing: Facing;
|
facing: Facing;
|
||||||
championName: ChampionName;
|
championName: ChampionId;
|
||||||
|
|
||||||
constructor(actorArgs: ActorArgs, facing: Facing, name: ChampionName) {
|
constructor(actorArgs: ActorArgs, facing: Facing, name: ChampionId) {
|
||||||
super(actorArgs);
|
super(actorArgs);
|
||||||
this.facing = facing;
|
this.facing = facing;
|
||||||
this.championName = name;
|
this.championName = name;
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import { Vector, clamp } from "excalibur";
|
import { Vector, clamp } from "excalibur";
|
||||||
import { Parabola as ParabolaJSON } from "../jsonTypes";
|
import { Parabola as ParabolaJSON } from "../jsonTypes";
|
||||||
import { gravitationalConstant } from "../configs/physicsConstant";
|
import {
|
||||||
|
gravitationalConstant,
|
||||||
|
pixelsPerMeter,
|
||||||
|
} from "../configs/physicsConstant";
|
||||||
|
|
||||||
export class Parabola {
|
export class Parabola {
|
||||||
constructor(
|
constructor(
|
||||||
@@ -16,14 +19,19 @@ export class Parabola {
|
|||||||
stopTime,
|
stopTime,
|
||||||
} = parabolaJSON;
|
} = parabolaJSON;
|
||||||
|
|
||||||
const startPosition = new Vector(start[0], start[1]);
|
const startPosition = new Vector(
|
||||||
const startVelocity = new Vector(velocity[0], velocity[1]);
|
start[0] * pixelsPerMeter,
|
||||||
|
start[1] * pixelsPerMeter,
|
||||||
|
);
|
||||||
|
const startVelocity = new Vector(
|
||||||
|
velocity[0] * pixelsPerMeter,
|
||||||
|
velocity[1] * pixelsPerMeter,
|
||||||
|
);
|
||||||
return new Parabola(startPosition, startVelocity, stopTime);
|
return new Parabola(startPosition, startVelocity, stopTime);
|
||||||
}
|
}
|
||||||
|
|
||||||
position(time: number): Vector {
|
position(timeMS: number): Vector {
|
||||||
const timeSeconds = clamp(time / 1000, 0, this.stopTime ?? Infinity);
|
const timeSeconds = clamp(timeMS / 1000, 0, this.stopTime ?? Infinity);
|
||||||
|
|
||||||
const x = this.startPos.x + this.startVelocity.x * timeSeconds;
|
const x = this.startPos.x + this.startVelocity.x * timeSeconds;
|
||||||
const y =
|
const y =
|
||||||
this.startVelocity.y * timeSeconds +
|
this.startVelocity.y * timeSeconds +
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
export type ChampionName = "lucas" | "berset";
|
import { ChampionId } from "../jsonTypes";
|
||||||
|
|
||||||
export interface ChampionConfig {
|
export interface ChampionConfig {
|
||||||
name: ChampionName;
|
name: ChampionId;
|
||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@ const berset: ChampionConfig = {
|
|||||||
height: 1.5,
|
height: 1.5,
|
||||||
};
|
};
|
||||||
|
|
||||||
export const champions: Record<ChampionName, ChampionConfig> = {
|
export const champions: Record<ChampionId, ChampionConfig> = {
|
||||||
lucas,
|
lucas,
|
||||||
berset,
|
berset,
|
||||||
};
|
};
|
||||||
@@ -4,9 +4,9 @@ import { Clock } from "../Timers/Clock";
|
|||||||
export class BaseScene extends Scene {
|
export class BaseScene extends Scene {
|
||||||
private _clocks = new Array<Clock>();
|
private _clocks = new Array<Clock>();
|
||||||
|
|
||||||
override update(engine: Engine, elapsed: number): void {
|
override update(engine: Engine, elapsedMS: number): void {
|
||||||
super.update(engine, elapsed);
|
super.update(engine, elapsedMS);
|
||||||
this._clocks.forEach((clock) => clock.update(elapsed));
|
this._clocks.forEach((clock) => clock.update(elapsedMS));
|
||||||
}
|
}
|
||||||
|
|
||||||
addClock(clock: Clock): void {
|
addClock(clock: Clock): void {
|
||||||
@@ -14,7 +14,7 @@ export class BaseScene extends Scene {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected updateActorVisibility(actor: Actor, visible: boolean): void {
|
protected updateActorVisibility(actor: Actor, visible: boolean): void {
|
||||||
const previousVisible = this.actors.includes(actor);
|
const previousVisible = actor.isAdded;
|
||||||
|
|
||||||
if (visible && !previousVisible) {
|
if (visible && !previousVisible) {
|
||||||
this.add(actor);
|
this.add(actor);
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
import { Action, Table } from "../jsonTypes";
|
import { Action, Table } from "../jsonTypes";
|
||||||
import { assertNotNull, assertNull } from "../utils/assertUtils";
|
import { assertNotNull, assertNull } from "../utils/assertUtils";
|
||||||
import { colorDistance } from "../utils/colorUtils";
|
import { colorDistance } from "../utils/colorUtils";
|
||||||
import { randomColor, randomInteger } from "../utils/randomUtils";
|
import { randomColor } from "../utils/randomUtils";
|
||||||
import { BaseScene } from "./BaseScene";
|
import { BaseScene } from "./BaseScene";
|
||||||
import { Parabola } from "../GameElements/Parabola";
|
import { Parabola } from "../GameElements/Parabola";
|
||||||
import { Engine, vec, Color } from "excalibur";
|
import { Engine, vec, Color } from "excalibur";
|
||||||
@@ -83,20 +83,6 @@ export class MatchScene extends BaseScene {
|
|||||||
this._cups.push(cup);
|
this._cups.push(cup);
|
||||||
});
|
});
|
||||||
|
|
||||||
championPositions.forEach((offsetX, index) => {
|
|
||||||
const facing = index < 3 ? "right" : "left";
|
|
||||||
const champion = new Champion(
|
|
||||||
{
|
|
||||||
color: randomNonGroundColor(),
|
|
||||||
pos: vec(offsetX, groundHeight),
|
|
||||||
},
|
|
||||||
facing,
|
|
||||||
randomInteger(0, 2) === 0 ? "berset" : "lucas",
|
|
||||||
);
|
|
||||||
this.add(champion);
|
|
||||||
this._champions.push(champion);
|
|
||||||
});
|
|
||||||
|
|
||||||
this._ball = new Ball({}, defaultBallConfiguration);
|
this._ball = new Ball({}, defaultBallConfiguration);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,6 +136,30 @@ export class MatchScene extends BaseScene {
|
|||||||
assertNotNull(cup);
|
assertNotNull(cup);
|
||||||
this.updateActorVisibility(cup, visible);
|
this.updateActorVisibility(cup, visible);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this._updateChampions(table);
|
||||||
|
}
|
||||||
|
|
||||||
|
private _updateChampions(table: Table): void {
|
||||||
|
this._champions.forEach((champion) => this.remove(champion));
|
||||||
|
this._champions = [];
|
||||||
|
|
||||||
|
championPositions.forEach((offsetX, index) => {
|
||||||
|
const facing = index < 3 ? "right" : "left";
|
||||||
|
const championName =
|
||||||
|
index < 3 ? table.teamA[index] : table.teamB[index - 3];
|
||||||
|
|
||||||
|
const champion = new Champion(
|
||||||
|
{
|
||||||
|
color: randomNonGroundColor(),
|
||||||
|
pos: vec(offsetX, groundHeight),
|
||||||
|
},
|
||||||
|
facing,
|
||||||
|
championName,
|
||||||
|
);
|
||||||
|
this.add(champion);
|
||||||
|
this._champions.push(champion);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private _updateFromActionState(action: Action): void {
|
private _updateFromActionState(action: Action): void {
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ export class Button extends ex.ScreenElement {
|
|||||||
onInitialize(_engine: ex.Engine): void {
|
onInitialize(_engine: ex.Engine): void {
|
||||||
const { height, width } = this;
|
const { height, width } = this;
|
||||||
|
|
||||||
|
// Annoying Excalibur bug. It queries the graphics hash grid with worldPos, but ScreenElement transforms
|
||||||
|
// are in screen space. Setting localBounds activates the path that correctly uses screenPos.
|
||||||
|
this.pointer.useGraphicsBounds = false;
|
||||||
|
this.pointer.localBounds = new ex.BoundingBox({
|
||||||
|
left: -width / 2,
|
||||||
|
top: 0,
|
||||||
|
right: width / 2,
|
||||||
|
bottom: height,
|
||||||
|
});
|
||||||
|
|
||||||
this._textElement = new Text({
|
this._textElement = new Text({
|
||||||
text: this._text,
|
text: this._text,
|
||||||
font: paragraphFont,
|
font: paragraphFont,
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import * as ex from "excalibur";
|
import { Color, ScreenElement } from "excalibur";
|
||||||
|
|
||||||
import { spacingS } from "../utils/formattingUtils";
|
import { spacingS } from "../utils/formattingUtils";
|
||||||
import { headingFont, paragraphFont } from "../utils/fontUtil";
|
import { headingFont, paragraphFont } from "../utils/fontUtil";
|
||||||
import { Text } from "./Text";
|
import { Text } from "./Text";
|
||||||
import { Client, getClient, Player, Spectator } from "../jsonTypes";
|
import { Client, getClient, Player, Spectator } from "../jsonTypes";
|
||||||
|
|
||||||
const clientColor = ex.Color.fromHex("40E0D0");
|
const clientColor = Color.fromHex("40E0D0");
|
||||||
|
|
||||||
export class ClientListScreenElement extends ex.ScreenElement {
|
export class ClientListScreenElement extends ScreenElement {
|
||||||
protected _clients: Player[] | Spectator[] = [];
|
protected _clients: Player[] | Spectator[] = [];
|
||||||
protected _client: Client | null = null;
|
protected _client: Client | null = null;
|
||||||
|
|
||||||
@@ -45,48 +45,50 @@ export class ClientListScreenElement extends ex.ScreenElement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected updateList(): void {
|
protected resizePool<T extends ex.Actor>(
|
||||||
this.clearLabelEntities();
|
pool: T[],
|
||||||
|
count: number,
|
||||||
let y = headingFont.size + spacingS;
|
create: () => T,
|
||||||
|
): void {
|
||||||
for (const currentClient of this._clients) {
|
while (pool.length < count) {
|
||||||
const isClient = getClient(currentClient).id === this._client?.id;
|
const entity = create();
|
||||||
const label = this.createLabel(currentClient, y, isClient);
|
this.addChild(entity);
|
||||||
|
pool.push(entity);
|
||||||
y += label.font.size + spacingS;
|
|
||||||
this.addChild(label);
|
|
||||||
this.entities.push(label);
|
|
||||||
}
|
}
|
||||||
|
while (pool.length > count) {
|
||||||
if (this._clients.length === 0) {
|
this.removeChild(pool.pop()!);
|
||||||
const label = new Text({
|
|
||||||
text: "No one cares.",
|
|
||||||
font: paragraphFont,
|
|
||||||
});
|
|
||||||
label.pos = ex.vec(0, y);
|
|
||||||
label.anchor = ex.vec(0.5, 0);
|
|
||||||
this.addChild(label);
|
|
||||||
this.entities.push(label);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected createLabel(
|
protected updateList(): void {
|
||||||
client: Player | Spectator,
|
const clients = this._clients;
|
||||||
y: number,
|
const count = clients.length === 0 ? 1 : clients.length;
|
||||||
isClient: boolean,
|
|
||||||
): Text {
|
|
||||||
const color = isClient ? clientColor : undefined;
|
|
||||||
const { name } = getClient(client);
|
|
||||||
const label = new Text({
|
|
||||||
text: name,
|
|
||||||
font: paragraphFont,
|
|
||||||
color,
|
|
||||||
});
|
|
||||||
label.pos.setTo(0, y);
|
|
||||||
label.anchor.setTo(0.5, 0);
|
|
||||||
|
|
||||||
return label;
|
this.resizePool(this.entities as Text[], count, () => {
|
||||||
|
const label = new Text({ font: paragraphFont });
|
||||||
|
label.anchor.setTo(0.5, 0);
|
||||||
|
return label;
|
||||||
|
});
|
||||||
|
|
||||||
|
let y = headingFont.size + spacingS;
|
||||||
|
|
||||||
|
if (clients.length === 0) {
|
||||||
|
const label = this.entities[0] as Text;
|
||||||
|
label.text = "No one cares.";
|
||||||
|
label.color = Color.White;
|
||||||
|
label.pos.setTo(0, y);
|
||||||
|
} else {
|
||||||
|
for (let i = 0; i < clients.length; i++) {
|
||||||
|
const currentClient = clients[i];
|
||||||
|
const isClient = getClient(currentClient).id === this._client?.id;
|
||||||
|
const label = this.entities[i] as Text;
|
||||||
|
const { name } = getClient(currentClient);
|
||||||
|
label.text = name;
|
||||||
|
label.color = isClient ? clientColor : Color.White;
|
||||||
|
label.pos.setTo(0, y);
|
||||||
|
y += paragraphFont.size + spacingS;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected computeChildrenHeight(numLabels: number): number {
|
protected computeChildrenHeight(numLabels: number): number {
|
||||||
@@ -96,11 +98,4 @@ export class ClientListScreenElement extends ex.ScreenElement {
|
|||||||
Math.max(1, numLabels) * (spacingS + paragraphFont.size)
|
Math.max(1, numLabels) * (spacingS + paragraphFont.size)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected clearLabelEntities(): void {
|
|
||||||
for (const labelEntity of this.entities) {
|
|
||||||
this.removeChild(labelEntity);
|
|
||||||
}
|
|
||||||
this.entities = [];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import * as ex from "excalibur";
|
import * as ex from "excalibur";
|
||||||
import { spacingS } from "../utils/formattingUtils";
|
import { spacingS } from "../utils/formattingUtils";
|
||||||
import { disabledFont } from "../utils/fontUtil";
|
import { disabledFont, paragraphFont } from "../utils/fontUtil";
|
||||||
import { Text } from "./Text";
|
import { Text } from "./Text";
|
||||||
import { Checkbox } from "./Checkbox";
|
import { Checkbox } from "./Checkbox";
|
||||||
import { Player } from "../jsonTypes";
|
import { Player } from "../jsonTypes";
|
||||||
@@ -8,6 +8,9 @@ import { ClientListScreenElement } from "./ClientListScreenElement";
|
|||||||
|
|
||||||
export class PlayerListScreenElement extends ClientListScreenElement {
|
export class PlayerListScreenElement extends ClientListScreenElement {
|
||||||
protected override _clients: Player[] = [];
|
protected override _clients: Player[] = [];
|
||||||
|
private _labelPool: Text[] = [];
|
||||||
|
private _checkboxPool: Checkbox[] = [];
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
headingText: string,
|
headingText: string,
|
||||||
private _maxPlayers: number,
|
private _maxPlayers: number,
|
||||||
@@ -16,40 +19,44 @@ export class PlayerListScreenElement extends ClientListScreenElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected override updateList(): void {
|
protected override updateList(): void {
|
||||||
this.clearLabelEntities();
|
const clients = this._clients.slice(0, this._maxPlayers);
|
||||||
|
|
||||||
|
this.resizePool(this._labelPool, this._maxPlayers, () => {
|
||||||
|
const label = new Text({ font: paragraphFont });
|
||||||
|
label.anchor.setTo(0.5, 0);
|
||||||
|
return label;
|
||||||
|
});
|
||||||
|
|
||||||
|
this.resizePool(
|
||||||
|
this._checkboxPool,
|
||||||
|
clients.length,
|
||||||
|
() => new Checkbox({ checked: false }),
|
||||||
|
);
|
||||||
|
|
||||||
let y = this.heading.font.size + spacingS;
|
let y = this.heading.font.size + spacingS;
|
||||||
|
|
||||||
const clients = this._clients.slice(0, this._maxPlayers);
|
for (let i = 0; i < this._maxPlayers; i++) {
|
||||||
|
const label = this._labelPool[i];
|
||||||
for (const currentClient of clients) {
|
|
||||||
const { name, id } = currentClient.client;
|
|
||||||
const isClient = id === this._client?.id;
|
|
||||||
const label = this.createLabel(currentClient, y, isClient);
|
|
||||||
|
|
||||||
this.addChild(label);
|
|
||||||
this.entities.push(label);
|
|
||||||
|
|
||||||
const ready = new Checkbox({ checked: currentClient.ready });
|
|
||||||
const textWidth = label.font.measureTextWithoutCache(name).width;
|
|
||||||
ready.pos = ex.vec(textWidth / 2 + spacingS, y);
|
|
||||||
this.addChild(ready);
|
|
||||||
|
|
||||||
this.entities.push(ready);
|
|
||||||
|
|
||||||
y += label.font.size + spacingS;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (let i = clients.length; i < this._maxPlayers; i++) {
|
|
||||||
const label = new Text({
|
|
||||||
text: "Empty",
|
|
||||||
font: disabledFont,
|
|
||||||
});
|
|
||||||
label.pos.setTo(0, y);
|
label.pos.setTo(0, y);
|
||||||
label.anchor.setTo(0.5, 0);
|
|
||||||
|
if (i < clients.length) {
|
||||||
|
const { name, id } = clients[i].client;
|
||||||
|
const isClient = id === this._client?.id;
|
||||||
|
label.font = paragraphFont;
|
||||||
|
label.text = name;
|
||||||
|
label.color = isClient ? ex.Color.fromHex("40E0D0") : ex.Color.White;
|
||||||
|
|
||||||
|
const cb = this._checkboxPool[i];
|
||||||
|
const textWidth = label.font.measureTextWithoutCache(name).width;
|
||||||
|
cb.pos.setTo(textWidth / 2 + spacingS, y);
|
||||||
|
cb.checked = clients[i].ready;
|
||||||
|
} else {
|
||||||
|
label.font = disabledFont;
|
||||||
|
label.text = "Empty";
|
||||||
|
label.color = ex.Color.White;
|
||||||
|
}
|
||||||
|
|
||||||
y += label.font.size + spacingS;
|
y += label.font.size + spacingS;
|
||||||
this.addChild(label);
|
|
||||||
this.entities.push(label);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,5 +5,11 @@ type ConstructProperties = ex.LabelOptions & ex.ActorArgs;
|
|||||||
export class Text extends ex.Label {
|
export class Text extends ex.Label {
|
||||||
constructor(options?: ConstructProperties) {
|
constructor(options?: ConstructProperties) {
|
||||||
super(options);
|
super(options);
|
||||||
|
// ex.Label sets this.text before this.font in its constructor, so
|
||||||
|
// _calculateDimension() runs with the default Font instead of options.font.
|
||||||
|
// Re-setting triggers recalculation with the now-correct font.
|
||||||
|
|
||||||
|
// eslint-disable-next-line no-self-assign
|
||||||
|
this.text = this.text;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -12,9 +12,16 @@ type ConstructProperties = ex.ActorArgs & TextInputProperties;
|
|||||||
|
|
||||||
type TextInputEvents = {
|
type TextInputEvents = {
|
||||||
textChanged: TextChangedEvent;
|
textChanged: TextChangedEvent;
|
||||||
|
submitText: TextSubmitEvent;
|
||||||
};
|
};
|
||||||
|
|
||||||
export class TextChangedEvent extends ex.GameEvent<string> {
|
export class TextChangedEvent extends ex.GameEvent<TextInput> {
|
||||||
|
constructor(public text: string) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TextSubmitEvent extends ex.GameEvent<TextInput> {
|
||||||
constructor(public text: string) {
|
constructor(public text: string) {
|
||||||
super();
|
super();
|
||||||
}
|
}
|
||||||
@@ -22,6 +29,7 @@ export class TextChangedEvent extends ex.GameEvent<string> {
|
|||||||
|
|
||||||
export const TextInputEvents = {
|
export const TextInputEvents = {
|
||||||
Textchanged: "textchanged",
|
Textchanged: "textchanged",
|
||||||
|
TextSubmit: "textsubmit",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export class TextInput extends ex.ScreenElement {
|
export class TextInput extends ex.ScreenElement {
|
||||||
@@ -85,8 +93,10 @@ export class TextInput extends ex.ScreenElement {
|
|||||||
engine.currentScene.add(this._cursorTimer);
|
engine.currentScene.add(this._cursorTimer);
|
||||||
this.addChild(this._cursor);
|
this.addChild(this._cursor);
|
||||||
|
|
||||||
this.on("pointerup", () => this._focus());
|
this.on("pointerup", () => this.focus());
|
||||||
engine.input.keyboard.on("press", (e) => this._onKeyPress(e));
|
engine.input.keyboard.on("press", (e) => this._onKeyPress(e));
|
||||||
|
|
||||||
|
this.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
get height(): number {
|
get height(): number {
|
||||||
@@ -121,13 +131,13 @@ export class TextInput extends ex.ScreenElement {
|
|||||||
this._updateCursor();
|
this._updateCursor();
|
||||||
}
|
}
|
||||||
|
|
||||||
private _focus(): void {
|
focus(): void {
|
||||||
this._focused = true;
|
this._focused = true;
|
||||||
this._cursorTimer.start();
|
this._cursorTimer.start();
|
||||||
this._cursor.graphics.isVisible = true;
|
this._cursor.graphics.isVisible = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private _unfocus(): void {
|
unfocus(): void {
|
||||||
this._focused = false;
|
this._focused = false;
|
||||||
this._cursorTimer.stop();
|
this._cursorTimer.stop();
|
||||||
this._cursor.graphics.isVisible = false;
|
this._cursor.graphics.isVisible = false;
|
||||||
@@ -151,11 +161,12 @@ export class TextInput extends ex.ScreenElement {
|
|||||||
const { key } = event;
|
const { key } = event;
|
||||||
|
|
||||||
if (key === ex.Keys.Esc) {
|
if (key === ex.Keys.Esc) {
|
||||||
this._unfocus();
|
this.unfocus();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (key === ex.Keys.Enter) {
|
if (key === ex.Keys.Enter) {
|
||||||
|
this.emit(TextInputEvents.TextSubmit, this.text);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,12 +12,14 @@ export class BallClock extends Clock {
|
|||||||
}
|
}
|
||||||
|
|
||||||
startWithParabola(parabola: Parabola): void {
|
startWithParabola(parabola: Parabola): void {
|
||||||
this.start(parabola.stopTime);
|
if (parabola.stopTime != null) {
|
||||||
|
this.start(parabola.stopTime * 1000);
|
||||||
|
}
|
||||||
this._parabola = parabola;
|
this._parabola = parabola;
|
||||||
}
|
}
|
||||||
|
|
||||||
update(elapsed: number): void {
|
update(elapsedMS: number): void {
|
||||||
super.update(elapsed);
|
super.update(elapsedMS);
|
||||||
|
|
||||||
if (!this.running) {
|
if (!this.running) {
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -15,19 +15,19 @@ export class Clock extends Evented<typeof TimerEvents> {
|
|||||||
|
|
||||||
speedFactor = 1;
|
speedFactor = 1;
|
||||||
|
|
||||||
constructor(duration?: number) {
|
constructor(durationMS?: number) {
|
||||||
super();
|
super();
|
||||||
this._durationMS = duration;
|
this._durationMS = durationMS;
|
||||||
}
|
}
|
||||||
|
|
||||||
get running(): boolean {
|
get running(): boolean {
|
||||||
return this._running;
|
return this._running;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(duration?: number): void {
|
start(durationMS?: number): void {
|
||||||
this.reset();
|
this.reset();
|
||||||
if (duration != null) {
|
if (durationMS != null) {
|
||||||
this._durationMS = duration;
|
this._durationMS = durationMS;
|
||||||
}
|
}
|
||||||
this._running = true;
|
this._running = true;
|
||||||
this.emit("start", {});
|
this.emit("start", {});
|
||||||
@@ -51,12 +51,12 @@ export class Clock extends Evented<typeof TimerEvents> {
|
|||||||
await promise;
|
await promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
async startAndWait(duration?: number): Promise<void> {
|
async startAndWait(durationMS?: number): Promise<void> {
|
||||||
this.start(duration);
|
this.start(durationMS);
|
||||||
await this.whenEnd();
|
await this.whenEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
update(elapsed: number): void {
|
update(elapsedMS: number): void {
|
||||||
if (!this.running) {
|
if (!this.running) {
|
||||||
assertNull(this._elapsedTimeMS);
|
assertNull(this._elapsedTimeMS);
|
||||||
return;
|
return;
|
||||||
@@ -65,7 +65,7 @@ export class Clock extends Evented<typeof TimerEvents> {
|
|||||||
if (this._elapsedTimeMS == null) {
|
if (this._elapsedTimeMS == null) {
|
||||||
this._elapsedTimeMS = 0;
|
this._elapsedTimeMS = 0;
|
||||||
}
|
}
|
||||||
this._elapsedTimeMS += elapsed * this.speedFactor;
|
this._elapsedTimeMS += elapsedMS * this.speedFactor;
|
||||||
|
|
||||||
if (this._durationMS != null) {
|
if (this._durationMS != null) {
|
||||||
if (this._elapsedTimeMS > this._durationMS) {
|
if (this._elapsedTimeMS > this._durationMS) {
|
||||||
|
|||||||
@@ -39,22 +39,87 @@ export class PlayerNameInput extends ex.ScreenElement {
|
|||||||
this._joinButton = new Button({
|
this._joinButton = new Button({
|
||||||
text: "Join",
|
text: "Join",
|
||||||
anchor: ex.vec(0.5, 0),
|
anchor: ex.vec(0.5, 0),
|
||||||
onClick: () => this._joinCallback(this._nameInput.text),
|
onClick: () => this._join(),
|
||||||
disabled: true,
|
disabled: true,
|
||||||
});
|
});
|
||||||
this.addChild(this._joinButton);
|
this.addChild(this._joinButton);
|
||||||
|
|
||||||
const rejoinClient = storedClient();
|
const rejoinClient = storedClient();
|
||||||
if (rejoinClient != null) {
|
if (rejoinClient != null) {
|
||||||
this._rejoinButton = new Button({
|
this._connection.canRejoin(rejoinClient.id).then((canRejoin) => {
|
||||||
text: "Rejoin as " + rejoinClient.name,
|
if (!canRejoin) {
|
||||||
anchor: ex.vec(0.5, 0),
|
return;
|
||||||
onClick: () => this._rejoinCallback(rejoinClient.id),
|
}
|
||||||
|
|
||||||
|
this._rejoinButton = new Button({
|
||||||
|
text: "Rejoin as " + rejoinClient.name,
|
||||||
|
anchor: ex.vec(0.5, 0),
|
||||||
|
onClick: () => this._rejoinCallback(rejoinClient.id),
|
||||||
|
});
|
||||||
|
this._updateVisibility();
|
||||||
|
this._updatePositions();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
this._nameInput.on(TextInputEvents.Textchanged, () => this._update());
|
this._nameInput.on(TextInputEvents.Textchanged, () =>
|
||||||
|
this._updateVisibility(),
|
||||||
|
);
|
||||||
|
this._nameInput.on(TextInputEvents.TextSubmit, () => {
|
||||||
|
this._join();
|
||||||
|
});
|
||||||
|
|
||||||
|
this._updatePositions();
|
||||||
|
|
||||||
|
this._connection.on("connect", () => this._updateVisibility());
|
||||||
|
this._connection.on("disconnect", () => this._updateVisibility());
|
||||||
|
this._updateVisibility();
|
||||||
|
}
|
||||||
|
|
||||||
|
get playerName(): string {
|
||||||
|
return this._nameInput.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
override get height(): number {
|
||||||
|
return this._height;
|
||||||
|
}
|
||||||
|
|
||||||
|
clear(): void {
|
||||||
|
this._nameInput.text = "";
|
||||||
|
this._updateVisibility();
|
||||||
|
}
|
||||||
|
|
||||||
|
private get _nameValid(): boolean {
|
||||||
|
const name = this._nameInput.text;
|
||||||
|
if (name === "") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private _join(): void {
|
||||||
|
if (this._nameValid && !this._connection.joined) {
|
||||||
|
this._joinCallback(this._nameInput.text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _updateVisibility(): void {
|
||||||
|
const { connected } = this._connection;
|
||||||
|
const joinDisabled = !connected || !this._nameValid;
|
||||||
|
this._joinButton.disabled = joinDisabled;
|
||||||
|
|
||||||
|
if (this._rejoinButton != null) {
|
||||||
|
if (connected) {
|
||||||
|
if (!this.children.includes(this._rejoinButton)) {
|
||||||
|
this.addChild(this._rejoinButton);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.removeChild(this._rejoinButton);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private _updatePositions(): void {
|
||||||
let y = 0;
|
let y = 0;
|
||||||
this._nameLabel.pos = ex.vec(0, y);
|
this._nameLabel.pos = ex.vec(0, y);
|
||||||
y += this._nameLabel.font.size + spacingM;
|
y += this._nameLabel.font.size + spacingM;
|
||||||
@@ -71,44 +136,5 @@ export class PlayerNameInput extends ex.ScreenElement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this._height = y;
|
this._height = y;
|
||||||
|
|
||||||
this._connection.on("connect", () => this._onConnect());
|
|
||||||
this._connection.on("disconnect", () => this._onDisconnect());
|
|
||||||
}
|
|
||||||
|
|
||||||
get playerName(): string {
|
|
||||||
return this._nameInput.text;
|
|
||||||
}
|
|
||||||
|
|
||||||
override get height(): number {
|
|
||||||
return this._height;
|
|
||||||
}
|
|
||||||
|
|
||||||
clear(): void {
|
|
||||||
this._nameInput.text = "";
|
|
||||||
this._update();
|
|
||||||
}
|
|
||||||
|
|
||||||
private _onConnect(): void {
|
|
||||||
this._update();
|
|
||||||
}
|
|
||||||
|
|
||||||
private _onDisconnect(): void {
|
|
||||||
this._update();
|
|
||||||
}
|
|
||||||
|
|
||||||
private _update(): void {
|
|
||||||
const joinDisabled =
|
|
||||||
!this._connection.connected || this._nameInput.text === "";
|
|
||||||
this._joinButton.disabled = joinDisabled;
|
|
||||||
|
|
||||||
if (this._rejoinButton != null) {
|
|
||||||
const rejoinVisible = this._connection.connected;
|
|
||||||
if (rejoinVisible) {
|
|
||||||
this.addChild(this._rejoinButton);
|
|
||||||
} else {
|
|
||||||
this.removeChild(this._rejoinButton);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,6 @@ export class Title extends ScreenElement {
|
|||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
onInitialize(_engine: Engine): void {
|
onInitialize(_engine: Engine): void {
|
||||||
// Title
|
|
||||||
this._title = new Text({
|
this._title = new Text({
|
||||||
text: "Auto Beer Pong",
|
text: "Auto Beer Pong",
|
||||||
font: titleFont,
|
font: titleFont,
|
||||||
@@ -17,7 +16,6 @@ export class Title extends ScreenElement {
|
|||||||
this._title.anchor = vec(0.5, 0);
|
this._title.anchor = vec(0.5, 0);
|
||||||
this.addChild(this._title);
|
this.addChild(this._title);
|
||||||
|
|
||||||
// Sub title
|
|
||||||
this._subTitle = new Text({
|
this._subTitle = new Text({
|
||||||
text: "An auto battler with stupid people.",
|
text: "An auto battler with stupid people.",
|
||||||
font: subTitleFont,
|
font: subTitleFont,
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
export type Id = number;
|
export type Id = number;
|
||||||
|
export type ChampionId = "lucas" | "berset";
|
||||||
|
|
||||||
export type MessageRaw = LobbyStateRaw | MatchStateRaw;
|
export type MessageRaw = LobbyStateRaw | MatchStateRaw;
|
||||||
|
|
||||||
@@ -32,8 +33,8 @@ export interface MatchStateRaw {
|
|||||||
export interface Table {
|
export interface Table {
|
||||||
cupsA: [boolean, boolean, boolean];
|
cupsA: [boolean, boolean, boolean];
|
||||||
cupsB: [boolean, boolean, boolean];
|
cupsB: [boolean, boolean, boolean];
|
||||||
teamA: [Id, Id, Id];
|
teamA: [ChampionId, ChampionId, ChampionId];
|
||||||
teamB: [Id, Id, Id];
|
teamB: [ChampionId, ChampionId, ChampionId];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Action {
|
export interface Action {
|
||||||
|
|||||||
@@ -31,10 +31,10 @@ const mocked = urlParams.get("mock");
|
|||||||
|
|
||||||
await game.start();
|
await game.start();
|
||||||
await loadImages();
|
await loadImages();
|
||||||
await game.goToScene("lobby");
|
await goToScene(game, "lobby");
|
||||||
|
|
||||||
connection.on("lobby-message", () => game.goToScene("lobby"));
|
connection.on("lobby-message", () => goToScene(game, "lobby"));
|
||||||
connection.on("match-message", () => game.goToScene("match"));
|
connection.on("match-message", () => goToScene(game, "match"));
|
||||||
|
|
||||||
if (mocked != null) {
|
if (mocked != null) {
|
||||||
runMockScenario(mocked, connection, mockSocket!);
|
runMockScenario(mocked, connection, mockSocket!);
|
||||||
@@ -58,3 +58,14 @@ function runMockScenario(
|
|||||||
mockSocket.sendToClient(mockGameMessage());
|
mockSocket.sendToClient(mockGameMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function waitEngine(engine: ex.Engine): Promise<void> {
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
engine.once("postupdate", () => resolve());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function goToScene(engine: ex.Engine, scene: string): Promise<void> {
|
||||||
|
await engine.goToScene(scene);
|
||||||
|
await waitEngine(engine);
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@ import playerSchemaFile from "../../schema/common/player.json";
|
|||||||
import joinSchemaFile from "../../schema/lobby/join.json";
|
import joinSchemaFile from "../../schema/lobby/join.json";
|
||||||
import joinResponseSchemaFile from "../../schema/lobby/join_response.json";
|
import joinResponseSchemaFile from "../../schema/lobby/join_response.json";
|
||||||
import rejoinSchemaFile from "../../schema/lobby/rejoin.json";
|
import rejoinSchemaFile from "../../schema/lobby/rejoin.json";
|
||||||
|
import canRejoinSchemaFile from "../../schema/lobby/can_rejoin.json";
|
||||||
|
import canRejoinResponseSchemaFile from "../../schema/lobby/can_rejoin_response.json";
|
||||||
import lobbyStateSchemaFile from "../../schema/lobby/state.json";
|
import lobbyStateSchemaFile from "../../schema/lobby/state.json";
|
||||||
import toggleReadySchemaFile from "../../schema/lobby/toggle_ready.json";
|
import toggleReadySchemaFile from "../../schema/lobby/toggle_ready.json";
|
||||||
import toggleRoleSchemaFile from "../../schema/lobby/toggle_role.json";
|
import toggleRoleSchemaFile from "../../schema/lobby/toggle_role.json";
|
||||||
@@ -28,6 +30,8 @@ ajv.addSchema(playerSchemaFile, "player.json");
|
|||||||
ajv.addSchema(joinSchemaFile, "join.json");
|
ajv.addSchema(joinSchemaFile, "join.json");
|
||||||
ajv.addSchema(joinResponseSchemaFile, "join_response.json");
|
ajv.addSchema(joinResponseSchemaFile, "join_response.json");
|
||||||
ajv.addSchema(rejoinSchemaFile, "rejoin.json");
|
ajv.addSchema(rejoinSchemaFile, "rejoin.json");
|
||||||
|
ajv.addSchema(canRejoinSchemaFile, "can_rejoin.json");
|
||||||
|
ajv.addSchema(canRejoinResponseSchemaFile, "can_rejoin_response.json");
|
||||||
ajv.addSchema(lobbyStateSchemaFile, "lobby_state.json");
|
ajv.addSchema(lobbyStateSchemaFile, "lobby_state.json");
|
||||||
ajv.addSchema(toggleReadySchemaFile, "toggle_ready.json");
|
ajv.addSchema(toggleReadySchemaFile, "toggle_ready.json");
|
||||||
ajv.addSchema(toggleRoleSchemaFile, "toggle_role.json");
|
ajv.addSchema(toggleRoleSchemaFile, "toggle_role.json");
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ export function mockLobbyMessage(): string {
|
|||||||
export function mockGameMessage(): string {
|
export function mockGameMessage(): string {
|
||||||
const matchUpdate = {
|
const matchUpdate = {
|
||||||
messageType: "matchState",
|
messageType: "matchState",
|
||||||
messsageContent: {
|
messageContent: {
|
||||||
history: [
|
history: [
|
||||||
{
|
{
|
||||||
cupsA: [true, true, true],
|
cupsA: [true, true, true],
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"$id": "http://localhost/lobby/can_rejoin.json",
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"messageType": {
|
||||||
|
"const": "canRejoin"
|
||||||
|
},
|
||||||
|
"messageContent": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {
|
||||||
|
"type": "number",
|
||||||
|
"minimum": 0
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"id"
|
||||||
|
],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"$id": "http://localhost/lobby/can_rejoin_response.json",
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"messageType": {
|
||||||
|
"const": "canRejoinResponse"
|
||||||
|
},
|
||||||
|
"messageContent": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"canRejoin": {
|
||||||
|
"type": "boolean"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"required": [
|
||||||
|
"canRejoin"
|
||||||
|
],
|
||||||
|
"additionalProperties": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -35,7 +35,11 @@
|
|||||||
"team": {
|
"team": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"items": {
|
"items": {
|
||||||
"type": "number"
|
"type": "string",
|
||||||
|
"enum": [
|
||||||
|
"berset",
|
||||||
|
"lucas"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"minItems": 3,
|
"minItems": 3,
|
||||||
"maxItems": 3
|
"maxItems": 3
|
||||||
|
|||||||
@@ -21,6 +21,12 @@
|
|||||||
{
|
{
|
||||||
"$ref": "./lobby/rejoin.json"
|
"$ref": "./lobby/rejoin.json"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"$ref": "./lobby/can_rejoin.json"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "./lobby/can_rejoin_response.json"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"$ref": "./lobby/state.json"
|
"$ref": "./lobby/state.json"
|
||||||
},
|
},
|
||||||
|
|||||||
Reference in new issue
Block a user