Backend - Add parabola calculations (#45)
* add global constants file * use only float * add constants dir * load constants.json * add table half width constant * add pixels per meter conversion to frontend * fix and clarify conversion between seconds and milliseconds * add basic working parabola calucations * add cup offsets * make parabola end at cup positions * add cup constants * add simple match resolvement logic * fix lint errors * remove console log * remove print statement
This commit is contained in:
1 parent
ede991de51
commit
0ac5630ae9
23 files changed
+282
-111
No files matched your search
@@ -2,8 +2,8 @@ import json
|
||||
|
||||
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.types.raw import ClientRaw_T, MessageRaw_T, PlayerRaw_T
|
||||
|
||||
|
||||
class Client:
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import tomllib
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import tomllib
|
||||
|
||||
CONFIG_FILE = Path(f"{Path(__file__).parent.parent}") / "config.toml"
|
||||
|
||||
with open(CONFIG_FILE, "rb") as 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_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,4 +1,5 @@
|
||||
import json
|
||||
|
||||
from websockets.asyncio.server import ServerConnection
|
||||
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
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.contexts.lobby import LobbyContext
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.types.client_map import ClientMap_T
|
||||
|
||||
|
||||
class ServerContext:
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
class NoMessageTypeException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMessageTypeException(Exception):
|
||||
pass
|
||||
@@ -1,16 +1,86 @@
|
||||
import random
|
||||
|
||||
from autobeerpong import constants
|
||||
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:
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, opposite: bool = False) -> None:
|
||||
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:
|
||||
self.formation.insert(0, self.formation.pop())
|
||||
@@ -24,52 +94,90 @@ class Match:
|
||||
def __init__(self) -> None:
|
||||
self.turn = True
|
||||
self.team_a = Team()
|
||||
self.team_b = Team()
|
||||
self.team_b = Team(opposite=True)
|
||||
self.history: list[MessageRaw_T] = []
|
||||
|
||||
def get_table_state(self) -> MessageRaw_T:
|
||||
return {
|
||||
"cupsA": self.team_a.cups.copy(),
|
||||
"cupsB": self.team_b.cups.copy(),
|
||||
"cupsA": [not cup.is_hit for cup in self.team_a.cups],
|
||||
"cupsB": [not cup.is_hit for cup in self.team_b.cups],
|
||||
"teamA": self.team_a.formation.copy(),
|
||||
"teamB": self.team_b.formation.copy(),
|
||||
}
|
||||
|
||||
def get_action(self) -> MessageRaw_T:
|
||||
turn = "a" if self.turn else "b"
|
||||
x_pos = -150 if self.turn else 150
|
||||
x_vel = 250 if self.turn else -250
|
||||
def calculate_relative_end_position(
|
||||
self, start_pos: Vec2D, end_pos: Vec2D
|
||||
) -> Vec2D:
|
||||
return Vec2D(
|
||||
abs(start_pos.x - end_pos.x),
|
||||
-abs(start_pos.y + end_pos.y),
|
||||
)
|
||||
|
||||
# determine if hit
|
||||
# is_hit = True if random.random() >= 0.5 else False
|
||||
def calculate_relative_start_velocity(
|
||||
self, r_end_pos: Vec2D, stop_time: float
|
||||
) -> Vec2D:
|
||||
r_vel_x = r_end_pos.x / stop_time
|
||||
|
||||
return {
|
||||
"turn": turn,
|
||||
"parabola": {
|
||||
"startPosition": [x_pos, -200],
|
||||
"startVelocity": [x_vel, -300],
|
||||
"stopTime": 900,
|
||||
},
|
||||
}
|
||||
if not self.turn:
|
||||
r_vel_x *= -1
|
||||
|
||||
def match_not_over(self) -> bool:
|
||||
return any(self.team_a.cups) and any(self.team_b.cups)
|
||||
r_vel_y = (
|
||||
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:
|
||||
# first send table state
|
||||
self.history.append(self.get_table_state())
|
||||
|
||||
while self.match_not_over():
|
||||
while not self.match_over():
|
||||
# action
|
||||
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())
|
||||
|
||||
for i in range(len(other_team.cups)):
|
||||
if other_team.cups[i]:
|
||||
other_team.cups[i] = False
|
||||
break
|
||||
self.history.extend(self.get_actions(active_team, opposite_team))
|
||||
|
||||
active_team.rotate()
|
||||
# table state
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
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
|
||||
|
||||
from autobeerpong.messages.lobby.can_rejoin_response import CanRejoinResponseMessage
|
||||
|
||||
class CanRejoinMessage(Message):
|
||||
has_direct_response = True
|
||||
@@ -27,14 +27,15 @@ class CanRejoinMessage(Message):
|
||||
|
||||
canRejoin = self._canRejoin(server_context)
|
||||
|
||||
can_rejoin_response_raw = CanRejoinResponseMessage({
|
||||
"messageType": "canRejoinResponse",
|
||||
"messageContent": { "canRejoin": canRejoin}
|
||||
})
|
||||
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)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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 CanRejoinResponseMessage(Message):
|
||||
|
||||
@@ -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.contexts.server import ServerContext
|
||||
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.server import ServerState
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
class JoinMessage(Message):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
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):
|
||||
|
||||
@@ -1,6 +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.server import ServerContext
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.states.client import ClientState
|
||||
|
||||
|
||||
@@ -25,7 +25,9 @@ class RejoinMessage(Message):
|
||||
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.')
|
||||
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)
|
||||
|
||||
@@ -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.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.server import ServerState
|
||||
|
||||
|
||||
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.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.server import ServerState
|
||||
|
||||
|
||||
class ToggleRoleMessage(Message):
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import jsonschema
|
||||
import jsonschema.protocols
|
||||
|
||||
from pathlib import Path
|
||||
from referencing import Registry, Resource
|
||||
from referencing.jsonschema import DRAFT202012
|
||||
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong import config
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.contexts.server import ServerContext
|
||||
from autobeerpong.types.raw import MessageRaw_T
|
||||
|
||||
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
import json
|
||||
import asyncio
|
||||
import json
|
||||
from typing import ClassVar
|
||||
|
||||
from websockets import Data
|
||||
from websockets.asyncio.server import ServerConnection, serve
|
||||
from websockets.exceptions import ConnectionClosedOK
|
||||
|
||||
import autobeerpong.config as config
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong import config
|
||||
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_response import JoinResponseMessage
|
||||
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.state import LobbyStateMessage
|
||||
from autobeerpong.messages.lobby.toggle_ready import ToggleReadyMessage
|
||||
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.contexts.server import ServerContext
|
||||
from autobeerpong.contexts.client import ClientContext
|
||||
from autobeerpong.messages.match.start_match import StartMatchMessage
|
||||
from autobeerpong.messages.message import Message, MessageRaw_T
|
||||
from autobeerpong.states.client import ClientState
|
||||
from autobeerpong.states.server import ServerState
|
||||
from autobeerpong.match import Match
|
||||
|
||||
|
||||
class AutobeerpongServer:
|
||||
message_map: dict[str, type[Message]] = {
|
||||
message_map: ClassVar[dict[str, type[Message]]] = {
|
||||
# LOBBY
|
||||
"join": JoinMessage,
|
||||
"joinResponse": JoinResponseMessage,
|
||||
@@ -64,14 +66,15 @@ class AutobeerpongServer:
|
||||
)
|
||||
)
|
||||
|
||||
if self.context.lobby.is_players_full() and 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
|
||||
await self.transition_to_match()
|
||||
|
||||
elif state is ServerState.MATCH:
|
||||
if not self.context.lobby.is_players_full():
|
||||
await self.transition_to_lobby()
|
||||
pass
|
||||
|
||||
async def broadcast_lobby_state(self):
|
||||
players = list(
|
||||
@@ -87,7 +90,7 @@ class AutobeerpongServer:
|
||||
)
|
||||
)
|
||||
|
||||
lobby_message = LobbyStateMessage(
|
||||
lobby_message = LobbyStateMessage(
|
||||
{
|
||||
"messageType": "lobbyState",
|
||||
"messageContent": {
|
||||
@@ -99,7 +102,6 @@ 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
|
||||
@@ -114,12 +116,11 @@ class AutobeerpongServer:
|
||||
|
||||
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(),
|
||||
lambda x: x.state is ClientState.PLAYER,
|
||||
self.context.lobby._clients.values(),
|
||||
)
|
||||
for player in players:
|
||||
player.ready = False
|
||||
@@ -156,12 +157,12 @@ class AutobeerpongServer:
|
||||
message_type = str(message_raw.get("messageType"))
|
||||
|
||||
if message_type is None:
|
||||
raise Exception("Message has no messageType property.")
|
||||
raise NoMessageTypeException("Message has no messageType property.")
|
||||
|
||||
MessageClass = self.message_map.get(message_type)
|
||||
|
||||
if MessageClass is None:
|
||||
raise Exception(f"Unknown messageType: {message_type}.")
|
||||
raise UnknownMessageTypeException(f"Unknown messageType: {message_type}.")
|
||||
|
||||
return MessageClass(message_raw)
|
||||
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
|
||||
from autobeerpong.messages.message import Message
|
||||
from autobeerpong.messages.lobby.join import JoinMessage
|
||||
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.manager import TestClientManager
|
||||
from tests.utils.server import manage_server
|
||||
|
||||
|
||||
def get_two_players_join_and_ready(
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import { Clock } from "../Timers/Clock";
|
||||
export class BaseActor extends Actor {
|
||||
private _clocks: Clock[] = [];
|
||||
|
||||
override update(engine: Engine, elapsed: number): void {
|
||||
super.update(engine, elapsed);
|
||||
this._clocks.forEach((clock) => clock.update(elapsed));
|
||||
override update(engine: Engine, elapsedMS: number): void {
|
||||
super.update(engine, elapsedMS);
|
||||
this._clocks.forEach((clock) => clock.update(elapsedMS));
|
||||
}
|
||||
|
||||
protected addClock(timer: Clock): void {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Vector, clamp } from "excalibur";
|
||||
import { Parabola as ParabolaJSON } from "../jsonTypes";
|
||||
import { gravitationalConstant } from "../configs/physicsConstant";
|
||||
import {
|
||||
gravitationalConstant,
|
||||
pixelsPerMeter,
|
||||
} from "../configs/physicsConstant";
|
||||
|
||||
export class Parabola {
|
||||
constructor(
|
||||
@@ -16,14 +19,19 @@ export class Parabola {
|
||||
stopTime,
|
||||
} = parabolaJSON;
|
||||
|
||||
const startPosition = new Vector(start[0], start[1]);
|
||||
const startVelocity = new Vector(velocity[0], velocity[1]);
|
||||
const startPosition = new Vector(
|
||||
start[0] * pixelsPerMeter,
|
||||
start[1] * pixelsPerMeter,
|
||||
);
|
||||
const startVelocity = new Vector(
|
||||
velocity[0] * pixelsPerMeter,
|
||||
velocity[1] * pixelsPerMeter,
|
||||
);
|
||||
return new Parabola(startPosition, startVelocity, stopTime);
|
||||
}
|
||||
|
||||
position(time: number): Vector {
|
||||
const timeSeconds = clamp(time / 1000, 0, this.stopTime ?? Infinity);
|
||||
|
||||
position(timeMS: number): Vector {
|
||||
const timeSeconds = clamp(timeMS / 1000, 0, this.stopTime ?? Infinity);
|
||||
const x = this.startPos.x + this.startVelocity.x * timeSeconds;
|
||||
const y =
|
||||
this.startVelocity.y * timeSeconds +
|
||||
|
||||
@@ -4,9 +4,9 @@ import { Clock } from "../Timers/Clock";
|
||||
export class BaseScene extends Scene {
|
||||
private _clocks = new Array<Clock>();
|
||||
|
||||
override update(engine: Engine, elapsed: number): void {
|
||||
super.update(engine, elapsed);
|
||||
this._clocks.forEach((clock) => clock.update(elapsed));
|
||||
override update(engine: Engine, elapsedMS: number): void {
|
||||
super.update(engine, elapsedMS);
|
||||
this._clocks.forEach((clock) => clock.update(elapsedMS));
|
||||
}
|
||||
|
||||
addClock(clock: Clock): void {
|
||||
|
||||
@@ -12,12 +12,14 @@ export class BallClock extends Clock {
|
||||
}
|
||||
|
||||
startWithParabola(parabola: Parabola): void {
|
||||
this.start(parabola.stopTime);
|
||||
if (parabola.stopTime != null) {
|
||||
this.start(parabola.stopTime * 1000);
|
||||
}
|
||||
this._parabola = parabola;
|
||||
}
|
||||
|
||||
update(elapsed: number): void {
|
||||
super.update(elapsed);
|
||||
update(elapsedMS: number): void {
|
||||
super.update(elapsedMS);
|
||||
|
||||
if (!this.running) {
|
||||
return;
|
||||
|
||||
@@ -15,19 +15,19 @@ export class Clock extends Evented<typeof TimerEvents> {
|
||||
|
||||
speedFactor = 1;
|
||||
|
||||
constructor(duration?: number) {
|
||||
constructor(durationMS?: number) {
|
||||
super();
|
||||
this._durationMS = duration;
|
||||
this._durationMS = durationMS;
|
||||
}
|
||||
|
||||
get running(): boolean {
|
||||
return this._running;
|
||||
}
|
||||
|
||||
start(duration?: number): void {
|
||||
start(durationMS?: number): void {
|
||||
this.reset();
|
||||
if (duration != null) {
|
||||
this._durationMS = duration;
|
||||
if (durationMS != null) {
|
||||
this._durationMS = durationMS;
|
||||
}
|
||||
this._running = true;
|
||||
this.emit("start", {});
|
||||
@@ -51,12 +51,12 @@ export class Clock extends Evented<typeof TimerEvents> {
|
||||
await promise;
|
||||
}
|
||||
|
||||
async startAndWait(duration?: number): Promise<void> {
|
||||
this.start(duration);
|
||||
async startAndWait(durationMS?: number): Promise<void> {
|
||||
this.start(durationMS);
|
||||
await this.whenEnd();
|
||||
}
|
||||
|
||||
update(elapsed: number): void {
|
||||
update(elapsedMS: number): void {
|
||||
if (!this.running) {
|
||||
assertNull(this._elapsedTimeMS);
|
||||
return;
|
||||
@@ -65,7 +65,7 @@ export class Clock extends Evented<typeof TimerEvents> {
|
||||
if (this._elapsedTimeMS == null) {
|
||||
this._elapsedTimeMS = 0;
|
||||
}
|
||||
this._elapsedTimeMS += elapsed * this.speedFactor;
|
||||
this._elapsedTimeMS += elapsedMS * this.speedFactor;
|
||||
|
||||
if (this._durationMS != null) {
|
||||
if (this._elapsedTimeMS > this._durationMS) {
|
||||
|
||||
Reference in new issue
Block a user