Backend - Add parabola calculations (#45)
CI / lint_frontend (push) Failing after 2m52s
CI / lint_backend (push) Failing after 1m48s

* 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:
Denis authored and GitHub committed 2026-08-31 20:57:50 +02:00
1 parent ede991de51
commit 0ac5630ae9
23 files changed
+275 -104

No files matched your search

+1 -1
View File
@@ -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:
+5 -3
View File
@@ -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"])
+21
View File
@@ -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 import json
from websockets.asyncio.server import ServerConnection from websockets.asyncio.server import ServerConnection
from autobeerpong.types.raw import MessageRaw_T from autobeerpong.types.raw import MessageRaw_T
+3 -4
View File
@@ -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:
+6
View File
@@ -0,0 +1,6 @@
class NoMessageTypeException(Exception):
pass
class UnknownMessageTypeException(Exception):
pass
+134 -26
View File
@@ -1,16 +1,86 @@
import random import random
from autobeerpong import constants
from autobeerpong.types.raw import MessageRaw_T from autobeerpong.types.raw import MessageRaw_T
champions = ["berset", "lucas"] champions = ["berset", "lucas"]
def randomChampion() -> str: def randomChampion() -> str:
return random.choice(champions) 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 = [randomChampion(), randomChampion(), randomChampion()] 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())
@@ -24,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
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": { "parabola": {
"startPosition": [x_pos, -200], "startPosition": [
"startVelocity": [x_vel, -300], start_pos.x,
"stopTime": 900, start_pos.y,
],
"startVelocity": [r_start_vel.x, r_start_vel.y],
"stopTime": stop_time,
}, },
} }
)
def match_not_over(self) -> bool: return actions
return any(self.team_a.cups) and any(self.team_b.cups)
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
@@ -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.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.states.client import ClientState
from autobeerpong.messages.lobby.can_rejoin_response import CanRejoinResponseMessage
class CanRejoinMessage(Message): class CanRejoinMessage(Message):
has_direct_response = True has_direct_response = True
@@ -27,14 +27,15 @@ class CanRejoinMessage(Message):
canRejoin = self._canRejoin(server_context) canRejoin = self._canRejoin(server_context)
can_rejoin_response_raw = CanRejoinResponseMessage({ can_rejoin_response_raw = CanRejoinResponseMessage(
{
"messageType": "canRejoinResponse", "messageType": "canRejoinResponse",
"messageContent": { "canRejoin": canRejoin} "messageContent": {"canRejoin": canRejoin},
}) }
)
await client_context.send(can_rejoin_response_raw.to_raw()) await client_context.send(can_rejoin_response_raw.to_raw())
def _canRejoin(self, server_context: ServerContext) -> bool: def _canRejoin(self, server_context: ServerContext) -> bool:
client_exists = server_context.has_client(self.id) client_exists = server_context.has_client(self.id)
@@ -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 CanRejoinResponseMessage(Message): 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.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,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.client import ClientContext
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
@@ -25,7 +25,9 @@ class RejoinMessage(Message):
assert client_context.has_joined is False assert client_context.has_joined is False
if not server_context.has_client(self.id): 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 return
client = server_context.get_client(self.id) 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.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):
+4 -4
View File
@@ -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
+18 -17
View File
@@ -1,31 +1,33 @@
import json
import asyncio import asyncio
import json
from typing import ClassVar
from websockets import Data 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.can_rejoin import CanRejoinMessage from autobeerpong.messages.lobby.state import LobbyStateMessage
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.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,
@@ -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 # all players are ready, advance server state to match
await self.transition_to_match() await self.transition_to_match()
elif state is ServerState.MATCH: elif state is ServerState.MATCH:
if not self.context.lobby.is_players_full(): if not self.context.lobby.is_players_full():
await self.transition_to_lobby() await self.transition_to_lobby()
pass
async def broadcast_lobby_state(self): async def broadcast_lobby_state(self):
players = list( players = list(
@@ -99,7 +102,6 @@ class AutobeerpongServer:
await self.broadcast(lobby_message.to_raw()) await self.broadcast(lobby_message.to_raw())
async def transition_to_match(self): async def transition_to_match(self):
self.context.state = ServerState.MATCH self.context.state = ServerState.MATCH
# send match start message to all connected clients # send match start message to all connected clients
@@ -114,7 +116,6 @@ class AutobeerpongServer:
await self.broadcast(match.to_raw()) await self.broadcast(match.to_raw())
async def transition_to_lobby(self): async def transition_to_lobby(self):
self.context.state = ServerState.LOBBY self.context.state = ServerState.LOBBY
players = filter( players = filter(
@@ -156,12 +157,12 @@ class AutobeerpongServer:
message_type = str(message_raw.get("messageType")) message_type = str(message_raw.get("messageType"))
if message_type is None: 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) MessageClass = self.message_map.get(message_type)
if MessageClass is None: if MessageClass is None:
raise Exception(f"Unknown messageType: {message_type}.") raise UnknownMessageTypeException(f"Unknown messageType: {message_type}.")
return MessageClass(message_raw) return MessageClass(message_raw)
+3 -2
View File
@@ -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(
+19
View File
@@ -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]
}
+3 -3
View File
@@ -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 {
+14 -6
View File
@@ -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 +
+3 -3
View File
@@ -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 {
+5 -3
View File
@@ -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;
+9 -9
View File
@@ -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) {