orbi2d 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- orbi2d/__init__.py +4 -0
- orbi2d/__main__.py +29 -0
- orbi2d/game.py +157 -0
- orbi2d/physics.py +182 -0
- orbi2d/view.py +365 -0
- orbi2d-0.1.0.dist-info/METADATA +93 -0
- orbi2d-0.1.0.dist-info/RECORD +11 -0
- orbi2d-0.1.0.dist-info/WHEEL +5 -0
- orbi2d-0.1.0.dist-info/entry_points.txt +2 -0
- orbi2d-0.1.0.dist-info/licenses/LICENSE +21 -0
- orbi2d-0.1.0.dist-info/top_level.txt +1 -0
orbi2d/__init__.py
ADDED
orbi2d/__main__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PiRK
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from PySide6.QtWidgets import QApplication, QMainWindow
|
|
8
|
+
|
|
9
|
+
from .view import GameWidget
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main() -> int:
|
|
13
|
+
parser = argparse.ArgumentParser(description="Bring your rocket into the target orbit.")
|
|
14
|
+
parser.add_argument("--seed", type=int, default=None, help="seed for the first level")
|
|
15
|
+
args = parser.parse_args()
|
|
16
|
+
|
|
17
|
+
app = QApplication(sys.argv[:1])
|
|
18
|
+
win = QMainWindow()
|
|
19
|
+
win.setWindowTitle("orbi2d")
|
|
20
|
+
widget = GameWidget(seed=args.seed)
|
|
21
|
+
win.setCentralWidget(widget)
|
|
22
|
+
win.resize(1100, 850)
|
|
23
|
+
win.show()
|
|
24
|
+
widget.setFocus()
|
|
25
|
+
return app.exec()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
if __name__ == "__main__":
|
|
29
|
+
sys.exit(main())
|
orbi2d/game.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PiRK
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Game state and rules (no Qt dependency, so it can be unit-tested)."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
import random
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from .physics import Orbit, Vec, propagate
|
|
13
|
+
|
|
14
|
+
# ---- tuning --------------------------------------------------------------
|
|
15
|
+
MU = 1.5e6 # gravitational parameter (world units^3 / s^2)
|
|
16
|
+
PLANET_RADIUS = 40.0 # world units
|
|
17
|
+
MIN_PERIAPSIS = 80.0 # random orbits never come closer than this
|
|
18
|
+
MAX_APOAPSIS = 330.0 # ... nor farther than this
|
|
19
|
+
MAIN_THRUST = 15.0 # main engine acceleration (units / s^2)
|
|
20
|
+
FINE_THRUST = 1.5 # with Shift held
|
|
21
|
+
ROTATION_SPEED = math.radians(180) # rad / s
|
|
22
|
+
FINE_ROTATION_SPEED = math.radians(40) # with Shift held
|
|
23
|
+
TOLERANCE = 0.02 # max relative radial deviation to win (2 %)
|
|
24
|
+
ESCAPE_RADIUS = 3000.0 # beyond this the rocket is lost
|
|
25
|
+
MAX_STEP_DISTANCE = 4.0 # sub-step size used for collision / thrust
|
|
26
|
+
WARP_PRESETS = (0.25, 0.5, 1.0, 2.0, 4.0, 8.0) # keys 1-6
|
|
27
|
+
DEFAULT_WARP = 0.5
|
|
28
|
+
MIN_WARP = 0.1
|
|
29
|
+
MAX_WARP = 16.0
|
|
30
|
+
WARP_STEP = 1.25 # +/- multiply / divide the warp by this
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Controls:
|
|
35
|
+
left: bool = False
|
|
36
|
+
right: bool = False
|
|
37
|
+
thrust: bool = False
|
|
38
|
+
fine: bool = False
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def state_on_orbit(orbit: Orbit, true_anomaly: float, mu: float) -> tuple[Vec, Vec]:
|
|
42
|
+
"""Position and velocity of a body at ``true_anomaly`` on ``orbit``."""
|
|
43
|
+
r = orbit.point_at(true_anomaly)
|
|
44
|
+
k = math.sqrt(mu / orbit.p) * orbit.h_sign
|
|
45
|
+
# Perifocal velocity, then rotate by omega.
|
|
46
|
+
vpx = -k * math.sin(true_anomaly)
|
|
47
|
+
vpy = k * (orbit.e + math.cos(true_anomaly))
|
|
48
|
+
c, s = math.cos(orbit.omega), math.sin(orbit.omega)
|
|
49
|
+
return r, (c * vpx - s * vpy, s * vpx + c * vpy)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def random_orbit(rng: random.Random) -> Orbit:
|
|
53
|
+
rp = rng.uniform(MIN_PERIAPSIS, MAX_APOAPSIS * 0.7)
|
|
54
|
+
ra = rng.uniform(rp, MAX_APOAPSIS)
|
|
55
|
+
return Orbit.from_apsides(rp, ra, rng.uniform(0, 2 * math.pi))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass
|
|
59
|
+
class Game:
|
|
60
|
+
seed: int | None = None
|
|
61
|
+
mu: float = MU
|
|
62
|
+
planet_radius: float = PLANET_RADIUS
|
|
63
|
+
tolerance: float = TOLERANCE
|
|
64
|
+
|
|
65
|
+
r: Vec = (0.0, 0.0)
|
|
66
|
+
v: Vec = (0.0, 0.0)
|
|
67
|
+
heading: float = 0.0 # direction the nose points (rad)
|
|
68
|
+
orbit: Orbit = field(default=None) # type: ignore[assignment]
|
|
69
|
+
target: Orbit = field(default=None) # type: ignore[assignment]
|
|
70
|
+
status: str = "playing" # playing | won | crashed | escaped
|
|
71
|
+
thrusting: bool = False
|
|
72
|
+
rotating: int = 0 # -1 right (cw), +1 left (ccw), 0 none
|
|
73
|
+
time_warp: float = DEFAULT_WARP # game seconds per real second
|
|
74
|
+
elapsed: float = 0.0
|
|
75
|
+
burn_dv: float = 0.0 # total delta-v spent
|
|
76
|
+
deviation: float = math.inf
|
|
77
|
+
|
|
78
|
+
def __post_init__(self) -> None:
|
|
79
|
+
self.reset(self.seed)
|
|
80
|
+
|
|
81
|
+
# ------------------------------------------------------------------
|
|
82
|
+
def reset(self, seed: int | None = None) -> None:
|
|
83
|
+
rng = random.Random(seed)
|
|
84
|
+
start = random_orbit(rng)
|
|
85
|
+
target = random_orbit(rng)
|
|
86
|
+
# Make sure there is actually something to do.
|
|
87
|
+
while target.deviation_from(start) < 0.3 or start.deviation_from(target) < 0.3:
|
|
88
|
+
target = random_orbit(rng)
|
|
89
|
+
self.target = target
|
|
90
|
+
self.r, self.v = state_on_orbit(start, rng.uniform(0, 2 * math.pi), self.mu)
|
|
91
|
+
self.heading = math.atan2(self.v[1], self.v[0]) # start pointing prograde
|
|
92
|
+
self.status = "playing"
|
|
93
|
+
self.thrusting = False
|
|
94
|
+
self.rotating = 0
|
|
95
|
+
self.elapsed = 0.0
|
|
96
|
+
self.burn_dv = 0.0
|
|
97
|
+
self._refresh_orbit()
|
|
98
|
+
|
|
99
|
+
def set_warp(self, warp: float) -> None:
|
|
100
|
+
# Snap to 3 significant digits so repeated +/- steps don't drift
|
|
101
|
+
# (0.5 * 1.25 / 1.25 lands back on exactly 0.5).
|
|
102
|
+
warp = float(f"{warp:.3g}")
|
|
103
|
+
self.time_warp = max(MIN_WARP, min(MAX_WARP, warp))
|
|
104
|
+
|
|
105
|
+
def faster(self) -> None:
|
|
106
|
+
self.set_warp(self.time_warp * WARP_STEP)
|
|
107
|
+
|
|
108
|
+
def slower(self) -> None:
|
|
109
|
+
self.set_warp(self.time_warp / WARP_STEP)
|
|
110
|
+
|
|
111
|
+
def _refresh_orbit(self) -> None:
|
|
112
|
+
self.orbit = Orbit.from_state(self.r, self.v, self.mu)
|
|
113
|
+
self.deviation = self.orbit.deviation_from(self.target)
|
|
114
|
+
|
|
115
|
+
# ------------------------------------------------------------------
|
|
116
|
+
def update(self, dt: float, controls: Controls) -> None:
|
|
117
|
+
if self.status != "playing":
|
|
118
|
+
self.thrusting = False
|
|
119
|
+
self.rotating = 0
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
# Side thrusters: orientation only, real time (not warped).
|
|
123
|
+
self.rotating = int(controls.left) - int(controls.right)
|
|
124
|
+
rot = FINE_ROTATION_SPEED if controls.fine else ROTATION_SPEED
|
|
125
|
+
self.heading = (self.heading + self.rotating * rot * dt) % (2 * math.pi)
|
|
126
|
+
|
|
127
|
+
self.thrusting = controls.thrust
|
|
128
|
+
accel = (FINE_THRUST if controls.fine else MAIN_THRUST) if self.thrusting else 0.0
|
|
129
|
+
|
|
130
|
+
sim_dt = dt * self.time_warp
|
|
131
|
+
self.elapsed += sim_dt
|
|
132
|
+
speed = math.hypot(*self.v)
|
|
133
|
+
n = max(1, math.ceil(speed * sim_dt / MAX_STEP_DISTANCE))
|
|
134
|
+
h = sim_dt / n
|
|
135
|
+
ux, uy = math.cos(self.heading), math.sin(self.heading)
|
|
136
|
+
for _ in range(n):
|
|
137
|
+
if accel:
|
|
138
|
+
# Kick-drift-kick: half an impulse, exact Kepler coast, half
|
|
139
|
+
# an impulse. Second order accurate for finite burns.
|
|
140
|
+
dv = 0.5 * accel * h
|
|
141
|
+
self.v = (self.v[0] + dv * ux, self.v[1] + dv * uy)
|
|
142
|
+
self.r, self.v = propagate(self.r, self.v, h, self.mu)
|
|
143
|
+
self.v = (self.v[0] + dv * ux, self.v[1] + dv * uy)
|
|
144
|
+
self.burn_dv += accel * h
|
|
145
|
+
else:
|
|
146
|
+
self.r, self.v = propagate(self.r, self.v, h, self.mu)
|
|
147
|
+
if math.hypot(*self.r) <= self.planet_radius:
|
|
148
|
+
self.status = "crashed"
|
|
149
|
+
break
|
|
150
|
+
|
|
151
|
+
self._refresh_orbit()
|
|
152
|
+
if self.status != "playing":
|
|
153
|
+
return
|
|
154
|
+
if math.hypot(*self.r) > ESCAPE_RADIUS:
|
|
155
|
+
self.status = "escaped"
|
|
156
|
+
elif not self.thrusting and self.deviation <= self.tolerance:
|
|
157
|
+
self.status = "won"
|
orbi2d/physics.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PiRK
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Two-body orbital mechanics in 2D.
|
|
5
|
+
|
|
6
|
+
The rocket is a point mass orbiting a planet of gravitational parameter ``mu``.
|
|
7
|
+
Coasting is propagated *analytically* with the universal-variable Kepler
|
|
8
|
+
solution, so the rocket follows its conic exactly (no integrator drift) and
|
|
9
|
+
the drawn orbit always matches the actual trajectory. Thrust is applied as a
|
|
10
|
+
sequence of small velocity kicks; after every kick the osculating orbit is
|
|
11
|
+
recomputed from the new state vector. That makes every manoeuvre - prograde,
|
|
12
|
+
retrograde, radial, or any arbitrary direction at any point of the orbit -
|
|
13
|
+
behave according to real orbital mechanics.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
|
|
21
|
+
Vec = tuple[float, float]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _stumpff(z: float) -> tuple[float, float]:
|
|
25
|
+
"""Stumpff functions C(z), S(z)."""
|
|
26
|
+
if z > 1e-4:
|
|
27
|
+
s = math.sqrt(z)
|
|
28
|
+
return (1.0 - math.cos(s)) / z, (s - math.sin(s)) / (s * s * s)
|
|
29
|
+
if z < -1e-4:
|
|
30
|
+
s = math.sqrt(-z)
|
|
31
|
+
return (math.cosh(s) - 1.0) / (-z), (math.sinh(s) - s) / (s * s * s)
|
|
32
|
+
# Series expansion around z = 0 (parabolic / very short arcs).
|
|
33
|
+
return (
|
|
34
|
+
1.0 / 2 - z / 24 + z * z / 720 - z ** 3 / 40320,
|
|
35
|
+
1.0 / 6 - z / 120 + z * z / 5040 - z ** 3 / 362880,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def propagate(r0: Vec, v0: Vec, dt: float, mu: float) -> tuple[Vec, Vec]:
|
|
40
|
+
"""Advance a Keplerian state (r0, v0) by ``dt`` (any conic: ellipse,
|
|
41
|
+
parabola or hyperbola) using the universal-variable formulation."""
|
|
42
|
+
if dt == 0.0:
|
|
43
|
+
return r0, v0
|
|
44
|
+
x0, y0 = r0
|
|
45
|
+
vx0, vy0 = v0
|
|
46
|
+
rn = math.hypot(x0, y0)
|
|
47
|
+
v2 = vx0 * vx0 + vy0 * vy0
|
|
48
|
+
vr = (x0 * vx0 + y0 * vy0) / rn
|
|
49
|
+
sqmu = math.sqrt(mu)
|
|
50
|
+
alpha = 2.0 / rn - v2 / mu # 1/a (negative for hyperbolas)
|
|
51
|
+
|
|
52
|
+
# Newton iteration on the universal anomaly chi.
|
|
53
|
+
if alpha > 1e-9:
|
|
54
|
+
chi = sqmu * dt * alpha
|
|
55
|
+
else:
|
|
56
|
+
chi = sqmu * dt / rn
|
|
57
|
+
k1 = rn * vr / sqmu
|
|
58
|
+
k2 = 1.0 - alpha * rn
|
|
59
|
+
for _ in range(50):
|
|
60
|
+
z = alpha * chi * chi
|
|
61
|
+
c, s = _stumpff(z)
|
|
62
|
+
chi2 = chi * chi
|
|
63
|
+
f = k1 * chi2 * c + k2 * chi2 * chi * s + rn * chi - sqmu * dt
|
|
64
|
+
fp = k1 * chi * (1.0 - z * s) + k2 * chi2 * c + rn
|
|
65
|
+
step = f / fp
|
|
66
|
+
chi -= step
|
|
67
|
+
if abs(step) < 1e-12 * max(1.0, abs(chi)):
|
|
68
|
+
break
|
|
69
|
+
|
|
70
|
+
z = alpha * chi * chi
|
|
71
|
+
c, s = _stumpff(z)
|
|
72
|
+
chi2 = chi * chi
|
|
73
|
+
f = 1.0 - chi2 / rn * c
|
|
74
|
+
g = dt - chi2 * chi / sqmu * s
|
|
75
|
+
x = f * x0 + g * vx0
|
|
76
|
+
y = f * y0 + g * vy0
|
|
77
|
+
r = math.hypot(x, y)
|
|
78
|
+
fdot = sqmu / (r * rn) * (alpha * chi2 * chi * s - chi)
|
|
79
|
+
gdot = 1.0 - chi2 / r * c
|
|
80
|
+
return (x, y), (fdot * x0 + gdot * vx0, fdot * y0 + gdot * vy0)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass(frozen=True)
|
|
84
|
+
class Orbit:
|
|
85
|
+
"""Shape of a conic orbit around the planet (focus at the origin).
|
|
86
|
+
|
|
87
|
+
Defined by the semi-latus rectum ``p``, eccentricity ``e`` and argument of
|
|
88
|
+
periapsis ``omega`` (angle of the periapsis direction). ``h_sign`` is +1
|
|
89
|
+
for counter-clockwise motion and -1 for clockwise motion.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
p: float
|
|
93
|
+
e: float
|
|
94
|
+
omega: float
|
|
95
|
+
h_sign: float = 1.0
|
|
96
|
+
|
|
97
|
+
# ---- construction -------------------------------------------------
|
|
98
|
+
@staticmethod
|
|
99
|
+
def from_apsides(rp: float, ra: float, omega: float, h_sign: float = 1.0) -> "Orbit":
|
|
100
|
+
e = (ra - rp) / (ra + rp)
|
|
101
|
+
return Orbit(p=rp * (1.0 + e), e=e, omega=omega, h_sign=h_sign)
|
|
102
|
+
|
|
103
|
+
@staticmethod
|
|
104
|
+
def from_state(r: Vec, v: Vec, mu: float) -> "Orbit":
|
|
105
|
+
x, y = r
|
|
106
|
+
vx, vy = v
|
|
107
|
+
rn = math.hypot(x, y)
|
|
108
|
+
v2 = vx * vx + vy * vy
|
|
109
|
+
h = x * vy - y * vx
|
|
110
|
+
rv = x * vx + y * vy
|
|
111
|
+
ex = ((v2 - mu / rn) * x - rv * vx) / mu
|
|
112
|
+
ey = ((v2 - mu / rn) * y - rv * vy) / mu
|
|
113
|
+
e = math.hypot(ex, ey)
|
|
114
|
+
omega = math.atan2(ey, ex) if e > 1e-12 else 0.0
|
|
115
|
+
return Orbit(p=h * h / mu, e=e, omega=omega, h_sign=1.0 if h >= 0 else -1.0)
|
|
116
|
+
|
|
117
|
+
# ---- derived quantities -------------------------------------------
|
|
118
|
+
@property
|
|
119
|
+
def bound(self) -> bool:
|
|
120
|
+
return self.e < 1.0
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def periapsis(self) -> float:
|
|
124
|
+
return self.p / (1.0 + self.e)
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def apoapsis(self) -> float:
|
|
128
|
+
return self.p / (1.0 - self.e) if self.e < 1.0 else math.inf
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def semi_major_axis(self) -> float:
|
|
132
|
+
return self.p / (1.0 - self.e * self.e) if self.e != 1.0 else math.inf
|
|
133
|
+
|
|
134
|
+
def period(self, mu: float) -> float:
|
|
135
|
+
if not self.bound:
|
|
136
|
+
return math.inf
|
|
137
|
+
a = self.semi_major_axis
|
|
138
|
+
return 2.0 * math.pi * math.sqrt(a ** 3 / mu)
|
|
139
|
+
|
|
140
|
+
def radius_at(self, true_anomaly: float) -> float:
|
|
141
|
+
denom = 1.0 + self.e * math.cos(true_anomaly)
|
|
142
|
+
return self.p / denom if denom > 1e-12 else math.inf
|
|
143
|
+
|
|
144
|
+
def radius_at_angle(self, theta: float) -> float:
|
|
145
|
+
"""Radius of the orbit curve along polar direction ``theta``."""
|
|
146
|
+
return self.radius_at(theta - self.omega)
|
|
147
|
+
|
|
148
|
+
def point_at(self, true_anomaly: float) -> Vec:
|
|
149
|
+
r = self.radius_at(true_anomaly)
|
|
150
|
+
ang = self.omega + true_anomaly
|
|
151
|
+
return r * math.cos(ang), r * math.sin(ang)
|
|
152
|
+
|
|
153
|
+
def sample(self, n: int = 360, r_max: float = math.inf) -> list[Vec]:
|
|
154
|
+
"""Points along the orbit curve (closed loop for ellipses, a single
|
|
155
|
+
clipped branch for parabolas / hyperbolas)."""
|
|
156
|
+
if self.bound:
|
|
157
|
+
return [self.point_at(2.0 * math.pi * i / n) for i in range(n + 1)]
|
|
158
|
+
# Asymptote true anomaly; clip the branch at r_max.
|
|
159
|
+
nu_inf = math.acos(-1.0 / self.e)
|
|
160
|
+
nu_lim = nu_inf - 1e-3
|
|
161
|
+
if math.isfinite(r_max):
|
|
162
|
+
# r(nu) = r_max -> cos(nu) = (p / r_max - 1) / e
|
|
163
|
+
c = (self.p / r_max - 1.0) / self.e
|
|
164
|
+
if -1.0 <= c <= 1.0:
|
|
165
|
+
nu_lim = min(nu_lim, math.acos(c))
|
|
166
|
+
return [self.point_at(-nu_lim + 2.0 * nu_lim * i / n) for i in range(n + 1)]
|
|
167
|
+
|
|
168
|
+
def deviation_from(self, target: "Orbit", samples: int = 360) -> float:
|
|
169
|
+
"""Maximum relative radial distance between this orbit's curve and
|
|
170
|
+
``target``'s curve, over all polar directions. 0 means identical.
|
|
171
|
+
|
|
172
|
+
This is a purely geometric comparison: it is well defined for
|
|
173
|
+
near-circular orbits (where the argument of periapsis is meaningless)
|
|
174
|
+
and treats any combination of size, shape and orientation errors."""
|
|
175
|
+
if not self.bound:
|
|
176
|
+
return math.inf
|
|
177
|
+
worst = 0.0
|
|
178
|
+
for i in range(samples):
|
|
179
|
+
th = 2.0 * math.pi * i / samples
|
|
180
|
+
rt = target.radius_at_angle(th)
|
|
181
|
+
worst = max(worst, abs(self.radius_at_angle(th) - rt) / rt)
|
|
182
|
+
return worst
|
orbi2d/view.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 PiRK
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
|
|
4
|
+
"""Qt rendering and input handling."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import math
|
|
9
|
+
import random
|
|
10
|
+
|
|
11
|
+
from PySide6.QtCore import QElapsedTimer, QPointF, QRectF, Qt, QTimer
|
|
12
|
+
from PySide6.QtGui import (
|
|
13
|
+
QBrush,
|
|
14
|
+
QColor,
|
|
15
|
+
QFont,
|
|
16
|
+
QKeyEvent,
|
|
17
|
+
QPainter,
|
|
18
|
+
QPainterPath,
|
|
19
|
+
QPen,
|
|
20
|
+
QPolygonF,
|
|
21
|
+
QRadialGradient,
|
|
22
|
+
)
|
|
23
|
+
from PySide6.QtWidgets import QWidget
|
|
24
|
+
|
|
25
|
+
from . import game as g
|
|
26
|
+
from .physics import Orbit
|
|
27
|
+
|
|
28
|
+
BG = QColor(6, 8, 18)
|
|
29
|
+
CURRENT_COLOR = QColor(80, 190, 255)
|
|
30
|
+
TARGET_COLOR = QColor(110, 255, 140)
|
|
31
|
+
WARN_COLOR = QColor(255, 200, 80)
|
|
32
|
+
BAD_COLOR = QColor(255, 90, 90)
|
|
33
|
+
TEXT_COLOR = QColor(220, 225, 235)
|
|
34
|
+
DIM_TEXT = QColor(140, 150, 170)
|
|
35
|
+
|
|
36
|
+
MIN_VIEW_EXTENT = 380.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class GameWidget(QWidget):
|
|
40
|
+
def __init__(self, seed: int | None = None) -> None:
|
|
41
|
+
super().__init__()
|
|
42
|
+
self.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
|
43
|
+
self.setMinimumSize(640, 480)
|
|
44
|
+
self.game = g.Game(seed=seed)
|
|
45
|
+
self.controls = g.Controls()
|
|
46
|
+
self.paused = False
|
|
47
|
+
self.show_help = True
|
|
48
|
+
self.view_extent = self._desired_extent()
|
|
49
|
+
|
|
50
|
+
rng = random.Random(1234)
|
|
51
|
+
self.stars = [(rng.random(), rng.random(), rng.uniform(0.3, 1.0)) for _ in range(220)]
|
|
52
|
+
|
|
53
|
+
self.clock = QElapsedTimer()
|
|
54
|
+
self.clock.start()
|
|
55
|
+
self.timer = QTimer(self)
|
|
56
|
+
self.timer.timeout.connect(self._tick)
|
|
57
|
+
self.timer.start(16)
|
|
58
|
+
|
|
59
|
+
# ---- loop ------------------------------------------------------------
|
|
60
|
+
def _tick(self) -> None:
|
|
61
|
+
dt = min(self.clock.restart() / 1000.0, 0.05)
|
|
62
|
+
if not self.paused:
|
|
63
|
+
self.game.update(dt, self.controls)
|
|
64
|
+
desired = self._desired_extent()
|
|
65
|
+
self.view_extent += (desired - self.view_extent) * min(1.0, dt * 2.5)
|
|
66
|
+
self.update()
|
|
67
|
+
|
|
68
|
+
def _desired_extent(self) -> float:
|
|
69
|
+
gm = self.game
|
|
70
|
+
rn = math.hypot(*gm.r)
|
|
71
|
+
far = max(gm.target.apoapsis, rn)
|
|
72
|
+
if gm.orbit.bound:
|
|
73
|
+
far = max(far, min(gm.orbit.apoapsis, g.ESCAPE_RADIUS))
|
|
74
|
+
return max(MIN_VIEW_EXTENT, 1.12 * far)
|
|
75
|
+
|
|
76
|
+
# ---- input -----------------------------------------------------------
|
|
77
|
+
def _set_key(self, event: QKeyEvent, pressed: bool) -> bool:
|
|
78
|
+
key = event.key()
|
|
79
|
+
if key == Qt.Key.Key_Left:
|
|
80
|
+
self.controls.left = pressed
|
|
81
|
+
elif key == Qt.Key.Key_Right:
|
|
82
|
+
self.controls.right = pressed
|
|
83
|
+
elif key == Qt.Key.Key_Up:
|
|
84
|
+
self.controls.thrust = pressed
|
|
85
|
+
elif key == Qt.Key.Key_Shift:
|
|
86
|
+
self.controls.fine = pressed
|
|
87
|
+
else:
|
|
88
|
+
return False
|
|
89
|
+
return True
|
|
90
|
+
|
|
91
|
+
def keyPressEvent(self, event: QKeyEvent) -> None: # noqa: N802
|
|
92
|
+
if self._set_key(event, True):
|
|
93
|
+
return
|
|
94
|
+
if event.isAutoRepeat():
|
|
95
|
+
return
|
|
96
|
+
key = event.key()
|
|
97
|
+
gm = self.game
|
|
98
|
+
if key in (Qt.Key.Key_R, Qt.Key.Key_N) or (
|
|
99
|
+
key in (Qt.Key.Key_Space, Qt.Key.Key_Return, Qt.Key.Key_Enter)
|
|
100
|
+
and gm.status != "playing"
|
|
101
|
+
):
|
|
102
|
+
gm.reset()
|
|
103
|
+
self.paused = False
|
|
104
|
+
elif key == Qt.Key.Key_P:
|
|
105
|
+
self.paused = not self.paused
|
|
106
|
+
elif key == Qt.Key.Key_H:
|
|
107
|
+
self.show_help = not self.show_help
|
|
108
|
+
elif Qt.Key.Key_1 <= key < Qt.Key.Key_1 + len(g.WARP_PRESETS):
|
|
109
|
+
gm.set_warp(g.WARP_PRESETS[key - Qt.Key.Key_1])
|
|
110
|
+
elif key in (Qt.Key.Key_Plus, Qt.Key.Key_Equal):
|
|
111
|
+
gm.faster()
|
|
112
|
+
elif key in (Qt.Key.Key_Minus, Qt.Key.Key_Underscore):
|
|
113
|
+
gm.slower()
|
|
114
|
+
elif key in (Qt.Key.Key_Escape, Qt.Key.Key_Q):
|
|
115
|
+
self.window().close()
|
|
116
|
+
else:
|
|
117
|
+
super().keyPressEvent(event)
|
|
118
|
+
|
|
119
|
+
def keyReleaseEvent(self, event: QKeyEvent) -> None: # noqa: N802
|
|
120
|
+
if event.isAutoRepeat():
|
|
121
|
+
return
|
|
122
|
+
if not self._set_key(event, False):
|
|
123
|
+
super().keyReleaseEvent(event)
|
|
124
|
+
|
|
125
|
+
def focusOutEvent(self, event) -> None: # noqa: N802
|
|
126
|
+
# Don't leave the engine stuck on when the window loses focus.
|
|
127
|
+
self.controls = g.Controls()
|
|
128
|
+
super().focusOutEvent(event)
|
|
129
|
+
|
|
130
|
+
# ---- coordinates -------------------------------------------------------
|
|
131
|
+
@property
|
|
132
|
+
def scale(self) -> float:
|
|
133
|
+
return 0.5 * min(self.width(), self.height()) / self.view_extent
|
|
134
|
+
|
|
135
|
+
def to_screen(self, x: float, y: float) -> QPointF:
|
|
136
|
+
s = self.scale
|
|
137
|
+
return QPointF(self.width() / 2 + x * s, self.height() / 2 - y * s)
|
|
138
|
+
|
|
139
|
+
# ---- painting ----------------------------------------------------------
|
|
140
|
+
def paintEvent(self, event) -> None: # noqa: N802
|
|
141
|
+
p = QPainter(self)
|
|
142
|
+
p.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
143
|
+
p.fillRect(self.rect(), BG)
|
|
144
|
+
self._draw_stars(p)
|
|
145
|
+
|
|
146
|
+
gm = self.game
|
|
147
|
+
matched = gm.deviation <= gm.tolerance
|
|
148
|
+
self._draw_orbit(p, gm.target, TARGET_COLOR, dashed=True, width=2.0 if not matched else 3.0)
|
|
149
|
+
cur_color = TARGET_COLOR if matched else (BAD_COLOR if not gm.orbit.bound else CURRENT_COLOR)
|
|
150
|
+
self._draw_orbit(p, gm.orbit, cur_color, dashed=False, width=1.6)
|
|
151
|
+
self._draw_planet(p)
|
|
152
|
+
self._draw_apsides(p, gm.target, TARGET_COLOR)
|
|
153
|
+
self._draw_apsides(p, gm.orbit, cur_color)
|
|
154
|
+
self._draw_rocket(p)
|
|
155
|
+
self._draw_hud(p)
|
|
156
|
+
self._draw_banner(p)
|
|
157
|
+
p.end()
|
|
158
|
+
|
|
159
|
+
def _draw_stars(self, p: QPainter) -> None:
|
|
160
|
+
w, h = self.width(), self.height()
|
|
161
|
+
for sx, sy, b in self.stars:
|
|
162
|
+
c = int(90 + 120 * b)
|
|
163
|
+
p.setPen(QColor(c, c, c + 20 if c < 235 else 255))
|
|
164
|
+
p.drawPoint(QPointF(sx * w, sy * h))
|
|
165
|
+
|
|
166
|
+
def _draw_planet(self, p: QPainter) -> None:
|
|
167
|
+
c = self.to_screen(0, 0)
|
|
168
|
+
r = self.game.planet_radius * self.scale
|
|
169
|
+
grad = QRadialGradient(c + QPointF(-0.35 * r, -0.35 * r), 1.3 * r)
|
|
170
|
+
grad.setColorAt(0.0, QColor(120, 170, 255))
|
|
171
|
+
grad.setColorAt(0.6, QColor(40, 90, 190))
|
|
172
|
+
grad.setColorAt(1.0, QColor(10, 25, 70))
|
|
173
|
+
# Thin atmosphere glow.
|
|
174
|
+
glow = QRadialGradient(c, r * 1.25)
|
|
175
|
+
glow.setColorAt(0.75, QColor(100, 160, 255, 90))
|
|
176
|
+
glow.setColorAt(1.0, QColor(100, 160, 255, 0))
|
|
177
|
+
p.setPen(Qt.PenStyle.NoPen)
|
|
178
|
+
p.setBrush(QBrush(glow))
|
|
179
|
+
p.drawEllipse(c, r * 1.25, r * 1.25)
|
|
180
|
+
p.setBrush(QBrush(grad))
|
|
181
|
+
p.drawEllipse(c, r, r)
|
|
182
|
+
|
|
183
|
+
def _draw_orbit(self, p: QPainter, orbit: Orbit, color: QColor, dashed: bool, width: float) -> None:
|
|
184
|
+
pts = orbit.sample(480, r_max=g.ESCAPE_RADIUS)
|
|
185
|
+
path = QPainterPath(self.to_screen(*pts[0]))
|
|
186
|
+
for x, y in pts[1:]:
|
|
187
|
+
path.lineTo(self.to_screen(x, y))
|
|
188
|
+
pen = QPen(color, width)
|
|
189
|
+
if dashed:
|
|
190
|
+
pen.setStyle(Qt.PenStyle.DashLine)
|
|
191
|
+
p.setPen(pen)
|
|
192
|
+
p.setBrush(Qt.BrushStyle.NoBrush)
|
|
193
|
+
p.drawPath(path)
|
|
194
|
+
|
|
195
|
+
def _draw_apsides(self, p: QPainter, orbit: Orbit, color: QColor) -> None:
|
|
196
|
+
if orbit.e < 1e-3:
|
|
197
|
+
return # circular: apsides undefined
|
|
198
|
+
p.setFont(QFont("monospace", 8))
|
|
199
|
+
marks = [("Pe", 0.0)]
|
|
200
|
+
if orbit.bound:
|
|
201
|
+
marks.append(("Ap", math.pi))
|
|
202
|
+
for label, nu in marks:
|
|
203
|
+
pt = self.to_screen(*orbit.point_at(nu))
|
|
204
|
+
p.setPen(QPen(color, 1.5))
|
|
205
|
+
p.setBrush(QBrush(BG))
|
|
206
|
+
p.drawEllipse(pt, 3.5, 3.5)
|
|
207
|
+
p.setPen(color)
|
|
208
|
+
p.drawText(pt + QPointF(6, -6), label)
|
|
209
|
+
|
|
210
|
+
def _draw_rocket(self, p: QPainter) -> None:
|
|
211
|
+
gm = self.game
|
|
212
|
+
pos = self.to_screen(*gm.r)
|
|
213
|
+
# Screen y is flipped, so negate the angle for Qt's rotation.
|
|
214
|
+
p.save()
|
|
215
|
+
p.translate(pos)
|
|
216
|
+
|
|
217
|
+
# Prograde / retrograde markers around the ship.
|
|
218
|
+
vx, vy = gm.v
|
|
219
|
+
vang = -math.atan2(vy, vx)
|
|
220
|
+
ring = 26.0
|
|
221
|
+
pro = QPointF(ring * math.cos(vang), ring * math.sin(vang))
|
|
222
|
+
p.setPen(QPen(QColor(230, 230, 100), 1.4))
|
|
223
|
+
p.setBrush(Qt.BrushStyle.NoBrush)
|
|
224
|
+
p.drawEllipse(pro, 3.5, 3.5)
|
|
225
|
+
p.drawLine(pro + QPointF(0, -3.5), pro + QPointF(0, -7))
|
|
226
|
+
retro = -pro
|
|
227
|
+
p.setPen(QPen(QColor(230, 120, 100), 1.4))
|
|
228
|
+
p.drawLine(retro + QPointF(-3.5, -3.5), retro + QPointF(3.5, 3.5))
|
|
229
|
+
p.drawLine(retro + QPointF(-3.5, 3.5), retro + QPointF(3.5, -3.5))
|
|
230
|
+
|
|
231
|
+
p.rotate(-math.degrees(gm.heading))
|
|
232
|
+
p.scale(1.4, 1.4)
|
|
233
|
+
# Ship body pointing along +x.
|
|
234
|
+
body = QPolygonF([
|
|
235
|
+
QPointF(13, 0), QPointF(4, -5), QPointF(-9, -5),
|
|
236
|
+
QPointF(-9, 5), QPointF(4, 5),
|
|
237
|
+
])
|
|
238
|
+
if gm.thrusting:
|
|
239
|
+
flame_len = (10 + 8 * random.random()) * (0.5 if self.controls.fine else 1.0)
|
|
240
|
+
flame = QPolygonF([QPointF(-9, -3.5), QPointF(-9 - flame_len, 0), QPointF(-9, 3.5)])
|
|
241
|
+
p.setPen(Qt.PenStyle.NoPen)
|
|
242
|
+
p.setBrush(QColor(255, 160, 40))
|
|
243
|
+
p.drawPolygon(flame)
|
|
244
|
+
p.setBrush(QColor(255, 240, 160))
|
|
245
|
+
p.drawPolygon(QPolygonF([QPointF(-9, -2), QPointF(-9 - flame_len * 0.5, 0), QPointF(-9, 2)]))
|
|
246
|
+
if gm.rotating:
|
|
247
|
+
# Side thrusters at the nose: firing left side pushes nose right.
|
|
248
|
+
side = 1 if gm.rotating > 0 else -1 # +1 = ccw (nose turns up/left)
|
|
249
|
+
p.setPen(Qt.PenStyle.NoPen)
|
|
250
|
+
p.setBrush(QColor(200, 220, 255))
|
|
251
|
+
y0 = 5 * side
|
|
252
|
+
p.drawPolygon(QPolygonF([
|
|
253
|
+
QPointF(6, y0), QPointF(8, y0 + 6 * side), QPointF(4, y0 + 6 * side),
|
|
254
|
+
]))
|
|
255
|
+
p.drawPolygon(QPolygonF([
|
|
256
|
+
QPointF(-6, -y0), QPointF(-4, -y0 - 6 * side), QPointF(-8, -y0 - 6 * side),
|
|
257
|
+
]))
|
|
258
|
+
p.setPen(QPen(QColor(30, 30, 40), 1))
|
|
259
|
+
p.setBrush(QColor(235, 235, 245))
|
|
260
|
+
p.drawPolygon(body)
|
|
261
|
+
p.setBrush(QColor(200, 60, 60))
|
|
262
|
+
p.drawPolygon(QPolygonF([QPointF(13, 0), QPointF(4, -5), QPointF(4, 5)]))
|
|
263
|
+
p.restore()
|
|
264
|
+
|
|
265
|
+
def _draw_hud(self, p: QPainter) -> None:
|
|
266
|
+
gm = self.game
|
|
267
|
+
o, t = gm.orbit, gm.target
|
|
268
|
+
rn = math.hypot(*gm.r)
|
|
269
|
+
speed = math.hypot(*gm.v)
|
|
270
|
+
|
|
271
|
+
def fmt(x: float) -> str:
|
|
272
|
+
return " ∞ " if not math.isfinite(x) else f"{x:7.1f}"
|
|
273
|
+
|
|
274
|
+
lines = [
|
|
275
|
+
(TEXT_COLOR, f"Altitude {rn - gm.planet_radius:7.1f} Speed {speed:6.1f}"),
|
|
276
|
+
(TEXT_COLOR, f"Δv used {gm.burn_dv:7.1f} Time {gm.elapsed:6.1f}s"),
|
|
277
|
+
(TEXT_COLOR, ""),
|
|
278
|
+
(DIM_TEXT, " Periapsis Apoapsis Ecc."),
|
|
279
|
+
(CURRENT_COLOR, f"Current {fmt(o.periapsis)} {fmt(o.apoapsis)} {o.e:5.3f}"),
|
|
280
|
+
(TARGET_COLOR, f"Target {fmt(t.periapsis)} {fmt(t.apoapsis)} {t.e:5.3f}"),
|
|
281
|
+
]
|
|
282
|
+
p.setFont(QFont("monospace", 10))
|
|
283
|
+
y = 22
|
|
284
|
+
for color, text in lines:
|
|
285
|
+
p.setPen(color)
|
|
286
|
+
p.drawText(14, y, text)
|
|
287
|
+
y += 17
|
|
288
|
+
|
|
289
|
+
# Deviation gauge (log scale, tolerance marked).
|
|
290
|
+
dev = gm.deviation
|
|
291
|
+
y += 6
|
|
292
|
+
p.setPen(DIM_TEXT)
|
|
293
|
+
dev_txt = "escape" if not math.isfinite(dev) else f"{100 * dev:6.2f}%"
|
|
294
|
+
p.drawText(14, y + 11, f"Deviation {dev_txt} (win ≤ {100 * gm.tolerance:.1f}%)")
|
|
295
|
+
bar = QRectF(14, y + 18, 300, 10)
|
|
296
|
+
p.setPen(QPen(DIM_TEXT, 1))
|
|
297
|
+
p.setBrush(Qt.BrushStyle.NoBrush)
|
|
298
|
+
p.drawRect(bar)
|
|
299
|
+
lo, hi = math.log10(gm.tolerance / 4), math.log10(2.0)
|
|
300
|
+
|
|
301
|
+
def frac(x: float) -> float:
|
|
302
|
+
return max(0.0, min(1.0, (math.log10(max(x, 1e-9)) - lo) / (hi - lo)))
|
|
303
|
+
|
|
304
|
+
fill = 1.0 - frac(dev) if math.isfinite(dev) else 0.0
|
|
305
|
+
color = TARGET_COLOR if dev <= gm.tolerance else (WARN_COLOR if dev <= 5 * gm.tolerance else BAD_COLOR)
|
|
306
|
+
p.fillRect(QRectF(bar.x() + 1, bar.y() + 1, (bar.width() - 2) * fill, bar.height() - 2), color)
|
|
307
|
+
tx = bar.x() + bar.width() * (1.0 - frac(gm.tolerance))
|
|
308
|
+
p.setPen(QPen(TEXT_COLOR, 2))
|
|
309
|
+
p.drawLine(QPointF(tx, bar.y() - 3), QPointF(tx, bar.bottom() + 3))
|
|
310
|
+
|
|
311
|
+
# Top-right status.
|
|
312
|
+
p.setFont(QFont("monospace", 10))
|
|
313
|
+
right = []
|
|
314
|
+
right.append((TEXT_COLOR, f"Time warp x{gm.time_warp:g}"))
|
|
315
|
+
if self.paused:
|
|
316
|
+
right.append((WARN_COLOR, "PAUSED"))
|
|
317
|
+
if gm.thrusting:
|
|
318
|
+
right.append((WARN_COLOR, "ENGINE " + ("FINE" if self.controls.fine else "FULL")))
|
|
319
|
+
if not o.bound and gm.status == "playing":
|
|
320
|
+
right.append((BAD_COLOR, "ESCAPE TRAJECTORY"))
|
|
321
|
+
elif o.periapsis < gm.planet_radius and gm.status == "playing":
|
|
322
|
+
right.append((BAD_COLOR, "IMPACT TRAJECTORY"))
|
|
323
|
+
y = 22
|
|
324
|
+
for color, text in right:
|
|
325
|
+
p.setPen(color)
|
|
326
|
+
w = p.fontMetrics().horizontalAdvance(text)
|
|
327
|
+
p.drawText(self.width() - 14 - w, y, text)
|
|
328
|
+
y += 17
|
|
329
|
+
|
|
330
|
+
if self.show_help:
|
|
331
|
+
help_lines = [
|
|
332
|
+
"←/→ rotate ↑ main engine Shift fine control",
|
|
333
|
+
"1-6 or +/- time warp P pause R new orbit H hide help Esc quit",
|
|
334
|
+
]
|
|
335
|
+
p.setFont(QFont("monospace", 9))
|
|
336
|
+
p.setPen(DIM_TEXT)
|
|
337
|
+
y = self.height() - 12 - 15 * (len(help_lines) - 1)
|
|
338
|
+
for text in help_lines:
|
|
339
|
+
p.drawText(14, y, text)
|
|
340
|
+
y += 15
|
|
341
|
+
|
|
342
|
+
def _draw_banner(self, p: QPainter) -> None:
|
|
343
|
+
gm = self.game
|
|
344
|
+
if gm.status == "playing":
|
|
345
|
+
return
|
|
346
|
+
title, color = {
|
|
347
|
+
"won": ("ORBIT ACHIEVED", TARGET_COLOR),
|
|
348
|
+
"crashed": ("CRASHED", BAD_COLOR),
|
|
349
|
+
"escaped": ("LOST IN SPACE", BAD_COLOR),
|
|
350
|
+
}[gm.status]
|
|
351
|
+
sub = (
|
|
352
|
+
f"Δv {gm.burn_dv:.1f} time {gm.elapsed:.1f}s deviation {100 * gm.deviation:.2f}%"
|
|
353
|
+
if gm.status == "won" else ""
|
|
354
|
+
)
|
|
355
|
+
rect = QRectF(0, self.height() * 0.18, self.width(), 50)
|
|
356
|
+
p.setFont(QFont("sans-serif", 28, QFont.Weight.Bold))
|
|
357
|
+
p.setPen(color)
|
|
358
|
+
p.drawText(rect, Qt.AlignmentFlag.AlignCenter, title)
|
|
359
|
+
p.setFont(QFont("monospace", 11))
|
|
360
|
+
p.setPen(TEXT_COLOR)
|
|
361
|
+
rect2 = QRectF(0, rect.bottom() + 4, self.width(), 22)
|
|
362
|
+
if sub:
|
|
363
|
+
p.drawText(rect2, Qt.AlignmentFlag.AlignCenter, sub)
|
|
364
|
+
rect2.translate(0, 22)
|
|
365
|
+
p.drawText(rect2, Qt.AlignmentFlag.AlignCenter, "Press Space / Enter for a new orbit")
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: orbi2d
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 2D orbital mechanics game: steer a rocket onto a target orbit
|
|
5
|
+
Author: PiRK
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/PiRK/orbi2d
|
|
8
|
+
Project-URL: Source, https://github.com/PiRK/orbi2d
|
|
9
|
+
Project-URL: Issues, https://github.com/PiRK/orbi2d/issues
|
|
10
|
+
Keywords: game,orbital mechanics,kepler,physics,qt
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: X11 Applications :: Qt
|
|
13
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
14
|
+
Classifier: Intended Audience :: Education
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Topic :: Games/Entertainment :: Simulation
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Physics
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: PySide6>=6.5
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# orbi2d
|
|
26
|
+
|
|
27
|
+

|
|
28
|
+
|
|
29
|
+
A 2D orbital-mechanics game in Python + Qt (PySide6). Your rocket starts on a
|
|
30
|
+
random orbit around a planet. Put it on the dashed green target orbit, to
|
|
31
|
+
within 2% (the largest radial gap between the two curves, relative to the
|
|
32
|
+
target).
|
|
33
|
+
|
|
34
|
+
This started as a vibe-coding project. The first few prompts are documented
|
|
35
|
+
for posterity in [claude_session.txt](https://github.com/PiRK/orbi2d/blob/master/claude_session.txt).
|
|
36
|
+
|
|
37
|
+
## Install and run
|
|
38
|
+
|
|
39
|
+
pip install orbi2d
|
|
40
|
+
orbi2d
|
|
41
|
+
|
|
42
|
+
From a clone of this repository:
|
|
43
|
+
|
|
44
|
+
pip install -r requirements.txt
|
|
45
|
+
python -m orbi2d # or: python -m orbi2d --seed 42
|
|
46
|
+
|
|
47
|
+
## Controls
|
|
48
|
+
|
|
49
|
+
| Key | Action |
|
|
50
|
+
|----------------|--------------------------------------------------|
|
|
51
|
+
| ← / → | Side thrusters: rotate the ship (orientation only) |
|
|
52
|
+
| ↑ | Main engine |
|
|
53
|
+
| Shift (held) | Fine control: 10% thrust, slower rotation |
|
|
54
|
+
| 1–6 | Time warp presets ×0.25 / ×0.5 / ×1 / ×2 / ×4 / ×8 |
|
|
55
|
+
| + / − | Time warp ×1.25 / ÷1.25 (range ×0.1 – ×16) |
|
|
56
|
+
| P | Pause |
|
|
57
|
+
| R / N | New random level |
|
|
58
|
+
| H | Toggle help |
|
|
59
|
+
| Esc / Q | Quit |
|
|
60
|
+
|
|
61
|
+
The yellow circle next to the ship marks the **prograde** direction (where the
|
|
62
|
+
ship is moving). The red ✕ marks **retrograde**. Pe/Ap mark periapsis and
|
|
63
|
+
apoapsis.
|
|
64
|
+
|
|
65
|
+
The game starts at ×0.5 time warp. Turning always happens in real time, but
|
|
66
|
+
orbital motion and engine thrust follow the warp. Slow motion therefore also
|
|
67
|
+
makes burns finer: at ×0.25 a tap on ↑ changes your speed 4× less.
|
|
68
|
+
|
|
69
|
+
## Physics
|
|
70
|
+
|
|
71
|
+
- The rocket and planet form a two-body Kepler system. Coasting uses the
|
|
72
|
+
analytic universal-variable solution, so the ship follows the drawn conic
|
|
73
|
+
exactly with no numerical drift. This works for ellipses, parabolas and
|
|
74
|
+
hyperbolas.
|
|
75
|
+
- The main engine is modelled as a finite burn. Each frame is split into short
|
|
76
|
+
sub-steps, and each sub-step uses kick, exact Kepler coast, kick. After each
|
|
77
|
+
frame the osculating orbit is recomputed from the state vector and redrawn.
|
|
78
|
+
So a burn in any direction at any point of the orbit changes the orbit the
|
|
79
|
+
way it would in reality. For example, a prograde burn at one apsis raises the
|
|
80
|
+
other apsis, and a radial burn rotates the line of apsides.
|
|
81
|
+
- You win when the engine is off and your orbit is within the tolerance of
|
|
82
|
+
the target. Only the shape of the orbit counts, not the direction of travel.
|
|
83
|
+
You lose if you hit the planet or escape.
|
|
84
|
+
|
|
85
|
+
Tuning constants are at the top of `orbi2d/game.py`.
|
|
86
|
+
|
|
87
|
+
## Tests
|
|
88
|
+
|
|
89
|
+
python -m pytest
|
|
90
|
+
|
|
91
|
+
## License
|
|
92
|
+
|
|
93
|
+
MIT. See [LICENSE](https://github.com/PiRK/orbi2d/blob/master/LICENSE).
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
orbi2d/__init__.py,sha256=FgELO1m6LCWuKOdvUMQnTDQ604cQ0Jx3hmSJTnUu_yo,113
|
|
2
|
+
orbi2d/__main__.py,sha256=YUAR3MuwNb9uwTM5mLtB7rxxAYpwu-wwKWlV7QFkG5U,721
|
|
3
|
+
orbi2d/game.py,sha256=nPanjWgZWKHvB8UPAMXKych00WBVlm_3nvbwtUb1ARM,6141
|
|
4
|
+
orbi2d/physics.py,sha256=5HcK7BipwI-1nzjGNhIuOoJhb6EMKkDUMXtG4miScJM,6615
|
|
5
|
+
orbi2d/view.py,sha256=oZzZ0Cc-g5b4BJ-kkJt63yYK9cpxmy6YGFNBd2P4NXE,14143
|
|
6
|
+
orbi2d-0.1.0.dist-info/licenses/LICENSE,sha256=ZaLE8r3djRUEDTv3BWteW_FBvUdrvGGUTJQ-3bXIpDE,1061
|
|
7
|
+
orbi2d-0.1.0.dist-info/METADATA,sha256=tgB8N--rcH83nYgx6gZBb4jcVuwsrLqk6cr6fHiRHYc,3994
|
|
8
|
+
orbi2d-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
9
|
+
orbi2d-0.1.0.dist-info/entry_points.txt,sha256=FMX46A5agTqqGgN7Ueqt3dCoZVvddJiCu9oeGUYZX9Y,44
|
|
10
|
+
orbi2d-0.1.0.dist-info/top_level.txt,sha256=OO__SYP8_CjV7GHfxBg7FHYEE9IhbgDwrPPhJyZophQ,7
|
|
11
|
+
orbi2d-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PiRK
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
orbi2d
|