-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.py
208 lines (160 loc) · 6.37 KB
/
env.py
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
# import gymnasium as gym
# from gymnasium import spaces
# from gymnasium.envs.registration import register
import gym
from gym import spaces
from gym.envs.registration import register
import pygame
import numpy as np
import random
from objects_manager import ObjectsManager
from player import Player, PlayerAction
from missile import Missile
class SpaceInvaders2Env(gym.Env):
metadata = {"render_modes": ["human", "rgb_array", "simple_array"]}
window_size = 720
observation_size = window_size // 10
observation_shape = (observation_size, observation_size)
fps_limit = 10
def __init__(self, render_mode=None):
if render_mode == "simple_array":
shape = (self.observation_size, self.observation_size)
self.observation_space = spaces.Box(0, 255, shape, np.float32)
else:
shape = (self.observation_size, self.observation_size, 3)
self.observation_space = spaces.Box(0, 255, shape, np.float32)
self.action_space = spaces.Discrete(2)
self.__action_mapping = {
#0: PlayerAction.STAY,
0: PlayerAction.LEFT,
1: PlayerAction.RIGHT,
}
assert render_mode is None or render_mode in self.metadata["render_modes"]
self.render_mode = render_mode
self.__window = None
self.__clock = None
self.__canvas = None
self.__enemies_spawn_interval = 1.0
self.__time_since_last_spawn = self.__enemies_spawn_interval
self.__enemies_to_spawn = 5
self.__timeout = 20
self.__timeout_reached = False
@staticmethod
def create_human_game():
env = SpaceInvaders2Env("human")
env.reset()
return env
def __get_state(self):
new_canvas = pygame.Surface(self.observation_shape)
pygame.transform.scale(self.__canvas, self.observation_shape, new_canvas)
if self.render_mode == "simple_array":
return pygame.surfarray.pixels3d(new_canvas).transpose(1, 0, 2)[:, :, 2].astype('float32')
else:
return pygame.surfarray.pixels3d(new_canvas).transpose(1, 0, 2)
#return self.__get_frame_as_array().astype('float32')
def __get_frame_as_array(self):
return pygame.surfarray.pixels3d(self.__canvas).transpose(1, 0, 2)
def __get_info(self):
return {}
def reset(self, seed=None, options=None):
#super().reset(seed=seed)
pygame.init()
if self.render_mode == "human":
self.__window = pygame.display.set_mode((self.window_size, self.window_size))
self.__clock = pygame.time.Clock()
self.__running = True
self.__dt = 0
self.__time_since_last_spawn = self.__enemies_spawn_interval
self.__timeout = 20
self.__timeout_reached = False
player = Player((self.window_size, self.window_size))
objects = ObjectsManager(pygame.Rect(0, 0, self.window_size, self.window_size))
objects.add_player(player)
self.__objects = objects
self.__spawn_random_enemies(200)
self.__render_frame()
observation = self.__get_state()
info = self.__get_info()
return observation #, info
def __spawn_random_enemies(self, height=10):
left_limit = 10
right_limit = self.window_size - 10
for _ in range(self.__enemies_to_spawn):
#x = self.np_random.integers(left_limit, right_limit)
x = random.randint(left_limit, right_limit)
self.__objects.add_enemy_object(Missile((x, height)))
self.__objects.add_enemy_object(Missile((left_limit, height)))
self.__objects.add_enemy_object(Missile((right_limit, height)))
def __frame_step(self, action):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.__running = False
self.__objects.update(self.__dt, action)
self.__time_since_last_spawn += self.__dt
if self.__time_since_last_spawn > self.__enemies_spawn_interval:
self.__time_since_last_spawn -= self.__enemies_spawn_interval
self.__spawn_random_enemies()
if self.__objects.does_player_collide():
self.__running = False
if self.render_mode == "human":
self.__dt = self.__clock.tick(self.fps_limit) / 1000
else:
self.__dt = 1 / self.fps_limit
self.__timeout -= self.__dt
if self.__timeout < 0:
self.__running = False
self.__timeout_reached = True
def run_human_game(self):
assert self.render_mode == "human"
while self.__running:
action = PlayerAction.STAY
keys = pygame.key.get_pressed()
if keys[pygame.K_a] or keys[pygame.K_LEFT]:
action = PlayerAction.LEFT
if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
action = PlayerAction.RIGHT
self.__frame_step(action)
self.__render_frame()
self.close()
def step(self, action=0):
if self.__running:
self.__frame_step(self.__action_mapping[action])
terminated = not self.__running
if self.__timeout_reached:
reward = 0
elif terminated:
reward = -10
else:
reward = 1
#reward = 0 if terminated else 1
if self.render_mode == "human":
self.__render_frame()
observation = self.__get_state()
info = self.__get_info()
#return observation, reward, terminated, False, info
return observation, reward, terminated, info
def render(self, mode, **kwargs):
#print(mode, self.render_mode, kwargs)
if self.render_mode == "rgb_array":
return self.__render_frame()
def __render_frame(self):
canvas = pygame.Surface((self.window_size, self.window_size))
self.__canvas = canvas
#canvas.fill("cyan2")
canvas.fill("cyan4")
self.__objects.draw(canvas)
if self.render_mode == "human":
self.__window.blit(canvas, canvas.get_rect())
pygame.event.pump()
pygame.display.flip()
else:
return self.__get_frame_as_array()
def close(self):
self.__objects = None
self.__window = None
self.__clock = None
pygame.quit()
register(
id="games/SpaceInvaders-v2",
entry_point="env:SpaceInvaders2Env",
)