Datasets:
Publish WeightProgramBench: 317 training games and 5 held-out MinAtar tasks (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- runtime/minatar_synth/games/smoke_g.pyAdded+167
- runtime/minatar_synth/games/snake1.pyAdded+94
- runtime/minatar_synth/games/snaky.pyAdded+137
- runtime/minatar_synth/games/solaris.pyAdded+269
- runtime/minatar_synth/games/spearain.pyAdded+113
- runtime/minatar_synth/games/spin_cell.pyAdded+130
- runtime/minatar_synth/games/splitzig.pyAdded+129
- runtime/minatar_synth/games/square_bar.pyAdded+156
- runtime/minatar_synth/games/stage_separation.pyAdded+121
- runtime/minatar_synth/games/star_eater.pyAdded+124
- runtime/minatar_synth/games/star_gunner.pyAdded+218
- runtime/minatar_synth/games/stillfire_choir.pyAdded+131
- runtime/minatar_synth/games/stomping_bubbles.pyAdded+128
- runtime/minatar_synth/games/stompshelter.pyAdded+157
- runtime/minatar_synth/games/stormveil.pyAdded+113
- runtime/minatar_synth/games/sub_jump.pyAdded+133
- runtime/minatar_synth/games/sum_ten.pyAdded+114
- runtime/minatar_synth/games/sunflower_sway.pyAdded+113
- runtime/minatar_synth/games/survivor.pyAdded+166
- runtime/minatar_synth/games/swingby.pyAdded+129
- runtime/minatar_synth/games/switchboard.pyAdded+143
- runtime/minatar_synth/games/t_hanoi.pyAdded+104
- runtime/minatar_synth/games/t_lanes.pyAdded+154
- runtime/minatar_synth/games/t_laser.pyAdded+143
- runtime/minatar_synth/games/t_punch.pyAdded+146
- runtime/minatar_synth/games/tape_j.pyAdded+158
- runtime/minatar_synth/games/tappump.pyAdded+110
- runtime/minatar_synth/games/tarutobi.pyAdded+104
- runtime/minatar_synth/games/tectonic_tether.pyAdded+157
- runtime/minatar_synth/games/teeter.pyAdded+153
- runtime/minatar_synth/games/tennis.pyAdded+224
- runtime/minatar_synth/games/throw_m.pyAdded+131
- runtime/minatar_synth/games/thrust_lr.pyAdded+113
- runtime/minatar_synth/games/thunder.pyAdded+160
- runtime/minatar_synth/games/tilted.pyAdded+186
- runtime/minatar_synth/games/timber_test.pyAdded+97
- runtime/minatar_synth/games/time_pilot.pyAdded+263
- runtime/minatar_synth/games/tongue_hunter.pyAdded+135
- runtime/minatar_synth/games/tornado_twister.pyAdded+153
- runtime/minatar_synth/games/totoge.pyAdded+125
- runtime/minatar_synth/games/tr_beam.pyAdded+169
- runtime/minatar_synth/games/trojan_defense.pyAdded+144
- runtime/minatar_synth/games/tt_fence.pyAdded+151
- runtime/minatar_synth/games/turbo_tunnel.pyAdded+136
- runtime/minatar_synth/games/turbulent.pyAdded+167
- runtime/minatar_synth/games/turtle_tide.pyAdded+104
- runtime/minatar_synth/games/tutankham.pyAdded+226
- runtime/minatar_synth/games/twhols.pyAdded+90
- runtime/minatar_synth/games/twin_jumpers.pyAdded+130
- runtime/minatar_synth/games/twin_p.pyAdded+140
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167from dataclasses import dataclassfrom math import atan2, cos, hypot, pi, sin
import numpy as np
@dataclassclass Grenade: x: float y: float tx: float ty: float age: int = 0
@dataclassclass Smoke: x: float y: float radius: float = 0 growing: bool = True
@dataclassclass Enemy: x: float y: float angle: float
class SmokeGEnvironment: score_cap = 20 moves = ((0, 0), (-1, 0), (0, -1), (1, 0), (0, 1), (0, 0))
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 50, 45 self.angle = -pi / 2 self.steps = self.action = self.side_count = 0 self.side = 1 self.distance = 0. self.terminal = False self.grenades, self.smoke, self.enemies = [], [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action tap = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): dx, dy = self.moves[self.action] self.x = min(99, max(0, self.x + 3 * dx)) self.y = min(99, max(0, self.y + 3 * dy)) if tap and len(self.smoke) < 9: self.grenades.append(Grenade(50, 90, self.x, self.y)) for grenade in self.grenades: grenade.age += 1 grenade.x += (grenade.tx - grenade.x) * 0.1 grenade.y += (grenade.ty - grenade.y) * 0.1 + cos(grenade.age * pi * 4 / 30) + 0.1 if grenade.age > 30: self.smoke.append(Smoke(grenade.tx, grenade.ty)) self.grenades = [grenade for grenade in self.grenades if grenade.age <= 30] for smoke in self.smoke: smoke.y += 0.1 if smoke.growing: smoke.radius += (10 - smoke.radius) * 0.2 if smoke.radius > 9: smoke.radius, smoke.growing = 10, False else: smoke.radius *= 0.995 self.smoke = [smoke for smoke in self.smoke if smoke.growing or smoke.radius >= 2] if not self.enemies: self.distance = 0 self.distance -= 0.1 if self.distance < 0: self.side_count -= 1 if self.side_count < 0: self.side *= -1 self.side_count = self.random.uniform(1, 5) self.distance += 7 x = 50 + self.random.uniform(0, 40) * self.side self.enemies.append(Enemy(x, -3, atan2(-93, x - 50) + self.random.uniform(-0.2, 0.2))) self.distance += self.random.uniform(5, 9) visible = [enemy for enemy in self.enemies if hypot(enemy.x - 50, enemy.y - 90) < 99 and not self._blocked(enemy)] if visible: target = min(visible, key=lambda enemy: hypot(enemy.x - 50, enemy.y - 90)) self.angle = self._turn(self.angle, atan2(target.y - 90, target.x - 50), 0.012) reward = 0 remaining = [] for enemy in self.enemies: enemy.y += 0.1 if not self._blocked(enemy): enemy.angle = self._turn(enemy.angle, atan2(90 - enemy.y, 50 - enemy.x), 0.008) self.terminal |= self._ray_hit(enemy.x, enemy.y, enemy.angle, 50, 90, 50) if self._ray_hit(50, 90, self.angle, enemy.x, enemy.y, 55): reward += 1 else: self.terminal |= enemy.y > 99 remaining.append(enemy) self.enemies = remaining return reward
def _blocked(self, enemy): dx, dy = enemy.x - 50, enemy.y - 90 length = dx * dx + dy * dy for smoke in self.smoke: t = min(1, max(0, ((smoke.x - 50) * dx + (smoke.y - 90) * dy) / max(length, 1e-9))) nearest = hypot(smoke.x - 50 - t * dx, smoke.y - 90 - t * dy) farthest = max(hypot(smoke.x - 50, smoke.y - 90), hypot(smoke.x - enemy.x, smoke.y - enemy.y)) if nearest <= smoke.radius + 1 and farthest >= smoke.radius - 1: return True return False
@staticmethod def _turn(angle, target, speed): difference = (target - angle + pi) % (2 * pi) - pi return angle + min(speed, max(-speed, difference))
@staticmethod def _ray_hit(x, y, angle, tx, ty, reach): dx, dy = tx - x, ty - y along = dx * cos(angle) + dy * sin(angle) across = dy * cos(angle) - dx * sin(angle) return -4 < along < reach + 4 and abs(across) < 4
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[9, 5, 0] = True state[self.y // 10, self.x // 10, 1] = True for enemy in self.enemies: if 0 <= enemy.y < 100: state[int(enemy.y // 10), int(enemy.x // 10), 2] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for smoke in self.smoke: state[:, :, 3] |= abs(np.hypot(cols - smoke.x, rows - smoke.y) - smoke.radius) < 6 for grenade in self.grenades: if 0 <= grenade.y < 100: state[int(grenade.y // 10), int(grenade.x // 10), 4] = True values = (self.steps, self.action, round((self.angle % (2 * pi)) * 100)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) return state12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394from collections import deque
import numpy as np
class Snake1Environment: score_cap = 20 directions = ((1, 0), (0, 1), (-1, 0), (0, -1))
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.head = (8, 8) self.direction = self.timer = self.steps = 0 self.rotation = 1 self.queued = self.grow = self.held = self.terminal = False self.body = deque((x, 8) for x in range(4, 8)) self.dollars = [(12, 8)]
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 self.queued |= held and not self.held self.held = held self.steps += 1 reward = 0 for _ in range(4): self.timer -= 1 if self.timer < 0: self.timer = 20 reward += self._move() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _move(self): if not self.grow: self.body.popleft() self.grow = False self.body.append(self.head) if self.queued: self.direction = (self.direction + self.rotation) % 4 self.queued = False dx, dy = self.directions[self.direction] self.head = self.head[0] + dx, self.head[1] + dy x, y = self.head self.terminal = self.head in self.body or not (1 <= x <= 14 and 2 <= y <= 14) if self.head not in self.dollars: return 0 self.dollars = [dollar for dollar in self.dollars if dollar != self.head] self.grow = True self.rotation *= -1 for _ in range(2): for _ in range(99): position = tuple(self.random.integers((2, 3), (14, 14))) if position != self.head and position not in self.body: self.dollars.append(position) break return 1
def state(self): state = np.zeros((10, 10, 6), dtype=bool)
def mark(x, y, channel): state[min(9, max(0, (y - 1) * 10 // 15)), min(9, max(0, x * 10 // 16)), channel] = True
mark(*self.head, 0) for point in self.body: mark(*point, 1) for point in self.dollars: mark(*point, 2) state[[0, 9], :, 3] = True state[:, [0, 9], 3] = True dx, dy = self.directions[(self.direction + self.rotation) % 4] mark(self.head[0] + dx, self.head[1] + dy, 4) values = (self.steps, self.direction, self.rotation > 0, self.timer, self.queued, self.grow, self.held, *self.head) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137from dataclasses import dataclassfrom math import cos, pi, sin, sqrt
import numpy as np
@dataclassclass Item: x: float y: float red: bool vx: float = -0.1
class SnakyEnvironment: score_cap = 400
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.angles = [0., 0.] self.velocities = [0., 0.] self.items = [] self.timer = self.steps = 0 self.red_count = 2 self.next_y = 50. self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _segments(self): length = 50 / len(self.angles) + 3 x, y = 0., 50. for angle in self.angles: end_x, end_y = x + length * cos(angle), y + length * sin(angle) yield x, y, end_x, end_y x, y = end_x, end_y
def _advance(self): limit = pi / (sqrt(len(self.angles) - 1) + 3) for index, angle in enumerate(self.angles): velocity = self.velocities[index] if index == 0: updated = min(limit, max(-limit, angle + (-0.03 if self.held else 0.03))) velocity = updated - angle else: updated = angle + velocity difference = updated - self.angles[index - 1] if abs(difference) > limit and difference * velocity > 0: velocity *= -0.2 self.angles[index] = updated self.velocities[index] = velocity * 0.95 if index + 1 < len(self.angles): self.velocities[index + 1] += velocity * 0.95 * 0.07 if index: self.velocities[index - 1] += velocity * 0.95 * 0.01 segments = list(self._segments()) self.timer -= 1 if self.timer < 0: self.red_count -= 1 red = self.red_count < 0 if red: self.red_count = 7 self.items.append(Item(103, self.next_y, red)) y = self.random.uniform(20, 80) self.timer = 4 * abs(self.next_y - y + 10) self.next_y = y reward = 0 remaining = [] for item in self.items: item.vx *= 1.005 item.x += item.vx size = len(self.angles) if self._touches(item, segments[-1]): reward += size ** 2 if item.red else size if item.red and size < 10: self.angles.append(0.) self.velocities.append(0.) elif any(self._touches(item, segment) for segment in segments[:-1]): reward += -size if item.red else 1 if item.red and size > 1: self.angles.pop() self.velocities.pop() else: self.terminal |= item.x < 0 remaining.append(item) self.items = remaining return reward
@staticmethod def _touches(item, segment): x, y, end_x, end_y = segment dx, dy = end_x - x, end_y - y t = ((item.x - x) * dx + (item.y - y) * dy) / (dx * dx + dy * dy) t = min(1, max(0, t)) return (item.x - x - t * dx) ** 2 + (item.y - y - t * dy) ** 2 < 4.5 ** 2
def state(self): state = np.zeros((10, 10, 6), dtype=bool) segments = list(self._segments()) for index, (x, y, end_x, end_y) in enumerate(segments): points = np.linspace((x, y), (end_x, end_y), 32) visible = points[np.all((points >= 0) & (points < 100), axis=1)] cols, rows = (visible // 10).astype(int).T state[rows, cols, int(index == len(segments) - 1)] = True for item in self.items: if 0 <= item.x < 100: state[int(item.y // 10), int(item.x // 10), 2 + int(item.red)] = True state[int(self.next_y // 10), 9, 4] = True for row, value in enumerate((self.steps, len(self.angles), self.held, min(511, round(max(0, self.timer))), self.red_count)): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269import numpy as np
ENEMY_VALUES = { "flagship": 500, "raider": 400, "pirate": 320, "targeter": 320, "glider": 320, "mechnoid": 300, "blockader": 260, "cobra": 80, "guardian": 60, "distractor": 20,}SECTORS = { (0, 1): ("enemies", ("flagship",)), (0, 2): ("enemies", ("raider",)), (0, 3): ("federation", ()), (1, 0): ("enemies", ("pirate",)), (1, 1): ("enemies", ("targeter",)), (1, 2): ("planet", ("guardian",)), (1, 3): ("enemies", ("glider",)), (2, 0): ("enemies", ("mechnoid",)), (2, 1): ("corridor", ("guardian",)), (2, 2): ("enemies", ("blockader",)), (2, 3): ("enemies", ("cobra",)), (3, 0): ("enemies", ("distractor",)), (3, 1): ("federation", ()), (3, 2): ("enemies", ("flagship", "mechnoid", "pirate")), (3, 3): ("solaris", ()),}
class SolarisEnvironment: """Scanner navigation and targeting combat on a finite route to Solaris."""
score_cap = 19_760.0
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = 2_000): self.sticky_action_prob = sticky_action_prob self.horizon = horizon self.random = np.random.RandomState() self.seed(0) self.reset()
@classmethod def normalize_score(cls, raw_score: float) -> float: return min(max(raw_score, 0.0), cls.score_cap) / cls.score_cap
def seed(self, seed: int) -> None: self.random.seed(seed)
def reset(self) -> None: self.mode = "scanner" self.ship_row = 0 self.ship_column = 0 self.cursor_row = 0 self.cursor_column = 0 self.warp_target = (0, 0) self.focus_offset = 0 self.fuel = 100 self.lives = 3 self.targeting_damaged = False self.score = 0.0 self.steps = 0 self.last_action = 0 self.cleared: set[tuple[int, int]] = set() self.defeated: set[tuple[int, int, int]] = set() self.red_rows: set[int] = set() self.crosshair_row = 5 self.crosshair_column = 5 self.enemies: list[dict[str, int | str]] = [] self.combat_steps = 0 self.terminal = False
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.rand() < self.sticky_action_prob: action = self.last_action self.last_action = action if self.mode == "scanner": reward = self._act_scanner(action) elif self.mode == "warp": reward = self._act_warp(action) else: reward = self._act_combat(action) self.score += reward self.steps += 1 if self.steps >= 40 and (0, 2) not in self.cleared: self.red_rows.add(0) if self.steps >= self.horizon: self.terminal = True return reward, self.terminal
def _act_scanner(self, action: int) -> float: if action == 5: self.warp_target = (self.cursor_row, self.cursor_column) self.focus_offset = int(self.random.randint(-3, 4)) self.mode = "warp" return 0.0 if self.ship_row in self.red_rows: action = {1: 3, 2: 4, 3: 1, 4: 2}.get(action, action) if action == 1: self.cursor_column = max(0, self.cursor_column - 1) elif action == 2: self.cursor_row = max(0, self.cursor_row - 1) elif action == 3: self.cursor_column = min(3, self.cursor_column + 1) elif action == 4: self.cursor_row = min(3, self.cursor_row + 1) return 0.0
def _act_warp(self, action: int) -> float: if action == 1: self.focus_offset = min(3, self.focus_offset + 1) return 0.0 if action == 3: self.focus_offset = max(-3, self.focus_offset - 1) return 0.0 if action != 5: return 0.0 distance = abs(self.warp_target[0] - self.ship_row) + abs(self.warp_target[1] - self.ship_column) self.fuel -= 4 + distance * 3 + abs(self.focus_offset) * 2 self.ship_row, self.ship_column = self.warp_target self.cursor_row, self.cursor_column = self.warp_target if self.fuel <= 0: self._lose_ship() return 0.0 sector_kind, enemy_kinds = SECTORS.get(self.warp_target, ("empty", ())) if sector_kind == "solaris": self.terminal = True self.mode = "scanner" elif sector_kind == "federation": self.fuel = 100 self.targeting_damaged = False self.mode = "scanner" elif self.warp_target in self.cleared or not enemy_kinds: self.mode = "scanner" else: self._start_combat(enemy_kinds) return 0.0
def _start_combat(self, enemy_kinds: tuple[str, ...]) -> None: self.mode = "combat" self.crosshair_row = 5 self.crosshair_column = 5 self.combat_steps = 0 self.enemies = [] for index, kind in enumerate(enemy_kinds): identity = (self.ship_row, self.ship_column, index) if identity in self.defeated: continue code = list(ENEMY_VALUES).index(kind) self.enemies.append( { "kind": kind, "index": index, "row": 1 + (code * 3 + index * 2) % 8, "column": 1 + (code * 5 + index * 3) % 8, } )
def _act_combat(self, action: int) -> float: if action == 1: self.crosshair_column = max(0, self.crosshair_column - 1) elif action == 2: self.crosshair_row = max(0, self.crosshair_row - 1) elif action == 3: self.crosshair_column = min(9, self.crosshair_column + 1) elif action == 4: self.crosshair_row = min(9, self.crosshair_row + 1) reward = 0.0 if action == 5 and self.enemies: enemy = self.enemies[0] if self.crosshair_row == enemy["row"] and self.crosshair_column == enemy["column"]: reward += float(ENEMY_VALUES[str(enemy["kind"])]) self.defeated.add((self.ship_row, self.ship_column, int(enemy["index"]))) self.enemies.pop(0) if not self.enemies: reward += self._clear_sector() return reward self.combat_steps += 1 self.fuel -= 1 if self.combat_steps % 10 == 0: self._enemy_hit() if self.fuel <= 0: self._lose_ship() return reward
def _clear_sector(self) -> float: position = (self.ship_row, self.ship_column) self.cleared.add(position) kind = SECTORS[position][0] reward = 0.0 if kind in {"planet", "corridor"}: reward = 8_000.0 if kind == "planet": self.lives = min(9, self.lives + 1) self.mode = "scanner" self.combat_steps = 0 return reward
def _enemy_hit(self) -> None: if self.enemies and self.enemies[0]["kind"] == "flagship": self._lose_ship() return if not self.targeting_damaged: self.targeting_damaged = True else: self.fuel -= 15
def _lose_ship(self) -> None: self.lives -= 1 if self.lives <= 0: self.terminal = True return self.fuel = 100 self.targeting_damaged = False self.mode = "scanner" self.enemies = []
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) if self.mode in {"scanner", "warp"}: state[self.ship_row * 2 + 1, self.ship_column * 2 + 1, 0] = True state[self.cursor_row * 2 + 1, self.cursor_column * 2 + 1, 3] = True for (row, column), (kind, _) in SECTORS.items(): screen_row = row * 2 + 1 screen_column = column * 2 + 1 channel = 2 if kind in {"federation", "solaris"} else 1 state[screen_row, screen_column, channel] = True if (row, column) in self.cleared: state[screen_row, screen_column, 4] = True for row in self.red_rows: state[row * 2 : row * 2 + 2, :8, 1] = True else: state[self.crosshair_row, self.crosshair_column, 0] = True if self.enemies: enemy = self.enemies[0] state[int(enemy["row"]), int(enemy["column"]), 1] = True for index, position in enumerate(SECTORS): state[index // 10, index % 10, 5] = position in self.cleared for row, column, enemy_index in self.defeated: index = 72 + (row * 4 + column + enemy_index) % 28 state[index // 10, index % 10, 5] = True values = ( (self.ship_row, 2), (self.ship_column, 2), (self.cursor_row, 2), (self.cursor_column, 2), (self.fuel, 7), (self.lives, 4), (self.focus_offset + 3, 3), (("scanner", "warp", "combat").index(self.mode), 2), (self.crosshair_row, 4), (self.crosshair_column, 4), (self.combat_steps, 8), (self.steps, 11), ) offset = 16 for value, width in values: for bit in range(width): index = offset + bit state[index // 10, index % 10, 5] = bool(value & (1 << bit)) offset += width state[7, 0, 5] = self.targeting_damaged return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113from dataclasses import dataclassfrom math import sqrt
import numpy as np
@dataclassclass Drop: x: float speed: float bonus: bool y: float = 2
class SpearainEnvironment: score_cap = 150
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = 50. self.direction = 1 self.speed = self.spawn_rate = 1. self.timer = self.steps = self.bonus_count = 0 self.held = self.terminal = False self.drops = []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 press, release = held and not self.held, self.held and not held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(press and frame == 0, release and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, press, release): self.timer -= 1 if self.timer < 0: self.bonus_count -= 1 bonus = self.bonus_count < 0 self.drops.append(Drop(self.random.uniform(12, 88), self.random.uniform(1, 2) / (3 if bonus else 1), bonus)) if bonus: self.bonus_count = 12 self.timer += self.random.uniform(40, 60) / self.spawn_rate if press: self.speed *= 0.5 if self.speed < 1 and self.held: self.speed *= 0.98 self.spawn_rate *= 1.05 else: self.speed += (1 - self.speed) * 0.05 self.spawn_rate = 1 if self.speed < 0.03 or release: self.speed = 1 / sqrt(self.speed) # Collision uses the pre-movement position, where the source draws the drop. visible = [(drop.x, drop.y, drop.bonus) for drop in self.drops] for drop in self.drops: velocity = drop.speed * self.speed if drop.bonus and velocity > 78: velocity *= 0.2 elif not drop.bonus and velocity > 74: velocity *= 1.5 drop.y += velocity self.drops = [drop for drop in self.drops if drop.y < 87] self.x += self.direction / sqrt(self.speed) reward = 0 if (self.x < 12 and self.direction < 0) or (self.x > 88 and self.direction > 0): self.direction *= -1 reward = 1 hits = [bonus for x, y, bonus in visible if abs(x - self.x) < 4 and abs(y - 87) < 5] if any(hits): reward += len(self.drops) self.drops.clear() self.spawn_rate = 1 self.timer = 60 elif hits: self.terminal = True return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[8, int(np.clip(self.x // 10, 0, 9)), 0] = True for drop in self.drops: state[int(drop.y // 10), int(drop.x // 10), 2 if drop.bonus else 1] = True state[9, :, 3] = True state[:, [0, 9], 3] = True x = self.x + 10 * self.direction state[8, int(np.clip(x // 10, 0, 9)), 4] = True values = (self.steps, self.held, round(self.speed * 100), self.bonus_count, round(max(0, self.timer))) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130from math import floor, hypot, sqrt
import numpy as np
CORNERS = ((14, 14), (86, 14), (86, 86), (14, 86))
class SpinCellEnvironment: score_cap = 100
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 50., 40. self.vx, self.vy = self.random.uniform(0.4, 0.8), 0. self.spikes = {1, 7} self.gem = int(self.random.integers(4)) self.timer, self.warning = 400, -1 self.steps = self.death = 0 self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): if self.death: self.death -= 1 self.terminal = self.death == 0 return 0 if tap: self.spikes = {(segment + 1) % 12 for segment in self.spikes} if self.warning >= 0: self.warning = (self.warning + 1) % 12 if self.y > 87: self.vx = max(-1.4, min(1.4, self.vx - 0.6)) self.timer -= 1 if self.timer < 0: if self.warning >= 0: self.spikes.add(self.warning) self.warning = -1 self.timer = 200 * sqrt(len(self.spikes) + 1) elif len(self.spikes) < 8: self.warning = int(self.random.choice(sorted(set(range(12)) - self.spikes))) self.timer = 90 else: self.timer = 500 self.vy += 0.06 self.x += self.vx self.y += self.vy segment = self._bounce() if segment in self.spikes: self.death = 7 return 0 x, y = CORNERS[self.gem] if hypot(self.x - x, self.y - y) < 8: reward = max(1, len(self.spikes)) ** 2 if self.spikes: self.spikes.remove(int(self.random.choice(sorted(self.spikes)))) self.gem = (self.gem + int(self.random.integers(1, 4))) % 4 return reward return 0
def _bounce(self): if self.y < 9: side, offset = 0, self.x self.y, self.vy = 9, abs(self.vy) * 0.9 elif self.x > 91: side, offset = 1, self.y self.x, self.vx = 91, -abs(self.vx) * 0.95 elif self.y > 91: side, offset = 2, self.x self.y, self.vy = 91, -3.1 self.vx = min(1.2, max(-1.2, self.vx + self.random.uniform(-0.25, 0.25))) elif self.x < 9: side, offset = 3, self.y self.x, self.vx = 9, abs(self.vx) * 0.95 else: return -1 index = min(2, max(0, floor((offset - 7) * 3 / 86))) return side * 3 + (2 - index if side >= 2 else index)
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(self.y // 10), int(self.x // 10), 0] = True gx, gy = CORNERS[self.gem] state[gy // 10, gx // 10, 1] = True for side in range(4): for index in range(3): segment = side * 3 + index channel = 2 if segment in self.spikes else 3 if segment == self.warning else 4 span = slice(1 + 3 * index, min(9, 4 + 3 * index)) reverse = slice(10 - span.stop, 10 - span.start) if side == 0: state[0, span, channel] = True elif side == 1: state[span, 9, channel] = True elif side == 2: state[9, reverse, channel] = True else: state[reverse, 0, channel] = True values = (self.steps, self.held, self.death, round(self.timer), round((self.vx + 2) * 100), round((self.vy + 8) * 40)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from dataclasses import dataclass
import numpy as np
SIZES = (5, 8, 12)
@dataclassclass Block: x: float y: float vx: float vy: float size: int squash: float = 1. angle: float = 0.
class SplitzigEnvironment: score_cap = 250
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 50., 80. self.direction = 1 self.squash = 1. self.tilt = self.stack = 0. self.frame = self.steps = self.timer = 0 self.held = self.terminal = False self.blocks, self.bullets = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 if held and not self.held: self.direction *= -1 self.squash = 0.5 self.held = held self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): self.squash += (1 - self.squash) * 0.15 self.tilt += (self.direction * 0.3 - self.tilt) * 0.2 self.x = (self.x + self.direction * 1.5) % 100 self.stack *= 0.998 self.y = 90 - self.stack self.terminal = self.y < 0 if self.frame % 7 == 0: self.bullets.append((self.x, self.y - 5)) self.bullets = [(x, y - 3) for x, y in self.bullets if y - 3 >= -5] self.timer += 1 if self.timer >= self.random.uniform(88, 111): self.timer = 0 self.blocks.append(Block(self.random.uniform(15, 85), -10, self.random.uniform(-0.3, 0.3), self.random.uniform(0.2, 0.8), 2)) reward = 0 spent = set() remaining = [] for block in self.blocks: block.x += block.vx block.y += block.vy if (block.x < 5 and block.vx < 0) or (block.x > 95 and block.vx > 0): block.vx *= -1 block.squash = 0.6 block.squash += (1 - block.squash) * 0.1 block.angle += block.vx * 0.05 size = SIZES[block.size] c, s = abs(np.cos(block.angle)), abs(np.sin(block.angle)) half_x = size * (c / block.squash + s * block.squash) / 2 half_y = size * (s / block.squash + c * block.squash) / 2 hits = [index for index, (x, y) in enumerate(self.bullets) if abs(block.x - x) < half_x + 1 and abs(block.y - y) < half_y + 2] if hits: spent.update(hits) reward += 3 - block.size if block.size: for direction in (-1, 1): remaining.append(Block(block.x + 5 * direction, block.y, direction * self.random.uniform(0.8, 1.1), block.vy * 0.8, block.size - 1, 0.6, block.angle)) elif abs(block.x - self.x) < half_x + 3 / self.squash and abs(block.y - self.y) < half_y + 3: self.terminal = True elif block.y > 100 - self.stack - size / 2: self.stack += size / 2 else: remaining.append(block) self.blocks = remaining self.bullets = [bullet for index, bullet in enumerate(self.bullets) if index not in spent] self.frame += 1 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(np.clip(self.y // 10, 0, 9)), int(self.x // 10), 0] = True for x, y in self.bullets: if 0 <= y < 100: state[int(y // 10), int(x // 10), 1] = True for block in self.blocks: if 0 <= block.x < 100 and 0 <= block.y < 100: state[int(block.y // 10), int(block.x // 10), block.size + 2] = True rows = np.arange(10) * 10 state[rows + 10 > 100 - self.stack, :, 5] = True values = (self.steps, self.direction > 0, self.held, self.frame % 7, self.timer) state[:5, :9, 5] = False for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156from dataclasses import dataclassfrom math import atan2, cos, hypot, pi, sin
import numpy as np
DIRECTIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))STARTS = ((50, 29), (71, 50), (50, 71), (29, 50))
@dataclassclass Bar: x: float y: float length: float angle: float side: int pivot: float = 0
def advance(self): self.angle = (self.angle + 0.03) % 4 if not self.side <= self.angle < self.side + pi / 4: return self.angle = self.side dx, dy = DIRECTIONS[self.side] distance = self.length * (1 - self.pivot) room = (71 - self.x, 71 - self.y, self.x - 29, self.y - 29)[self.side] if distance > room: self.x += room * dx self.y += room * dy self.pivot = 1 - (distance - room) / self.length self.side = (self.side + 1) % 4 else: self.x += distance * dx self.y += distance * dy self.angle = (self.angle + 2) % 4 self.pivot = 0
def points(self): distance = np.linspace(-self.pivot, 1 - self.pivot, 32) * self.length angle = self.angle * pi / 2 return self.x + distance * cos(angle), self.y + distance * sin(angle)
@dataclassclass Item: x: float y: float spike: bool timer: int size: int = 0
class SquareBarEnvironment: score_cap = 300
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.player = Bar(50, 29, 9, 3, 0) self.enemy = Bar(50, 71, 12, 1, 2) self.items = [self._item(i < 3) for i in range(10)] self.steps = 0 self.multiplier = 1 self.held = self.terminal = False
def _item(self, spike): for _ in range(99): x = self.random.uniform(9, 70) - 50 y = self.random.uniform(9, 15 if spike else 26) - 50 dx, dy = DIRECTIONS[self.random.integers(4)] px, py = 50 + dx * x - dy * y, 50 + dy * x + dx * y if hypot(px - self.player.x, py - self.player.y) > 36: break return Item(px, py, spike, int(self.random.integers(777, 999)))
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _chased(self): difference = atan2(self.player.y - 50, self.player.x - 50) - atan2( self.enemy.y - 50, self.enemy.x - 50) return (difference + pi) % (2 * pi) - pi > 0
def _advance(self): chased = self._chased() target, rate = (29, 0.1) if self.held else (9, 0.2) self.player.length += (target - self.player.length) * rate self.enemy.length = 15 self.player.advance() self.enemy.advance() px, py = self.player.points() ex, ey = self.enemy.points() reward = 0 if np.any(np.hypot(px[:, None] - ex, py[:, None] - ey) < 3): if chased: self.terminal = True else: reward += 10 * self.multiplier self.multiplier += 1 side = (self.player.side + 2) % 4 self.enemy = Bar(*STARTS[side], 12, (side - 1) % 4, side) for index, item in enumerate(self.items): if item.timer % 15 == 0: item.size = max(0, item.size - 1) if item.timer < 60 else min(4, item.size + 1) reach = item.size / 2 + 1.5 hit = item.size > 0 and np.any((abs(px - item.x) < reach) & (abs(py - item.y) < reach)) if hit and not item.spike: reward += self.multiplier self.items[index] = self._item(False) else: self.terminal |= bool(hit and item.size == 4) item.timer -= 1 if item.timer < 0: self.items[index] = self._item(item.spike) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for channel, bar in ((0, self.player), (1, self.enemy)): x, y = bar.points() cols = np.clip(x // 10, 0, 9).astype(int) rows = np.clip(y // 10, 0, 9).astype(int) state[rows, cols, channel] = True for item in self.items: if item.size: channel = 2 if not item.spike else 3 if item.size == 4 else 4 state[int(item.y // 10), int(item.x // 10), channel] = True values = (self.steps, self.multiplier, self.held, self._chased(), round(self.player.length * 10), self.player.side, self.enemy.side) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121from dataclasses import dataclassfrom math import sqrt
import numpy as np
@dataclassclass Body: x: float y: float vx: float vy: float size: float
class StageSeparationEnvironment: score_cap = 1500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.y, self.vy = 90., -0.5 self.stage, self.burn = 4., 100 self.camera, self.zoom = 0., 1. self.distance = 99. self.steps = 0 self.held = self.terminal = False self.stages, self.debris = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0. for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _advance(self, tap): reward = -self.vy * 0.1 self.camera += max(-99, min(0, (self.y - 130 * self.zoom - self.camera) * 0.1)) self.zoom = min(3, max(1, 1 - self.y / 9999)) self.vy += 0.05 - self.burn / 600 self.y += self.vy self.burn = max(0, self.burn - 1) if tap and self.stage > 2: self.stages.append(Body(50, self.y + 10 * (self.stage - 1), self.random.uniform(-0.5, 0.5), self.vy + 0.5, 10)) self.stage -= 1 self.vy -= 0.5 self.burn = 60 self.stage = min(4, self.stage + 0.02) self.terminal = self.y - self.camera > 150 * self.zoom for stage in self.stages: stage.vy += 0.1 stage.x += stage.vx stage.y += stage.vy self.stages = [stage for stage in self.stages if stage.y <= self.camera + 200 * self.zoom] self.distance += self.vy if self.distance < 0: side = self.random.choice((-1, 1)) self.debris.append(Body(50 + side * 70 * self.zoom, self.camera - self.random.uniform(0, 200) * self.zoom, -side * self.random.uniform(0.5, 0.8) * self.zoom / 2, self.random.uniform(-15, 0) * self.zoom / 2, self.random.uniform(5, 15))) self.distance = self.random.uniform(120, 160) / sqrt(self.zoom) for debris in self.debris: debris.x += debris.vx debris.y += debris.vy self.terminal |= self._hits(debris) self.debris = [debris for debris in self.debris if abs(debris.x - 50) <= 70 * self.zoom] return reward
def _hits(self, debris): dx = abs(debris.x - 50) dy = max(self.y - debris.y, debris.y - (self.y + self.stage * 10), 0) near = sqrt(max(0, dx - 5) ** 2 + dy ** 2) far = sqrt((dx + 5) ** 2 + max(abs(debris.y - self.y), abs(debris.y - self.y - self.stage * 10)) ** 2) return near <= debris.size + 2 and far >= debris.size - 2
def state(self): state = np.zeros((10, 10, 6), dtype=bool) rows, cols = np.ogrid[7.5:150:15, 5:100:10] world_x = 50 + (cols - 50) * self.zoom world_y = self.camera + rows * self.zoom for x, y, height, channel in [(50, self.y, self.stage * 10, 0), *((s.x, s.y, s.size, 1) for s in self.stages)]: state[:, :, channel] |= (abs(world_x - x) < 5 + 5 * self.zoom) & ( (world_y > y - 7.5 * self.zoom) & (world_y < y + height + 7.5 * self.zoom)) for debris in self.debris: state[:, :, 2] |= abs(np.hypot(world_x - debris.x, world_y - debris.y) - debris.size) < 8 * self.zoom if self.burn: y = (self.y + 10 * self.stage - self.camera) / self.zoom if 0 <= y < 150: state[int(y // 15), 5, 3] = True state[9, :, 4] = True values = (self.steps, round(self.stage * 100), self.burn, min(2047, max(0, round((self.vy + 100) * 10))), self.held) for row, value in enumerate(values): for bit in range(11): state[row + bit // 10 * 5, bit % 10, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124from dataclasses import dataclassfrom math import hypot, sin
import numpy as np
@dataclassclass Asteroid: x: float y: float vx: float vy: float size: float
class StarEaterEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = self.y = 50. self.charge = self.timer = self.steps = self.frame = 0 self.blast_timer = self.destroyed = 0 self.blast_x = self.blast_y = self.blast_radius = 0. self.held = self.terminal = False self.asteroids = []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 release = self.held and not held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(release and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _spawn(self): edge = self.random.integers(4) offset = self.random.uniform(0, 100) drift = self.random.uniform(-0.3, 0.3) speed = self.random.uniform(0.5, 0.7) x, y, vx, vy = ((offset, 0, drift, speed), (offset, 100, drift, -speed), (0, offset, speed, drift), (100, offset, -speed, drift))[edge] if min(hypot(x - self.x, y - self.y), hypot(x - self.x + 100, y - self.y)) > 50: self.asteroids.append(Asteroid(x, y, vx, vy, self.random.uniform(5, 9))) self.timer = self.random.uniform(22, 55)
def _advance(self, release): self.timer -= 1 if self.timer <= 0: self._spawn() speed = 1.8 if self.held else 1 self.x += 0.2 * speed if self.x > 100: self.x = 0. self.y = min(95, max(5, self.y + sin(self.frame * 0.02 * speed) * 0.1)) if self.held: self.charge = min(60, self.charge + 1) elif release and self.charge > 10: self.blast_x, self.blast_y = self.x, self.y self.blast_radius = 15 + self.charge * 0.8 self.blast_timer = 12 self.charge = self.destroyed = 0 else: self.charge = max(0, self.charge - 2) self.blast_timer = max(0, self.blast_timer - 1) reward = 0 remaining = [] for asteroid in self.asteroids: asteroid.x += asteroid.vx asteroid.y += asteroid.vy if not (-10 < asteroid.x < 110 and -10 < asteroid.y < 110): continue if self.blast_timer and min( hypot(asteroid.x - self.blast_x, asteroid.y - self.blast_y), hypot(asteroid.x - self.blast_x + 100, asteroid.y - self.blast_y), ) < self.blast_radius + asteroid.size / 2: self.destroyed += 1 reward += self.destroyed ** 2 else: self.terminal |= hypot(asteroid.x - self.x, asteroid.y - self.y) < ( 5 + self.charge * 0.15 + asteroid.size / 2) remaining.append(asteroid) self.asteroids = remaining self.frame += 1 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(self.y // 10), min(9, int(self.x // 10)), 0] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for asteroid in self.asteroids: state[:, :, 1] |= np.hypot(cols - asteroid.x, rows - asteroid.y) < asteroid.size / 2 + 5 if self.charge: state[:, :, 2] = np.hypot(cols - self.x, rows - self.y) < 10 + self.charge * 0.15 if self.blast_timer: for x in (self.blast_x, self.blast_x - 100): state[:, :, 3] |= np.hypot(cols - x, rows - self.blast_y) < self.blast_radius if self.charge > 10: for x in (self.x, self.x - 100): state[:, :, 4] |= np.hypot(cols - x, rows - self.y) < 15 + self.charge * 0.8 values = (self.steps, self.charge, self.held, self.blast_timer, self.destroyed) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import numpy as np
WAVE_QUOTAS = (10, 20, 30)WAVE_VALUES = (100, 200, 300)LEVEL_BONUSES = (400, 600, 1_000, 1_100, 1_400, 1_600, 2_000, 2_100)
class StarGunnerEnvironment: """Eight escalating three-wave invasions with bidirectional single-shot fire."""
score_cap = 142_600.0
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = 5_000): self.sticky_action_prob = sticky_action_prob self.horizon = horizon self.random = np.random.RandomState() self.seed(0) self.reset()
@classmethod def normalize_score(cls, raw_score: float) -> float: return min(max(raw_score, 0.0), cls.score_cap) / cls.score_cap
def seed(self, seed: int) -> None: self.random.seed(seed)
def reset(self) -> None: self.row = 5 self.column = 5 self.previous_row = self.row self.previous_column = self.column self.facing = 1 self.lives = 5 self.level = 0 self.wave = 0 self.spawned = 0 self.killed = 0 self.next_enemy_id = 0 self.enemies: list[dict[str, int]] = [] self.lasers: list[list[int]] = [] self.bombs: list[list[int]] = [] self.previous_enemies: list[tuple[int, int]] = [] self.fire_ready = True self.score = 0.0 self.next_extra_life = 10_000 self.steps = 0 self.last_action = 0 self.terminal = False self._fill_formation()
@property def active_limit(self) -> int: return self.wave + 1
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.rand() < self.sticky_action_prob: action = self.last_action self.last_action = action self.previous_row = self.row self.previous_column = self.column self.previous_enemies = [(enemy["row"], enemy["column"]) for enemy in self.enemies] if action != 5: self.fire_ready = True if action == 1: self.column = max(0, self.column - 1) self.facing = -1 elif action == 2: self.row = max(0, self.row - 1) elif action == 3: self.column = min(9, self.column + 1) self.facing = 1 elif action == 4: self.row = min(9, self.row + 1) elif action == 5 and self.fire_ready: self.lasers.append([self.row, self.column, self.facing]) self.fire_ready = False self._move_lasers() self._move_enemies() self._move_bombs() reward = self._resolve_hits() self._resolve_player_collisions() if not self.terminal: self._fill_formation() if self.killed >= WAVE_QUOTAS[self.wave] and not self.enemies: reward += float(LEVEL_BONUSES[self.level]) self._advance_wave() future_score = self.score + reward while future_score >= self.next_extra_life: self.lives = min(255, self.lives + 1) self.next_extra_life += 10_000 self.score = future_score self.steps += 1 if self.steps >= self.horizon: self.terminal = True return reward, self.terminal
def _fill_formation(self) -> None: quota = WAVE_QUOTAS[self.wave] while len(self.enemies) < self.active_limit and self.spawned < quota: enemy_id = self.next_enemy_id self.next_enemy_id += 1 self.spawned += 1 self.enemies.append( { "id": enemy_id, "row": int(self.random.randint(1, 9)), "column": 0 if self.random.rand() < 0.5 else 9, "forming": 2, } )
def _move_lasers(self) -> None: for laser in self.lasers: laser[1] += laser[2] self.lasers = [laser for laser in self.lasers if 0 <= laser[1] < 10]
def _move_enemies(self) -> None: interval = max(1, 4 - self.level // 2) for enemy in self.enemies: if enemy["forming"] > 0: enemy["forming"] -= 1 continue if self.steps % interval == 0: enemy["column"] += int(np.sign(self.column - enemy["column"])) if self.steps % 2 == 0: enemy["row"] += int(np.sign(self.row - enemy["row"]))
def _move_bombs(self) -> None: if self.steps % max(5, 11 - self.level) == 0: self.bombs.append([0, int(self.random.randint(10))]) for bomb in self.bombs: bomb[0] += 1 self.bombs = [bomb for bomb in self.bombs if bomb[0] < 10]
def _resolve_hits(self) -> float: reward = 0.0 hit_enemy_ids: set[int] = set() hit_lasers: set[int] = set() for laser_index, laser in enumerate(self.lasers): for enemy in self.enemies: if enemy["forming"] > 0 or laser[:2] != [enemy["row"], enemy["column"]]: continue hit_enemy_ids.add(enemy["id"]) hit_lasers.add(laser_index) reward += float(WAVE_VALUES[self.wave]) break self.enemies = [enemy for enemy in self.enemies if enemy["id"] not in hit_enemy_ids] self.lasers = [laser for index, laser in enumerate(self.lasers) if index not in hit_lasers] self.killed += len(hit_enemy_ids) return reward
def _resolve_player_collisions(self) -> None: colliding_enemy_ids = { enemy["id"] for enemy in self.enemies if enemy["row"] == self.row and enemy["column"] == self.column } collision = bool(colliding_enemy_ids) or any(bomb == [self.row, self.column] for bomb in self.bombs) if not collision: return self.lives -= 1 self.row = 5 self.column = 5 self.lasers.clear() self.bombs.clear() self.enemies = [enemy for enemy in self.enemies if enemy["id"] not in colliding_enemy_ids] self.spawned -= len(colliding_enemy_ids) if self.lives <= 0: self.terminal = True
def _advance_wave(self) -> None: self.wave += 1 if self.wave >= 3: self.wave = 0 self.level += 1 if self.level >= 8: self.terminal = True return self.spawned = 0 self.killed = 0 self._fill_formation()
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) state[self.row, self.column, 0] = True state[self.previous_row, self.previous_column, 4] = True for enemy in self.enemies: channel = 2 if enemy["forming"] > 0 else 1 state[enemy["row"], enemy["column"], channel] = True for row, column in self.previous_enemies: state[row, column, 4] = True for row, column, _ in self.lasers: state[row, column, 3] = True for row, column in self.bombs: state[row, column, 1] = True values = ( (self.level, 4), (self.wave, 2), (self.spawned, 5), (self.killed, 5), (self.lives, 8), (self.row, 4), (self.column, 4), (self.facing + 1, 2), (self.steps, 13), (self.next_extra_life // 10_000, 5), ) offset = 0 for value, width in values: for bit in range(width): index = offset + bit state[index // 10, index % 10, 5] = bool(value & (1 << bit)) offset += width state[6, 0, 5] = self.fire_ready return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131from dataclasses import dataclass
import numpy as np
@dataclassclass Voice: x: float y: float vx: float size: float
def move(self, edge): self.x += self.vx if not edge <= self.x <= 100 - edge: self.x = min(100 - edge, max(edge, self.x)) self.vx *= -1
@dataclassclass Falling: x: float y: float speed: float size: float = 5
def touches(self, voice): reach = (self.size + voice.size) / 2 return abs(self.x - voice.x) < reach and abs(self.y - voice.y) < reach
class StillfireChoirEnvironment: score_cap = 400
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.player = Voice(50, 88, 0.72, 7) self.allies, self.enemies, self.items = [], [], [] self.beams = [] self.volley, self.enemy_timer, self.item_timer = 62, 25, 75 self.steps = self.glow = 0 self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): voices = [self.player, *self.allies] if not self.held: self.player.move(5) for ally in self.allies: ally.move(4) self.volley -= 1 firing = self.volley <= 0 if firing: self.volley = 62 self.glow = 4 self.beams = [(voice.x, voice.y) for voice in voices] if self.glow else [] self.glow = max(0, self.glow - 1) self.enemy_timer -= 1 if self.enemy_timer <= 0: self.enemies.append(Falling(self.random.uniform(5, 95), -4, self.random.uniform(0.45, 0.78), self.random.uniform(5, 9))) self.enemy_timer = self.random.uniform(31, 49) self.item_timer -= 1 if self.item_timer <= 0: self.items.append(Falling(self.random.uniform(7, 93), -3, self.random.uniform(0.36, 0.52))) self.item_timer = self.random.uniform(125, 175) reward = 0 remaining = [] for item in self.items: item.y += item.speed if any(item.touches(voice) for voice in voices): speed = self.random.uniform(0.48, 0.9) * self.random.choice((-1, 1)) self.allies.append(Voice(item.x, item.y, speed, 5)) reward += 5 elif item.y <= 105: remaining.append(item) self.items = remaining remaining = [] for enemy in self.enemies: enemy.y += enemy.speed half = enemy.size / 2 if firing and any(abs(enemy.x - x) < half + 1 and enemy.y + half > 6 and enemy.y - half < y - 2 for x, y in self.beams): reward += 10 + 2 * len(self.allies) else: self.terminal |= any(enemy.touches(voice) for voice in voices) if enemy.y <= 105: remaining.append(enemy) self.enemies = remaining return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) groups = ((self.player,), self.allies, self.enemies, self.items) for channel, entities in enumerate(groups): for entity in entities: if 0 <= entity.y < 100: state[int(entity.y // 10), int(entity.x // 10), channel] = True for x, y in self.beams: state[:int(y // 10) + 1, int(x // 10), 4] = True values = (self.steps, self.volley, self.held, len(self.allies), self.player.vx > 0, self.glow) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from dataclasses import dataclassfrom math import hypot
import numpy as np
@dataclassclass Bubble: x: float y: float radius: float speed: float
@dataclassclass Chain: x: float y: float radius: float life: int = 5
class StompingBubblesEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 50., 0. self.vx, self.vy = 1.5, 0. self.timer = self.steps = 0 self.multiplier = 1 self.held = self.terminal = False self.bubbles, self.chains = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): self.x += self.vx if (self.x > 95 and self.vx > 0) or (self.x < 5 and self.vx < 0): self.vx *= -1 self.y += self.vy self.vy = (self.vy + (0.09 if self.held else 0.01)) * 0.99 if self.y < 0 and self.vy < 0: self.vy *= -0.5 self.terminal = self.y > 99 self.timer -= 1 if self.timer < 0: size = self.random.uniform(5, 9) self.bubbles.append(Bubble(self.random.uniform(0, 100), 102 + size, size, self.random.uniform(0.1, 0.3))) self.timer += 9 for chain in self.chains: chain.radius += 1 chain.life -= 1 self.chains = [chain for chain in self.chains if chain.life > 0] active = tuple(self.chains) x, y = self.x, self.y reward = 0 bounced = False remaining = [] for bubble in self.bubbles: bubble.y -= bubble.speed dx, dy = abs(bubble.x - x), abs(bubble.y - y) near = hypot(max(0, dx - 2.5), max(0, dy - 2.5)) far = hypot(dx + 2.5, dy + 2.5) direct = near < bubble.radius + 1 and far > bubble.radius - 1 chained = any(self._intersects(bubble, chain) for chain in active) if direct or chained: reward += self.multiplier self.multiplier += 1 self.chains.append(Chain(bubble.x, bubble.y, bubble.radius)) if direct and not bounced: self.vy *= -1 self.y += self.vy * 2 bounced = True elif bubble.y >= -bubble.radius: remaining.append(bubble) self.bubbles = remaining if not self.chains: self.multiplier = 1 return reward
@staticmethod def _intersects(bubble, chain): distance = hypot(bubble.x - chain.x, bubble.y - chain.y) return abs(bubble.radius - chain.radius) - 2 < distance < bubble.radius + chain.radius + 2
def state(self): state = np.zeros((10, 10, 6), dtype=bool) row = int(np.clip(self.y // 10, 0, 9)) state[row, int(self.x // 10), 0] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for channel, circles in ((1, self.bubbles), (2, self.chains)): for circle in circles: state[:, :, channel] |= abs(np.hypot(cols - circle.x, rows - circle.y) - circle.radius) < 7 ahead = int(np.clip((self.x + 6 * self.vx) // 10, 0, 9)) state[row, ahead, 3] = True state[9, :, 4] = True values = (self.steps, self.timer, self.multiplier, self.held, int(np.clip(round((self.vy + 15) * 16), 0, 511))) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157from dataclasses import dataclassfrom math import floor
import numpy as np
@dataclassclass Platform: x: float y: float width: float hp: int = 120
@dataclassclass Enemy: x: float y: float direction: int
class StompshelterEnvironment: score_cap = 600
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 50., 70. self.vx, self.vy = 1, 0. self.steps = self.frame = self.jumps = self.combo = 0 self.lava, self.distance = 102., 100. self.held = self.terminal = self.grounded = False self.platforms = [Platform(self.random.uniform(20, 60), y, self.random.uniform(25, 38)) for y in range(15, 91, 15)] self.enemies, self.debris = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): self.lava -= 0.025 top = min((platform.y for platform in self.platforms), default=15) if top > 5: self.platforms.append(Platform(self.random.uniform(10, 55), top - self.random.uniform(13, 17), self.random.uniform(25, 38))) if self.distance < 0: candidates = [p for p in self.platforms if p.y < 20 and p.hp > 60] if candidates: platform = candidates[self.random.integers(len(candidates))] self.enemies.append(Enemy(platform.x + platform.width / 2, platform.y - 5, int(self.random.choice((-1, 1))))) self.distance = self.random.uniform(100, 200) if self.frame % 70 == 0: self.debris.append((self.random.uniform(8, 92), -4)) if tap and (self.grounded or self.jumps < 2): self.vy = -2.6 self.jumps += 1 self.vy += 0.1 self.y += self.vy self.x += self.vx * (1 if self.held else 0.1) if (self.x > 90 and self.vx > 0) or (self.x < 10 and self.vx < 0): self.vx *= -1 self.grounded = False for p in self.platforms: if self.vy > 0 and p.hp > 0 and p.x - 3 < self.x < p.x + p.width + 3 and p.y - 8 < self.y < p.y + 2: self.y, self.vy, self.grounded = p.y - 4, 0, True self.jumps = self.combo = 0 p.hp -= 1 break scroll = max(0, 60 - self.y) self.y += scroll self.lava += scroll self.distance -= scroll reward = floor(scroll) for p in self.platforms: p.y += scroll self.platforms = [p for p in self.platforms if p.y < 110 and p.hp > 0] self.lava -= max(0, self.lava - 100) * 0.5 self.terminal = self.y > self.lava - 3 remaining = [] for enemy in self.enemies: enemy.y += scroll if enemy.y >= 105: continue enemy.x += enemy.direction * 0.35 for p in self.platforms: if abs(enemy.y + 5 - p.y) < 2: if enemy.x <= p.x + 2: enemy.direction = 1 if enemy.x >= p.x + p.width - 2: enemy.direction = -1 if abs(enemy.x - self.x) < 6.5 and abs(enemy.y - self.y) < 5: if self.vy > 0.5 and self.y < enemy.y - 2: self.vy = -2.2 self.combo += 1 reward += 8 + self.combo * 4 continue self.terminal = True remaining.append(enemy) self.enemies = remaining remaining = [] for x, y in self.debris: y += scroll + 0.5 if y >= 105: continue blockers = [p for p in self.platforms if p.hp > 0 and p.x < x < p.x + p.width and p.y - 2 < y < p.y + 5] if blockers: for p in blockers: p.hp -= 15 else: self.terminal |= abs(x - self.x) < 5 and abs(y - self.y) < 4 remaining.append((x, y)) self.debris = remaining self.frame += 1 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(np.clip(self.y // 10, 0, 9)), int(self.x // 10), 0] = True rows, cols = np.ogrid[:100:10, :100:10] for p in self.platforms: if p.hp > 0: state[:, :, 1] |= (rows < p.y + 4) & (rows + 10 > p.y) & (cols < p.x + p.width) & (cols + 10 > p.x) for channel, positions in ((2, [(e.x, e.y) for e in self.enemies]), (3, self.debris)): for x, y in positions: if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), channel] = True state[np.arange(10) * 10 + 10 > self.lava, :, 4] = True values = (self.steps, self.jumps, self.combo, self.held, self.vx > 0, int(np.clip(round((self.vy + 4) * 40), 0, 511)), self.grounded) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113from dataclasses import dataclassfrom math import cos, pi, sin
import numpy as np
LANES = (25, 50, 75)
@dataclassclass Falling: lane: int y: float = -5 phase: float = 0
class StormveilEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = 50. self.lane = 1 self.squash = 1. self.steps = self.frame = self.timer = 0 self.multiplier = 1 self.held = self.terminal = False self.obstacles, self.coins = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 if held and not self.held: self.lane = (self.lane + 1) % 3 self.squash = 0.6 self.held = held self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): vx = (LANES[self.lane] - self.x) * 0.5 self.x += vx self.squash += (1 - self.squash) * 0.15 breathe = 1 + sin(self.frame * 0.1) * 0.05 tilt = vx * 0.08 width, height = 3 * self.squash * breathe, 3 * (2 - self.squash) * breathe half_x = abs(cos(tilt)) * height + abs(sin(tilt)) * width half_y = abs(sin(tilt)) * height + abs(cos(tilt)) * width self.timer -= 1 if self.timer < 0: blocked = int(self.random.integers(3)) self.obstacles.append(Falling(blocked, phase=self.random.uniform(0, 2 * pi))) coin_lane = int(self.random.choice([lane for lane in range(3) if lane != blocked])) self.coins.append(Falling(coin_lane)) self.timer += 40 for obstacle in self.obstacles: obstacle.y += 1.5 obstacle.phase += 0.2 pulse = 1 + sin(obstacle.phase) * 0.15 self.terminal |= self._touches(obstacle, half_x + 3 * pulse, half_y + 3 * (2 - pulse)) self.obstacles = [obstacle for obstacle in self.obstacles if obstacle.y <= 105] reward = 0 remaining = [] for coin in self.coins: coin.y += 1.5 coin.phase += 0.12 if self._touches(coin, half_x + 1 + 2 * abs(cos(coin.phase)), half_y + 3): reward += self.multiplier self.multiplier = min(16, self.multiplier + 1) elif coin.y > 105: self.multiplier = 1 else: remaining.append(coin) self.coins = remaining self.frame += 1 return reward
def _touches(self, item, half_x, half_y): return abs(LANES[item.lane] - self.x) < half_x and abs(item.y - 85) < half_y
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[8, int(self.x // 10), 0] = True for channel, items in ((1, self.obstacles), (2, self.coins)): for item in items: if 0 <= item.y < 100: state[int(item.y // 10), LANES[item.lane] // 10, channel] = True state[:, [x // 10 for x in LANES], 3] = True state[8, LANES[self.lane] // 10, 4] = True values = (self.steps, self.multiplier, self.held, self.timer, round(self.squash * 100)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133from dataclasses import dataclass
import numpy as np
@dataclassclass Point: x: float y: float
class SubJumpEnvironment: score_cap = 300
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 5., 60. self.vx = self.vy = self.terrain_velocity = 0. self.terrain_distance, self.coin_distance = 50., 0. self.steps = 0 self.multiplier = 1 self.land = self.held = self.terminal = False self.points = [Point(i * 10 - 10, self.random.uniform(75, 85)) for i in range(12)] self.coins = []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _scroll_terrain(self, scroll): self.terrain_distance -= scroll for index, point in enumerate(self.points): point.x -= scroll if point.x >= -10: continue if self.terrain_distance < 0: self.land = not self.land self.terrain_distance = self.random.uniform(200, 300) / (7 if self.land else 1) point.x += 120 previous = self.points[index - 1].y self.terrain_velocity = (self.terrain_velocity + self.random.uniform(-2, 2)) * 0.95 if self.land: if previous > 50: self.terrain_velocity -= 5 elif (previous < 40 and self.terrain_velocity < 0) or (previous > 45 and self.terrain_velocity > 0): self.terrain_velocity *= -0.5 y = previous + self.terrain_velocity / 3 else: if previous < 65: self.terrain_velocity += 5 if previous < 55 else 3 elif previous > 90 and self.terrain_velocity > 0: self.terrain_velocity *= -0.5 y = previous + self.terrain_velocity if self.terrain_distance < 60: self.terrain_velocity += 4 point.y = min(95, max(35, y)) + self.random.uniform(-5, 5)
def _advance(self): scroll = max(0, self.x - 10) * 0.2 self._scroll_terrain(scroll) submerged = self.y > 50 if self.held: self.vy += -0.06 if submerged else 0.01 else: self.vy += 0.03 if submerged else 0.05 self.vx += ((1 if self.held else 0.5) - self.vx) * 0.1 drag = 0.95 if submerged else 0.99 self.vx *= drag self.vy *= drag self.x += self.vx - scroll self.y += self.vy ordered = sorted(self.points, key=lambda point: point.x) terrain_y = np.interp(self.x, [point.x for point in ordered], [point.y for point in ordered]) self.terminal = bool(abs(self.y - terrain_y) < 4) self.coin_distance -= scroll if self.coin_distance < 0: edge = ordered[-1] offset = self.random.uniform(5, 10) if edge.y < 50 else self.random.uniform(10, 20) self.coins.append(Point(edge.x, edge.y - offset)) self.coin_distance = self.random.uniform(10, 40) reward = 0 remaining = [] for coin in self.coins: coin.x -= scroll if abs(coin.x - self.x) < 5 and abs(coin.y - self.y) < 5: reward += self.multiplier self.multiplier += 1 elif coin.x < -3: self.multiplier = max(1, self.multiplier - 1) else: remaining.append(coin) self.coins = remaining return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(np.clip(self.y // 10, 0, 9)), int(self.x // 10), 0] = True ordered = sorted(self.points, key=lambda point: point.x) heights = np.interp(np.arange(5, 100, 10), [point.x for point in ordered], [point.y for point in ordered]) for col, y in enumerate(heights): state[min(9, int(y // 10)), col, 1 if y < 50 else 2] = True state[5, :, 3] = True for coin in self.coins: if 0 <= coin.x < 100 and 0 <= coin.y < 100: state[int(coin.y // 10), int(coin.x // 10), 4] = True values = (self.steps, self.multiplier, self.held, round((self.vy + 5) * 40), round(self.vx * 100)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114import numpy as np
class SumTenEnvironment: score_cap = 1000 directions = ((-1, 0), (0, -1))
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.grid = np.zeros((10, 10), dtype=np.uint8) self.grid[:, 0] = self.random.integers(1, 10, 10) self.grid[6, 1:7] = (6, 5, 8, 1, 7, 3) self.x, self.y = 7, 6 self.scroll_x, self.scroll_y = 100., 0. self.direction = self.timer = self.total = self.count = self.steps = 0 self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def _next(self, direction): dx, dy = self.directions[direction] return self.x + dx, self.y + dy
def _value(self, x, y): return int(self.grid[y, x]) if 0 <= x < 10 and 0 <= y < 10 else 0
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): self.timer += 1 if self.timer == 30: alternate = 1 - self.direction if self._value(*self._next(alternate)): self.direction = alternate self.timer = 0 if self.scroll_x - self.x * 11 < 0 or self.scroll_y + self.y * 11 + 1 > 91: self.terminal = True return 0 reward = 0 if tap: x, y = self._next(self.direction) value = self._value(x, y) if not value: self.terminal = True return 0 self.x, self.y = x, y self.timer = 0 self.total += value self.count += 1 if self.total % 10 == 0: reward = (self.total // 10) ** 2 * 10 self.total = self.count = 0 elif self.count == 10: self.terminal = True if not self._value(*self._next(self.direction)): self.direction = 1 - self.direction self.scroll_x -= max(0, 7 - self.x) * 0.5 + 0.01 self.scroll_y += max(0, 6 - self.y) * 0.5 + 0.01 if self.scroll_x <= 90: self.grid[:, 1:] = self.grid[:, :-1].copy() self.grid[:, 0] = self.random.integers(1, 10, 10) gap = int(self.random.integers(1, 15)) if gap < 10 and self.grid[gap - 1, 1]: self.grid[gap, 0] = 0 self.scroll_x += 10 self.x += 1 if self.scroll_y >= 10: self.grid[1:] = self.grid[:-1].copy() self.grid[0] = self.random.integers(1, 10, 10) gap = int(self.random.integers(1, 15)) if gap < 10 and self.grid[1, gap - 1]: self.grid[0, gap] = 0 self.scroll_y -= 10 self.y += 1 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for bit in range(4): state[:, :, bit] = (self.grid & (1 << bit)) != 0 if 0 <= self.x < 10 and 0 <= self.y < 10: state[self.y, self.x, 4] = True x, y = self._next(self.direction) if 0 <= x < 10 and 0 <= y < 10: state[y, x, 5] = True # Reserve a column for each gauge by using the marker planes' last rows. packed = (self.total | (self.count << 7) | (self.timer << 11) | (int(self.held) << 16) | (self.direction << 17)) for bit in range(18): state[8 + bit // 10, bit % 10, 5] = bool(packed & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113from dataclasses import dataclassfrom math import cos, sin
import numpy as np
@dataclassclass Falling: x: float y: float speed: float
class SunflowerSwayEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.height, self.angle, self.velocity = 40., 0., 0.001 self.sun = 120. self.drop_timer, self.insect_timer = 30., 60. self.steps = 0 self.held = self.terminal = False self.drops, self.insects = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0. for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _head(self): return 30 + self.height * sin(self.angle), 95 - self.height * cos(self.angle)
def _advance(self): if self.held: self.velocity += 0.005 self.sun += ((80 if self.held else 120) - self.sun) * 0.1 self.velocity *= 0.97 self.angle += self.velocity self.velocity -= self.angle * 0.01 self.height = min(70, self.height - 0.045) self.terminal = self.height < 9 x, y = self._head() self.drop_timer -= 1 if self.drop_timer <= 0: self.drops.append(Falling(self.random.uniform(0, 99), -3, self.random.uniform(0.5, 1))) self.drop_timer = self.random.uniform(30, 40) reward = 0. remaining = [] for drop in self.drops: drop.y += drop.speed if abs(drop.x - x) < 5.5 and abs(drop.y - y) < 5.5: reward += self.height self.height += 7 elif drop.y <= 90: remaining.append(drop) self.drops = remaining self.insect_timer -= 1 if self.insect_timer <= 0: bounds = (0, 20) if self.random.random() < 0.25 else (40, 99) self.insects.append(Falling(self.random.uniform(*bounds), -3, self.random.uniform(0.3, 0.8))) self.insect_timer = self.random.uniform(60, 70) remaining = [] for insect in self.insects: insect.y += insect.speed if abs(insect.x - x) < 6 and abs(insect.y - y) < 6: self.height -= 15 elif insect.y <= 90: remaining.append(insect) self.insects = remaining return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) x, y = self._head() row, col = np.clip(np.array([y, x]) // 10, 0, 9).astype(int) state[row, col, 0] = True stem = np.linspace((30, 95), (x, y), 24) cols, rows = np.clip(stem // 10, 0, 9).astype(int).T state[rows, cols, 1] = True for channel, objects in ((2, self.drops), (3, self.insects)): for obj in objects: if 0 <= obj.y < 100: state[int(obj.y // 10), int(obj.x // 10), channel] = True if self.sun < 100: state[1, int(self.sun // 10), 4] = True values = (self.steps, round(self.height * 5), self.held, round((self.angle + 2) * 100), round((self.velocity + 1) * 100), round(self.drop_timer), round(self.insect_timer)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166from dataclasses import dataclassfrom math import hypot, sqrt
import numpy as np
@dataclass(eq=False)class Runner: x: float y: float vx: float = 0 vy: float = 0 grounded: bool = False jumped: bool = False below: "Runner | None" = None above: "Runner | None" = None
class SurvivorEnvironment: score_cap = 100
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.runners, self.downed = [], [] self.steps = 0 self.held = self.terminal = False self._wave()
def _runner(self): return Runner(self.random.uniform(10, 40), self.random.uniform(-9, 9))
def _wave(self): self.runners.extend(self._runner() for _ in range(9 - len(self.runners))) self.radius = self.random.uniform(5, 25) self.barrel_x = 120 + self.radius self.barrel_speed = self.random.uniform(1, 2) / sqrt(1 + self.radius * 0.3) self.next_wave = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): if self.next_wave: self._wave() self.barrel_x -= self.barrel_speed jumped = [] replacements = 0 for runner in tuple(self.runners): if runner.grounded and runner.below is None: self._stack(runner) if tap and (runner.grounded or (runner.below is not None and runner.below.jumped)): self._detach(runner) runner.vx, runner.vy, runner.grounded = 0, -1.5, False jumped.append(runner) if runner.below is not None: runner.x, runner.y = runner.below.x, runner.below.y - 6 runner.vx = runner.vy = 0 else: self._move(runner) distance = hypot(runner.x - self.barrel_x, runner.y - (93 - self.radius)) hit = abs(distance - self.radius) < 4.5 + self.radius * 0.05 escaped = not (0 <= runner.x <= 100 and -50 <= runner.y <= 100) if hit or escaped: self._detach(runner) if runner.above is not None: jumped.append(runner.above) self._detach(runner.above) self.runners.remove(runner) if hit: self.downed.append(Runner(runner.x, runner.y, runner.vx - 2 * self.barrel_speed, runner.vy)) else: replacements += 1 self.runners.extend(self._runner() for _ in range(replacements)) for runner in jumped: runner.jumped = True for runner in self.downed: runner.x += runner.vx runner.y += runner.vy runner.vy += 0.2 self.downed = [runner for runner in self.downed if runner.y < 105] self.terminal = not self.runners self.next_wave = self.barrel_x < -self.radius return len(self.runners) if self.next_wave else 0
@staticmethod def _detach(runner): if runner.below is not None: runner.below.above = None runner.below = None
def _stack(self, runner): own = {runner} top = runner while top.above is not None: top = top.above own.add(top) for other in self.runners: if other in own or hypot(runner.x - other.x, runner.y - other.y) >= 4: continue while other.above is not None: other = other.above runner.below = other other.above = runner member = top while member is not None: member.jumped = member.grounded = False member = member.below break
def _move(self, runner): runner.x += runner.vx runner.y += runner.vy runner.vx *= 0.95 if (runner.x < 7 and runner.vx < 0) or (runner.x >= 77 and runner.vx > 0): runner.vx *= -0.5 runner.vx += (0.01 if runner.x < 50 else -0.01) * sqrt(abs(50 - runner.x) + 1) if runner.grounded: if runner.x < self.barrel_x: runner.vx -= 0.1 * sqrt(self.radius) / sqrt(self.barrel_x - runner.x + 1) else: runner.vy += 0.1 if runner.y > 90: runner.y, runner.vy = 90, 0 runner.grounded, runner.jumped = True, False if runner.y < 0 and runner.vy < 0: runner.vy *= -0.5
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for runner in self.runners: if 0 <= runner.x < 100 and 0 <= runner.y < 100: channel = 2 if runner.below is not None else int(not runner.grounded) state[int(runner.y // 10), int(runner.x // 10), channel] = True for runner in self.downed: if 0 <= runner.x < 100 and 0 <= runner.y < 100: state[int(runner.y // 10), int(runner.x // 10), 4] = True rows, cols = np.ogrid[5:100:10, 5:100:10] state[:, :, 3] = abs(np.hypot(cols - self.barrel_x, rows - (93 - self.radius)) - self.radius) < 7 for row, value in enumerate((self.steps, self.held, len(self.runners), round(self.radius * 10))): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129from dataclasses import dataclassfrom math import atan2, cos, floor, hypot, pi, sin, sqrt
import numpy as np
@dataclassclass Star: x: float y: float radius: float
class SwingbyEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = self.y = self.vx = self.vy = self.anchor_x = self.anchor_y = 0. self.screen_x = self.screen_y = 50. self.damage = self.steps = self.score = 0 self.held = self.terminal = False self.stars = [Star(0, 0, 20)] for _ in range(20): self._spawn(0, 0, 150, -pi, pi) self.stars.pop(0) self.display = []
def _spawn(self, x, y, reach, start, stop): for _ in range(99): angle = self.random.uniform(start, stop) distance = self.random.uniform(0, reach) px, py = x + distance * cos(angle), y + distance * sin(angle) radius = self.random.uniform(5, 15) if all(hypot(px - star.x, py - star.y) >= radius + star.radius + 30 for star in self.stars): self.stars.append(Star(px, py, radius)) break
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 previous = self.score for _ in range(4): self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(self.score - previous), self.terminal
def _advance(self): remaining = [] self.display = [] collision = False for star in self.stars: dx, dy = star.x - self.x, star.y - self.y distance = hypot(dx, dy) force = star.radius * 0.01 / min(99, max(2, distance - star.radius)) angle = atan2(dy, dx) self.vx += force * cos(angle) self.vy += force * sin(angle) if distance < 99 + star.radius: self.display.append((dx, dy, star.radius)) collision |= abs(distance - (star.radius - 2)) < 4.5 if distance <= 150: remaining.append(star) self.stars = remaining dx, dy = self.x - self.anchor_x, self.y - self.anchor_y if hypot(dx, dy) > 50: angle = atan2(dy, dx) self.anchor_x, self.anchor_y = self.x, self.y for _ in range(5): self._spawn(self.x + 100 * cos(angle), self.y + 100 * sin(angle), 70, angle - pi / 2, angle + pi / 2) self.vx *= 0.99 self.vy *= 0.99 angle = atan2(self.vy, self.vx) lead = min(30, max(1, sqrt(hypot(self.vx, self.vy)) * 19)) self.screen_x, self.screen_y = 50 - lead * cos(angle), 50 - lead * sin(angle) if self.held: self.vx -= 0.05 * sin(angle) self.vy += 0.05 * cos(angle) angle = atan2(self.vy, self.vx) self.vx += 0.01 * cos(angle) self.vy += 0.01 * sin(angle) self.x += self.vx self.y += self.vy if collision: self.vx *= 0.99 self.vy *= 0.99 self.damage += 4 else: self.damage = max(0, self.damage - 1) self.terminal = self.damage > 99 self.score = floor(hypot(self.x, self.y))
def state(self): state = np.zeros((10, 10, 6), dtype=bool) x, y = self.screen_x, self.screen_y state[int(y // 10), int(x // 10), 0] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for dx, dy, radius in self.display: state[:, :, 1] |= abs(np.hypot(cols - x - dx, rows - y - dy) - (radius - 2)) < 8 origin = np.clip(np.array([x - self.x, y - self.y]) // 10, 0, 9).astype(int) state[origin[1], origin[0], 2] = True angle = atan2(self.vy, self.vx) state[int((y + 10 * sin(angle)) // 10), int((x + 10 * cos(angle)) // 10), 3] = True state[int(y // 10), int(x // 10), 4] = self.damage > 0 values = (self.steps, self.damage, self.held, min(2047, self.score), round((self.vx + 10) * 50), round((self.vy + 10) * 50)) for row, value in enumerate(values): for bit in range(10): state[row, bit % 10, 5] = bool(value & (1 << bit)) state[6, 0, 5] = self.score >= 1024 return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from dataclasses import dataclassfrom math import cos, floor, pi, sin
import numpy as np
SPACING = 2 * pi / 9PLUGS = tuple((50 + 30 * sin(i * SPACING), 50 - 30 * cos(i * SPACING)) for i in range(9))
@dataclassclass Call: source: int destination: int remaining: int
class SwitchboardEnvironment: score_cap = 25
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.angle = 0. self.cursor = self.steps = self.lost = 0 self.origin = None self.timer = 180 self.multiplier = 1. self.active = set(range(9)) self.requests = [Call(2, 6, 900)] self.connections = [] self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 press, release = held and not self.held, self.held and not held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(press and frame == 0, release and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _spawn(self): available = set(range(9)) for call in (*self.requests, *self.connections): available.difference_update((call.source, call.destination)) sources = available & self.active if sources and len(available) >= 2: source = int(self.random.choice(sorted(sources))) destination = int(self.random.choice(sorted(available - {source}))) self.requests.append(Call(source, destination, int(self.random.integers(600, 1200))))
def _lose(self, call): self.active.discard(call.source) self.lost += 1 self.terminal |= self.lost >= 3
def _advance(self, press, release): self.angle += 0.024 if self.held else 0.042 if self.angle >= 2 * pi: self.angle = 0. self.cursor = floor(self.angle / SPACING + 0.5) % 9 self.multiplier += (1 - self.multiplier) * 0.001 self.timer -= 1 if self.timer <= 0: self._spawn() self.timer = int(self.random.integers(100, 200)) remaining = [] for call in self.requests: call.remaining -= 1 if call.remaining <= 0: self._lose(call) else: remaining.append(call) self.requests = remaining if press and self.origin is None and self.active: self.origin = min(sorted(self.active), key=lambda plug: abs((plug * SPACING - self.angle + pi) % (2 * pi) - pi)) reward = 0 if release and self.origin is not None: endpoints = {self.origin, self.cursor} match = next((call for call in self.requests if {call.source, call.destination} == endpoints), None) if match is not None: self.requests.remove(match) self.connections.append(Call(match.source, match.destination, int(self.random.integers(100, 200)))) self.lost = max(0, self.lost - len(endpoints - self.active)) self.active.update(endpoints) reward = floor(self.multiplier + 0.5) self.multiplier += 1 else: remaining = [] for call in self.requests: if call.source in endpoints: self._lose(call) else: remaining.append(call) self.requests = remaining self.origin = None for call in self.connections: call.remaining -= 1 self.connections = [call for call in self.connections if call.remaining > 0] return reward
@staticmethod def _mark(state, plug, channel): x, y = PLUGS[plug] state[int(y // 10), int(x // 10), channel] = True
def state(self): state = np.zeros((10, 10, 6), dtype=bool) self._mark(state, self.cursor, 0) for plug in self.active: self._mark(state, plug, 1) if self.origin is not None: self._mark(state, self.origin, 2) for call in self.requests: state[call.source, call.destination, 3] = True for call in self.connections: state[call.source, call.destination, 4] = True values = (self.steps, self.lost, self.held, round(self.multiplier * 32), round(self.angle * 100), min((call.remaining for call in self.requests), default=0)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) state[6, 0, 5] = values[-1] >= 1024 return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from math import floor, sqrt
import numpy as np
class THanoiEnvironment: score_cap = 1000 action_rods = {1: 0, 2: 1, 3: 2}
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(400, horizon) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.rods = [[], [], []] self.heights = [90.] * 3 self.selected = None self.steps = self.action = self.timer = self.hold = 0 self.multiplier = 100 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action rod = self.action_rods.get(self.action) tap = rod is not None and previous not in self.action_rods self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(rod, tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, rod, tap): if not self.rods[0]: self.timer = 0 self.timer -= 1 if self.timer < 0: self.rods[0].insert(0, int(self.random.integers(1, 5))) self.timer = 99 * sqrt(len(self.rods[0])) if tap: if self.selected is None: if self.rods[rod]: self.selected = rod else: source = self.rods[self.selected] target = self.rods[rod] if rod != self.selected and (rod == 0 or not target or source[-1] <= target[-1]): target.append(source.pop()) self.selected = None if rod is None: self.hold = 0 else: self.hold += 1 if rod: self.heights[rod] -= self.hold ** 2 / 10000 reward = 0 for index, disks in enumerate(self.rods): self.heights[index] -= 0.01 if self.heights[index] >= 6 * len(disks): continue if index == 0: self.terminal = True else: points = len(disks) ** 2 reward += points * (self.multiplier // 100) self.multiplier += points disks.clear() self.heights[index] = 90. self.heights[0] = min(90, max(0, self.heights[0] + points / 4)) if self.selected == index: self.selected = None self.hold = 0 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for rod, disks in enumerate(self.rods): for index, disk in enumerate(disks): row, col = 9 - index % 10, 2 * rod + index // 10 for bit in range(3): state[row, col, bit] = bool(disk & (1 << bit)) state[9, 2 * rod, 3] = self.selected == rod state[9, 2 * rod, 4] = self.action_rods.get(self.action) == rod values = (self.steps, floor(max(0, self.timer)), self.hold, self.multiplier, *(round(max(0, height) * 10) for height in self.heights)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154from dataclasses import dataclassfrom math import sqrt
import numpy as np
@dataclassclass Car: x: float y: float speed: float = 0 turn: int = 0 target: float = 0 cooldown: int = 0 junction: object = None
@dataclass(eq=False)class Junction: x: float y: float turn: int enabled: bool
class TLanesEnvironment: score_cap = 2000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.cars = [Car(20, 50, 0.1), Car(99, 50)] self.junctions, self.stops, self.routes = [], [], [] self.scroll = self.car_dist = self.cross_dist = 0. self.stop_dist = 199. self.steps = 0 self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): moving = sum(car.speed > 0 for car in self.cars) if not moving: self.terminal = True return 0 reward = 0 scroll = self.scroll self.cross_dist -= scroll if self.cross_dist < 0: reward += moving if not self.routes: self.routes = list(self.random.permutation((0, 1, 2, 3, 6, 7, 8, 9))) route = self.routes.pop() self.junctions.append(Junction(200, 10 + 20 * (route % 5), 1 if route < 5 else -1, self.random.random() < 0.5)) self.cross_dist = 24 for junction in self.junctions: junction.x -= scroll if tap: junction.enabled = not junction.enabled self.junctions = [junction for junction in self.junctions if junction.x >= -20] self.stop_dist -= scroll if self.stop_dist < 0: self.stops.append((205, 10 + 20 * self.random.integers(5))) self.stop_dist += self.random.uniform(99, 120) self.stops = [(x - scroll, y) for x, y in self.stops if x - scroll >= -3 and not any( y == junction.y and abs(x - scroll - junction.x - 3) < 5 for junction in self.junctions)] self.car_dist -= scroll if self.car_dist < 0: self.cars.append(Car(203, 10 + 20 * self.random.integers(5))) self.car_dist += self.random.uniform(40, 60) survivors = [] for car in self.cars: car.x -= scroll if tap and car.x < 50: car.x -= (50 - car.x) * 0.1 if car.speed: car.speed += (1 - car.speed) * 0.05 if car.turn: car.x += car.speed / sqrt(2) car.y += car.turn * car.speed / sqrt(2) if (car.y - car.target) * car.turn > 0: car.y, car.turn, car.cooldown = car.target, 0, 5 else: car.x += car.speed car.cooldown -= 1 if not car.turn and car.cooldown < 0 and any( y == car.y and abs(x - car.x) < 5 for x, y in self.stops ): continue if not car.speed and any(other.speed > 0 and not other.turn and abs(other.x - scroll - car.x) < 5 and other.y == car.y for other in self.cars if other is not car): reward += moving * 10 car.speed = self.random.uniform(0.01, 0.3) if car.speed and not car.turn: junction = next((j for j in self.junctions if j.y == car.y and abs(j.x + 3 - car.x) < 5), None) if junction is not None and junction is not car.junction and junction.enabled: car.turn = junction.turn car.target = car.y + 20 * car.turn car.x = junction.x - 2 car.junction = junction if car.x >= -3: survivors.append(car) self.cars = survivors self.terminal = not self.cars front = max((car.x for car in self.cars if car.speed), default=0) self.scroll = max(0, (front - 50) * 0.1) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for car in self.cars: if 0 <= car.x < 200: state[int(car.y // 10), int(car.x // 20), int(not car.speed)] = True for junction in self.junctions: if 0 <= junction.x + 3 < 200: state[int(junction.y // 10), int((junction.x + 3) // 20), 2 + int(junction.enabled)] = True for x, y in self.stops: if 0 <= x < 200: state[int(y // 10), int(x // 20), 4] = True for row, value in enumerate((self.steps, self.held, round(self.scroll * 100), sum(car.speed > 0 for car in self.cars))): for bit in range(9): state[2 * row + 1, bit, 5] = bool(value & (1 << bit)) for junction in self.junctions: if 0 <= junction.x + 3 < 200 and junction.turn > 0: state[max(0, int(junction.y // 10) - 1), int((junction.x + 3) // 20), 5] = True return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143from collections import dequefrom dataclasses import dataclassfrom math import sqrt
import numpy as np
@dataclassclass Enemy: x: float y: float z: float vy: float lock: int = -1
class TLaserEnvironment: score_cap = 500 moves = ((0, 0), (-1, 0), (0, -1), (1, 0), (0, 1), (0, 0))
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(400, horizon) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = self.y = 50 self.action = self.steps = self.timer = self.lock_index = 0 self.multiplier = 1 self.terminal = False self.enemies = [] self.laser = None self.history = deque(maxlen=19) self.velocity = np.zeros(2) self.depth = 1.
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.action = action self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): dx, dy = self.moves[self.action] self.x = min(99, max(0, self.x + dx * 3)) self.y = min(99, max(0, self.y + dy * 3)) target = min((enemy for enemy in self.enemies if enemy.lock >= 0), key=lambda enemy: enemy.lock, default=None) if target is not None and self.laser is None: self.laser = np.array([50., 99.]) self.velocity[:] = 0, -1 self.depth = 1. self.multiplier = 1 self.history.clear() self.history.append(self.laser.copy()) if self.laser is not None: change = 0. if target is not None: self.velocity = (self.velocity + 0.5 * (np.array([target.x, target.y]) - self.laser)) * 0.5 change = (target.z - self.depth) * 0.1 self.depth += change else: speed = np.linalg.norm(self.velocity) if speed: self.velocity *= 5 / speed self.laser += self.velocity / (self.depth * (1 + 9 * abs(change))) self.history.append(self.laser.copy()) margin = 99 / self.depth if np.any((self.laser < -margin) | (self.laser > 100 + margin)): self.laser = None self.history.clear() self.multiplier = 1 self.timer -= 1 if self.timer < 0: depth = self.random.uniform(0.5, 3) vy = self.random.choice((-1, 1)) * self.random.uniform(0.2, 0.3) / sqrt(depth) x, y = self.random.uniform(10, 90), -5 if vy > 0 else 105 self.enemies.extend(Enemy(x, y - vy * i * 30, depth, vy) for i in range(self.random.integers(3, 6))) self.timer += self.random.uniform(60, 99) reward = 0 survivors = [] for enemy in self.enemies: enemy.y += enemy.vy half = 3 / sqrt(enemy.z) if enemy is target and self._laser_hit(enemy, half): reward += self.multiplier self.multiplier += 1 continue if enemy.lock < 0 and abs(enemy.x - self.x) < half + 3 and abs(enemy.y - self.y) < half + 3: enemy.lock = self.lock_index self.lock_index += 1 if enemy.lock < 0 and (enemy.y < 0 if enemy.vy < 0 else enemy.y > 99): self.terminal = True survivors.append(enemy) self.enemies = survivors return reward
def _laser_hit(self, enemy, half): if len(self.history) < 2: return False path = np.asarray(self.history) starts, vectors = path[:-1], np.diff(path, axis=0) delta = np.array([enemy.x, enemy.y]) - starts length_sq = np.sum(vectors * vectors, axis=1) ratio = np.sum(delta * vectors, axis=1) / np.maximum(length_sq, 1e-9) nearest = delta - vectors * np.clip(ratio, 0, 1)[:, None] return bool(np.any(np.linalg.norm(nearest, axis=1) < half + 1.5 / self.depth))
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[self.y // 10, self.x // 10, 0] = True for enemy in self.enemies: if 0 <= enemy.y < 100: col, row = int(enemy.x // 10), int(enemy.y // 10) state[row, col, 1 if enemy.lock < 0 else 2] = True state[row, col, 4] |= enemy.vy > 0 for start, end in zip(self.history, list(self.history)[1:]): points = np.linspace(start, end, 20) points = points[np.all((points >= 0) & (points < 100), axis=1)] cols, rows = (points // 10).astype(int).T state[rows, cols, 3] = True for row, value in enumerate((self.steps, self.multiplier, self.action, max(0, round(self.timer)), round(self.depth * 100))): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146from dataclasses import dataclassfrom math import cos, hypot, pi, sin, sqrt
import numpy as np
@dataclassclass Orb: x: float y: float vx: float vy: float age: int = 0
class TPunchEnvironment: score_cap = 1500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.angle = self.angular_velocity = self.length = 0. self.arms = [True] * 6 self.enemies, self.bonuses = [], [] self.timer = self.steps = 0 self.multiplier = 1 self.attacking = self.held = self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 if held and not self.held: self.attacking = self.length < 5 self.multiplier = 1 self.held = held self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _segments(self): size = 3 + sqrt(self.length) * 0.5 for index, alive in enumerate(self.arms): if not alive: continue angle = self.angle + (index + 1) * pi / 3 for segment in range(5): radius = 5 + segment * self.length / 4 punch = segment == 4 and self.attacking yield index, 50 + cos(angle) * radius, 50 + sin(angle) * radius, size * (1.5 if punch else 1), punch
@staticmethod def _contact(orb, segment): _, x, y, size, _ = segment return abs(orb.x - x) < 3 + size / 2 and abs(orb.y - y) < 3 + size / 2
def _advance(self): if not self.held or self.length > 30: self.attacking = False self.length += ((36 if self.held else 0) - self.length) * 0.1 self.angular_velocity += 0.001 if self.held else (0.03 - self.angular_velocity) * 0.2 self.angle = (self.angle + self.angular_velocity) % (2 * pi) segments = list(self._segments()) self.timer = self.timer - 1 if self.enemies else -1 if self.timer < 0: x = self.random.uniform(0, 99) y = int(self.random.choice((-3, 3))) if self.random.random() < 0.5: x, y = y, x vx, vy = self.random.uniform(-0.3, 0.3, 2) self.enemies.append(Orb(x, y, vx, vy)) self.timer = self.random.uniform(60, 99) reward = 0 remaining = [] for bonus in self.bonuses: distance = max(1e-9, hypot(bonus.x - 50, bonus.y - 50)) bonus.vx = (bonus.vx + 0.002 * (bonus.x - 50) / distance) * 0.98 bonus.vy = (bonus.vy + 0.002 * (bonus.y - 50) / distance) * 0.98 bonus.x += bonus.vx bonus.y += bonus.vy if bonus.age > 60 and any(self._contact(bonus, segment) for segment in segments): reward += self.multiplier self.multiplier += 1 elif -3 <= bonus.x <= 103 and -3 <= bonus.y <= 103: bonus.age += 1 remaining.append(bonus) self.bonuses = remaining remaining = [] for enemy in self.enemies: distance = hypot(50 - enemy.x, 50 - enemy.y) if distance > 30: enemy.vx = (enemy.vx + 0.005 * (50 - enemy.x) / distance) * 0.99 enemy.vy = (enemy.vy + 0.005 * (50 - enemy.y) / distance) * 0.99 enemy.x += enemy.vx enemy.y += enemy.vy hits = [segment for segment in segments if self._contact(enemy, segment)] if any(segment[-1] for segment in hits): self.bonuses.extend(Orb(enemy.x, enemy.y, i * 0.05 * cos(i), i * 0.05 * sin(i)) for i in range(16)) start = int(self.random.integers(6)) for offset in range(6): index = (start + offset) % 6 if not self.arms[index]: self.arms[index] = True break elif hits: for index, *_ in hits: self.arms[index] = False else: self.terminal |= abs(enemy.x - 49) < 6 and abs(enemy.y - 49) < 6 remaining.append(enemy) self.enemies = remaining self.terminal |= not any(self.arms) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[4, 4, 0] = True points = [(x, y, int(punch)) for _, x, y, _, punch in self._segments()] points.extend((enemy.x, enemy.y, 2) for enemy in self.enemies) points.extend((bonus.x, bonus.y, 4 if bonus.age > 60 else 3) for bonus in self.bonuses) for x, y, channel in points: if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), channel] = True values = (self.steps, self.multiplier, self.held, self.attacking, round(self.length * 10), round(self.angle * 70)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158from dataclasses import dataclassfrom math import floor, hypot, sqrt
import numpy as np
@dataclassclass Block: x: float width: float height: float
@dataclassclass Fire: x: float y: float vx: float vy: float size: float
class TapeJEnvironment: score_cap = 4000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.tip = np.array([100., 89.]) self.base = self.tip.copy() self.mode = "ground" self.block = None self.scroll = self.distance = self.block_timer = 0. self.fire_timer = 100. self.steps = 0 self.held = self.terminal = False self.blocks, self.tapes, self.fires = [], [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.held = action == 5 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _corner(self, mode): self.tapes.append((self.base.copy(), self.tip.copy())) self.base = self.tip.copy() self.mode = mode
def _pull(self): self.distance += 1 if self.mode in ("ground", "top"): self.tip[0] += 1 if self.mode == "up": self.tip[1] -= 1 height = 90 - self.block.height if self.tip[1] < height: self.tip[1] = height self._corner("top") elif self.mode == "top" and self.tip[0] > self.block.x + self.block.width + 1: self.tip[0] = self.block.x + self.block.width + 1 self._corner("down") elif self.mode == "down": self.tip[1] += 1 if self.tip[1] > 89: self.tip[1] = 89 self._corner("ground") self.tip[0] += 3 self.block = None
def _advance(self): reward = 0 if self.held: self._pull() else: if self.distance: reward = floor(sqrt(self.distance) * self.distance * 0.1 + 1) self.distance = 0 start, end = self.tapes[0] if self.tapes else (self.base, self.tip) start += (end - start) * 0.2 if self.tapes and np.linalg.norm(end - start) < 3: self.tapes.pop(0) self.terminal = self.tip[0] < 0 for start, end in [*self.tapes, (self.base, self.tip)]: start[0] = max(0, start[0] - self.scroll) end[0] -= self.scroll self.tapes = [(start, end) for start, end in self.tapes if end[0] >= 0] self.scroll = 0.1 + max(0, self.tip[0] - 50) * 0.1 self.block_timer -= self.scroll if self.block_timer < 0: width = self.random.uniform(20, 40) self.blocks.append(Block(200, width, self.random.uniform(10, 50))) self.block_timer = width + self.random.uniform(20, 70) for block in self.blocks: if self.mode == "ground" and block.x - 1.5 < self.tip[0] < block.x + block.width + 1.5: self.tip[:] = block.x - 1, 89 self._corner("up") self.block = block block.x -= self.scroll self.blocks = [block for block in self.blocks if block.x + block.width >= 0] self.fire_timer -= 1 if self.fire_timer < 0: size = self.random.uniform(5, 15) self.fires.append(Fire(self.random.uniform(150, 220), -size, -self.random.uniform(0.5, 1), self.random.uniform(0.8, 1.2), size)) self.fire_timer = self.random.uniform(40, 60) points = self._tape_points() for fire in self.fires: fire.x += fire.vx - self.scroll fire.y += fire.vy self.terminal |= bool(np.any((abs(points[:, 0] - fire.x) < fire.size / 2 + 1.5) & (abs(points[:, 1] - fire.y) < fire.size / 2 + 1.5))) self.fires = [fire for fire in self.fires if fire.y <= 90] return reward
def _tape_points(self): segments = [*self.tapes, (self.base, self.tip)] return np.concatenate([np.linspace(start, end, max(2, int(hypot(*(end - start))) + 1)) for start, end in segments])
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for channel, points in ((0, self.tip[None]), (1, self._tape_points()), (4, (self.tapes[0][0] if self.tapes else self.base)[None])): visible = points[(points[:, 0] >= 0) & (points[:, 0] < 200)] cols, rows = (visible // (20, 10)).astype(int).T state[rows, cols, channel] = True rows, cols = np.ogrid[:100:10, :200:20] state[9, :, 2] = True for block in self.blocks: state[:, :, 2] |= (cols < block.x + block.width) & (cols + 20 > block.x) & (rows + 10 > 90 - block.height) for fire in self.fires: state[:, :, 3] |= (abs(cols + 10 - fire.x) < fire.size / 2 + 10) & ( abs(rows + 5 - fire.y) < fire.size / 2 + 5) values = (self.steps, int(self.distance), self.held, ("ground", "up", "top", "down").index(self.mode)) for row, value in enumerate(values): for bit in range(11): state[row + bit // 10 * 4, bit % 10, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from math import ceil, hypot
import numpy as np
class TappumpEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y = 10., 20. self.vy = self.radial_speed = self.coin_vy = 0. self.radius = 1. self.coin_y = 50. self.spike_distance, self.coin_distance = 40., 0. self.steps = 0 self.held = self.terminal = False self.spikes, self.coins = [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 tap = held and not self.held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(tap and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, tap): scroll = max(0, self.x - 20) * 0.2 self.spike_distance -= scroll if self.spike_distance < 0: self.spikes.append((103, self.random.uniform(0, 99))) self.spike_distance += self.random.uniform(40, 140) self.spikes = [(x - scroll, y) for x, y in self.spikes if x - scroll >= -2] if tap: self.vy -= 2 self.vy += -0.03 if self.held else 0.12 if self.held: self.radial_speed += 0.08 self.radius += self.radial_speed else: self.radius += (1 - self.radius) * 0.04 self.radial_speed = 0. self.x += 1 - scroll self.y += self.vy self.terminal = not -5 - self.radius <= self.y <= 105 + self.radius self.terminal |= any(self._touches(x, y, 2.5) for x, y in self.spikes) self.coin_distance -= scroll self.coin_vy = (self.coin_vy + self.random.uniform(-0.1, 0.1)) * 0.98 self.coin_y += self.coin_vy if (self.coin_y < 10 and self.coin_vy < 0) or (self.coin_y > 90 and self.coin_vy > 0): self.coin_vy *= -1 if self.coin_distance < 0: self.coins.append((103, self.coin_y + self.random.uniform(-9, 9))) self.coin_distance += self.random.uniform(6, 9) reward = 0 remaining = [] for x, y in self.coins: x -= scroll if self._touches(x, y, 3): reward += ceil(self.radius) elif x >= -3 and not any(abs(x - sx) < 5.5 and abs(y - sy) < 5.5 for sx, sy in self.spikes): remaining.append((x, y)) self.coins = remaining return reward
def _touches(self, x, y, half_size): dx, dy = abs(x - self.x), abs(y - self.y) near = hypot(max(0, dx - half_size), max(0, dy - half_size)) far = hypot(dx + half_size, dy + half_size) return near <= self.radius + 2.5 and far >= self.radius - 2.5
def state(self): state = np.zeros((10, 10, 6), dtype=bool) row = int(np.clip(self.y // 10, 0, 9)) col = int(self.x // 10) state[row, col, 0] = True rows, cols = np.ogrid[5:100:10, 5:100:10] state[:, :, 1] = abs(np.hypot(cols - self.x, rows - self.y) - self.radius) < 8 for channel, objects in ((2, self.spikes), (3, self.coins)): for x, y in objects: if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), channel] = True ahead = int(np.clip((self.y + 4 * self.vy) // 10, 0, 9)) state[ahead, col, 4] = True values = (self.steps, self.held, round(self.radius * 4), round((self.vy + 20) * 20), round(self.radial_speed * 40)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(int(np.clip(value, 0, 1023)) & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from dataclasses import dataclass
import numpy as np
@dataclassclass Barrel: x: float speed: float scored: bool = False
class TarutobiEnvironment: score_cap = 100
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = self.y = self.cursor = 30. self.vx = self.vy = 0. self.multiplier = 1 self.steps = self.action = 0 self.airborne = True self.terminal = False self.barrels = []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.action = action self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): self.cursor = min(120, max(0, self.cursor + 3 * ((self.action == 3) - (self.action == 1)))) if self.random.random() < 0.01: self.barrels.append(Barrel(123, self.random.uniform(0.4, 0.8))) reward = 0 dangerous = self.airborne for barrel in self.barrels: barrel.x -= barrel.speed if not barrel.scored and barrel.x < self.x: reward += self.multiplier self.multiplier += 1 barrel.scored = True self.barrels = [barrel for barrel in self.barrels if barrel.x > 0] if self.airborne: self.vy += 0.1 if self.y > 47: self.airborne = False self.y, self.vy = 47, 0. else: self.vx *= 0.95 self.vy *= 0.95 self.multiplier = 1 if not 0 <= self.x <= 120: self.x = min(120, max(0, self.x)) self.vx = 0. offset = min(7, max(-7, self.cursor - self.x)) self.vx += offset * (0.004 if self.airborne else 0.01) self.x += self.vx self.y += self.vy if any(abs(barrel.x - self.x) < 5.5 for barrel in self.barrels) and abs(47 - self.y) < 5.5: if dangerous: self.terminal = True else: self.airborne = True self.y, self.vy = 42, -1.2 - abs(self.vx) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) row = int(np.clip(self.y // 6, 0, 9)) col = int(np.clip(self.x // 12, 0, 9)) state[row, col, 0] = True for barrel in self.barrels: if 0 <= barrel.x < 120: state[7, int(barrel.x // 12), 2 if self.airborne else 1] = True state[8:, :, 3] = True state[9, min(9, int(self.cursor // 12)), 4] = True values = (self.steps, self.airborne, self.multiplier, self.action, round((self.vx + 4) * 50), round((self.vy + 4) * 50)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(int(np.clip(value, 0, 511)) & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157from dataclasses import dataclassfrom math import atan2, cos, pi, sin
import numpy as np
CENTER = np.array([50., 50.])
@dataclassclass Rock: position: np.ndarray velocity: np.ndarray size: float
@dataclassclass Geode: position: np.ndarray velocity: np.ndarray age: int
class TectonicTetherEnvironment: score_cap = 200
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.position = np.array([50., 10.]) self.angle, self.angular_speed, self.length = 0., 0.01, 35. self.charge = self.boost = 0. self.power = 30. self.steps = 0 self.held = self.terminal = False self.rocks = [Rock(self.random.uniform(20, 80, 2), np.zeros(2), self.random.uniform(8, 12)) for _ in range(5)] self.geodes = [Geode(self.random.uniform(10, 90, 2), np.zeros(2), 60) for _ in range(7)]
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 if self.held and not held: self.boost, self.charge = self.charge, 0. self.held = held self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): if self.held: self.length -= 0.7 self.angular_speed = min(0.05, self.angular_speed + 0.001) if self.length <= 10: self.charge = min(5, self.charge + 0.1) else: self.length += 0.7 + self.boost self.angular_speed = max(0.01, self.angular_speed - 0.0005) self.boost *= 0.92 self.angle = (self.angle + self.angular_speed) % (2 * pi) self.position = np.clip(CENTER + self.length * np.array([cos(self.angle), sin(self.angle)]), 3, 97) self.length = max(10, float(np.linalg.norm(self.position - CENTER))) self.power -= 0.05 self.terminal = self.power <= 0 reward = 0 remaining = [] for geode in self.geodes: geode.age = min(60, geode.age + 1) if geode.age < 60: geode.position += geode.velocity geode.velocity *= 0.96 else: delta = self.position - geode.position distance = np.linalg.norm(delta) if 0 < distance < 15 + self.power: geode.position += delta / distance * (0.3 + self.power * 0.05) np.clip(geode.position, 5, 95, out=geode.position) if geode.age == 60 and np.all(abs(geode.position - self.position) < 5.5): self.power = min(30, self.power + 1.5) reward += 1 else: remaining.append(geode) self.geodes = remaining for index, rock in enumerate(self.rocks): rock.position += rock.velocity rock.velocity *= 0.95 delta = rock.position - self.position if np.all(abs(delta) < rock.size / 2 + 3): count = int(self.angular_speed * self.length) outside = np.linalg.norm(rock.position - CENTER) > np.linalg.norm(self.position - CENTER) self.length += -5 if outside else 5 distance = np.linalg.norm(delta) if distance: rock.velocity += delta / distance * 0.8 angle = atan2(-delta[1], -delta[0]) self._scatter(rock, count, angle, pi / 3, 3, 0.45, 1.05) edge = rock.size / 2 + 2 if np.any((rock.position < edge) | (rock.position > 100 - edge)): reward += 10 self._scatter(rock, int(rock.size / 2 + 1), pi, pi, 8, 1, 1.5) rock.position = self.random.uniform(20, 80, 2) rock.velocity[:] = 0 for other in self.rocks[index + 1:]: offset = rock.position - other.position distance = np.linalg.norm(offset) limit = (rock.size + other.size) / 2 if 0 < distance < limit: normal = offset / distance separation = normal * (limit - distance) / 2 rock.position += separation other.position -= separation rock.velocity += normal * 0.4 other.velocity -= normal * 0.4 return reward
def _scatter(self, rock, count, angle, spread, jitter, low, high): for _ in range(count): heading = angle + self.random.uniform(-spread, spread) position = np.clip(rock.position + self.random.uniform(-jitter, jitter, 2), 10, 90) speed = self.random.uniform(low, high) self.geodes.append(Geode(position, speed * np.array([cos(heading), sin(heading)]), 0))
def state(self): state = np.zeros((10, 10, 6), dtype=bool) x, y = (self.position // 10).astype(int) state[y, x, 0] = True for rock in self.rocks: x, y = np.clip(rock.position // 10, 0, 9).astype(int) state[y, x, 1] = True for geode in self.geodes: x, y = (geode.position // 10).astype(int) state[y, x, 2 if geode.age == 60 else 3] = True cols, rows = (np.linspace(CENTER, self.position, 20) // 10).astype(int).T state[rows, cols, 4] = True values = (self.steps, round(max(0, self.power) * 10), round(self.charge * 20), self.held, round(self.length * 5), round(self.angular_speed * 1000)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from dataclasses import dataclassfrom math import cos, sin
import numpy as np
@dataclassclass Bar: x: float y: float width: float angle: float
@dataclassclass Floor: x: float width: float score: int change: int = 0
class TeeterEnvironment: score_cap = 100
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.bars = [] for _ in range(7): self._add_bar() self.floors = [] self.ball = self.target = None self.sign, self.steps = 1, 0 self.held = self.terminal = False
def _add_bar(self): for _ in range(99): width = self.random.uniform(12, 18) angle = self.random.uniform(0.2, 0.8) * self.random.choice((-1, 1)) margin = 5 + width * cos(angle) / 2 x, y = self.random.uniform(margin, 100 - margin), self.random.uniform(20, 70) if all(abs(x - bar.x) >= (width + bar.width) / 2 + 5 or abs(y - bar.y) >= 6 + (width * abs(sin(angle)) + bar.width * abs(sin(bar.angle))) / 2 for bar in self.bars): self.bars.append(Bar(x, y, width, angle)) return True return False
def _drop(self): for _ in range(99): x = self.random.uniform(20, 80) if any(abs(bar.x - x) < bar.width * cos(bar.angle) / 2 for bar in self.bars): break self.target = np.array([x, -4.]) self.ball = self.target.copy() self.floors = [] edge = 0. while edge < 100: width = self.random.uniform(20, 30) score = int(np.prod(self.random.uniform(1, 3.1, 2))) self.floors.append(Floor(edge + width / 2, width, score)) edge += width for sign in (1, -1): floor = self.floors[self.random.integers(len(self.floors))] floor.score = 0 floor.change = sign * int(np.prod(self.random.uniform(1, 2.2, 2))) for floor in self.floors: floor.x -= (edge - 100) / 2
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 if held and not self.held: self.sign *= -1 self.held = held self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): if self.ball is None: self._drop() self.target[1] += 0.5 self.ball += (self.target - self.ball) * 0.5 x, y = self.ball for bar in self.bars: angle = bar.angle * self.sign dx, dy = cos(angle), sin(angle) ox, oy = x - bar.x, y - bar.y if abs(ox * dx + oy * dy) < bar.width / 2 + 3 and abs(oy * dx - ox * dy) < 4.5: reach = (bar.width / 2 + 7) * (1 if angle > 0 else -1) self.target[:] = bar.x + reach * dx, bar.y + reach * dy reward = change = 0 remaining = [] for floor in self.floors: if abs(floor.x - x) < floor.width / 2 + 2.5 and abs(y - 95) < 8: reward += floor.score change += floor.change else: remaining.append(floor) self.floors = remaining if change > 0: for _ in range(change): reward += int(not self._add_bar()) elif change < 0: for _ in range(min(-change, len(self.bars))): self.bars.pop(self.random.integers(len(self.bars))) if y > 99: self.terminal = not self.bars self.ball = self.target = None return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) if self.ball is not None: x, y = np.clip(self.ball // 10, 0, 9).astype(int) state[y, x, 0] = True for bar in self.bars: angle = bar.angle * self.sign offset = np.linspace(-bar.width / 2, bar.width / 2, 20) cols = ((bar.x + offset * cos(angle)) // 10).astype(int) rows = ((bar.y + offset * sin(angle)) // 10).astype(int) state[rows, cols, 1] = True columns = np.arange(5, 100, 10) for floor in self.floors: channel = 2 if floor.score else 3 if floor.change > 0 else 4 state[9, :, channel] |= abs(columns - floor.x) < floor.width / 2 for index, floor in enumerate(sorted(self.floors, key=lambda floor: floor.x)): value = floor.score or abs(floor.change) for bit in range(4): state[index, bit, 5] = bool(value & (1 << bit)) for row, value in enumerate((self.steps, self.sign > 0, len(self.bars), self.held)): for bit in range(9): state[6 + row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import numpy as np
MOVE_DELTAS = {1: (0, -1), 2: (-1, 0), 3: (0, 1), 4: (1, 0)}
class TennisEnvironment: """One Activision-style set with automatic positional racket contact."""
score_cap = 6.0
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = 2_000): self.sticky_action_prob = sticky_action_prob self.horizon = horizon self.random = np.random.RandomState() self.seed(0) self.reset()
@classmethod def normalize_score(cls, raw_score: float) -> float: return min(max(raw_score, 0.0), cls.score_cap) / cls.score_cap
def seed(self, seed: int) -> None: self.random.seed(seed)
def reset(self) -> None: self.player = [8, 5] self.opponent = [1, 5] self.previous_player = self.player.copy() self.previous_opponent = self.opponent.copy() self.ball = self.player.copy() self.previous_ball = self.ball.copy() self.ball_velocity = [0, 0] self.server = "player" self.phase = "serve" self.serve_delay = 2 self.player_points = 0 self.opponent_points = 0 self.player_games = 0 self.opponent_games = 0 self.tiebreak_reset = False self.side_swapped = False self.score = 0.0 self.steps = 0 self.last_action = 0 self.winner: str | None = None self.terminal = False
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.rand() < self.sticky_action_prob: action = self.last_action self.last_action = action self.previous_player = self.player.copy() self.previous_opponent = self.opponent.copy() self.previous_ball = self.ball.copy() previous_progress = self._progress_score() self._move_player(action) if self.phase == "serve": self._serve(action) else: self._player_return() self._move_opponent() self._opponent_return() self._move_ball() self.steps += 1 if self.steps >= self.horizon: self.terminal = True progress = self._progress_score() self.score = progress return progress - previous_progress, self.terminal
def _move_player(self, action: int) -> None: if action not in MOVE_DELTAS: return row_delta, column_delta = MOVE_DELTAS[action] if self.phase == "serve": row_delta = 0 self.player[0] = int(np.clip(self.player[0] + row_delta, 5, 9)) self.player[1] = int(np.clip(self.player[1] + column_delta, 1, 8)) if self.phase == "serve" and self.server == "player": self.ball = self.player.copy()
def _serve(self, action: int) -> None: if self.server == "player": if action != 5: return lateral = int(np.sign(self.player[1] - 5)) self.ball = self.player.copy() self.ball_velocity = [-1, lateral] self.phase = "rally" return self.serve_delay -= 1 if self.serve_delay > 0: return lateral = -1 if self.player[1] >= 5 else 1 self.ball = self.opponent.copy() self.ball_velocity = [1, lateral] self.phase = "rally"
def _player_return(self) -> None: if self.ball_velocity[0] <= 0 or self.ball[0] < 6: return row_distance = abs(self.player[0] - self.ball[0]) column_offset = self.ball[1] - self.player[1] if row_distance > 1 or abs(column_offset) > 1: return lateral = int(np.sign(column_offset)) if self.player[0] <= 6 and lateral == 0: lateral = -1 if self.opponent[1] >= 5 else 1 self.ball_velocity = [-1, lateral]
def _move_opponent(self) -> None: if self.ball_velocity[0] < 0: target_row = int(np.clip(self.ball[0] - 2, 0, 4)) target_column = int(np.clip(self.ball[1] + self.ball_velocity[1] * 2, 1, 8)) else: target_row = 1 target_column = 5 if self.opponent[1] != target_column: self.opponent[1] += int(np.sign(target_column - self.opponent[1])) elif self.opponent[0] != target_row: self.opponent[0] += int(np.sign(target_row - self.opponent[0]))
def _opponent_return(self) -> None: if self.ball_velocity[0] >= 0 or self.ball[0] > 3: return if abs(self.opponent[0] - self.ball[0]) > 1 or abs(self.opponent[1] - self.ball[1]) > 1: return lateral = -1 if self.player[1] >= 5 else 1 if self.opponent[0] >= 3: lateral = int(np.clip(lateral * 2, -1, 1)) self.ball_velocity = [1, lateral]
def _move_ball(self) -> None: self.ball[0] += self.ball_velocity[0] self.ball[1] += self.ball_velocity[1] if self.ball[1] <= 0 or self.ball[1] >= 9: self.ball[1] = int(np.clip(self.ball[1], 0, 9)) self.ball_velocity[1] *= -1 if self.ball[0] < 0: self._award_point("player") elif self.ball[0] > 9: self._award_point("opponent")
def _award_point(self, winner: str) -> None: if winner == "player": self.player_points += 1 else: self.opponent_points += 1 if max(self.player_points, self.opponent_points) >= 4 and abs( self.player_points - self.opponent_points ) >= 2: self._award_game(winner) return self._reset_point()
def _award_game(self, winner: str) -> None: if winner == "player": self.player_games += 1 else: self.opponent_games += 1 self.player_points = 0 self.opponent_points = 0 games_played = self.player_games + self.opponent_games self.server = "player" if games_played % 2 == 0 else "opponent" self.side_swapped = games_played % 2 == 1 if self.player_games == 6 and self.opponent_games == 6: self.player_games = 0 self.opponent_games = 0 self.tiebreak_reset = True lead = self.player_games - self.opponent_games if self.tiebreak_reset and abs(lead) >= 2: self.winner = "player" if lead > 0 else "opponent" self.terminal = True elif not self.tiebreak_reset and max(self.player_games, self.opponent_games) >= 6 and abs(lead) >= 2: self.winner = "player" if lead > 0 else "opponent" self.terminal = True if not self.terminal: self._reset_point()
def _reset_point(self) -> None: self.phase = "serve" self.serve_delay = 2 self.player = [8, 5] self.opponent = [1, 5] self.ball = (self.player if self.server == "player" else self.opponent).copy() self.ball_velocity = [0, 0]
def _progress_score(self) -> float: if self.terminal and self.winner == "player": return self.score_cap return float(min(6, self.player_games))
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) state[*self.player, 0] = True state[*self.opponent, 1] = True state[*self.ball, 2] = True state[4:6, :, 3] = True state[*self.previous_player, 4] = True state[*self.previous_opponent, 4] = True state[*self.previous_ball, 4] = True values = ( (self.player_points, 4), (self.opponent_points, 4), (self.player_games, 3), (self.opponent_games, 3), (self.ball_velocity[0] + 1, 2), (self.ball_velocity[1] + 1, 2), (self.steps, 11), ) offset = 0 for value, width in values: for bit in range(width): index = offset + bit state[index // 10, index % 10, 5] = bool(value & (1 << bit)) offset += width state[3, 0, 5] = self.server == "player" state[3, 1, 5] = self.phase == "rally" state[3, 2, 5] = self.tiebreak_reset state[3, 3, 5] = self.side_swapped return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131from dataclasses import dataclassfrom math import cos, pi, sin
import numpy as np
@dataclassclass Shot: x: float y: float vx: float = 0.5 vy: float = 0.
@dataclassclass Enemy: x: float y: float vy: float timer: float interval: float falling: bool = False
class ThrowMEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.y, self.vy = 50., -0.5 self.angle = None self.steps = self.timer = 0 self.multiplier = 1 self.held = self.terminal = False self.enemies, self.bullets, self.shots = [], [], []
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True held = self.held if self.random.random() < self.sticky_action_prob else action == 5 press, release = held and not self.held, self.held and not held self.held = held self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(press and frame == 0, release and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _hit(self, x, y): return any(abs(shot.x - x) < 5 and abs(shot.y - y) < 5 for shot in self.shots)
def _advance(self, press, release): for shot in self.shots: shot.x += shot.vx shot.y += shot.vy shot.vy += 0.07 self.shots = [shot for shot in self.shots if shot.y <= 103] self.timer -= 1 if self.timer < 0: interval = self.random.uniform(200, 300) self.enemies.append(Enemy(self.random.uniform(3, 50), -5, self.random.uniform(0.1, 0.4), self.random.uniform(0, interval), interval)) self.timer = self.random.uniform(50, 60) reward = 0 for enemy in self.enemies: enemy.y += enemy.vy if enemy.falling: enemy.vy += 0.1 continue enemy.timer -= 1 if enemy.timer < 0: self.bullets.append(Shot(enemy.x, enemy.y)) enemy.timer = enemy.interval if self._hit(enemy.x, enemy.y) or self._hit(enemy.x, enemy.y - 6): enemy.falling = True reward += self.multiplier self.multiplier *= 2 self.enemies = [enemy for enemy in self.enemies if enemy.y <= 105] bullets = [] for bullet in self.bullets: bullet.x += bullet.vx if self._hit(bullet.x, bullet.y): reward += self.multiplier self.multiplier += 1 elif bullet.x <= 103 and not (bullet.x > 83 and (bullet.y < 12 or bullet.y > 90)): bullets.append(bullet) self.bullets = bullets self.y += self.vy if (self.y < 19 and self.vy < 0) or (self.y > 90 and self.vy > 0): self.vy *= -1 self.terminal = any(abs(bullet.x - 90) < 5 and abs(bullet.y - self.y + 6) < 4 for bullet in bullets) if self.angle is None and press: self.angle = 3 * pi / 4 if self.angle is not None: self.angle += 0.1 if release or self.angle > 11 * pi / 8: self.shots.append(Shot(90, self.y, 3 * cos(self.angle), 3 * sin(self.angle))) self.angle = None self.multiplier = 1 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(self.y // 10), 9, 0] = True for channel, objects in ((1, self.enemies), (3, self.bullets), (4, self.shots)): for obj in objects: if 0 <= obj.x < 100 and 0 <= obj.y < 100: layer = 2 if channel == 1 and obj.falling else channel state[int(obj.y // 10), int(obj.x // 10), layer] = True values = (self.steps, self.held, self.vy > 0, round((self.angle or 0) * 100), min(1023, self.multiplier)) for row, value in enumerate(values): for bit in range(10): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113from dataclasses import dataclassfrom math import floor
import numpy as np
@dataclassclass Diamond: x: float y: float size: float vx: float = 0.
class ThrustLrEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.vx, self.distance = 50., 0., 0. self.action = self.steps = 0 self.terminal = False self.diamonds = [] for y in (60, 40, 20): self._spawn(y)
def _spawn(self, y=0): small = self.random.random() < 0.3 size = self.random.uniform(7, 12) if small else self.random.uniform(20, 30) x = self.random.uniform(10, 90) if small else ( 50 + self.random.choice((-1, 1)) * self.random.uniform(40, 60) ) self.diamonds.append(Diamond(x, y - size, size)) return size
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.action = action self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): thrust = 50 * ((self.action == 3) - (self.action == 1)) self.distance -= 0.2 if self.distance < 0: size = self._spawn() self.distance = 10 + (size - 10) * self.random.random() reward = 0 remaining = [] for diamond in self.diamonds: diamond.y += 0.2 dy = abs(diamond.y - 85) if dy < diamond.size: dx = diamond.x - self.x if dx * thrust < 0: clearance = abs(dx) - (diamond.size - dy) diamond.vx -= thrust * 0.2 / (max(0.5, clearance) * diamond.size) diamond.vx *= 0.98 diamond.x += diamond.vx if diamond.x < -diamond.size or diamond.x > 99 + diamond.size: reward += floor(diamond.size) elif diamond.y - 2 * diamond.size <= 99: remaining.append(diamond) self.diamonds = remaining self.vx += thrust * 0.001 self.x = min(96, max(4, self.x + self.vx)) if (self.x < 5 and self.vx < 0) or (self.x > 95 and self.vx > 0): self.vx *= -0.7 self.vx *= 0.95 self.terminal = any( abs(abs(self.x + side * (1 + t) - diamond.x) + abs(83 + 4 * t - diamond.y) - diamond.size) < 2.5 for diamond in self.diamonds for side in (-1, 1) for t in (0, 0.5, 1) ) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[8, int(self.x // 10), 0] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for diamond in self.diamonds: mask = abs(abs(cols - diamond.x) + abs(rows - diamond.y) - diamond.size) < 10 state[:, :, 1 if diamond.size < 15 else 2] |= mask if abs(diamond.y - 85) < diamond.size: state[:, :, 3] |= mask if self.action in (1, 3): offset = 10 if self.action == 1 else -10 state[8, int(np.clip((self.x + offset) // 10, 0, 9)), 4] = True values = (self.steps, self.action, round((self.vx + 2) * 100), round(self.distance * 10)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160from dataclasses import dataclassfrom math import ceil, cos, hypot, pi, sin
import numpy as np
@dataclassclass Bolt: x: float y: float angle: float speed: float ticks: int parent: "Bolt | None" = None active: bool = False
def __post_init__(self): self.origin = (self.x, self.y)
@dataclassclass Star: x: float y: float vy: float
class ThunderEnvironment: score_cap = 300
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.bolts = [] self.stars = [] self.active_ticks = -1 self.x, self.vx = 40., 1 self.multiplier = 1 self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action turn = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(turn and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, turn): if not self.bolts: self.bolts.append(Bolt(self.random.uniform(30, 70), 0, pi / 2, 0.5, 30)) self.active_ticks -= 1 remaining = [] for bolt in self.bolts: if bolt.active: if self.active_ticks >= 0: remaining.append(bolt) continue bolt.ticks -= 1 if self.active_ticks > 0: if bolt.ticks > 0: self.stars.append(Star(bolt.x, bolt.y, -bolt.y * 0.02)) continue remaining.append(bolt) if bolt.ticks > 0: bolt.x += cos(bolt.angle) * bolt.speed bolt.y += sin(bolt.angle) * bolt.speed if self.active_ticks < 0 and (bolt.y > 90 or len(self.bolts) > 160): self._strike(bolt) elif bolt.ticks == 0: for _ in range(self.random.integers(1, 4)): remaining.append(Bolt( bolt.x, bolt.y, bolt.angle + self.random.uniform(-0.7, 0.7), self.random.uniform(0.3, 1), ceil(self.random.uniform(20, 40)), bolt, )) self.bolts = remaining if turn or (self.x < 0 and self.vx < 0) or (self.x > 99 and self.vx > 0): self.vx *= -1 self.x += self.vx self.terminal = any( bolt.active and _segment_distance(self.x, 87, bolt) <= 5 for bolt in self.bolts ) if self.terminal: return 0 reward = 0 stars = [] for star in self.stars: star.vy += 0.1 star.y += star.vy if star.y > 89 and star.vy > 0: star.vy *= -0.5 if star.vy > -0.1: continue if abs(star.x - self.x) <= 5 and abs(star.y - 87) <= 5: reward += self.multiplier self.multiplier += 1 else: stars.append(star) self.stars = stars return reward
def _strike(self, bolt): self.active_ticks = 20 self.multiplier = 1 for _ in range(99): bolt.active = True bolt = bolt.parent if bolt is None: break
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[8, int(np.clip(self.x // 10, 0, 9)), 0] = True for bolt in self.bolts: start_x, start_y = bolt.origin samples = ceil(hypot(bolt.x - start_x, bolt.y - start_y) / 3) + 1 for x, y in zip(np.linspace(start_x, bolt.x, samples), np.linspace(start_y, bolt.y, samples), strict=True): if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), 2 if bolt.active else 1] = True for star in self.stars: if 0 <= star.x < 100 and 0 <= star.y < 100: state[int(star.y // 10), int(star.x // 10), 3] = True state[9, :, 4] = True values = (self.steps, self.action, self.vx > 0, self.multiplier, self.active_ticks + 1) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
def _segment_distance(x, y, bolt): start_x, start_y = bolt.origin dx, dy = bolt.x - start_x, bolt.y - start_y length_squared = dx * dx + dy * dy if length_squared == 0: return hypot(x - start_x, y - start_y) fraction = min(1, max(0, ((x - start_x) * dx + (y - start_y) * dy) / length_squared)) return hypot(x - start_x - fraction * dx, y - start_y - fraction * dy)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186from dataclasses import dataclassfrom math import cos, hypot, pi, sin
import numpy as np
@dataclassclass Bar: x: float y: float angle: float length: float
def coordinates(self, x, y): dx, dy = x - self.x, y - self.y return dx * cos(self.angle) + dy * sin(self.angle), dy * cos(self.angle) - dx * sin(self.angle)
@dataclassclass Ball: x: float y: float vx: float vy: float = 0 age: int = 0
class TiltedEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.bar = Bar(50, 0, 0, 90) self.bars = [self.bar] self.balls = [] self.bar_distance, self.bar_count, self.ball_timer = 10, 0, 60 self.x, self.y, self.vx, self.vy = 50., -6., 1., 0. self.jumps = self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action pressed = self.action == 5 and previous != 5 self.steps += 1 reward = 0. for frame in range(4): reward += self._advance(pressed and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _advance(self, pressed): scroll = 0.02 + max(0, 60 - self.y) * 0.1 if self.bar is not None: bar = self.bar distance = hypot(self.x - bar.x, self.y + 5 - bar.y) distance = (-distance if self.x < bar.x else distance) + self.vx / 2 self.x = bar.x + cos(bar.angle) * distance self.y = bar.y + sin(bar.angle) * distance - 5 if abs(distance) > bar.length / 2 + 6: self.bar = None self.jumps = 0 if pressed: self.bar = None self.vy, self.jumps = -2, 1 self.y -= 2 else: if pressed: if self.jumps: self.vx *= -1 self.jumps = max(1, self.jumps) self.vy = -2 / self.jumps ** 2 self.jumps += 1 self.vy += 0.05 if self.action == 5 else 0.1 self.x += self.vx / 2 self.y += scroll + self.vy / 2 if (self.x < 8 and self.vx < 0) or (self.x > 92 and self.vx > 0): self.vx *= -1 if self.y > 99: self.terminal = True return scroll self._advance_balls(scroll) for bar in self.bars: bar.y += scroll along, normal = bar.coordinates(self.x, self.y + 3) if self.bar is None and abs(along) <= bar.length / 2 + 2 and abs(normal) <= 4: if self.vy <= 0: self.vy *= -0.5 self.y += 3 * self.vy else: self.bar = bar for ball in self.balls: along, normal = bar.coordinates(ball.x, ball.y) if abs(along) <= bar.length / 2 + 3 and abs(normal) <= 4: tangent_x, tangent_y = cos(bar.angle), sin(bar.angle) projection = ball.vx * tangent_x + ball.vy * tangent_y ball.vx = 2 * projection * tangent_x - ball.vx ball.vy = 2 * projection * tangent_y - ball.vy ball.x += ball.vx ball.y += ball.vy ball.age += 30 break self.bars = [bar for bar in self.bars if bar.y <= 120] self.bar_distance -= scroll while self.bar_distance < 0: self._spawn_bar() return scroll
def _advance_balls(self, scroll): self.ball_timer -= 1 if self.ball_timer < 0: speed = self.random.choice((-1, 1)) * self.random.uniform(0.5, 1) self.balls.append(Ball(self.random.uniform(20, 80), -40, speed)) self.ball_timer += self.random.uniform(60, 80) for ball in self.balls: ball.vx *= 0.995 ball.vy = (ball.vy + 0.05) * 0.995 ball.x += ball.vx / 2 ball.y += scroll + ball.vy / 2 if (ball.x < 8 and ball.vx < 0) or (ball.x > 92 and ball.vx > 0): ball.vx *= -1 ball.age += 1 if hypot(ball.x - self.x, ball.y - self.y) <= 5: if self.bar is not None: self.bar.y = 999 self.bar = None self.vy += 1 else: self.vy += 4 ball.age = 999 for index, ball in enumerate(self.balls): for other in self.balls[index + 1:]: if ball.age <= 500 and other.age <= 500 and hypot(ball.x - other.x, ball.y - other.y) <= 5: ball.age = other.age = 999 self.balls = [ball for ball in self.balls if ball.age <= 500 and ball.y <= 103]
def _spawn_bar(self): side = self.bar_count % 2 length = self.random.uniform(15, 22) x = (50 + self.random.choice((-1, 1)) * self.random.uniform(25, 50 - length / 2) if side else self.random.uniform(35, 65)) angle = 0. if self.random.random() < (0.2 if side else 0.7) else ( self.random.choice((-1, 1)) * self.random.uniform(0, pi / 5) ) y = -9 - self.bar_distance self.bars.append(Bar(x, y, angle, length)) if side: self.bars.append(Bar(100 - x, y, -angle, length)) self.bar_distance += self.random.uniform(15, 20) self.bar_count += 1
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(np.clip(self.y // 10, 0, 9)), int(np.clip(self.x // 10, 0, 9)), 0] = True for bar in self.bars: for offset in np.linspace(-bar.length / 2, bar.length / 2, int(bar.length / 3) + 2): x = bar.x + offset * cos(bar.angle) y = bar.y + offset * sin(bar.angle) if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), 2 if bar is self.bar else 1] = True for ball in self.balls: if 0 <= ball.y < 100: state[int(ball.y // 10), int(ball.x // 10), 3] = True state[:, (0, 9), 4] = True gauges = (self.steps, self.action, self.vx > 0, self.jumps, round((self.vy + 8) * 16)) for row, value in enumerate(gauges): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import numpy as np
HORIZON = 400UNIT = 8MIN_WIDTH = 32MAX_PIECES = 4MAX_SPEED = 4SAW_LEAD = 6
class TimberTestEnvironment: score_cap = HORIZON // ((MIN_WIDTH + SAW_LEAD + MAX_SPEED - 1) // MAX_SPEED) * (MAX_PIECES - 1) * 100
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = HORIZON): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, HORIZON) self.seed(0) self.reset()
def seed(self, seed: int) -> None: self.random = np.random.default_rng(seed)
def reset(self) -> None: self.steps = self.round = self.last_action = 0 self.terminal = False self._new_log()
def _new_log(self) -> None: self.round += 1 width = int(self.random.integers(MIN_WIDTH, 65)) slack = 80 - width self.start = slack // 2 + int(self.random.integers(slack // 3 + 1)) self.end = self.start + width self.remaining = self.start self.target = int(self.random.integers(2, MAX_PIECES + 1)) self.saw = self.start - SAW_LEAD self.pieces: list[int] = []
@classmethod def normalize_score(cls, score: float) -> float: return min(max(score, 0), cls.score_cap) / cls.score_cap
def _grade(self) -> int: score = (self.target - 1) * 100 widths = self.pieces + [0] * max(0, self.target - len(self.pieces)) for index, (left, right) in enumerate(zip(widths, widths[1:]), 1): if index > self.target or left + right == 0: score -= 100 else: score -= abs(left - right) * 300 // (left + right) return score
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.random() < self.sticky_action_prob: action = self.last_action pressed = action == 5 and self.last_action != 5 self.last_action = action self.steps += 1 self.saw = min(self.end, self.saw + min(MAX_SPEED, 1 + (self.round - 1) // 3)) reward = 0 if self.saw == self.end: self.pieces.append(self.end - self.remaining) score = self._grade() if score < 0: self.terminal = True else: reward = score if self.steps < self.horizon: self._new_log() elif pressed and self.saw > self.remaining: self.pieces.append(self.saw - self.remaining) self.remaining = self.saw self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) state[1, max(0, min(9, self.saw // UNIT)), 0] = True state[2, self.remaining // UNIT:(self.end - 1) // UNIT + 1, 1] = True if self.round <= 3 and not self.pieces: for index in range(1, self.target): cut = self.start + round((self.end - self.start) * index / self.target) state[3, cut // UNIT, 2] = True cut = self.start for width in self.pieces: cut += width index = cut - 1 state[index // 10, index % 10, 3] = True values = (self.steps, self.round, self.target, self.start, self.end, self.remaining, self.saw + SAW_LEAD, int(self.last_action == 5)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import numpy as np
DIRECTIONS = ((-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1))ERAS = (1910, 1940, 1970, 1983, 2001)FORMATION_IDS = frozenset(range(20, 25))
class TimePilotEnvironment: """One five-era loop with scrolling flight, formations, and bosses."""
score_cap = 59_000.0
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = 5_000): self.sticky_action_prob = sticky_action_prob self.horizon = horizon self.random = np.random.RandomState() self.seed(0) self.reset()
@classmethod def normalize_score(cls, raw_score: float) -> float: return min(max(raw_score, 0.0), cls.score_cap) / cls.score_cap
def seed(self, seed: int) -> None: self.random.seed(seed)
def reset(self) -> None: self.era = 0 self.heading = 0 self.previous_heading = self.heading self.lives = 3 self.score = 0.0 self.steps = 0 self.last_action = 0 self.next_extra_life = 10_000 self.terminal = False self._start_era()
def _start_era(self) -> None: self.spawned = 0 self.killed = 0 self.special_spawned = self.era == 0 self.special_destroyed = self.era == 0 self.formation_destroyed: set[int] = set() self.formation_failed = False self.enemies: list[dict[str, int | str]] = [] self.bullets: list[list[int]] = [] self.enemy_shots: list[list[int]] = [] self.boss: dict[str, int] | None = None self.previous_objects: list[tuple[int, int]] = [] self._spawn_enemies()
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.rand() < self.sticky_action_prob: action = self.last_action self.last_action = action self.previous_heading = self.heading self.previous_objects = [(int(enemy["row"]), int(enemy["column"])) for enemy in self.enemies] if self.boss is not None: self.previous_objects.append((self.boss["row"], self.boss["column"])) if action == 1: self.heading = (self.heading - 1) % 8 elif action == 2: self._scroll_world(1) elif action == 3: self.heading = (self.heading + 1) % 8 elif action == 4: self.heading = (self.heading + 4) % 8 elif action == 5: row_delta, column_delta = DIRECTIONS[self.heading] self.bullets.append([5 + row_delta, 5 + column_delta, row_delta, column_delta]) self._move_bullets() self._move_enemies() self._move_enemy_shots() reward = self._resolve_hits() self._resolve_collisions() if not self.terminal: self._spawn_enemies() self._spawn_boss_if_ready() future_score = self.score + reward while future_score >= self.next_extra_life: self.lives += 1 self.next_extra_life += 50_000 if self.next_extra_life >= 10_000 else 10_000 self.score = future_score self.steps += 1 if self.steps >= self.horizon: self.terminal = True return reward, self.terminal
def _scroll_world(self, distance: int) -> None: row_delta, column_delta = DIRECTIONS[self.heading] for enemy in self.enemies: enemy["row"] -= row_delta * distance enemy["column"] -= column_delta * distance if self.boss is not None: self.boss["row"] -= row_delta * distance self.boss["column"] -= column_delta * distance
def _spawn_enemies(self) -> None: if self.killed >= 56: return active_normal = sum(enemy["kind"] == "normal" for enemy in self.enemies) target_active = 3 + self.era // 2 if self.spawned == 20 and not FORMATION_IDS.intersection( int(enemy["id"]) for enemy in self.enemies ): for enemy_id in FORMATION_IDS: self.enemies.append(self._new_enemy(enemy_id, "normal")) self.spawned = 25 return while active_normal < target_active and self.spawned < 56 and self.spawned not in FORMATION_IDS: self.enemies.append(self._new_enemy(self.spawned, "normal")) self.spawned += 1 active_normal += 1 if self.era > 0 and not self.special_spawned and self.killed >= 10: self.enemies.append(self._new_enemy(100 + self.era, "special")) self.special_spawned = True
def _new_enemy(self, enemy_id: int, kind: str) -> dict[str, int | str]: edge = int(self.random.randint(4)) coordinate = int(self.random.randint(1, 9)) row, column = ((0, coordinate), (9, coordinate), (coordinate, 0), (coordinate, 9))[edge] return {"id": enemy_id, "kind": kind, "row": row, "column": column}
def _move_bullets(self) -> None: for bullet in self.bullets: bullet[0] += bullet[2] bullet[1] += bullet[3] self.bullets = [bullet for bullet in self.bullets if 0 <= bullet[0] < 10 and 0 <= bullet[1] < 10]
def _move_enemies(self) -> None: interval = max(1, 4 - self.era // 2) if self.steps % interval == 0: for enemy in self.enemies: enemy["row"] += int(np.sign(5 - int(enemy["row"]))) enemy["column"] += int(np.sign(5 - int(enemy["column"]))) if self.boss is not None: self.boss["row"] += int(np.sign(5 - self.boss["row"])) self.boss["column"] += int(np.sign(5 - self.boss["column"])) if self.steps % max(5, 12 - self.era) == 0 and (self.enemies or self.boss is not None): source = self.enemies[0] if self.enemies else self.boss row = int(source["row"]) column = int(source["column"]) self.enemy_shots.append([row, column, int(np.sign(5 - row)), int(np.sign(5 - column))])
def _move_enemy_shots(self) -> None: for shot in self.enemy_shots: if self.era >= 2: shot[2] = int(np.sign(5 - shot[0])) shot[3] = int(np.sign(5 - shot[1])) shot[0] += shot[2] shot[1] += shot[3] self.enemy_shots = [shot for shot in self.enemy_shots if 0 <= shot[0] < 10 and 0 <= shot[1] < 10]
def _resolve_hits(self) -> float: reward = 0.0 hit_bullets: set[int] = set() hit_enemy_ids: set[int] = set() for bullet_index, bullet in enumerate(self.bullets): for enemy in self.enemies: if bullet[:2] != [enemy["row"], enemy["column"]]: continue hit_bullets.add(bullet_index) hit_enemy_ids.add(int(enemy["id"])) if enemy["kind"] == "normal": reward += 100.0 self.killed += 1 if int(enemy["id"]) in FORMATION_IDS: self.formation_destroyed.add(int(enemy["id"])) else: reward += 1_500.0 self.special_destroyed = True break if self.boss is not None and bullet[:2] == [self.boss["row"], self.boss["column"]]: hit_bullets.add(bullet_index) self.boss["hp"] -= 1 if self.boss["hp"] == 0: reward += 3_000.0 self.boss = None self.era += 1 if self.era >= 5: self.terminal = True else: self._start_era() break self.enemies = [enemy for enemy in self.enemies if int(enemy["id"]) not in hit_enemy_ids] self.bullets = [bullet for index, bullet in enumerate(self.bullets) if index not in hit_bullets] if not self.formation_failed and self.formation_destroyed == FORMATION_IDS: reward += 2_000.0 self.formation_failed = True return reward
def _resolve_collisions(self) -> None: colliding_ids = { int(enemy["id"]) for enemy in self.enemies if int(enemy["row"]) == 5 and int(enemy["column"]) == 5 } collision = bool(colliding_ids) or any(shot[:2] == [5, 5] for shot in self.enemy_shots) if self.boss is not None and [self.boss["row"], self.boss["column"]] == [5, 5]: collision = True if not collision: return if colliding_ids.intersection(FORMATION_IDS): self.formation_failed = True for enemy in self.enemies: if int(enemy["id"]) in colliding_ids: enemy["row"] = 0 enemy["column"] = 1 + int(enemy["id"]) % 8 if self.boss is not None and [self.boss["row"], self.boss["column"]] == [5, 5]: self.boss["row"] = 0 self.boss["column"] = 5 self.bullets.clear() self.enemy_shots.clear() self.lives -= 1 if self.lives <= 0: self.terminal = True
def _spawn_boss_if_ready(self) -> None: if self.killed < 56 or self.enemies or not self.special_destroyed or self.boss is not None: return self.boss = {"row": 0, "column": 5, "hp": 7}
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) state[5, 5, 0] = True for enemy in self.enemies: channel = 2 if enemy["kind"] == "special" else 1 state[int(enemy["row"]), int(enemy["column"]), channel] = True if self.boss is not None: state[self.boss["row"], self.boss["column"], 2] = True for bullet in self.bullets: state[bullet[0], bullet[1], 3] = True for shot in self.enemy_shots: state[shot[0], shot[1], 1] = True for row, column in self.previous_objects: if 0 <= row < 10 and 0 <= column < 10: state[row, column, 4] = True values = ( (self.era, 3), (self.heading, 3), (self.previous_heading, 3), (self.lives, 5), (self.spawned, 6), (self.killed, 6), (self.steps, 13), (0 if self.boss is None else self.boss["hp"], 3), ) offset = 0 for value, width in values: for bit in range(width): index = offset + bit state[index // 10, index % 10, 5] = bool(value & (1 << bit)) offset += width for enemy_id in self.formation_destroyed: state[5, enemy_id - 20, 5] = True state[5, 5, 5] = self.formation_failed state[5, 6, 5] = self.special_spawned state[5, 7, 5] = self.special_destroyed return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135from dataclasses import dataclassfrom math import atan2, ceil, cos, pi, sin
import numpy as np
@dataclassclass Prey: x: float y: float vx: float
@dataclassclass Hazard: x: float y: float = -5.
class TongueHunterEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.prey, self.hazards = [], [] self.length, self.angle = 0., -pi / 2 self.tip = (50., 90.) self.combo = 1 self.steps = self.frames = self.action = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.action = action self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): if self.frames % 60 == 0: left = self.random.random() < 0.5 speed = self.random.uniform(0.3, 0.6) self.prey.append(Prey(-5 if left else 105, self.random.uniform(20, 60), speed if left else -speed)) if self.frames % 90 == 0: self.hazards.append(Hazard(self.random.uniform(10, 90)))
dx, dy = cos(self.angle) * self.length, sin(self.angle) * self.length tip_x, tip_y = self.tip = (50 + dx, 90 + dy) if self.action == 5 and self.prey: target = min(self.prey, key=lambda p: (p.x - tip_x) ** 2 + (p.y - tip_y) ** 2) angle = atan2(target.y - 90, target.x - 50) delta = angle - self.angle if abs(delta) < 0.1: self.angle = angle self.length += 8 else: self.angle += 0.1 if delta > 0 else -0.1 self.length = min(80, max(0, self.length - 5))
for prey in self.prey: prey.x += prey.vx * 1.05 self.prey = [p for p in self.prey if -10 < p.x < 110] for hazard in self.hazards: hazard.y += 0.5 self.hazards = [h for h in self.hazards if h.y < 110]
reward = 0 if self.length <= 5: self.combo = 1 else: radius = 2.5 + 3 * (1 + sin(self.frames * 0.3) * 0.2) if any(abs(p.x - tip_x) <= radius and abs(p.y - tip_y) <= radius for p in self.prey): target = min(self.prey, key=lambda p: (p.x - tip_x) ** 2 + (p.y - tip_y) ** 2) self.prey.remove(target) reward = ceil(self.length) * self.combo self.combo += 1 self.terminal = any(self._touches_tongue(h, dx, dy) for h in self.hazards) self.frames += 1 return reward
def _touches_tongue(self, hazard, dx, dy): radius = 1 + 4 * (1 + sin(self.frames * 0.15 + hazard.x) * 0.1) near, far = 0., 1. for offset, movement in ((hazard.x - 50, dx), (hazard.y - 90, dy)): if abs(movement) < 1e-9: if abs(offset) > radius: return False else: edges = sorted(((offset - radius) / movement, (offset + radius) / movement)) near, far = max(near, edges[0]), min(far, edges[1]) return near <= far
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[9, 5, 0] = True if self.length > 5: tip_x, tip_y = self.tip for x, y in zip(np.linspace(50, tip_x, 33), np.linspace(90, tip_y, 33), strict=True): self._mark(state, x, y, 1) self._mark(state, tip_x, tip_y, 2) for prey in self.prey: self._mark(state, prey.x, prey.y, 3) for hazard in self.hazards: self._mark(state, hazard.x, hazard.y, 4) values = (self.steps, self.action, self.combo, round(self.length * 4), round((self.angle + pi) * 128)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
@staticmethod def _mark(state, x, y, channel): if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), channel] = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from dataclasses import dataclassfrom math import atan2, cos, floor, hypot, sin, sqrt
import numpy as np
@dataclassclass Debris: x: float y: float size: int distance: float = 0. angle: float = 0.
@dataclassclass Obstacle: x: float y: float width: float height: float
class TornadoTwisterEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.y, self.direction, self.speed = 75., 1, 1. self.size = self.current_size = 7. points = self.random.uniform(-10, 10, (20, 2)) self.radii = np.hypot(points[:, 0], points[:, 1]) self.angles = np.arctan2(points[:, 1], points[:, 0]) self.debris, self.obstacles = [], [] self.debris_timer = self.obstacle_timer = 0. self.steps = self.frames = self.action = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action if self.action == 5 and previous != 5: self.direction *= -1 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _cloud(self): angles = self.angles + self.frames * 0.15 * (1 - np.arange(20) / 20) radius = self.radii * self.current_size / 10 return 20 + radius * np.cos(angles), self.y + radius * np.sin(angles)
def _advance(self): if self.action == 5: self.current_size += (3 - self.current_size) * 0.1 self.speed += (0.1 - self.speed) * 0.1 else: self.current_size += (self.size - self.current_size) * 0.03 self.speed += (1 - self.speed) * 0.1 self.y += self.direction * self.speed if self.y <= self.current_size: self.direction = 1 if self.y >= 100 - self.current_size: self.direction = -1
self.frames += 1 cloud_x, cloud_y = self._cloud() padding = sqrt(self.current_size)
def touches(x, y, width, height): return np.any((abs(cloud_x - x) <= (width + padding) / 2) & (abs(cloud_y - y) <= (height + padding) / 2))
self.debris_timer -= 1 if self.debris_timer <= 0: size = 3 if self.random.random() < 0.5 else (5 if self.random.random() < 0.7 else 4) self.debris.append(Debris(160, self.random.uniform(10, 90), size)) self.debris_timer = self.random.uniform(30, 50) reward = 0 remaining = [] for item in self.debris: if item.distance > 0: item.distance -= 1 item.angle += 0.2 if item.distance <= 0: self.size += item.size * 0.05 reward += floor(item.size * self.current_size) continue item.x = 20 + item.distance * cos(item.angle) item.y = self.y + item.distance * sin(item.angle) else: item.x -= 1 if touches(item.x, item.y, item.size, item.size): dx, dy = item.x - 20, item.y - self.y item.distance = max(1, hypot(dx, dy) * 1.5) item.angle = atan2(dy, dx) if item.x >= -item.size: remaining.append(item) self.debris = remaining
self.obstacle_timer -= 1 if self.obstacle_timer < 0: width = self.random.uniform(20, 30) self.obstacles.append(Obstacle(150 + width / 2, self.random.uniform(10, 90), width, self.random.uniform(10, 20))) self.obstacle_timer += self.random.uniform(50, 150) for obstacle in self.obstacles: obstacle.x -= 1 self.terminal = any(touches(o.x, o.y, o.width, o.height) for o in self.obstacles) self.obstacles = [o for o in self.obstacles if o.x > -o.width] return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) cloud_x, cloud_y = self._cloud() for x, y in zip(cloud_x, cloud_y, strict=True): if 0 <= x < 150 and 0 <= y < 100: state[int(y // 10), int(x // 15), 0] = True for item in self.debris: if 0 <= item.x < 150 and 0 <= item.y < 100: state[int(item.y // 10), int(item.x // 15), 3 if item.distance else 1] = True if item.size >= 4 and not item.distance: state[int(item.y // 10), int(item.x // 15), 2] = True rows, cols = np.ogrid[0:100:10, 0:150:15] for obstacle in self.obstacles: state[:, :, 4] |= ((abs(cols + 7.5 - obstacle.x) < obstacle.width / 2 + 7.5) & (abs(rows + 5 - obstacle.y) < obstacle.height / 2 + 5)) values = (self.steps, self.action, self.direction > 0, round(self.speed * 100), round(self.current_size * 16), round(self.size * 16)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125from dataclasses import dataclassfrom math import ceil
import numpy as np
@dataclassclass SpikeStrip: x: float y: float count: int
class TotogeEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y, self.vx, self.vy = 50., 9., 0.33, 0. self.scroll, self.next_wall = 0., 105. self.spikes = [] self.spike_distance, self.next_spike_x, self.spike_direction = 0., 10., 1 self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action jump = self.action == 5 and previous != 5 self.steps += 1 reward = 0. for frame in range(4): reward += self._advance(jump and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _advance(self, jump): reward = 0. while self.next_wall < 105: self.next_wall += 10 reward += 1 self.next_wall -= self.scroll
self.spike_distance -= self.scroll if self.spike_distance < 0: count = int(self.random.integers(2, 5)) x = float(np.clip(self.next_spike_x, 12, 93 - count * 6)) self.spikes.append(SpikeStrip(x, 199, count)) self.spike_distance = self.random.uniform(99, 199) self.next_spike_x += self.spike_direction * count * 6 if self.next_spike_x < 9 or self.next_spike_x > 90: self.spike_direction *= -1 for strip in self.spikes: strip.y -= self.scroll self.spikes = [strip for strip in self.spikes if strip.y > -99] samples = ceil(min(99, max(1, self.vy / 6))) if any(self._hits(strip, self.y - 6 * offset) for strip in self.spikes for offset in range(samples)): self.terminal = True return reward
self.x += self.vx self.y += self.vy - self.scroll if self.y < 10: self.scroll = (self.y - 10) / 2 elif self.y > 30: self.scroll = (self.y - 30) / 2 self.vy += 0.05 if (self.x < 9 and self.vx < 0) or (self.x > 90 and self.vx > 0): self.vx *= -1 if jump and self.vy > 0 and self.next_wall < 150: bonus = self.vy ** 2 if bonus > 10: reward += bonus self.vy = -1 return reward
def _hits(self, strip, y): draw_y = min(99, max(-99, strip.y)) for index in range(strip.count): dx = abs(self.x - strip.x - index * 6) dy = y - draw_y if dx < 6 and -5 < dy < 5 and dx < 4.5 + dy * 0.3: return True return False
def state(self): state = np.zeros((10, 10, 6), dtype=bool) col = int(np.clip(self.x // 10, 0, 9)) row = int(np.clip(self.y // 10, 0, 9)) state[row, col, 0] = True for strip in self.spikes: if 0 <= strip.y < 100: for index in range(strip.count): state[int(strip.y // 10), int((strip.x + index * 6) // 10), 1] = True elif strip.y >= 100: for index in range(strip.count): state[9, int((strip.x + index * 6) // 10), 2] = True for y in np.arange(self.next_wall - 10, -5, -10): if 0 <= y < 100: state[int(y // 10), (0, 9), 3] = True state[row, col, 4] = self.vy > 0 values = (self.steps, self.action, self.vx > 0, round((self.vy + 1) * 16), round((self.scroll + 4) * 16), round(self.next_wall * 2)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169from dataclasses import dataclassfrom math import cos, hypot, pi, sin, sqrt
import numpy as np
@dataclassclass Ball: x: float y: float radius: float red: bool = False vx: float = 0. vy: float = 0. beamed: bool = False
class TrBeamEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.phase = -pi * 0.3 self.x = 50 + sin(self.phase) * 40 self.length = 0. self.balls = [] self.spawn_timer = 0. self.until_red = 9 self.multiplier = 1 self.action = self.steps = self.frames = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action if self.action == 5 and previous != 5: self.multiplier = 1 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): self.phase += 0.03 self.x = 50 + sin(self.phase) * 40 self.length = min(82, self.length + 2) if self.action == 5 else self.length * 0.8 beams = self._beams() self.frames += 1 self.spawn_timer -= 1 if self.spawn_timer < 0: self.until_red -= 1 red = self.until_red < 0 if red: self.until_red = int(self.random.integers(9, 12)) radius = self.random.uniform(6, 12) self.balls.append(Ball(self.random.uniform(10, 90), 105 + radius, radius, red)) self.spawn_timer = self.random.uniform(20, 25) reward = 0 remaining = [] for ball in self.balls: self._move(ball) dx, dy = self.x - ball.x, 9 - ball.y distance = hypot(dx, dy) if abs(distance - ball.radius) <= 4: if ball.red: self.terminal = True break reward += self.multiplier self.multiplier += 1 continue if any(_crosses_ring(ball, *beam) for beam in beams): strength = 1 / (max(distance, 1e-9) * sqrt(ball.radius)) ball.vx += dx * (strength + 0.01) ball.vy += dy * strength ball.beamed = True elif ball.beamed: ball.vy *= 0.1 ball.vx *= 5 ball.beamed = False if not ball.beamed: if ball.red and (ball.x < ball.radius or ball.x > 99 - ball.radius): ball.red = False elif 10 <= ball.x < 90 and 12 <= ball.y - ball.radius < 17 and ball.vy > 0: ball.red = True if -20 <= ball.x <= 120: remaining.append(ball) if not self.terminal: self.balls = remaining return reward
def _move(self, ball): if ball.y > 99: ball.vy -= 1 drag = 0.5 elif ball.x < 0 or ball.x > 99: drag = 0.1 else: drag = 0.9 if ball.red: ball.vy *= 0.9 ball.vx *= drag ball.vy = ball.vy * drag + 0.1 ball.x += ball.vx ball.y += ball.vy for other in self.balls: if other is ball: continue dx, dy = ball.x - other.x, ball.y - other.y distance = hypot(dx, dy) overlap = ball.radius + other.radius - distance if overlap > 0 and distance > 0: scale = overlap / (distance * sqrt(ball.radius)) ball.vx += dx * scale ball.vy += dy * scale
def _beams(self): if self.length <= 1: return [] angle = (self.frames % 10) * pi / 40 offsets = [cos(angle + index * pi / 4) for index in range(4)] return [(self.x + 4 * offset, 14, self.x + 9 * offset, 14 + self.length) for offset in offsets]
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[0, int(self.x // 10), 0] = True for x1, y1, x2, y2 in self._beams(): for x, y in zip(np.linspace(x1, x2, 33), np.linspace(y1, y2, 33), strict=True): state[int(y // 10), int(x // 10), 1] = True rows, cols = np.ogrid[5:100:10, 5:100:10] for ball in self.balls: ring = abs(np.hypot(cols - ball.x, rows - ball.y) - ball.radius) <= 6 state[:, :, 3 if ball.red else 2] |= ring if ball.beamed: state[:, :, 4] |= ring values = (self.steps, self.action, round(self.length * 4), self.multiplier, round((self.phase % (2 * pi)) * 64), self.until_red + 1) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
def _crosses_ring(ball, x1, y1, x2, y2): dx, dy = x2 - x1, y2 - y1 fraction = ((ball.x - x1) * dx + (ball.y - y1) * dy) / (dx * dx + dy * dy) fraction = min(1, max(0, fraction)) near = hypot(ball.x - x1 - fraction * dx, ball.y - y1 - fraction * dy) far = max(hypot(ball.x - x1, ball.y - y1), hypot(ball.x - x2, ball.y - y2)) return near <= ball.radius + 2 and far >= ball.radius - 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144from dataclasses import dataclassfrom math import cos, hypot, pi, remainder, sin
import numpy as np
@dataclassclass Enemy: angle: float kind: int rate: float timer: float speed: float
@dataclassclass Shot: angle: float radius: float speed: float
class TrojanDefenseEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.angle, self.length, self.arc = 0., 10., pi / 8 self.direction = self.multiplier = 1 self.enemies, self.shots = [], [] self.wave_timer = 60. self.wave = self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action if self.action == 5 and previous != 5: self.direction *= -1 self.multiplier = 1 self.steps += 1 reward = 0 for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self): if self.action == 5: self.arc = min(pi / 3, self.arc + 0.02) self.length = min(20, self.length + 0.5) speed_factor = 1 - (self.arc - pi / 8) / (pi / 3 - pi / 8) * 0.7 else: self.arc = max(pi / 8, self.arc - 0.015) self.length = max(10, self.length - 0.3) speed_factor = 1.2 self.angle = (self.angle + self.direction * 0.06 * speed_factor) % (2 * pi) self.wave_timer -= 1 if self.wave_timer < 0: self._spawn_wave()
remaining = [] reward = 0 for shot in self.shots: shot.radius += shot.speed if shot.speed < 0: offset = abs(remainder(shot.angle - self.angle, 2 * pi)) if 4 <= shot.radius <= 6.5 + self.length and offset <= self.arc / 2 + 1.5 / shot.radius: shot.speed *= -1.5 elif shot.radius <= 5: self.terminal = True return reward else: hit = next((enemy for enemy in self.enemies if _enemy_distance(shot, enemy) <= 4), None) if hit is not None: self.enemies.remove(hit) reward += self.multiplier * (hit.kind + 1) * 10 self.multiplier += 1 continue if shot.radius <= 55: remaining.append(shot) self.shots = remaining
for enemy in self.enemies: enemy.timer -= 1 if enemy.timer <= 0: self.shots.append(Shot(enemy.angle, 50, -enemy.speed)) enemy.timer = enemy.rate * self.random.uniform(0.8, 1.2) return reward
def _spawn_wave(self): self.wave += 1 base = self.random.uniform(0, 2 * pi) for _ in range(min(5, 1 + self.wave // 3)): angle = base + self.random.uniform(-pi / 4, pi / 4) kind = 0 if self.random.random() < 0.7 else int(self.random.integers(1, 3)) low, high, speed = ((120, 180, 0.5), (80, 120, 0.8), (150, 200, 0.4))[kind] self.enemies.append(Enemy(angle, kind, self.random.uniform(low, high), self.random.uniform(30, 60), speed)) self.wave_timer = self.random.uniform(180, 300)
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[5, 5, 0] = True for angle in np.linspace(self.angle - self.arc / 2, self.angle + self.arc / 2, 9): for radius in np.linspace(5, 5 + self.length, 9): _mark(state, angle, radius, 1) for enemy in self.enemies: _mark(state, enemy.angle, 50, 2) for shot in self.shots: _mark(state, shot.angle, shot.radius, 3 if shot.speed < 0 else 4) values = (self.steps, self.action, self.direction > 0, round(self.angle * 64), round(self.length * 16), round(self.arc * 128), self.multiplier, self.wave) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
def _enemy_distance(shot, enemy): return hypot(shot.radius * cos(shot.angle) - 50 * cos(enemy.angle), shot.radius * sin(shot.angle) - 50 * sin(enemy.angle))
def _mark(state, angle, radius, channel): x, y = 50 + radius * cos(angle), 50 + radius * sin(angle) state[int(np.clip(y // 10, 0, 9)), int(np.clip(x // 10, 0, 9)), channel] = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151from collections import dequefrom math import ceil, sqrt
import numpy as np
_PATTERNS = ((0, 0, 0), (0, 1, 0), (0, 3, 0), (0, 0, 1), (0, 0, 3), (1, 0, 0), (3, 0, 0))_DIRECTIONS = ((0, 1), (1, 0), (0, -1), (-1, 0))_BOARD = tuple((row, col) for row in range(10) for col in range(10))_BORDER = tuple(cell for cell in _BOARD if 0 in cell or 9 in cell)
def _neighbors(cell): row, col = cell for dr, dc in _DIRECTIONS: neighbor = row + dr, col + dc if 0 <= neighbor[0] < 10 and 0 <= neighbor[1] < 10: yield neighbor
class TtFenceEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.tip = (4, 4) initial = self._path(int(self.random.integers(7)), int(self.random.integers(4))) self.fence = set(initial) self.tip = initial[-1] self.pattern = int(self.random.integers(7)) self.angle = 0 self.rotation_timer = 0 self.blast = set() self.blast_timer = 0 self.damage = self.damage_target = 0. self.steps = self.action = 0 self.terminal = False self.preview = self._rotate() self.rotation_timer = 30
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action place = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(place and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, place): self.blast_timer -= 1 reward = 0 if place and self.preview: self.damage_target += 2 + 9 * sum(cell in self.fence for cell in self.preview) self.fence.update(self.preview) self.tip = self.preview[-1] reward = self._bomb() self.pattern = int(self.random.integers(7)) self.rotation_timer = 0 self.rotation_timer -= 1 if self.rotation_timer < 0: self.preview = self._rotate() self.rotation_timer = 30 self.damage_target += 0.01 self.damage += (self.damage_target - self.damage) * 0.1 self.terminal = self.damage > 99 return reward
def _path(self, pattern, angle): row, col = self.tip cells = [] for offset in (0, *_PATTERNS[pattern]): dr, dc = _DIRECTIONS[(angle + offset) % 4] row, col = row + dr, col + dc cells.append((row, col)) return cells
def _rotate(self): fallback = None for turn in range(1, 5): angle = (self.angle + turn) % 4 path = self._path(self.pattern, angle) if all(0 <= row < 10 and 0 <= col < 10 for row, col in path): if not self.fence.intersection(path): self.angle = angle return path if fallback is None: fallback = angle, path if fallback is not None: self.angle, path = fallback return path self.damage_target = 100 return []
def _bomb(self): outside = set(_BORDER) - self.fence queue = deque(outside) while queue: for cell in _neighbors(queue.popleft()): if cell not in outside and cell not in self.fence: outside.add(cell) queue.append(cell) enclosed = set(_BOARD) - outside - self.fence self.blast = {neighbor for cell in enclosed for neighbor in _neighbors(cell)} for _ in range(int(sqrt(len(self.blast)) * 0.5)): for cell in _BOARD: if cell in self.blast: self.blast.update(neighbor for neighbor in _neighbors(cell) if neighbor in self.fence) self.blast_timer = 30 self.fence.difference_update(self.blast) count = len(self.blast) reward = ceil(count * sqrt(count)) if reward: self.damage_target = min(99, max(0, self.damage_target - reward * 0.1)) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for row, col in self.fence: state[row, col, 0] = True for row, col in self.preview: state[row, col, 1] = True for row, col in self.blast if self.blast_timer > 0 else (): state[row, col, 2] = True state[self.tip[0], self.tip[1], 3] = True state[9, :min(10, ceil(self.damage / 10)), 4] = True values = (self.steps, self.action, self.pattern, self.angle, self.rotation_timer, round(self.damage * 4), round(self.damage_target * 4)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136from dataclasses import dataclassfrom math import cos, hypot, pi, sin
import numpy as np
@dataclassclass Obstacle: angle: float radius: float speed: float fuse: int = -1
def position(self): return _position(self.angle, self.radius)
class TurboTunnelEnvironment: score_cap = 300
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.angle, self.radius, self.direction = pi / 2, 30., 1 self.obstacles = [] self.multiplier = 1 self.steps = self.action = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action turn = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(turn and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, turn): spawn = turn if turn: self.direction *= -1 self.angle = (self.angle + 0.5 / self.radius) % (2 * pi) self.radius += self.direction * 0.4 if (self.radius > 50 and self.direction > 0) or (self.radius < 10 and self.direction < 0): self.direction *= -1 spawn = True
player = _position(self.angle, self.radius) armed = [] loose = [] remaining = [] reward = 0 had_fuse = False for obstacle in self.obstacles: obstacle.angle += obstacle.speed / (obstacle.radius * 0.03) point = obstacle.position() if obstacle.fuse > 0: had_fuse = True obstacle.fuse -= 1 if obstacle.fuse == 0: reward += self.multiplier self.multiplier += 1 continue armed.append(point) elif any(_distance(point, other) <= 3.5 for other in loose): obstacle.fuse = 30 armed.append(point) else: loose.append(point) if _distance(point, player) <= 2.5: self.terminal = True remaining.append(obstacle) self.obstacles = remaining for obstacle in self.obstacles: if obstacle.fuse < 0 and any(_distance(obstacle.position(), point) <= 4.5 for point in armed): obstacle.fuse = 30 armed.append(obstacle.position()) had_fuse = True if not had_fuse: self.multiplier = 1
if spawn and not self.terminal: obstacle = Obstacle(self.angle - 3 / self.radius, self.radius, -self.random.uniform(0.01, 0.03)) x, y = obstacle.position() if not any(abs(x - ox) < 6.5 and abs(y - oy) < 6.5 for ox, oy in (other.position() for other in self.obstacles)): self.obstacles.append(obstacle) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) _mark(state, _position(self.angle, self.radius), 0) for obstacle in self.obstacles: _mark(state, obstacle.position(), 2 if obstacle.fuse > 0 else 1) rows, cols = np.ogrid[5:100:10, 5:100:10] radius = np.hypot(cols - 50, rows - 50) state[:, :, 3] = (abs(radius - 10) < 6) | (abs(radius - 50) < 6) _mark(state, _position(self.angle + 2 / self.radius, self.radius + self.direction * 1.6), 4) values = (self.steps, self.action, self.direction > 0, self.multiplier, round(self.radius * 8), round(self.angle * 64)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
def _position(angle, radius): return 50 + cos(angle) * radius, 50 + sin(angle) * radius
def _distance(first, second): return hypot(first[0] - second[0], first[1] - second[1])
def _mark(state, point, channel): x, y = point state[int(np.clip(y // 10, 0, 9)), int(np.clip(x // 10, 0, 9)), channel] = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167from bisect import bisect_rightfrom dataclasses import dataclassfrom math import atan2, ceil, cos, hypot, pi, remainder, sin
import numpy as np
@dataclassclass Wave: x: float height: float phase: float speed: float
@dataclassclass Mine: x: float vx: float = 0.
class TurbulentEnvironment: score_cap = 500
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.waves = [ Wave(i * 20 - 20, self.random.uniform(10, 30), (i % 2) * pi + self.random.uniform(-pi / 4, pi / 4), self.random.uniform(0.01, 0.02)) for i in range(7) ] self.mines = [] self.mine_distance = 0. self.x, self.y = 40., 60. self.vx = self.vy = self.angle = self.jump_x = 0. self.airborne = self.terminal = False self.steps = self.action = 0 self._surface_points()
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action jump = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(jump and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _surface_points(self): peaks = sorted((w.x, 60 + sin(w.phase) * w.height) for w in self.waves) points = [peaks[0]] for (x, y), (right, next_y) in zip(peaks, peaks[1:]): points.extend((x + 5 * i, y + (next_y - y) * ratio) for i, ratio in enumerate((0.2, 0.5, 0.8), 1)) points.append((right, next_y)) self.surface_x, self.surface_y = zip(*points, strict=True)
def _surface(self, x): index = min(len(self.surface_x) - 2, max(0, bisect_right(self.surface_x, x) - 1)) width = self.surface_x[index + 1] - self.surface_x[index] rise = self.surface_y[index + 1] - self.surface_y[index] height = self.surface_y[index] + rise * (x - self.surface_x[index]) / width return height, rise, width
def _advance(self, jump): scroll = 0.1 + max(0, self.x - 50) * 0.1 for wave in self.waves: wave.x -= scroll if wave.x < -20: wave.x += 140 wave.height = self.random.uniform(10, 30) wave.phase = self.random.uniform(0, 2 * pi) wave.speed = self.random.uniform(0.01, 0.02) wave.phase += wave.speed self._surface_points()
self.mine_distance -= scroll if self.mine_distance < 0: self.mines.append(Mine(103)) self.mine_distance = self.random.uniform(100, 120) mine_positions = [] remaining = [] for mine in self.mines: mine.x -= scroll if not self.surface_x[0] <= mine.x < self.surface_x[-1]: continue height, rise, width = self._surface(mine.x) mine.vx = (mine.vx + rise * 0.001) * 0.9 mine.x += mine.vx if mine.x >= -3: remaining.append(mine) mine_positions.append((mine.x, height + rise * mine.vx / width - 5)) self.mines = remaining
if self.airborne: self.jump_x -= scroll self.vx = (self.vx + 0.005) * 0.98 self.vy = (self.vy + (0.02 if self.action == 5 else 0.1)) * 0.98 self.x += self.vx self.y += self.vy angle = atan2(self.vy, self.vx) else: previous_x, previous_y = self.x, self.y height, rise, width = self._surface(self.x) self.vx = (self.vx + rise * 0.002) * 0.925 + 0.025 self.x += self.vx self.y = height + rise * self.vx / width angle = atan2(rise, width) if jump: self.jump_x = self.x self.vx = (self.x - previous_x) * 2 + sin(angle) self.vy = min(-1, (self.y - previous_y) * 5 - cos(angle)) self.x += self.vx self.y += self.vy self.airborne = True
self.x = min(95, max(5, self.x - scroll)) self.y = min(95, max(5, self.y)) self.angle += remainder(angle - self.angle, 2 * pi) * 0.1 nose_x = self.x + 5.8 * sin(self.angle) nose_y = self.y - 5.8 * cos(self.angle) reward = 0 if self.airborne and nose_y >= self._surface(nose_x)[0] - 2: reward = max(0, ceil(self.x - self.jump_x)) self.airborne = False self.vx *= 0.5 self.terminal = any(hypot(x - nose_x, y - nose_y) <= 4 for x, y in mine_positions) return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) state[int(self.y // 10), int(self.x // 10), 0] = True for col in range(10): heights = [self._surface(col * 10 + offset)[0] for offset in (0, 5, 10)] state[int(min(heights) // 10):int(max(heights) // 10) + 1, col, 1] = True for mine in self.mines: row = int((self._surface(mine.x)[0] - 5) // 10) state[row, int(np.clip(mine.x // 10, 0, 9)), 2] = True if self.airborne: state[int(self.y // 10), int(self.x // 10), 3] = True state[9, int(np.clip(self.jump_x // 10, 0, 9)), 4] = True values = (self.steps, self.action, round((self.vx + 8) * 16), round((self.vy + 16) * 8), round((self.angle + pi) * 64)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104from dataclasses import dataclassfrom math import sin
import numpy as np
@dataclassclass Obstacle: x: float y: float width: float height: float underwater: bool
class TurtleTideEnvironment: score_cap = 600
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.y = self.water = 50. self.speed, self.frequency, self.amplitude = 1., 0.05, 10. self.obstacles = [] self.obstacle_distance = 60. self.action = self.steps = self.frames = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True if self.random.random() >= self.sticky_action_prob: self.action = action self.steps += 1 reward = 0. for _ in range(4): reward += self._advance() if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _advance(self): self.frequency = min(0.05, max(0, self.frequency + self.random.uniform(-0.0001, 0.0001))) self.amplitude = min(10, max(0, self.amplitude + self.random.uniform(-0.01, 0.01))) target_water = 50 + sin(self.frames * self.frequency) * self.amplitude self.water += (target_water - self.water) * 0.1 self.frames += 1 if self.action == 5: self.speed = min(9, self.speed + 0.01) self.y += (self.water + 15 - self.y) * 0.1 else: self.speed += (1 - self.speed) * 0.1 self.y += (self.water - 5 - self.y) * 0.1 if self.y + 1 > self.water: self.y = self.water - 1
for obstacle in self.obstacles: obstacle.x -= self.speed self.obstacles = [obstacle for obstacle in self.obstacles if obstacle.x >= -10] self.obstacle_distance -= self.speed if self.obstacle_distance < 0: underwater = self.random.random() < 0.5 low, high = (self.water + 5, 95) if underwater else (5, self.water - 5) self.obstacles.append(Obstacle(110, self.random.uniform(low, high), self.random.uniform(5, 10), self.random.uniform(5, 10), underwater)) self.obstacle_distance = self.random.uniform(99, 120) self.terminal = any( abs(obstacle.x - 20) < obstacle.width / 2 + self.speed and abs(obstacle.y - self.y) < obstacle.height / 2 + 1 for obstacle in self.obstacles ) return self.speed * 0.1
def state(self): state = np.zeros((10, 10, 6), dtype=bool) rows, cols = np.ogrid[5:100:10, 5:100:10] state[int(self.y // 10), 2, 0] = True state[:, :, 1] = rows + 5 > self.water for obstacle in self.obstacles: mask = ((abs(cols - obstacle.x) < obstacle.width / 2 + 5) & (abs(rows - obstacle.y) < obstacle.height / 2 + 5)) state[:, :, 3 if obstacle.underwater else 2] |= mask target = self.water + (15 if self.action == 5 else -5) state[int(target // 10), 2, 4] = True values = (self.steps, self.action, round(self.speed * 50), round(self.water * 8) - 256, round(self.obstacle_distance * 4), round(self.frequency * 10000), round(self.amplitude * 40)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226import numpy as np
TREASURE_VALUES = ( (20, 15, 25, 25, 20, 45), (40, 30, 25, 40, 20, 20), (60, 35, 30, 25, 30, 5), (55, 40, 25, 80, 20, 40, 35),)CREATURE_VALUES = (1, 2, 3)START = (8, 1)EXIT = (1, 8)WARP_LEFT = (5, 0)WARP_RIGHT = (5, 9)
def _walls(chamber: int) -> set[tuple[int, int]]: walls = {(0, column) for column in range(10)} | {(9, column) for column in range(10)} walls |= {(row, 0) for row in range(1, 9) if row != 5} walls |= {(row, 9) for row in range(1, 9) if row != 5} patterns = ( {(2, column) for column in range(1, 7)} | {(6, column) for column in range(3, 9)}, {(row, 3) for row in range(1, 7)} | {(row, 6) for row in range(3, 9)}, {(2, column) for column in range(3, 9)} | {(7, column) for column in range(1, 7)}, {(row, 2) for row in range(2, 8)} | {(row, 7) for row in range(2, 8)}, ) return walls | patterns[chamber]
class TutankhamEnvironment: """Finite Atari 2600 Tutankham campaign through all sixteen chambers."""
score_cap = 5_396.0
def __init__(self, sticky_action_prob: float = 0.1, horizon: int = 6_000): self.sticky_action_prob = sticky_action_prob self.horizon = horizon self.random = np.random.RandomState() self.seed(0) self.reset()
@classmethod def normalize_score(cls, raw_score: float) -> float: return min(max(raw_score, 0.0), cls.score_cap) / cls.score_cap
def seed(self, seed: int) -> None: self.random.seed(seed)
def reset(self) -> None: self.stage = 0 self.lives = 3 self.flashes = 3 self.score = 0.0 self.steps = 0 self.last_action = 0 self.facing = 1 self.terminal = False self._start_chamber()
def _start_chamber(self) -> None: self.chamber = self.stage % 4 self.level = self.stage // 4 self.player = list(START) self.ammunition = 100 self.has_key = False self.walls = _walls(self.chamber) open_cells = [ (row, column) for row in range(1, 9) for column in range(1, 9) if (row, column) not in self.walls and (row, column) not in (START, EXIT) ] treasure_count = len(TREASURE_VALUES[self.chamber]) treasure_cells = open_cells[2 : 2 + treasure_count] self.treasures = { cell: (index, value) for index, (cell, value) in enumerate(zip(treasure_cells, TREASURE_VALUES[self.chamber])) } self.key_position = treasure_cells[0] self.nests = (open_cells[-1], open_cells[-2], open_cells[-3]) self.enemies: list[dict[str, int]] = [] self.spawned = 0 self.killed = 0 self.bullets: list[list[int]] = []
def act(self, action: int) -> tuple[float, bool]: if self.terminal: return 0.0, True if self.random.rand() < self.sticky_action_prob: action = self.last_action previous_action = self.last_action self.last_action = action reward = 0.0 if action in (1, 2, 3, 4): reward += self._move_player(action) elif action == 5: if previous_action == 5 and self.flashes > 0: self.flashes -= 1 self._flash_guardians() elif self.ammunition > 0: self.ammunition -= 1 self.bullets.append([self.player[0], self.player[1], self.facing]) self.ammunition = max(0, self.ammunition - 1) self._move_bullets() reward += self._resolve_bullet_hits() self._spawn_guardian() self._move_guardians() self._resolve_guardian_collision() self.score += reward self.steps += 1 if self.steps >= self.horizon: self.terminal = True return reward, self.terminal
def _move_player(self, action: int) -> float: deltas = {1: (0, -1), 2: (-1, 0), 3: (0, 1), 4: (1, 0)} row_delta, column_delta = deltas[action] if action == 1: self.facing = -1 elif action == 3: self.facing = 1 destination = (self.player[0] + row_delta, self.player[1] + column_delta) if destination == WARP_LEFT: destination = WARP_RIGHT elif destination == WARP_RIGHT: destination = WARP_LEFT if destination in self.walls: return 0.0 if destination == EXIT: if not self.has_key: return 0.0 reward = float(self.ammunition) self.stage += 1 if self.stage == 16: self.terminal = True else: self._start_chamber() return reward self.player[:] = destination treasure = self.treasures.pop(destination, None) if treasure is None: return 0.0 index, value = treasure if index == 0: self.has_key = True return float(value)
def _spawn_guardian(self) -> None: if self.spawned >= 18 or len(self.enemies) >= 3 or self.steps % 4: return kind = self.spawned % 3 row, column = self.nests[kind] self.enemies.append({"id": self.spawned, "kind": kind, "row": row, "column": column}) self.spawned += 1
def _move_guardians(self) -> None: interval = max(1, 4 - self.level) if self.steps % interval: return for enemy in self.enemies: row_delta = int(np.sign(self.player[0] - enemy["row"])) column_delta = int(np.sign(self.player[1] - enemy["column"])) candidates = ((enemy["row"] + row_delta, enemy["column"]), (enemy["row"], enemy["column"] + column_delta)) for destination in candidates: if destination not in self.walls: enemy["row"], enemy["column"] = destination break
def _move_bullets(self) -> None: for bullet in self.bullets: bullet[1] += bullet[2] self.bullets = [ bullet for bullet in self.bullets if 0 <= bullet[1] < 10 and tuple(bullet[:2]) not in self.walls ]
def _resolve_bullet_hits(self) -> float: hit_bullets: set[int] = set() hit_enemies: set[int] = set() reward = 0.0 for bullet_index, bullet in enumerate(self.bullets): for enemy in self.enemies: if bullet[:2] == [enemy["row"], enemy["column"]]: hit_bullets.add(bullet_index) hit_enemies.add(enemy["id"]) reward += CREATURE_VALUES[enemy["kind"]] self.killed += 1 break self.bullets = [bullet for index, bullet in enumerate(self.bullets) if index not in hit_bullets] self.enemies = [enemy for enemy in self.enemies if enemy["id"] not in hit_enemies] return float(reward)
def _flash_guardians(self) -> None: for enemy in self.enemies: enemy["row"], enemy["column"] = self.nests[enemy["kind"]]
def _resolve_guardian_collision(self) -> None: if not any([enemy["row"], enemy["column"]] == self.player for enemy in self.enemies): return self.lives -= 1 self.player[:] = START self.enemies.clear() self.bullets.clear() if self.lives == 0: self.terminal = True
def state(self) -> np.ndarray: state = np.zeros((10, 10, 6), dtype=bool) state[self.player[0], self.player[1], 0] = True for enemy in self.enemies: state[enemy["row"], enemy["column"], 1] = True for position, (index, _value) in self.treasures.items(): state[position[0], position[1], 2 if index == 0 else 3] = True state[EXIT[0], EXIT[1], 2] = True for row, column in self.walls: state[row, column, 4] = True for bullet in self.bullets: state[bullet[0], bullet[1], 5] = True values = ((self.stage, 4), (self.lives, 2), (self.flashes, 2), (self.ammunition, 7), (self.spawned, 5), (self.killed, 5)) offset = 0 for value, width in values: for bit in range(width): state[8 - offset // 10, offset % 10, 5] = bool(value & (1 << bit)) offset += 1 state[6, 0, 5] = self.has_key state[6, 1, 5] = self.facing > 0 return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990from dataclasses import dataclassfrom math import floor
import numpy as np
@dataclassclass Wall: y: int gap: float = 0. speed: float = 1.
class TwholsEnvironment: score_cap = 100
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x = self.y = 50. self.vx = self.vy = 1 self.walls = [Wall(9), Wall(79)] self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action turn = self.action == 5 and previous != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(turn and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _advance(self, turn): self.x += self.vx self.y += self.vy reward = 0 for wall in self.walls: if wall.y - 2.5 < self.y < wall.y + 7.5 and ( self.x - 2.5 < wall.gap or self.x + 2.5 > wall.gap + 40 ): self.vy = 1 if self.y < 50 else -1 reward = 1 wall.gap -= wall.speed if wall.gap < -40: wall.gap = 99 wall.speed = self.random.uniform(1, 2) if turn or self.x < 0 or self.x > 99: self.vx *= -1 self.terminal = self.y < 0 or self.y > 99 return reward
def state(self): state = np.zeros((10, 10, 6), dtype=bool) row, col = (min(9, max(0, floor(value / 10))) for value in (self.y, self.x)) state[row, col, 0] = True cols = np.arange(5, 100, 10) for wall in self.walls: wall_row = (wall.y + 2) // 10 gap = (cols >= wall.gap) & (cols < wall.gap + 40) state[wall_row, :, 1] = ~gap state[wall_row, :, 2] = gap state[row, col, 3] = self.vx > 0 state[row, col, 4] = self.vy > 0 values = (self.steps, self.action, round((self.walls[0].gap + 40) * 3), round((self.walls[1].gap + 40) * 3), *(round(wall.speed * 100) for wall in self.walls)) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130from dataclasses import dataclass
import numpy as np
@dataclassclass Jumper: x: float y: float = 70. vx: int = 1 vy: float = 0. grace: int = 0
@dataclassclass Platform: x: float y: float width: float
class TwinJumpersEnvironment: score_cap = 1000
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.jumpers = [Jumper(20), Jumper(80)] self.platforms = [Platform(50, 80, 100)] for y in (70, 40, 10): for low in (0, 60): self.platforms.append(Platform(self.random.uniform(low, low + 40), y, self.random.uniform(20, 50))) self.power = 1. self.platform_distance = 0. self.steps = self.action = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action jump = self.action == 5 and previous != 5 self.steps += 1 reward = 0. for frame in range(4): reward += self._advance(jump and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return reward, self.terminal
def _advance(self, jump): scroll = 0.1 + max(0, 60 - max(jumper.y for jumper in self.jumpers)) * 0.05 if jump: for jumper, strength in zip(self.jumpers, (3, 2.5), strict=True): if jumper.grace > 0: jumper.vy = -strength * self.power self.power *= 0.8 else: self.power = min(1, self.power + 0.01)
previous_y = [jumper.y for jumper in self.jumpers] for jumper in self.jumpers: jumper.y += jumper.vy jumper.vy += 0.1 if self.action == 5 else 0.2 jumper.x += jumper.vx * 0.6 jumper.grace = max(0, jumper.grace - 1) if (jumper.x < 3 and jumper.vx < 0) or (jumper.x > 97 and jumper.vx > 0): jumper.vx *= -1 if jumper.y < 0 and jumper.vy < 0: jumper.y = 0 jumper.vy *= -0.5
for platform in self.platforms: platform.y += scroll self.platforms = [platform for platform in self.platforms if platform.y <= 109] self.platform_distance -= scroll if self.platform_distance <= 0: for low in (0, 50): self.platforms.append(Platform(self.random.uniform(low, low + 50), -self.random.uniform(5, 25), self.random.uniform(30, 50))) self.platform_distance = self.random.uniform(20, 30) for jumper, old_y, offset in zip(self.jumpers, previous_y, (4, 3), strict=True): if jumper.vy <= 0: continue supports = [ platform.y - offset for platform in self.platforms if abs(platform.x - jumper.x) < platform.width / 2 + 2 and min(jumper.y - 2, old_y - scroll) <= platform.y - offset <= jumper.y + 1 ] if supports: jumper.y = min(supports) jumper.vy = 0. jumper.grace = 9 self.terminal = any(jumper.y > 102 for jumper in self.jumpers) return scroll
def state(self): state = np.zeros((10, 10, 6), dtype=bool) for index, jumper in enumerate(self.jumpers): row = int(np.clip(jumper.y // 10, 0, 9)) col = int(jumper.x // 10) state[row, col, index] = True state[row, col, 3 + index] = jumper.grace > 0 cols = np.arange(5, 100, 10) for platform in self.platforms: if 0 <= platform.y < 100: state[int(platform.y // 10), :, 2] |= abs(cols - platform.x) < platform.width / 2 + 5 values = (self.steps, self.action, round(self.power * 100), round(self.platform_distance * 10), *(value for jumper in self.jumpers for value in (jumper.vx > 0, jumper.grace, round((jumper.vy + 4) * 32)))) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140from dataclasses import dataclassfrom math import cos, hypot, pi, sin
import numpy as np
@dataclassclass Target: x: float y: float vx: float vy: float hazard: bool = False entered: bool = False
class TwinPEnvironment: score_cap = 200
def __init__(self, sticky_action_prob=0.1, horizon=400): self.sticky_action_prob = sticky_action_prob self.horizon = min(horizon, 400) self.seed(0) self.reset()
def seed(self, seed): self.random = np.random.default_rng(seed)
def reset(self): self.x, self.y, self.angle = 40., 50., 0. self.length = self.target_length = 15. self.targets = [] self.timer = 0. self.until_hazard = 9 self.multiplier = 1 self.action = self.steps = 0 self.terminal = False
@classmethod def normalize_score(cls, score): return min(max(score, 0), cls.score_cap) / cls.score_cap
def act(self, action): if self.terminal: return 0., True previous = self.action if self.random.random() >= self.sticky_action_prob: self.action = action pin = previous == 5 and self.action != 5 self.steps += 1 reward = 0 for frame in range(4): reward += self._advance(pin and frame == 0) if self.terminal: break self.terminal |= self.steps >= self.horizon return float(reward), self.terminal
def _endpoint(self): return self.x + cos(self.angle) * self.length, self.y + sin(self.angle) * self.length
def _advance(self, pin): end_x, end_y = self._endpoint() if not (_inside(self.x, self.y) or _inside(end_x, end_y)): self.terminal = True return 0
dx, dy = end_x - self.x, end_y - self.y start_x, start_y = self.x, self.y if pin: self.x, self.y = end_x, end_y self.angle += pi self.target_length = 15. elif self.action == 5: self.target_length = min(99, self.target_length + 0.2) self.angle = (self.angle + 0.05) % (2 * pi) self.length += (self.target_length - self.length) * 0.2
self.timer -= 1 if self.timer < 0: self._spawn() reward = 0 remaining = [] for target in self.targets: target.x += target.vx target.y += target.vy if -5 <= target.x < 105 and -5 <= target.y < 105: target.entered = True elif target.entered: if not target.hazard: self.multiplier = max(1, self.multiplier - 1) continue rx, ry = target.x - start_x, target.y - start_y along = min(1, max(0, (rx * dx + ry * dy) / (dx * dx + dy * dy))) if hypot(rx - along * dx, ry - along * dy) <= (3.5 if target.hazard else 3): if target.hazard: self.terminal = True else: reward += self.multiplier self.multiplier += 1 continue remaining.append(target) self.targets = remaining return reward
def _spawn(self): angle = self.random.uniform(0, 2 * pi) x, y = 50 + cos(angle) * 80, 50 + sin(angle) * 80 dx, dy = self.random.uniform(20, 80, 2) - (x, y) scale = 0.2 / hypot(dx, dy) self.targets.append(Target(x, y, dx * scale, dy * scale, self.until_hazard == 0)) self.until_hazard -= 1 if self.until_hazard < 0: self.until_hazard = int(self.random.integers(8, 12)) self.timer = self.random.uniform(60, 90)
def state(self): state = np.zeros((10, 10, 6), dtype=bool) end_x, end_y = self._endpoint() _mark(state, self.x, self.y, 0) _mark(state, end_x, end_y, 1) for x, y in zip(np.linspace(self.x, end_x, 41), np.linspace(self.y, end_y, 41), strict=True): _mark(state, x, y, 2) for target in self.targets: _mark(state, target.x, target.y, 4 if target.hazard else 3) values = (self.steps, self.action, round(self.length * 4), round(self.target_length * 4), round(self.angle * 64), self.multiplier, self.until_hazard) for row, value in enumerate(values): for bit in range(9): state[row, bit, 5] = bool(value & (1 << bit)) return state
def _inside(x, y): return 0 <= x < 99 and 0 <= y < 99
def _mark(state, x, y, channel): if 0 <= x < 100 and 0 <= y < 100: state[int(y // 10), int(x // 10), channel] = Trueruntime/minatar_synth/games/smoke_g.pyAdded+167
runtime/minatar_synth/games/snake1.pyAdded+94
runtime/minatar_synth/games/snaky.pyAdded+137
runtime/minatar_synth/games/solaris.pyAdded+269
runtime/minatar_synth/games/spearain.pyAdded+113
runtime/minatar_synth/games/spin_cell.pyAdded+130
runtime/minatar_synth/games/splitzig.pyAdded+129
runtime/minatar_synth/games/square_bar.pyAdded+156
runtime/minatar_synth/games/stage_separation.pyAdded+121
runtime/minatar_synth/games/star_eater.pyAdded+124
runtime/minatar_synth/games/star_gunner.pyAdded+218
runtime/minatar_synth/games/stillfire_choir.pyAdded+131
runtime/minatar_synth/games/stomping_bubbles.pyAdded+128
runtime/minatar_synth/games/stompshelter.pyAdded+157
runtime/minatar_synth/games/stormveil.pyAdded+113
runtime/minatar_synth/games/sub_jump.pyAdded+133
runtime/minatar_synth/games/sum_ten.pyAdded+114
runtime/minatar_synth/games/sunflower_sway.pyAdded+113
runtime/minatar_synth/games/survivor.pyAdded+166
runtime/minatar_synth/games/swingby.pyAdded+129
runtime/minatar_synth/games/switchboard.pyAdded+143
runtime/minatar_synth/games/t_hanoi.pyAdded+104
runtime/minatar_synth/games/t_lanes.pyAdded+154
runtime/minatar_synth/games/t_laser.pyAdded+143
runtime/minatar_synth/games/t_punch.pyAdded+146
runtime/minatar_synth/games/tape_j.pyAdded+158
runtime/minatar_synth/games/tappump.pyAdded+110
runtime/minatar_synth/games/tarutobi.pyAdded+104
runtime/minatar_synth/games/tectonic_tether.pyAdded+157
runtime/minatar_synth/games/teeter.pyAdded+153
runtime/minatar_synth/games/tennis.pyAdded+224
runtime/minatar_synth/games/throw_m.pyAdded+131
runtime/minatar_synth/games/thrust_lr.pyAdded+113
runtime/minatar_synth/games/thunder.pyAdded+160
runtime/minatar_synth/games/tilted.pyAdded+186
runtime/minatar_synth/games/timber_test.pyAdded+97
runtime/minatar_synth/games/time_pilot.pyAdded+263
runtime/minatar_synth/games/tongue_hunter.pyAdded+135
runtime/minatar_synth/games/tornado_twister.pyAdded+153
runtime/minatar_synth/games/totoge.pyAdded+125
runtime/minatar_synth/games/tr_beam.pyAdded+169
runtime/minatar_synth/games/trojan_defense.pyAdded+144
runtime/minatar_synth/games/tt_fence.pyAdded+151
runtime/minatar_synth/games/turbo_tunnel.pyAdded+136
runtime/minatar_synth/games/turbulent.pyAdded+167
runtime/minatar_synth/games/turtle_tide.pyAdded+104
runtime/minatar_synth/games/tutankham.pyAdded+226
runtime/minatar_synth/games/twhols.pyAdded+90
runtime/minatar_synth/games/twin_jumpers.pyAdded+130
runtime/minatar_synth/games/twin_p.pyAdded+140