Spaces:
Running
Running
File size: 15,390 Bytes
13eb3cb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 | """
Standalone table-tennis physics environment + baseline opponents for Mr. Pong.
This is a faithful port of the reference implementation shipped by the model
author in `inference.py` at https://huggingface.co/fromziro/MrPong (Apache-2.0).
Physics constants, collision handling, observation layout and the baseline
opponent policies are kept 1:1 with the original so that the behaviour shown in
this Space matches the numbers reported on the model card.
"""
import math
import random
from dataclasses import dataclass
from typing import Any, Dict, Optional, Tuple
import numpy as np
@dataclass
class PhysicsConfig:
table_width: float = 800.0
table_height: float = 500.0
paddle_width: float = 14.0
paddle_height: float = 80.0
paddle_speed: float = 8.0
paddle_smoothing: float = 0.70
ball_radius: float = 8.0
ball_speed_initial: float = 8.0
ball_speed_max: float = 16.0
ball_acceleration: float = 1.035
frame_skip: int = 3
max_rally_steps: int = 1500
class StandalonePongEnv:
"""Self-contained table tennis physics environment (port of the author's env)."""
def __init__(self, phys: Optional[PhysicsConfig] = None, seed: Optional[int] = None):
self.phys = phys or PhysicsConfig()
self.rng = random.Random(seed)
self.ego_paddle_h = self.phys.paddle_height
self.opp_paddle_h = self.phys.paddle_height
self.reset()
def reset(self, serve_direction: Optional[int] = None,
initial_speed: Optional[float] = None) -> np.ndarray:
self.ego_y = self.phys.table_height / 2.0
self.opp_y = self.phys.table_height / 2.0
self.ego_vy = 0.0
self.opp_vy = 0.0
self.prev_ego_action = 0
self.ball_x = self.phys.table_width / 2.0
self.ball_y = self.phys.table_height / 2.0
if serve_direction is None:
serve_direction = 1 if self.rng.random() < 0.5 else -1
serve_angle = self.rng.uniform(-math.pi / 7.0, math.pi / 7.0)
speed = initial_speed or self.phys.ball_speed_initial
self.ball_vx = serve_direction * speed * math.cos(serve_angle)
self.ball_vy = speed * math.sin(serve_angle)
self.rally_count = 0
self.step_count = 0
return self.get_ego_observation()
def _get_action_velocity(self, action: int) -> float:
if action == 1:
return -self.phys.paddle_speed
elif action == 2:
return self.phys.paddle_speed
return 0.0
def physics_substep(self, ego_action: int, opp_action: int) -> Tuple[bool, Dict[str, Any]]:
info = {"winner": None}
done = False
prev_ego_y = self.ego_y
prev_opp_y = self.opp_y
ego_target_v = self._get_action_velocity(ego_action)
opp_target_v = self._get_action_velocity(opp_action)
alpha = self.phys.paddle_smoothing
self.ego_vy = alpha * self.ego_vy + (1.0 - alpha) * ego_target_v
self.opp_vy = alpha * self.opp_vy + (1.0 - alpha) * opp_target_v
ego_half_h = self.ego_paddle_h / 2.0
opp_half_h = self.opp_paddle_h / 2.0
self.ego_y = float(np.clip(self.ego_y + self.ego_vy, ego_half_h,
self.phys.table_height - ego_half_h))
self.opp_y = float(np.clip(self.opp_y + self.opp_vy, opp_half_h,
self.phys.table_height - opp_half_h))
prev_ball_x = self.ball_x
prev_ball_y = self.ball_y
r = self.phys.ball_radius
ego_paddle_x = self.phys.paddle_width
opp_paddle_x = self.phys.table_width - self.phys.paddle_width
ego_impact_plane = ego_paddle_x + r
opp_impact_plane = opp_paddle_x - r
next_ball_x = prev_ball_x + self.ball_vx
next_ball_y = prev_ball_y + self.ball_vy
hit_occurred = False
# Left (ego) paddle — continuous collision detection
if self.ball_vx < 0 and prev_ball_x >= ego_impact_plane and next_ball_x <= ego_impact_plane:
t = float(np.clip((prev_ball_x - ego_impact_plane) / max(1e-6, -self.ball_vx), 0.0, 1.0))
y_ball_at_impact = prev_ball_y + t * self.ball_vy
y_ego_at_impact = prev_ego_y + t * (self.ego_y - prev_ego_y)
if abs(y_ball_at_impact - y_ego_at_impact) <= (ego_half_h + r * 0.6):
hit_occurred = True
self.rally_count += 1
offset = float(np.clip((y_ball_at_impact - y_ego_at_impact) / ego_half_h, -1.0, 1.0))
bounce_angle = offset * (math.pi / 3.0)
current_speed = math.hypot(self.ball_vx, self.ball_vy)
new_speed = min(current_speed * self.phys.ball_acceleration, self.phys.ball_speed_max)
new_vx = new_speed * math.cos(bounce_angle)
new_vy = new_speed * math.sin(bounce_angle) + 0.25 * self.ego_vy
rem_dt = 1.0 - t
self.ball_x = ego_impact_plane + rem_dt * new_vx
self.ball_y = y_ball_at_impact + rem_dt * new_vy
self.ball_vx = new_vx
self.ball_vy = new_vy
# Right (opponent) paddle
elif self.ball_vx > 0 and prev_ball_x <= opp_impact_plane and next_ball_x >= opp_impact_plane:
t = float(np.clip((opp_impact_plane - prev_ball_x) / max(1e-6, self.ball_vx), 0.0, 1.0))
y_ball_at_impact = prev_ball_y + t * self.ball_vy
y_opp_at_impact = prev_opp_y + t * (self.opp_y - prev_opp_y)
if abs(y_ball_at_impact - y_opp_at_impact) <= (opp_half_h + r * 0.6):
hit_occurred = True
self.rally_count += 1
offset = float(np.clip((y_ball_at_impact - y_opp_at_impact) / opp_half_h, -1.0, 1.0))
bounce_angle = offset * (math.pi / 3.0)
current_speed = math.hypot(self.ball_vx, self.ball_vy)
new_speed = min(current_speed * self.phys.ball_acceleration, self.phys.ball_speed_max)
new_vx = -new_speed * math.cos(bounce_angle)
new_vy = new_speed * math.sin(bounce_angle) + 0.25 * self.opp_vy
rem_dt = 1.0 - t
self.ball_x = opp_impact_plane + rem_dt * new_vx
self.ball_y = y_ball_at_impact + rem_dt * new_vy
self.ball_vx = new_vx
self.ball_vy = new_vy
if not hit_occurred:
self.ball_x = next_ball_x
self.ball_y = next_ball_y
# Wall collisions
if self.ball_y - r <= 0:
self.ball_y = r + abs(r - self.ball_y)
self.ball_vy = abs(self.ball_vy)
elif self.ball_y + r >= self.phys.table_height:
self.ball_y = (self.phys.table_height - r) - abs(self.ball_y + r - self.phys.table_height)
self.ball_vy = -abs(self.ball_vy)
# Goal boundaries
if self.ball_x - r < 0:
done = True
info["winner"] = "opponent"
elif self.ball_x + r > self.phys.table_width:
done = True
info["winner"] = "ego"
self.prev_ego_action = ego_action
return done, info
def step(self, ego_action: int, opp_action: int) -> Tuple[np.ndarray, bool, Dict[str, Any]]:
self.step_count += 1
done = False
info = {"winner": None}
for _ in range(self.phys.frame_skip):
d, sub_info = self.physics_substep(ego_action, opp_action)
if d:
done = True
info = sub_info
break
if not done and self.step_count >= self.phys.max_rally_steps:
done = True
info["winner"] = "draw"
return self.get_ego_observation(), done, info
def calculate_intercept_y(self, target_x: float, ball_x: float, ball_y: float,
ball_vx: float, ball_vy: float) -> float:
if (target_x > ball_x and ball_vx <= 0) or (target_x < ball_x and ball_vx >= 0):
return self.phys.table_height / 2.0
bx, by = float(ball_x), float(ball_y)
bvx, bvy = float(ball_vx), float(ball_vy)
h = self.phys.table_height
r = self.phys.ball_radius
for _ in range(10):
dt_x = (target_x - bx) / bvx if bvx != 0 else float("inf")
if dt_x <= 0:
break
if bvy > 0:
dt_y = (h - r - by) / bvy
elif bvy < 0:
dt_y = (r - by) / bvy
else:
dt_y = float("inf")
if dt_x <= dt_y:
by += bvy * dt_x
break
else:
bx += bvx * dt_y
by += bvy * dt_y
bvy = -bvy
return float(np.clip(by, r, h - r))
def get_ego_observation(self) -> np.ndarray:
w, h = self.phys.table_width, self.phys.table_height
v_max = self.phys.ball_speed_max
pv_max = self.phys.paddle_speed
half_h = self.ego_paddle_h / 2.0
ego_x = self.phys.paddle_width
pred_intercept_y = self.calculate_intercept_y(ego_x, self.ball_x, self.ball_y,
self.ball_vx, self.ball_vy)
rel_pred_y = (pred_intercept_y - self.ego_y) / h
pred_norm_y = pred_intercept_y / h
opp_y_norm = self.opp_y / h
opp_open_top = (self.opp_y - half_h) / h
opp_open_bottom = (h - (self.opp_y + half_h)) / h
speed_norm = math.hypot(self.ball_vx, self.ball_vy) / v_max
return np.array([
(self.ball_y - self.ego_y) / h,
(self.ball_x - ego_x) / w,
self.ball_vx / v_max,
self.ball_vy / v_max,
self.ego_y / h,
self.ego_vy / pv_max,
(self.opp_y - self.ego_y) / h,
self.opp_vy / pv_max,
self.ball_y / h,
self.ball_x / w,
rel_pred_y,
pred_norm_y,
opp_y_norm,
opp_open_top,
opp_open_bottom,
speed_norm,
], dtype=np.float32)
def get_opp_observation(self) -> np.ndarray:
w, h = self.phys.table_width, self.phys.table_height
v_max = self.phys.ball_speed_max
pv_max = self.phys.paddle_speed
half_h = self.opp_paddle_h / 2.0
opp_x = self.phys.table_width - self.phys.paddle_width
pred_intercept_y = self.calculate_intercept_y(opp_x, self.ball_x, self.ball_y,
self.ball_vx, self.ball_vy)
rel_pred_y = (pred_intercept_y - self.opp_y) / h
pred_norm_y = pred_intercept_y / h
ego_y_norm = self.ego_y / h
ego_open_top = (self.ego_y - half_h) / h
ego_open_bottom = (h - (self.ego_y + half_h)) / h
speed_norm = math.hypot(self.ball_vx, self.ball_vy) / v_max
return np.array([
(self.ball_y - self.opp_y) / h,
(opp_x - self.ball_x) / w,
-self.ball_vx / v_max,
self.ball_vy / v_max,
self.opp_y / h,
self.opp_vy / pv_max,
(self.ego_y - self.opp_y) / h,
self.ego_vy / pv_max,
self.ball_y / h,
(w - self.ball_x) / w,
rel_pred_y,
pred_norm_y,
ego_y_norm,
ego_open_top,
ego_open_bottom,
speed_norm,
], dtype=np.float32)
# ==================================================================================
# Baseline opponents (ported from the author's inference.py)
# ==================================================================================
def smooth_aim_action(current_y: float, target_y: float, prev_action: int,
deadzone: float = 6.0) -> int:
diff = target_y - current_y
if abs(diff) < deadzone:
return 0
return 2 if diff > 0 else 1
class RealisticHardOpponent:
def __init__(self, commit_x_ratio: float = 0.60, rng: Optional[random.Random] = None):
self.commit_x_ratio = commit_x_ratio
self.prev_action = 0
self.perceptual_noise = 0.0
self.rng = rng or random.Random()
def act(self, env: StandalonePongEnv) -> int:
if env.ball_vx <= 0:
target_y = env.phys.table_height / 2.0
self.perceptual_noise = self.rng.uniform(-12.0, 12.0)
elif env.ball_x < env.phys.table_width * self.commit_x_ratio:
target_y = env.phys.table_height / 2.0 + (env.ball_y - env.phys.table_height / 2.0) * 0.40
else:
target_x = env.phys.table_width - env.phys.paddle_width
exact_y = env.calculate_intercept_y(target_x, env.ball_x, env.ball_y,
env.ball_vx, env.ball_vy)
target_y = float(np.clip(exact_y + self.perceptual_noise, 8.0,
env.phys.table_height - 8.0))
action = smooth_aim_action(env.opp_y, target_y, self.prev_action, deadzone=7.0)
self.prev_action = action
return action
class MediumOpponent:
def __init__(self, rng: Optional[random.Random] = None):
self.prev_action = 0
self.rng = rng or random.Random()
def act(self, env: StandalonePongEnv) -> int:
if env.ball_vx <= 0:
target_y = env.phys.table_height / 2.0
else:
dt = (env.phys.table_width - env.phys.paddle_width - env.ball_x) / max(1.0, env.ball_vx)
target_y = env.ball_y + env.ball_vy * dt
target_y = float(np.clip(target_y, 0, env.phys.table_height))
action = smooth_aim_action(env.opp_y, target_y, self.prev_action, deadzone=14.0)
self.prev_action = action
return action
class EasyOpponent:
def __init__(self, rng: Optional[random.Random] = None):
self.prev_action = 0
self.rng = rng or random.Random()
def act(self, env: StandalonePongEnv) -> int:
if env.ball_vx <= 0 or env.ball_x < env.phys.table_width * 0.45:
target_y = env.phys.table_height / 2.0
else:
target_y = env.ball_y + self.rng.uniform(-30.0, 30.0)
action = smooth_aim_action(env.opp_y, target_y, self.prev_action, deadzone=25.0)
self.prev_action = action
return action
class ImpossibleHardOpponent:
def __init__(self, rng: Optional[random.Random] = None):
self.prev_action = 0
self.rng = rng or random.Random()
def act(self, env: StandalonePongEnv) -> int:
if env.ball_vx <= 0:
target_y = env.phys.table_height / 2.0
else:
target_x = env.phys.table_width - env.phys.paddle_width
target_y = env.calculate_intercept_y(target_x, env.ball_x, env.ball_y,
env.ball_vx, env.ball_vy)
action = smooth_aim_action(env.opp_y, target_y, self.prev_action, deadzone=2.0)
self.prev_action = action
return action
class RandomOpponent:
def __init__(self, rng: Optional[random.Random] = None):
self.rng = rng or random.Random()
def act(self, env: StandalonePongEnv) -> int:
return self.rng.randint(0, 2)
OPPONENTS = {
"Realistic Hard": RealisticHardOpponent,
"Medium Logic": MediumOpponent,
"Easy Logic": EasyOpponent,
"Impossible Hard": ImpossibleHardOpponent,
"Random Agent": RandomOpponent,
}
|