Duel arcade
demo-kit/ es lo que simula el dispositivo para la demostración en la página de inicio. El dispositivo en sí no lo necesita.
demo-kit/ es lo que simula el dispositivo para la demostración en la página de inicio. El dispositivo en sí no lo necesita.
#!/usr/bin/env python3
"""Rimshock: the game both cabinets play, and the computer player that fills an empty seat.
Two skimmers glide on a round plate. Whoever leaves the plate loses the round; the plate shrinks until
somebody does. The rules are in ../README.md. ``Game`` is the whole simulation: the host cabinet steps it
60 times a second with the two players' inputs, and everything a screen shows comes from ``snapshot()``
and the events ``step()`` returns. ../ui/demo-data.js has the same simulation in JavaScript for the demo.
Run this file to play computer against computer without a screen, as fast as the machine goes:
python game.py --matches 2
Only the standard library is used.
"""
from __future__ import annotations
import argparse
import math
import random
from typing import Any, Dict, List, Optional, Tuple
Input = Tuple[float, float, bool]
"""What one player does in one tick: the stick (x right, y down, together at most 1 long) and the button."""
NEUTRAL: Input = (0.0, 0.0, False)
TICKS_PER_SECOND = 60
DT = 1.0 / TICKS_PER_SECOND
# Lengths are in plate radii: the plate starts with radius 1 around (0, 0).
SKIMMER_RADIUS = 0.075
THRUST = 2.7 # acceleration at full stick, per second squared
DRAG = 1.8 # share of the speed lost per second; top speed is THRUST / DRAG
BOUNCE = 0.9 # how much of the closing speed two skimmers keep when they collide
START_X = 0.45 # the skimmers start this far left and right of the centre
SHOCK_RADIUS = 0.5 # how far a shock reaches
SHOCK_PUSH = 2.0 # the speed it gives a skimmer right next to it
SHOCK_FALLOFF = 0.55 # share of the push lost at the edge of its reach
SHOCK_RECOIL = 0.3 # share of the push that throws the sender back when the shock hits
BOOST_RADIUS = 0.64 # the same for a shock sent while holding a spark
BOOST_PUSH = 2.8
RECHARGE_SECONDS = 2.2
SPARK_RADIUS = 0.05
SPARK_DELAY = 2.5 # seconds from a spark being taken to the next one appearing
SHRINK_SECONDS = 14.0 # the plate shrinks from radius 1 to SMALL_RIM in this time,
SMALL_RIM = 0.4
COLLAPSE_SECONDS = 6.0 # and then to nothing in this time, so a round always ends
READY_SECONDS = 1.2 # before a round: the skimmers wait at their starting places
POINT_SECONDS = 2.2 # after a round: the point is shown
OVER_SECONDS = 6.0 # after a match: the result is shown, then the next match starts
TARGET = 5 # rounds to win a match
def rim_at(clock: float) -> float:
"""The radius of the plate `clock` seconds into a round."""
if clock <= SHRINK_SECONDS:
return 1.0 - (1.0 - SMALL_RIM) * (clock / SHRINK_SECONDS)
return SMALL_RIM * max(0.0, 1.0 - (clock - SHRINK_SECONDS) / COLLAPSE_SECONDS)
class Skimmer:
def __init__(self) -> None:
self.x = 0.0
self.y = 0.0
self.vx = 0.0
self.vy = 0.0
self.charge = 0.0 # 0 to 1; a shock needs 1
self.boost = False # holds a spark: the next shock is stronger
self.out = False # left the plate in this round
self.button = False # the button in the tick before, to fire on the press and not while held
def place(self, x: float) -> None:
self.x, self.y, self.vx, self.vy = x, 0.0, 0.0, 0.0
self.charge, self.boost, self.out = 0.5, False, False
class Game:
"""The authoritative state of a match. Not thread safe: one owner steps it."""
def __init__(self, rng: Optional[random.Random] = None) -> None:
self._rng = rng or random.Random()
self.t = 0.0 # seconds of simulation since the program started
self.skimmers = [Skimmer(), Skimmer()]
self.score = [0, 0]
self.round = 0
self.phase = "waiting" # waiting | ready | play | point | over
self.clock = 0.0 # seconds of play in this round
self.rim = 1.0
self.spark: Optional[Tuple[float, float]] = None
self._spark_in = 0.0
self._phase_left = 0.0
self._match_seconds = 0.0
self._events: List[Dict[str, Any]] = []
# --- what the owner does ---
def new_match(self) -> None:
"""Starts a match at 0 : 0, whatever was going on."""
self.score = [0, 0]
self.round = 0
self._match_seconds = 0.0
self._start_round()
def wait(self) -> None:
"""Stops play until new_match(): a seat is empty."""
self.phase = "waiting"
self._phase_left = 0.0
def step(self, inputs: List[Input]) -> List[Dict[str, Any]]:
"""Advances the game by one tick and returns what happened in it, as events."""
self._events = []
self.t += DT
if self.phase == "waiting":
return self._events
if self.phase == "play":
self._play(inputs)
return self._events
if self.phase == "point":
# The skimmer that stayed keeps gliding while the point is shown.
for skimmer, (x, y, _) in zip(self.skimmers, inputs):
if not skimmer.out:
self._move(skimmer, x, y)
self._phase_left -= DT
if self._phase_left <= 0:
if self.phase == "ready":
self.phase = "play"
self._emit("go", round=self.round)
elif self.phase == "point":
self._start_round()
else: # over
self.new_match()
return self._events
def snapshot(self) -> Dict[str, Any]:
"""Everything a screen needs to draw this moment."""
return {
"t": round(self.t, 3),
"phase": self.phase,
"round": self.round,
"clock": round(self.clock, 2),
"countdown": round(max(0.0, self._phase_left), 2),
"rim": round(self.rim, 4),
"score": list(self.score),
"target": TARGET,
"p": [
{
"x": round(s.x, 4),
"y": round(s.y, 4),
"vx": round(s.vx, 3),
"vy": round(s.vy, 3),
"charge": round(s.charge, 2),
"boost": s.boost,
"out": s.out,
}
for s in self.skimmers
],
"spark": [round(self.spark[0], 4), round(self.spark[1], 4)] if self.spark else None,
}
# --- the rules ---
def _emit(self, event: str, **details: Any) -> None:
self._events.append({"type": "event", "event": event, "t": round(self.t, 3), **details})
def _start_round(self) -> None:
self.round += 1
self.phase = "ready"
self._phase_left = READY_SECONDS
self.clock = 0.0
self.rim = 1.0
self.spark = None
self._spark_in = SPARK_DELAY
self.skimmers[0].place(-START_X)
self.skimmers[1].place(START_X)
self._emit("round", round=self.round, score=list(self.score))
def _move(skimmer: Skimmer, x: float, y: float) -> None:
length = math.hypot(x, y)
if length > 1.0:
x, y = x / length, y / length
skimmer.vx += x * THRUST * DT
skimmer.vy += y * THRUST * DT
keep = math.exp(-DRAG * DT)
skimmer.vx *= keep
skimmer.vy *= keep
skimmer.x += skimmer.vx * DT
skimmer.y += skimmer.vy * DT
def _play(self, inputs: List[Input]) -> None:
self.clock += DT
self._match_seconds += DT
self.rim = rim_at(self.clock)
one, two = self.skimmers
for skimmer, (x, y, _) in zip(self.skimmers, inputs):
self._move(skimmer, x, y)
skimmer.charge = min(1.0, skimmer.charge + DT / RECHARGE_SECONDS)
# Two skimmers that touch bounce off each other like two equal balls.
dx, dy = two.x - one.x, two.y - one.y
distance = math.hypot(dx, dy)
if 0 < distance < 2 * SKIMMER_RADIUS:
nx, ny = dx / distance, dy / distance
overlap = 2 * SKIMMER_RADIUS - distance
one.x -= nx * overlap / 2
one.y -= ny * overlap / 2
two.x += nx * overlap / 2
two.y += ny * overlap / 2
closing = (one.vx - two.vx) * nx + (one.vy - two.vy) * ny
if closing > 0:
change = closing * (1 + BOUNCE) / 2
one.vx -= nx * change
one.vy -= ny * change
two.vx += nx * change
two.vy += ny * change
if closing > 0.25:
self._emit("bump", x=round((one.x + two.x) / 2, 3), y=round((one.y + two.y) / 2, 3), speed=round(closing, 2))
# The button sends a shock when it is pressed with a full charge.
for seat, (skimmer, (_, _, button)) in enumerate(zip(self.skimmers, inputs)):
pressed = button and not skimmer.button
skimmer.button = button
if not pressed or skimmer.charge < 1.0:
continue
reach = BOOST_RADIUS if skimmer.boost else SHOCK_RADIUS
push = BOOST_PUSH if skimmer.boost else SHOCK_PUSH
self._emit("shock", seat=seat, x=round(skimmer.x, 3), y=round(skimmer.y, 3), reach=reach, boost=skimmer.boost)
skimmer.charge = 0.0
skimmer.boost = False
other = self.skimmers[1 - seat]
ox, oy = other.x - skimmer.x, other.y - skimmer.y
away = math.hypot(ox, oy)
if 0 < away < reach:
strength = push * (1 - SHOCK_FALLOFF * away / reach)
nx, ny = ox / away, oy / away
other.vx += nx * strength
other.vy += ny * strength
skimmer.vx -= nx * strength * SHOCK_RECOIL
skimmer.vy -= ny * strength * SHOCK_RECOIL
self._emit("hit", seat=1 - seat, by=seat, x=round(other.x, 3), y=round(other.y, 3), strength=round(strength, 2))
# One spark at a time lies on the plate; touching it fills the charge and makes the next shock stronger.
if self.spark is None:
self._spark_in -= DT
if self._spark_in <= 0 and self.rim > 0.3:
angle = self._rng.random() * 2 * math.pi
radius = math.sqrt(self._rng.random()) * self.rim * 0.7
self.spark = (radius * math.cos(angle), radius * math.sin(angle))
else:
if math.hypot(*self.spark) > self.rim - SPARK_RADIUS: # the plate shrank away under it
self.spark = None
self._spark_in = 0.6
else:
for seat, skimmer in enumerate(self.skimmers):
if math.hypot(skimmer.x - self.spark[0], skimmer.y - self.spark[1]) < SKIMMER_RADIUS + SPARK_RADIUS:
skimmer.charge = 1.0
skimmer.boost = True
self._emit("spark", seat=seat, x=round(self.spark[0], 3), y=round(self.spark[1], 3))
self.spark = None
self._spark_in = SPARK_DELAY
break
# Whoever is past the rim has left the plate. Both in the same tick: nobody scores.
for skimmer in self.skimmers:
skimmer.out = math.hypot(skimmer.x, skimmer.y) > self.rim
if not (one.out or two.out):
return
self.phase = "point"
self._phase_left = POINT_SECONDS
if one.out and two.out:
self._emit("draw", round=self.round)
return
loser = 0 if one.out else 1
winner = 1 - loser
self.score[winner] += 1
fallen = self.skimmers[loser]
self._emit("fall", seat=loser, x=round(fallen.x, 3), y=round(fallen.y, 3), score=list(self.score), round=self.round)
if self.score[winner] >= TARGET:
self.phase = "over"
self._phase_left = OVER_SECONDS
self._emit("match", winner=winner, score=list(self.score), rounds=self.round, seconds=round(self._match_seconds))
class ComputerPlayer:
"""Plays one seat from what a screen sees (a snapshot), so it works on the host and on the guest.
It goes for the spark when it is nearer to it, otherwise it gets between the other skimmer and the
centre and sends a shock once the other one is in reach and would be pushed outward. Near the rim it
turns back. It reacts a little late and steers a little off, each time differently.
"""
def __init__(self, seat: int, rng: Optional[random.Random] = None) -> None:
self._seat = seat
self._rng = rng or random.Random()
self._wobble = self._rng.random() * 6.28
self._aim_since: Optional[float] = None
self._react = 0.2
self._held = False
def decide(self, view: Optional[Dict[str, Any]]) -> Input:
if not view or view.get("phase") not in ("play", "point"):
self._held = False
return NEUTRAL
me, foe = view["p"][self._seat], view["p"][1 - self._seat]
rim, t = view["rim"], view["t"]
mx, my, fx, fy = me["x"], me["y"], foe["x"], foe["y"]
my_radius, foe_radius = math.hypot(mx, my), math.hypot(fx, fy)
gap = math.hypot(fx - mx, fy - my)
# Where to go.
spark = view.get("spark")
if view["phase"] == "point" or foe["out"]:
tx, ty = 0.0, 0.0
elif spark and not me["boost"] and math.hypot(spark[0] - mx, spark[1] - my) < math.hypot(spark[0] - fx, spark[1] - fy) + 0.2:
tx, ty = spark[0], spark[1]
elif foe_radius > 0.12:
inside = max(0.0, foe_radius - 0.2) / foe_radius # a point on the centre's side of the other skimmer
tx, ty = fx * inside, fy * inside
else:
tx, ty = fx, fy
sx, sy = (tx - mx) * 3.0 - me["vx"] * 0.9, (ty - my) * 3.0 - me["vy"] * 0.9
margin = rim - my_radius
if margin < 0.24 and my_radius > 0: # too close to the rim: back to the middle first
pull = (0.24 - margin) / 0.24 * 4.0
sx -= mx / my_radius * pull + me["vx"] * 0.8
sy -= my / my_radius * pull + me["vy"] * 0.8
self._wobble += 0.05
sx += math.sin(self._wobble * 1.3) * 0.35
sy += math.cos(self._wobble) * 0.35
length = math.hypot(sx, sy)
if length > 1.0:
sx, sy = sx / length, sy / length
# When to send a shock: the other skimmer is in reach and the push has an outward part.
reach = (BOOST_RADIUS if me["boost"] else SHOCK_RADIUS) * 0.72
outward = (fx - mx) * fx + (fy - my) * fy
aimed = view["phase"] == "play" and me["charge"] >= 1.0 and gap < reach and (outward > 0 or foe_radius < 0.1)
press = False
if aimed:
if self._aim_since is None:
self._aim_since = t
self._react = 0.08 + self._rng.random() * 0.3
press = t - self._aim_since >= self._react and not self._held
else:
self._aim_since = None
self._held = press # one tick down, then up again: the game fires on the press
return (sx, sy, press)
def main() -> int:
parser = argparse.ArgumentParser(description="Rimshock without a screen: two computer players, as fast as the machine goes.")
parser.add_argument("--matches", type=int, default=1, help="how many matches to play (default 1)")
parser.add_argument("--seed", type=int, default=None, help="the same seed plays the same matches")
args = parser.parse_args()
rng = random.Random(args.seed)
game = Game(rng)
players = [ComputerPlayer(0, rng), ComputerPlayer(1, rng)]
game.new_match()
matches, wins, rounds = 0, [0, 0], []
while matches < args.matches:
view = game.snapshot()
for event in game.step([players[0].decide(view), players[1].decide(view)]):
if event["event"] == "fall":
rounds.append(game.clock)
print(f" round {event['round']}: seat {event['seat']} left the plate after {game.clock:.1f} s, {event['score'][0]} : {event['score'][1]}")
elif event["event"] == "draw":
rounds.append(game.clock)
print(f" round {event['round']}: both left the plate after {game.clock:.1f} s, no point")
elif event["event"] == "match":
matches += 1
wins[event["winner"]] += 1
print(f"match {matches}: seat {event['winner']} wins {event['score'][0]} : {event['score'][1]} in {event['rounds']} rounds, {event['seconds']} s of play")
if game.t > args.matches * 3600:
print("The matches did not end within an hour of simulated time each.")
return 1
print(f"{matches} match(es), wins {wins[0]} : {wins[1]}, rounds from {min(rounds):.1f} s to {max(rounds):.1f} s, {sum(rounds) / len(rounds):.1f} s on average")
return 0
if __name__ == "__main__":
raise SystemExit(main())