forked from Farama-Foundation/Minigrid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minigrid.py
1351 lines (1077 loc) · 36.9 KB
/
minigrid.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
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import gym
from enum import IntEnum
import numpy as np
from gym import error, spaces, utils
from gym.utils import seeding
# Size in pixels of a cell in the full-scale human view
CELL_PIXELS = 32
# Map of color names to RGB values
COLORS = {
'red' : np.array([255, 0, 0]),
'green' : np.array([0, 255, 0]),
'blue' : np.array([0, 0, 255]),
'purple': np.array([112, 39, 195]),
'yellow': np.array([255, 255, 0]),
'grey' : np.array([100, 100, 100])
}
COLOR_NAMES = sorted(list(COLORS.keys()))
# Used to map colors to integers
COLOR_TO_IDX = {
'red' : 0,
'green' : 1,
'blue' : 2,
'purple': 3,
'yellow': 4,
'grey' : 5
}
IDX_TO_COLOR = dict(zip(COLOR_TO_IDX.values(), COLOR_TO_IDX.keys()))
# Map of object type to integers
OBJECT_TO_IDX = {
'unseen' : 0,
'empty' : 1,
'wall' : 2,
'floor' : 3,
'door' : 4,
'key' : 5,
'ball' : 6,
'box' : 7,
'goal' : 8,
'lava' : 9,
'agent' : 10,
}
IDX_TO_OBJECT = dict(zip(OBJECT_TO_IDX.values(), OBJECT_TO_IDX.keys()))
# Map of state names to integers
STATE_TO_IDX = {
'open' : 0,
'closed': 1,
'locked': 2,
}
# Map of agent direction indices to vectors
DIR_TO_VEC = [
# Pointing right (positive X)
np.array((1, 0)),
# Down (positive Y)
np.array((0, 1)),
# Pointing left (negative X)
np.array((-1, 0)),
# Up (negative Y)
np.array((0, -1)),
]
class WorldObj:
"""
Base class for grid world objects
"""
def __init__(self, type, color):
assert type in OBJECT_TO_IDX, type
assert color in COLOR_TO_IDX, color
self.type = type
self.color = color
self.contains = None
# Initial position of the object
self.init_pos = None
# Current position of the object
self.cur_pos = None
def can_overlap(self):
"""Can the agent overlap with this?"""
return False
def can_pickup(self):
"""Can the agent pick this up?"""
return False
def can_contain(self):
"""Can this contain another object?"""
return False
def see_behind(self):
"""Can the agent see behind this object?"""
return True
def toggle(self, env, pos):
"""Method to trigger/toggle an action this object performs"""
return False
def render(self, r):
"""Draw this object with the given renderer"""
raise NotImplementedError
def _set_color(self, r):
"""Set the color of this object as the active drawing color"""
c = COLORS[self.color]
r.setLineColor(c[0], c[1], c[2])
r.setColor(c[0], c[1], c[2])
class Goal(WorldObj):
def __init__(self):
super().__init__('goal', 'green')
def can_overlap(self):
return True
def render(self, r):
self._set_color(r)
r.drawPolygon([
(0 , CELL_PIXELS),
(CELL_PIXELS, CELL_PIXELS),
(CELL_PIXELS, 0),
(0 , 0)
])
class Floor(WorldObj):
"""
Colored floor tile the agent can walk over
"""
def __init__(self, color='blue'):
super().__init__('floor', color)
def can_overlap(self):
return True
def render(self, r):
# Give the floor a pale color
c = COLORS[self.color]
r.setLineColor(100, 100, 100, 0)
r.setColor(*c/2)
r.drawPolygon([
(1 , CELL_PIXELS),
(CELL_PIXELS, CELL_PIXELS),
(CELL_PIXELS, 1),
(1 , 1)
])
class Lava(WorldObj):
def __init__(self):
super().__init__('lava', 'red')
def can_overlap(self):
return True
def render(self, r):
orange = 255, 128, 0
r.setLineColor(*orange)
r.setColor(*orange)
r.drawPolygon([
(0 , CELL_PIXELS),
(CELL_PIXELS, CELL_PIXELS),
(CELL_PIXELS, 0),
(0 , 0)
])
# drawing the waves
r.setLineColor(0, 0, 0)
r.drawPolyline([
(.1 * CELL_PIXELS, .3 * CELL_PIXELS),
(.3 * CELL_PIXELS, .4 * CELL_PIXELS),
(.5 * CELL_PIXELS, .3 * CELL_PIXELS),
(.7 * CELL_PIXELS, .4 * CELL_PIXELS),
(.9 * CELL_PIXELS, .3 * CELL_PIXELS),
])
r.drawPolyline([
(.1 * CELL_PIXELS, .5 * CELL_PIXELS),
(.3 * CELL_PIXELS, .6 * CELL_PIXELS),
(.5 * CELL_PIXELS, .5 * CELL_PIXELS),
(.7 * CELL_PIXELS, .6 * CELL_PIXELS),
(.9 * CELL_PIXELS, .5 * CELL_PIXELS),
])
r.drawPolyline([
(.1 * CELL_PIXELS, .7 * CELL_PIXELS),
(.3 * CELL_PIXELS, .8 * CELL_PIXELS),
(.5 * CELL_PIXELS, .7 * CELL_PIXELS),
(.7 * CELL_PIXELS, .8 * CELL_PIXELS),
(.9 * CELL_PIXELS, .7 * CELL_PIXELS),
])
class Wall(WorldObj):
def __init__(self, color='grey'):
super().__init__('wall', color)
def see_behind(self):
return False
def render(self, r):
self._set_color(r)
r.drawPolygon([
(0 , CELL_PIXELS),
(CELL_PIXELS, CELL_PIXELS),
(CELL_PIXELS, 0),
(0 , 0)
])
class Door(WorldObj):
def __init__(self, color, is_open=False, is_locked=False):
super().__init__('door', color)
self.is_open = is_open
self.is_locked = is_locked
def can_overlap(self):
"""The agent can only walk over this cell when the door is open"""
return self.is_open
def see_behind(self):
return self.is_open
def toggle(self, env, pos):
# If the player has the right key to open the door
if self.is_locked:
if isinstance(env.carrying, Key) and env.carrying.color == self.color:
self.is_locked = False
self.is_open = True
return True
return False
self.is_open = not self.is_open
return True
def render(self, r):
c = COLORS[self.color]
r.setLineColor(c[0], c[1], c[2])
r.setColor(c[0], c[1], c[2], 50 if self.is_locked else 0)
if self.is_open:
r.drawPolygon([
(CELL_PIXELS-2, CELL_PIXELS),
(CELL_PIXELS , CELL_PIXELS),
(CELL_PIXELS , 0),
(CELL_PIXELS-2, 0)
])
return
r.drawPolygon([
(0 , CELL_PIXELS),
(CELL_PIXELS, CELL_PIXELS),
(CELL_PIXELS, 0),
(0 , 0)
])
r.drawPolygon([
(2 , CELL_PIXELS-2),
(CELL_PIXELS-2, CELL_PIXELS-2),
(CELL_PIXELS-2, 2),
(2 , 2)
])
if self.is_locked:
# Draw key slot
r.drawLine(
CELL_PIXELS * 0.55,
CELL_PIXELS * 0.5,
CELL_PIXELS * 0.75,
CELL_PIXELS * 0.5
)
else:
# Draw door handle
r.drawCircle(CELL_PIXELS * 0.75, CELL_PIXELS * 0.5, 2)
class Key(WorldObj):
def __init__(self, color='blue'):
super(Key, self).__init__('key', color)
def can_pickup(self):
return True
def render(self, r):
self._set_color(r)
# Vertical quad
r.drawPolygon([
(16, 10),
(20, 10),
(20, 28),
(16, 28)
])
# Teeth
r.drawPolygon([
(12, 19),
(16, 19),
(16, 21),
(12, 21)
])
r.drawPolygon([
(12, 26),
(16, 26),
(16, 28),
(12, 28)
])
r.drawCircle(18, 9, 6)
r.setLineColor(0, 0, 0)
r.setColor(0, 0, 0)
r.drawCircle(18, 9, 2)
class Ball(WorldObj):
def __init__(self, color='blue'):
super(Ball, self).__init__('ball', color)
def can_pickup(self):
return True
def render(self, r):
self._set_color(r)
r.drawCircle(CELL_PIXELS * 0.5, CELL_PIXELS * 0.5, 10)
class Box(WorldObj):
def __init__(self, color, contains=None):
super(Box, self).__init__('box', color)
self.contains = contains
def can_pickup(self):
return True
def render(self, r):
c = COLORS[self.color]
r.setLineColor(c[0], c[1], c[2])
r.setColor(0, 0, 0)
r.setLineWidth(2)
r.drawPolygon([
(4 , CELL_PIXELS-4),
(CELL_PIXELS-4, CELL_PIXELS-4),
(CELL_PIXELS-4, 4),
(4 , 4)
])
r.drawLine(
4,
CELL_PIXELS / 2,
CELL_PIXELS - 4,
CELL_PIXELS / 2
)
r.setLineWidth(1)
def toggle(self, env, pos):
# Replace the box by its contents
env.grid.set(*pos, self.contains)
return True
class Grid:
"""
Represent a grid and operations on it
"""
def __init__(self, width, height):
assert width >= 3
assert height >= 3
self.width = width
self.height = height
self.grid = [None] * width * height
def __contains__(self, key):
if isinstance(key, WorldObj):
for e in self.grid:
if e is key:
return True
elif isinstance(key, tuple):
for e in self.grid:
if e is None:
continue
if (e.color, e.type) == key:
return True
if key[0] is None and key[1] == e.type:
return True
return False
def __eq__(self, other):
grid1 = self.encode()
grid2 = other.encode()
return np.array_equal(grid2, grid1)
def __ne__(self, other):
return not self == other
def copy(self):
from copy import deepcopy
return deepcopy(self)
def set(self, i, j, v):
assert i >= 0 and i < self.width
assert j >= 0 and j < self.height
self.grid[j * self.width + i] = v
def get(self, i, j):
assert i >= 0 and i < self.width
assert j >= 0 and j < self.height
return self.grid[j * self.width + i]
def horz_wall(self, x, y, length=None):
if length is None:
length = self.width - x
for i in range(0, length):
self.set(x + i, y, Wall())
def vert_wall(self, x, y, length=None):
if length is None:
length = self.height - y
for j in range(0, length):
self.set(x, y + j, Wall())
def wall_rect(self, x, y, w, h):
self.horz_wall(x, y, w)
self.horz_wall(x, y+h-1, w)
self.vert_wall(x, y, h)
self.vert_wall(x+w-1, y, h)
def rotate_left(self):
"""
Rotate the grid to the left (counter-clockwise)
"""
grid = Grid(self.height, self.width)
for i in range(self.width):
for j in range(self.height):
v = self.get(i, j)
grid.set(j, grid.height - 1 - i, v)
return grid
def slice(self, topX, topY, width, height):
"""
Get a subset of the grid
"""
grid = Grid(width, height)
for j in range(0, height):
for i in range(0, width):
x = topX + i
y = topY + j
if x >= 0 and x < self.width and \
y >= 0 and y < self.height:
v = self.get(x, y)
else:
v = Wall()
grid.set(i, j, v)
return grid
def render(self, r, tile_size):
"""
Render this grid at a given scale
:param r: target renderer object
:param tile_size: tile size in pixels
"""
assert r.width == self.width * tile_size
assert r.height == self.height * tile_size
# Total grid size at native scale
widthPx = self.width * CELL_PIXELS
heightPx = self.height * CELL_PIXELS
r.push()
# Internally, we draw at the "large" full-grid resolution, but we
# use the renderer to scale back to the desired size
r.scale(tile_size / CELL_PIXELS, tile_size / CELL_PIXELS)
# Draw the background of the in-world cells black
r.fillRect(
0,
0,
widthPx,
heightPx,
0, 0, 0
)
# Draw grid lines
r.setLineColor(100, 100, 100)
for rowIdx in range(0, self.height):
y = CELL_PIXELS * rowIdx
r.drawLine(0, y, widthPx, y)
for colIdx in range(0, self.width):
x = CELL_PIXELS * colIdx
r.drawLine(x, 0, x, heightPx)
# Render the grid
for j in range(0, self.height):
for i in range(0, self.width):
cell = self.get(i, j)
if cell == None:
continue
r.push()
r.translate(i * CELL_PIXELS, j * CELL_PIXELS)
cell.render(r)
r.pop()
r.pop()
def encode(self, vis_mask=None):
"""
Produce a compact numpy encoding of the grid
"""
if vis_mask is None:
vis_mask = np.ones((self.width, self.height), dtype=bool)
array = np.zeros((self.width, self.height, 3), dtype='uint8')
for i in range(self.width):
for j in range(self.height):
if vis_mask[i, j]:
v = self.get(i, j)
if v is None:
array[i, j, 0] = OBJECT_TO_IDX['empty']
array[i, j, 1] = 0
array[i, j, 2] = 0
else:
# State, 0: open, 1: closed, 2: locked
state = 0
if hasattr(v, 'is_open') and not v.is_open:
state = 1
if hasattr(v, 'is_locked') and v.is_locked:
state = 2
array[i, j, 0] = OBJECT_TO_IDX[v.type]
array[i, j, 1] = COLOR_TO_IDX[v.color]
array[i, j, 2] = state
return array
@staticmethod
def decode(array):
"""
Decode an array grid encoding back into a grid
"""
width, height, channels = array.shape
assert channels == 3
grid = Grid(width, height)
for i in range(width):
for j in range(height):
typeIdx, colorIdx, state = array[i, j]
if typeIdx == OBJECT_TO_IDX['unseen'] or \
typeIdx == OBJECT_TO_IDX['empty']:
continue
objType = IDX_TO_OBJECT[typeIdx]
color = IDX_TO_COLOR[colorIdx]
# State, 0: open, 1: closed, 2: locked
is_open = state == 0
is_locked = state == 2
if objType == 'wall':
v = Wall(color)
elif objType == 'floor':
v = Floor(color)
elif objType == 'ball':
v = Ball(color)
elif objType == 'key':
v = Key(color)
elif objType == 'box':
v = Box(color)
elif objType == 'door':
v = Door(color, is_open, is_locked)
elif objType == 'goal':
v = Goal()
elif objType == 'lava':
v = Lava()
else:
assert False, "unknown obj type in decode '%s'" % objType
grid.set(i, j, v)
return grid
def process_vis(grid, agent_pos):
mask = np.zeros(shape=(grid.width, grid.height), dtype=np.bool)
mask[agent_pos[0], agent_pos[1]] = True
for j in reversed(range(0, grid.height)):
for i in range(0, grid.width-1):
if not mask[i, j]:
continue
cell = grid.get(i, j)
if cell and not cell.see_behind():
continue
mask[i+1, j] = True
if j > 0:
mask[i+1, j-1] = True
mask[i, j-1] = True
for i in reversed(range(1, grid.width)):
if not mask[i, j]:
continue
cell = grid.get(i, j)
if cell and not cell.see_behind():
continue
mask[i-1, j] = True
if j > 0:
mask[i-1, j-1] = True
mask[i, j-1] = True
for j in range(0, grid.height):
for i in range(0, grid.width):
if not mask[i, j]:
grid.set(i, j, None)
return mask
class MiniGridEnv(gym.Env):
"""
2D grid world game environment
"""
metadata = {
'render.modes': ['human', 'rgb_array', 'pixmap'],
'video.frames_per_second' : 10
}
# Enumeration of possible actions
class Actions(IntEnum):
# Turn left, turn right, move forward
left = 0
right = 1
forward = 2
# Pick up an object
pickup = 3
# Drop an object
drop = 4
# Toggle/activate an object
toggle = 5
# Done completing task
done = 6
def __init__(
self,
grid_size=None,
width=None,
height=None,
max_steps=100,
see_through_walls=False,
seed=1337,
agent_view_size=7
):
# Can't set both grid_size and width/height
if grid_size:
assert width == None and height == None
width = grid_size
height = grid_size
# Action enumeration for this environment
self.actions = MiniGridEnv.Actions
# Actions are discrete integer values
self.action_space = spaces.Discrete(len(self.actions))
# Number of cells (width and height) in the agent view
self.agent_view_size = agent_view_size
# Observations are dictionaries containing an
# encoding of the grid and a textual 'mission' string
self.observation_space = spaces.Box(
low=0,
high=255,
shape=(self.agent_view_size, self.agent_view_size, 3),
dtype='uint8'
)
self.observation_space = spaces.Dict({
'image': self.observation_space
})
# Range of possible rewards
self.reward_range = (0, 1)
# Renderer object used to render the whole grid (full-scale)
self.grid_render = None
# Renderer used to render observations (small-scale agent view)
self.obs_render = None
# Environment configuration
self.width = width
self.height = height
self.max_steps = max_steps
self.see_through_walls = see_through_walls
# Current position and direction of the agent
self.agent_pos = None
self.agent_dir = None
# Initialize the RNG
self.seed(seed=seed)
# Initialize the state
self.reset()
def reset(self):
# Current position and direction of the agent
self.agent_pos = None
self.agent_dir = None
# Generate a new random grid at the start of each episode
# To keep the same grid for each episode, call env.seed() with
# the same seed before calling env.reset()
self._gen_grid(self.width, self.height)
# These fields should be defined by _gen_grid
assert self.agent_pos is not None
assert self.agent_dir is not None
# Check that the agent doesn't overlap with an object
start_cell = self.grid.get(*self.agent_pos)
assert start_cell is None or start_cell.can_overlap()
# Item picked up, being carried, initially nothing
self.carrying = None
# Step count since episode start
self.step_count = 0
# Return first observation
obs = self.gen_obs()
return obs
def seed(self, seed=1337):
# Seed the random number generator
self.np_random, _ = seeding.np_random(seed)
return [seed]
@property
def steps_remaining(self):
return self.max_steps - self.step_count
def __str__(self):
"""
Produce a pretty string of the environment's grid along with the agent.
A grid cell is represented by 2-character string, the first one for
the object and the second one for the color.
"""
# Map of object types to short string
OBJECT_TO_STR = {
'wall' : 'W',
'floor' : 'F',
'door' : 'D',
'key' : 'K',
'ball' : 'A',
'box' : 'B',
'goal' : 'G',
'lava' : 'V',
}
# Short string for opened door
OPENDED_DOOR_IDS = '_'
# Map agent's direction to short string
AGENT_DIR_TO_STR = {
0: '>',
1: 'V',
2: '<',
3: '^'
}
str = ''
for j in range(self.grid.height):
for i in range(self.grid.width):
if i == self.agent_pos[0] and j == self.agent_pos[1]:
str += 2 * AGENT_DIR_TO_STR[self.agent_dir]
continue
c = self.grid.get(i, j)
if c == None:
str += ' '
continue
if c.type == 'door':
if c.is_open:
str += '__'
elif c.is_locked:
str += 'L' + c.color[0].upper()
else:
str += 'D' + c.color[0].upper()
continue
str += OBJECT_TO_STR[c.type] + c.color[0].upper()
if j < self.grid.height - 1:
str += '\n'
return str
def _gen_grid(self, width, height):
assert False, "_gen_grid needs to be implemented by each environment"
def _reward(self):
"""
Compute the reward to be given upon success
"""
return 1 - 0.9 * (self.step_count / self.max_steps)
def _rand_int(self, low, high):
"""
Generate random integer in [low,high[
"""
return self.np_random.randint(low, high)
def _rand_float(self, low, high):
"""
Generate random float in [low,high[
"""
return self.np_random.uniform(low, high)
def _rand_bool(self):
"""
Generate random boolean value
"""
return (self.np_random.randint(0, 2) == 0)
def _rand_elem(self, iterable):
"""
Pick a random element in a list
"""
lst = list(iterable)
idx = self._rand_int(0, len(lst))
return lst[idx]
def _rand_subset(self, iterable, num_elems):
"""
Sample a random subset of distinct elements of a list
"""
lst = list(iterable)
assert num_elems <= len(lst)
out = []
while len(out) < num_elems:
elem = self._rand_elem(lst)
lst.remove(elem)
out.append(elem)
return out
def _rand_color(self):
"""
Generate a random color name (string)
"""
return self._rand_elem(COLOR_NAMES)
def _rand_pos(self, xLow, xHigh, yLow, yHigh):
"""
Generate a random (x,y) position tuple
"""
return (
self.np_random.randint(xLow, xHigh),
self.np_random.randint(yLow, yHigh)
)
def place_obj(self,
obj,
top=None,
size=None,
reject_fn=None,
max_tries=math.inf
):
"""
Place an object at an empty position in the grid
:param top: top-left position of the rectangle where to place
:param size: size of the rectangle where to place
:param reject_fn: function to filter out potential positions
"""
if top is None:
top = (0, 0)
else:
top = (max(top[0], 0), max(top[1], 0))
if size is None:
size = (self.grid.width, self.grid.height)
num_tries = 0
while True:
# This is to handle with rare cases where rejection sampling
# gets stuck in an infinite loop
if num_tries > max_tries:
raise RecursionError('rejection sampling failed in place_obj')
num_tries += 1
pos = np.array((
self._rand_int(top[0], min(top[0] + size[0], self.grid.width)),
self._rand_int(top[1], min(top[1] + size[1], self.grid.height))
))
# Don't place the object on top of another object
if self.grid.get(*pos) != None:
continue
# Don't place the object where the agent is
if np.array_equal(pos, self.agent_pos):
continue
# Check if there is a filtering criterion
if reject_fn and reject_fn(self, pos):
continue
break
self.grid.set(*pos, obj)
if obj is not None:
obj.init_pos = pos
obj.cur_pos = pos
return pos
def place_agent(
self,
top=None,
size=None,
rand_dir=True,
max_tries=math.inf
):
"""
Set the agent's starting point at an empty position in the grid
"""
self.agent_pos = None
pos = self.place_obj(None, top, size, max_tries=max_tries)
self.agent_pos = pos
if rand_dir:
self.agent_dir = self._rand_int(0, 4)
return pos
@property
def dir_vec(self):
"""
Get the direction vector for the agent, pointing in the direction
of forward movement.
"""
assert self.agent_dir >= 0 and self.agent_dir < 4
return DIR_TO_VEC[self.agent_dir]
@property
def right_vec(self):
"""
Get the vector pointing to the right of the agent.
"""
dx, dy = self.dir_vec
return np.array((-dy, dx))
@property