neilkale commited on
Commit
cb8d15e
·
verified ·
1 Parent(s): 7248ace

Publish WeightProgramBench: 317 training games and 5 held-out MinAtar tasks (part 2)

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