-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.py
294 lines (250 loc) · 8.55 KB
/
demo.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
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
from typing import Callable, Optional, List, Union
import time
import os
import json
import pprint
import pygame
import numpy as np
from masurvival.envs.masurvival_env import MaSurvival
class MultiAgentPolicy:
def act(self, observations):
raise NotImplementedError
class RandomPolicy(MultiAgentPolicy):
def __init__(self, env):
self.action_space = env.action_space
def act(self, observations):
return self.action_space.sample()
def zero_action():
return [1, 1, 1, 0, 0, 0]
def get_action_from_keyboard(last_pressed):
keyboard = pygame.key.get_pressed()
#TODO update this with correct null actions
action = zero_action()
if keyboard[pygame.K_w] and not keyboard[pygame.K_s]:
action[0] = 2
if keyboard[pygame.K_s] and not keyboard[pygame.K_w]:
action[0] = 0
if keyboard[pygame.K_a] and not keyboard[pygame.K_d]:
action[1] = 2
if keyboard[pygame.K_d] and not keyboard[pygame.K_a]:
action[1] = 0
if keyboard[pygame.K_LEFT] and not keyboard[pygame.K_RIGHT]:
action[2] = 2
if keyboard[pygame.K_RIGHT] and not keyboard[pygame.K_LEFT]:
action[2] = 0
if keyboard[pygame.K_c] and not last_pressed[pygame.K_c]:
action[3] = 1
if keyboard[pygame.K_e] and not last_pressed[pygame.K_e]:
action[4] = 1
if keyboard[pygame.K_q] and not last_pressed[pygame.K_q]:
action[5] = 1
return action, keyboard
controls_doc = """Keyboard controls:
W,A,S,D: parallel and normal movement
LEFT,RIGHT: angular movement
C: attack
E: use item (last picked up)
Q: give item (last picked up)
-------------
"""
class HumanPolicy(MultiAgentPolicy):
def __init__(self, env):
self.action_space = env.action_space
self.n_agents = env.n_agents
def act(self, observations):
actions = self.action_space.sample()
user_action, self.pressed = get_action_from_keyboard(self.pressed)
if self.n_agents >= 2:
actions = (user_action,) + actions[1:]
elif self.n_agents == 1:
actions = (user_action,)
return actions
def demo_env(
env,
policy: str = 'random', # either 'random' or 'interactive'
max_steps: Optional[int] = None,
render: bool = False,
record: Optional[Callable[[int, np.ndarray], None]] = None,
print_benchmark: bool = False,
) -> None:
"""Run a demo of the environment.
If max_steps is None, the environment is ran for one episode.
Otherwise, the environment is ran either until the episode is done
or until max_steps steps have been performed, whichever occurs
first.
If policy == "interactive", the environment always gets rendered in
a window ("human" render mode), regardless of the value of render.
Otherwise, the value of render controls whether to render to a
window or not.
If record is not None, it forces the environment to render each
state and is called after each render with two arguments:
- t: the number of environment steps performed
- frame: the frame of the rendered environment state (as a numpy
array)
Note that the environment is rendered after the initial environment
reset and after each step. The render mode will be rgb_array if the
human render mode is not forced in any other way.
"""
interactive = policy == 'interactive'
if interactive:
print(controls_doc)
policy = HumanPolicy(env)
else:
assert policy == 'random'
policy = RandomPolicy(env)
render_mode = None
if record is not None:
render_mode = 'rgb_array'
if interactive or render:
render_mode = 'human'
times = None if not print_benchmark else []
t, observation, done = 0, env.reset(), False
def render():
if render_mode is not None:
frame = env.render(mode=render_mode)
if record is not None:
record(t, frame)
render()
if interactive:
policy.pressed = pygame.key.get_pressed()
while not done:
action = policy.act(observation)
t_start = time.process_time()
observation, reward, done, info = env.step(action)
t_end = time.process_time()
t += 1
if times is not None:
times.append(t_end - t_start)
render()
if max_steps is not None and t == max_steps:
print(f'Maximum number of steps {t} reached, terminating episode.')
break
print('Episode complete. Stats printed below.')
stats = env.flush_stats()
env.close()
pprint.PrettyPrinter().pprint(stats)
if print_benchmark:
times = np.array(times)
print(f'Performance test results: {times.mean()}, {times.std()}')
return
# Script stuff
def main(
policy: str,
max_steps: int,
env_config_fpath: Optional[str],
render: bool,
screenshot_fpath: Optional[str],
screenshot_step: int,
gif_fpath: Optional[str],
gif_record_interval: int,
print_benchmark: bool,
):
if env_config_fpath is not None:
with open(env_config_fpath) as f:
config = json.load(f)
env = MaSurvival(config=config)
else:
env = MaSurvival()
recording = dict(screenshot=None, gif=None if gif_fpath is None else [])
def record(t, frame):
if screenshot_fpath is not None and t == screenshot_step:
recording['screenshot'] = frame
if gif_fpath is not None and t % gif_record_interval == 0:
recording['gif'].append(frame)
demo_env(
env,
policy=policy,
max_steps=max_steps,
render=render,
record=record,
print_benchmark=print_benchmark,
)
if screenshot_fpath is not None:
import imageio
print(f'Saving screenshot to {screenshot_fpath}.')
imageio.imsave(screenshot_fpath, recording['screenshot'])
if gif_fpath is not None:
import imageio
from pygifsicle import optimize
with imageio.get_writer(gif_fpath, mode='I') as writer:
for frame in recording['gif']:
writer.append_data(frame)
optimize(gif_fpath)
argparse_desc = \
'Test the environment for one episode, either '
'interactively or with a random policy.'
argparse_args = [
(['policy'], dict(
metavar='POLICY',
type=str,
default='random',
nargs='?',
choices=['random', 'interactive'],
help='The policy to use for testing, either "random" or "interactive".',
)),
(['--max-steps'], dict(
dest='max_steps',
metavar='STEPS',
type=int,
default=None,
help='Run only for the given amount of steps.'
)),
(['-c', '--config'], dict(
dest='env_config_fpath',
metavar='PATH',
type=str,
default=None,
help='Use the given JSON file as the env configuration.'
)),
(['-r', '--render'], dict(
action='store_true',
dest='render',
default=False,
help='Whether to render to a window (when the policy is not interactive).',
)),
(['-s', '--screenshot'], dict(
dest='screenshot_fpath',
metavar='PATH',
type=str,
default=None,
help='Record a frame of the episode to the given file. Which frame is recorded can be controlled with --screenshot-step.'
)),
(['--screenshot-step'], dict(
dest='screenshot_step',
metavar='STEP',
type=int,
default=0,
help='Control which step gets recorded by --screenshot (0 corresponds to the frame rendered before the first step).'
)),
(['-g', '--gif'], dict(
dest='gif_fpath',
metavar='PATH',
type=str,
default=None,
help='Record a GIF to the given file. The gif framerate can be controlled with --gif-record-interval.'
)),
(['--gif-record-interval'], dict(
dest='gif_record_interval',
metavar='N',
type=int,
default=10,
help='The interval (in number of steps) between each frame of the gif recorded with --gif.'
)),
(['--benchmark'], dict(
dest='print_benchmark',
action='store_true',
default=False,
help='Print benchmark information at the end of the episode.'
)),
]
if __name__ == '__main__':
import argparse
argparser = argparse.ArgumentParser(
description=argparse_desc,
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
for args, kwargs in argparse_args:
argparser.add_argument(*args, **kwargs)
cli_args = argparser.parse_args()
#print(vars(cli_args))
main(**vars(cli_args))