Repository navigation
Expand file tree
/
Copy pathenv.py
More file actions
353 lines (296 loc) · 12.5 KB
/
Copy pathenv.py
File metadata and controls
353 lines (296 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import enum
from typing import Any, Tuple
import gymnasium as gym
from gymnasium import spaces
import numpy as np
import gameState
from game import Game
import typing
import math
import walls
import pygame
pygame.init()
class Display:
SCALE = 20
ROWS = 31
COLS = 28
class Shape(enum.Enum):
CIRCLE = 0
SQUARE = 1
def __init__(self, surface=None):
size = (Display.SCALE * Display.COLS, Display.SCALE * Display.ROWS)
if surface is None:
self.window = pygame.display.set_mode(size)
else:
self.window = surface
def drawItem(
self,
window: pygame.Surface,
color: typing.Tuple[float],
position: typing.Tuple[int],
shape: Shape,
scale=1,
):
row, col = position
x, y = col * Display.SCALE, row * Display.SCALE
width = height = Display.SCALE * scale
centerX, centerY = x + Display.SCALE / 2, y + Display.SCALE / 2
if shape == Display.Shape.CIRCLE:
pygame.draw.circle(
window, color, (centerX, centerY), Display.SCALE / 2 * scale
)
if shape == Display.Shape.SQUARE:
pygame.draw.rect(
window,
color,
pygame.rect.Rect(
centerX - width / 2, centerY - height / 2, width, height
),
)
def drawItems(self, window: pygame.surface.Surface, state: gameState.GameState):
for row in range(Display.ROWS):
for col in range(Display.COLS):
pos = (row, col)
config = None
if state.wallAt(*pos):
config = (0, 0, 150), 1, Display.Shape.SQUARE
if state.pelletAt(*pos):
config = (100, 100, 100), 0.5, Display.Shape.CIRCLE
if state.superPelletAt(*pos):
config = (255, 255, 255), 0.75, Display.Shape.CIRCLE
if state.fruitAt(*pos):
config = (255, 0, 0), 0.5, Display.Shape.CIRCLE
if config is None:
continue
color, scale, shape = config
self.drawItem(window, color, pos, shape, scale)
def drawEntities(self, window: pygame.surface.Surface, state: gameState.GameState):
ghostColors = ((255, 0, 0), (255, 100, 100), (100, 100, 255), (255, 100, 0))
freightened = (0, 0, 255)
for ghost in state.ghosts:
color = None
pos = ghost.location.row, ghost.location.col
if ghost.isFrightened():
color = freightened
else:
color = ghostColors[ghost.color]
self.drawItem(window, color, pos, Display.Shape.CIRCLE, 1)
pos = state.pacmanLoc.row, state.pacmanLoc.col
color = (255, 255, 0)
self.drawItem(window, color, pos, Display.Shape.CIRCLE, 1)
def render(self, state):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
self.window.fill((0, 0, 0))
self.drawItems(self.window, state)
self.drawEntities(self.window, state)
pygame.display.update()
TIME_PER_TICK = 1.5
MOVEMENT_TICK = 6
class MotionProfilePacman(gym.Env):
metadata = {"render_modes": ["human"], "render_fps": 60}
def __init__(self, render_mode):
self.screen = pygame.display.set_mode(
(Display.SCALE * Display.COLS, Display.SCALE * Display.ROWS)
)
if render_mode == "human":
self.display = Display(self.screen)
self.render_mode = render_mode
self.game = Game()
self.action = self.game.Action
self.last_score = 0
self.observation_space = spaces.Dict(
{
"pacbot_position": spaces.MultiDiscrete([33, 33]),
"pink_ghost_position": spaces.MultiDiscrete([33, 33]),
"blue_ghost_position": spaces.MultiDiscrete([33, 33]),
"orange_ghost_position": spaces.MultiDiscrete([33, 33]),
"red_ghost_position": spaces.MultiDiscrete([33, 33]),
"pink_ghost_frightened_step": spaces.Discrete(41),
"blue_ghost_frightened_step": spaces.Discrete(41),
"orange_ghost_frightened_step": spaces.Discrete(41),
"red_ghost_frightened_step": spaces.Discrete(41),
"cherry_on": spaces.Discrete(2),
}
)
# self.action_space = spaces.MultiDiscrete(
# [26, 5]
# ) # (dist,direction), direction is same as ENUM
self.action_space = spaces.Discrete(130)
# Motion constants
self.max_vel = 3 # 3 blocks per second, placeholder
self.max_accel = 1 # 1 block per second per second, placeholder
self.currTime = 0.0
# self.vec_motion_profile = np.vectorize(
# self.motion_profile, excluded={"self", "start", "end"}
# )
self.last_lives = 3
def reset(self, *args, **kwargs) -> Tuple[Any, dict]:
self.game.reset()
self.game.update()
obs = self._get_obs()
self.visited_positions = set()
return (obs, {})
def motion_profile(self, start: int, end: int, pos: int) -> float:
"""Receives the start position, end position, and the desired position. Outputs the real time when the bot arrives at that position"""
# See the Pacbot Potential RL Model Discussion google doc, simulation requirement section for more information about the equations used
# Most of these are just newton's motion equations
if pos > end or pos < start:
raise RuntimeError("position out of range")
length = end - start
if length < 0:
raise ValueError("Incorrect starting and end points")
if length <= self.max_vel**2 / self.max_accel:
v_cap = math.sqrt(length * self.max_accel)
# triangular profile because the distance is too short
if pos <= length / 2:
return math.sqrt((2 * pos) / self.max_accel)
half_t = math.sqrt(length / self.max_accel)
# pos = (end+start)/2 + vt - 1/2at^2, -1/2at^2 + vt + ((end+start)/2 - pos) = 0, 1/2at^2 - vt + (pos - (end+start)/2) = 0
temp = v_cap**2 - 4 * (0.5) * self.max_accel * (pos - (end + start) / 2)
if temp < -1e-5:
raise ValueError("Negative squareroot value")
else:
temp = abs(round(temp, 8))
remaining_t = v_cap - math.sqrt(temp) / self.max_accel
return half_t + remaining_t
# trapezoidal motion profile
if pos <= 0.5 * self.max_vel**2 / self.max_accel:
return math.sqrt((2 * pos) / self.max_accel)
if pos <= length - 0.5 * self.max_vel**2 / self.max_accel:
init_t = self.max_vel / self.max_accel
remaining_t = (pos - 0.5 * self.max_vel**2 / self.max_accel) / self.max_vel
return init_t + remaining_t
init_t = self.max_vel / self.max_accel
const_vel_t = (length - self.max_vel**2 / self.max_accel) / self.max_vel
remaining_t = (
self.max_vel
- math.sqrt(
self.max_vel**2
- 4
* (0.5)
* self.max_accel
* (pos - (length - 0.5 * self.max_vel**2 / self.max_accel))
)
/ self.max_accel
)
return init_t + const_vel_t + remaining_t
def max_dist_in_dir(self, dist: int, dir: int):
if dir == self.action.NONE:
return 0
pacloc = self.game.state.pacmanLoc
if pacloc.row == 32:
return 0 # not checking for columns because when it shifts out of bounds automatically equals to 0
for i in range(dist):
match dir:
case self.action.UP:
if walls.get(pacloc.row - i, pacloc.col):
return i - 1
case self.action.DOWN:
if walls.get(pacloc.row + i, pacloc.col):
return i - 1
case self.action.LEFT:
if walls.get(pacloc.row, pacloc.col - i):
return i - 1
case self.action.RIGHT:
if walls.get(pacloc.row, pacloc.col + i):
return i - 1
return 0
def step(self, action: Tuple[int, int]) -> Tuple[Any, float, bool, bool, dict]:
"""
old version:action should be a target location in format (row, col)
new versoin:action shoudl be (dist,dir)
"""
# dist, direction_idx = action
direction_idx = int(action % 5)
dist = int(action // 5)
action_dir = [e for e in self.action][direction_idx]
# move_dist = self.max_dist_in_dir(action[0],action_dir)
# if move_dist == None or move_dist <= 0:
# observation = self._get_obs()
# reward = self._get_reward()
# done = self.game.state.currLives <= 0
# return observation, reward, done, False, {}
# print(move_dist)
# pos_list = np.linspace(1, move_dist, move_dist)
# t_list = self.vec_motion_profile(
# 0, move_dist, pos_list
# ) # use broadcasting to vectorize and speed things up
# t_list[1:] -= t_list[:-1] # get time difference between each time stamp
# for t in t_list:
# last_tick = math.floor(self.currTime / TIME_PER_TICK)
# new_tick = math.floor((self.currTime + t) / TIME_PER_TICK)
# for i in range(round(new_tick - last_tick)):
# self.game.update()
# self.game.step([action_dir])
# self.currTime += t
# if self.render_mode == "human":
# self.render()
# #time.sleep(0.5) # Only for debugging
for i in range(MOVEMENT_TICK):
self.game.update()
self.game.step([action_dir])
if self.render_mode == "human":
self.render()
observation = self._get_obs()
reward = self._get_reward()
done = self.game.state.currLives <= 0
info = {}
if done:
info["terminal_observation"] = observation
# print(observation)
return observation, reward, done, False, info
def _get_obs(self):
# self.state.update(ctypes.cast(self.obs_func(), ctypes.POINTER(ctypes.c_byte * 159)).contents)
state = self.game.state
ghosts = state.ghosts
return {
"pacbot_position": np.array(
[state.pacmanLoc.row, state.pacmanLoc.col], dtype=np.int64
),
"red_ghost_position": np.array(
[ghosts[0].location.row, ghosts[0].location.col], dtype=np.int64
),
"pink_ghost_position": np.array(
[ghosts[1].location.row, ghosts[1].location.col], dtype=np.int64
),
"blue_ghost_position": np.array(
[ghosts[2].location.row, ghosts[2].location.col], dtype=np.int64
),
"orange_ghost_position": np.array(
[ghosts[3].location.row, ghosts[3].location.col], dtype=np.int64
),
"red_ghost_frightened_step": int(ghosts[0].frightSteps),
"pink_ghost_frightened_step": int(ghosts[1].frightSteps),
"blue_ghost_frightened_step": int(ghosts[2].frightSteps),
"orange_ghost_frightened_step": int(ghosts[3].frightSteps),
"cherry_on": int(state.fruitSteps > 0),
}
def _get_reward(self):
new_score = self.game.state.currScore
reward = float(new_score - self.last_score)
self.last_score = new_score
current_lives = self.game.state.currLives
if current_lives < self.last_lives: # If lives decreased
reward -= 50
self.last_lives = current_lives
pos = (self.game.state.pacmanLoc.row, self.game.state.pacmanLoc.col)
if pos not in self.visited_positions:
reward += 0.1
self.visited_positions.add(pos)
actual_score_gain = float(new_score - self.last_score)
if actual_score_gain > 0:
reward += actual_score_gain * 2
reward -= 0.01
return reward
def render(self):
self.display.render(self.game.state)
def _get_frame(self):
# Get the pixel array from the screen
return pygame.surfarray.array3d(self.screen)
def close(self):
# Close the environment and clean up resources
self.reset()
if __name__ == "__main__":
pass