-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver.py
More file actions
1463 lines (1261 loc) · 51.9 KB
/
Copy pathsolver.py
File metadata and controls
1463 lines (1261 loc) · 51.9 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
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
"""Randolph's robot game homemade solver.
This is the first version of an algorithm to solve
Randolph's robot game.
It is not optimised in any way, and was just to test my own
first try to solve this problem without any external help.
More info could be found in the literature, which I deliberetaly have not read
before coding this
- On the Complexity of Randolph’s Robot Game,
Birgit Engels Tom Kamphans, 2005
- The Parameterized Complexity of Ricochet Robots,
Adam Hesterberg Justin Kopinsky, 2017
(Could Dijkstra's algorithm have helped?)
This algorithm does not handle re-collisions.
For efficiency's sake, the algorithm can't process that
a robot can collide twice on the same robot.
Bumpers are not implemented.
All tiles data are not entered in tiles.json.
Only one group of tiles was done so far.
"""
import numpy as np
from matplotlib import pyplot as plt
import json
from copy import deepcopy
# Importing tiles data
with open('tiles.json', 'r') as f:
tiles_data = json.load(f)
def get_idx(idx, idx_names):
"""Sanitise index of an element in a list.
Will match the first character of the list,
and will accept integer as input parameters if
it was already an integer.
Parameters
----------
idx: str (or int)
Element to match to the list.
If integer, will return it as is.
idx_names: list of str
List of all elements to match to.
Returns
-------
int
Index of the element in the list.
"""
if isinstance(idx, int) or isinstance(idx, np.int64):
if idx > len(idx_names):
raise Exception(f'ID "{idx}" higher than number '
f'in the map ({len(idx_names)}).')
return idx
elif isinstance(idx, str):
idx_names_firsts = [n[0].lower() for n in idx_names]
if idx[0].lower() in idx_names_firsts:
return idx_names_firsts.index(idx[0].lower())
else:
raise Exception(f'ID {idx} not recognised.')
class Moves():
"""Class for list of moves on a board.
Parameters
----------
robots_colors: list of str
List of all robots colors.
This could probably be a global variable of some sort.
Attributes
----------
data: N*2 numpy array
For each of the N moves, contains the robot index and the direction
index of the move.
direction_names: list of str
List of direction. Used to translate a direction index into direction
and vice-versa.
"""
def __init__(self, robots_colors):
"""Init function."""
self.data = np.zeros((0, 2), dtype=int)
self.direction_names = ['up', 'down', 'left', 'right']
self.robots_colors = robots_colors
def __len__(self):
"""Length function, which is how many moves in this object."""
return self.data.shape[0]
def __repr__(self):
"""Representation (and string) function."""
message = []
for robot_id, direction in self.data:
message.append(f'{self.robots_colors[robot_id]}_'
f'{self.direction_names[direction]}')
if len(message) == 0:
return 'NO MOVE'
return '-'.join(message)
def add_move(self, robot_id, direction):
"""Append a move to the move list.
Parameters
----------
robot_id: int
Index of the robot to move. Corresponds to self.robots_colors
direction: int
Index of the direction to move. Corresponds to self.direction_names
"""
robot_id = get_idx(robot_id, self.robots_colors)
direction = get_idx(direction, self.direction_names)
add_vector = np.array([robot_id, direction], dtype=int).reshape(1, -1)
self.data = np.concatenate([self.data, add_vector])
def add_moves(self, moves):
"""Append a Moves() class to the current one.
Parameters
----------
moves: Moves()
Moves class containing the moves to append to the current class.
"""
self.data = np.vstack([self.data, moves.data])
def is_equal(self, moves):
"""Check if the current class is equal to another Moves() class.
Parameters
----------
moves: Moves()
Moves class to compare the current class to.
Returns
-------
bool
If True, the two classes instanciation are equal.
"""
if moves.data.shape != self.data.shape:
return False
return (moves.data == self.data).all()
def copy(self):
"""Return deep copy of the current class object.
Returns
-------
Moves()
A copy of the current object.
"""
return deepcopy(self)
class TMap():
"""Tracking Maps of a single robot.
A TMap contains all reachable positions of a robot
Each position keeps track of the shortest path(s) to it, and the
conditional positions of other robots to reach it.
Parameters
----------
robot_id: int
Robot index of the current TMap.
Corresponds to the list self.robots_colors.
initial_position: list of (int, int)
Initial position on the board for each robots.
The order corresponds to self.robots_colors.
self.robots_colors: list of str
List of color of all robots on the board.
This could probably be a global variable.
Attributes
----------
directions: list of str
List of all directions of movement.
Useful for curation status when exploring the TMap's position.
Note: This could probably be a global variable, since the Moves()
class also uses its own directions list.
data: 2D int numpy array
All data relevant to a position except the move list.
[0: 2]: coordinate (ROW, COLUMN) from (0, 0) being the top left,
of the position
[2] : Length of moves required to reach the position.
[3: 7]: Curation statuses for the position. Used during computation.
Each of the 4 curation statuses corresponds to a
specific direction.
[7] : Level of the position. A level corresponds roughly to
the number of collisions required. Used during
computation
[8: X]: Conditions of the current position.
A condition is a position where a robot needs to be,
for a collision to reach the position.
The condition list is a concatenation of all (X, Y)
position of all robots on the map, corresponding
to self.robot_colors.
Default is (-1, -1), indicating no collision is
necessary.
all_moves: list of Moves()
For each position, indicates the moves list to attain it.
It is indexed in the same way as self.data.
"""
def __init__(self, robot_id, initial_position, robots_colors):
"""Init function."""
self.robot_id = robot_id
self.robots_colors = robots_colors
self.directions = ['U', 'D', 'L', 'R']
add_vector = (list(initial_position) + [0]*6 +
[-1]*len(self.robots_colors)*2)
self.data = np.array(add_vector, dtype=int).reshape(1, -1)
self.all_moves = [Moves(robots_colors)]
def __len__(self):
"""Length function, which is how many positions are in this TMap."""
return self.data.shape[0]
def add_position(self, position, moves, level, conditions):
"""Append a new position to the current TMap object.
Will automatically compare it to a position currently
in this object if that's the case, and will only keep the position
with the shortest path. In case of multiple paths of same length,
it will keep all of them.
Parameters
----------
position: (int, int)
Position on the board that is attainable by robot self.robot_id
moves: Moves()
The movement -from the starting positions on the board-
necessary for the robot to reach its position.
level: int
The level depth corresponding to the current position data.
Each level depth corresponds roughly to a collision with another
robot.
It is more for tracking/debugging purposes when computing paths.
conditions: 2N int list
For each of the N robots (order corresponding to
self.robots_colors),
indicates which position another robot must be in order for this
position to be reachable, i.e. where another robot must be
for a collision to occur.
Like level, this is only for the efficiency of the computing paths
algorithms, since this information is technically in [moves].
Default is [-1, -1] for each robot, meaning that no collision
is needed with that particular robot.
Returns
-------
1D np.array
indexes of the Tmap that were removed during the function call
"""
add_vector = np.array((list(position) + [len(moves)] +
[0]*4 + [level] + list(conditions)),
dtype=int)
add_vector = add_vector.reshape(1, -1)
pos_idx = (self.get_positions() == position).all(axis=1)
if pos_idx.sum() == 0:
self.data = np.concatenate([self.data, add_vector])
self.all_moves.append(moves)
return
n_moves = self.get_moves_length()[pos_idx]
if len(np.unique(n_moves)) != 1:
raise Exception(f'Multiple moves length for single position '
f'{position} of robot '
f'{self.robots_colors[self.robot_id]}')
n_moves = n_moves[0]
removed_ids = []
if len(moves) < n_moves:
self.data = self.data[~pos_idx]
self.all_moves = [self.all_moves[i]
for i in np.where(~pos_idx)[0]]
removed_ids = np.where(pos_idx)[0]
if len(moves) == n_moves:
for i in np.where(pos_idx)[0]:
if self.all_moves[i].is_equal(moves):
return removed_ids
if len(moves) <= n_moves:
self.data = np.concatenate([self.data, add_vector])
self.all_moves.append(moves)
return removed_ids
def remove_position(self, tmap_id):
"""Remove a position from the TMap.
Parameters
----------
tmap_id: int
The index of the position in the position list (self.data)
to remove. Note that this will reindex all other position
of higher indexes.
"""
pos_idx = np.ones(len(self.data), dtype=bool)
pos_idx[tmap_id] = False
self.data = self.data[pos_idx].copy()
self.all_moves = [self.all_moves[i] for i in np.where(pos_idx)[0]]
def get_positions(self):
"""Return positions that are reachable by the robot.
Returns
-------
N*2 2D numpy array
"""
return self.data[:, :2]
def get_moves_length(self):
"""Return number of moves to reach each position.
Returns
-------
N-length 1D numpy array
"""
return self.data[:, 2]
def get_curation(self):
"""Return curation status of each position.
A curation status can be set to 0 or 1.
This is useful when we need to check every position in the
list, but each check can affect the list's index and order.
Each position has 4 curation status, corresponding to
the 4 directions.
Returns
-------
N*4 2D numpy array
"""
return self.data[:, 3:7]
def reset_curation(self):
"""Reset curation status to 0 for all position."""
self.data[:, 3:7] = 0
def set_curation(self, tmap_id, direction):
"""Set curation status to 1 for a specific position/direction combo.
Parameters
----------
tmap_id: int
The index of the position in the position list (self.data)
to curate.
direction: int (or str)
The direction to curate.
"""
if isinstance(direction, str):
direction = direction[0].upper()
direction_id = get_idx(direction, self.directions)
self.data[tmap_id, 3+direction_id] = 1
def get_idx_curation(self):
"""Return all position's indexes that were not curated yet (status 0).
Returns
-------
list of int
List of tmap_id
"""
return list(map(list, zip(*np.where(self.get_curation() == 0))))
def get_levels(self):
"""Return level of each position.
Returns
-------
N-length 1D numpy array
"""
return self.data[:, 7]
def get_max_level(self):
"""Return the maximum level of all positions in the object.
This helps set up the next step of path searches.
Returns
-------
int
"""
return max(self.get_levels())
def get_conditions(self):
"""Return the conditions of the position.
Returns
-------
N*(2R) 2D numpy array
Conditions for all N positions. A condition list is
the concatenation of (X, Y) positions for all R robots,
in case the position is conditional to a collision to another
robot.
Default value is -1 if no collision is needed.
"""
return self.data[:, 8:]
def get_condition(self, robot_id):
"""Return a single robot condition of the position.
Parameters
----------
robot_id: int
Index of the robot on whom to check conditions.
Returns
-------
N*2 2D numpy array
Condition for all N positions for the specified other robot.
The condition is a single (X, Y) coordinate for the
specified robot in case the position is conditional to a collision
to this specified robot.
Default value is -1 if no collision is needed.
"""
robot_id = self.get_robot_id(robot_id)
return self.get_conditions()[2*robot_id: 2*(robot_id+1)]
def get_robot_id(self, robot_id):
"""Sanitise robot index.
Will sanitise the robot index to a proper integer
if that was not the case.
Parameters
----------
robot_id: int or str
Returns
-------
int
"""
return get_idx(robot_id, self.robots_colors)
def get_idx_intersect(self, start_position, end_position, level=None):
"""Get all intersecting indexes of the TMap's position list.
Those are positions that intersect with a movement from start_position
to end_position.
Parameters
----------
start_position: (int, int)
(ROW, COLUMN) starting position of a single move to analyse.
(0, 0) is the top left of the board.
end_position: (int, int)
(ROW, COLUMN) ending position of a single move to analyse.
(0, 0) is the top left of the board.
level: int, optional
If specified, will only check for positions
under or equal to a certain level.
Default is None, which checks for all levels.
Returns
-------
1D int numpy array
List of all position in the TMap that intersects with the
specified movement.
"""
start_row, start_col = start_position
end_row, end_col = end_position
if level is None:
level_filter = np.ones(self.get_levels().shape, dtype=bool)
else:
level_filter = self.get_levels() <= level
if start_col == end_col:
if start_row > end_row:
# Move up
tmap_ids = np.where(
(self.get_positions()[:, 1] == start_col) &
(self.get_positions()[:, 0] < start_row) &
(self.get_positions()[:, 0] >= end_row) &
level_filter
)[0]
elif start_row < end_row:
# Move down
tmap_ids = np.where(
(self.get_positions()[:, 1] == start_col) &
(self.get_positions()[:, 0] > start_row) &
(self.get_positions()[:, 0] <= end_row) &
level_filter
)[0]
else:
raise Exception(f'Can\'t infer movement from {start_position} '
f'to {end_position}')
elif start_row == end_row:
if start_col > end_col:
# Move left
tmap_ids = np.where(
(self.get_positions()[:, 0] == start_row) &
(self.get_positions()[:, 1] < start_col) &
(self.get_positions()[:, 1] >= end_col) &
level_filter
)[0]
elif start_col < end_col:
# Move right
tmap_ids = np.where(
(self.get_positions()[:, 0] == start_row) &
(self.get_positions()[:, 1] > start_col) &
(self.get_positions()[:, 1] <= end_col) &
level_filter
)[0]
else:
raise Exception(f'Can\'t infer movement from {start_position} '
f'to {end_position}')
return tmap_ids
class Board():
"""Board class of the game.
Parameters
----------
tiles_names: list of str
Tiles that define the board. Tile names correspond to data
in tiles.json.
Order of tiles is clockwise, starting from top left.
robots_positions: N*2 2D numpy array
Positions of all N robots on the board.
A position is (ROW, COLUMN) where (0, 0) is the top left corner.
Order corresponds to self.robots_colors.
Attributes
----------
robots_colors: list of str
List of all robot colors on the board. Currently hardcoded.
robots_tmaps: dict of {int: Tmap()}
Dictionnary of TMaps() for all robots.
key: robot index or the corresponding TMap()
value: TMap() object corresponding to the robot
height: int
Number of rows of the board. Hardcoded to 16.
width: int
Number of columns of the board. Harcocded to 16.
robot_size: int
Size of the robot on the matplotlib display.
vertical_walls: H*(W-1) 2D bool numpy array
Data for vertical walls of the board.
If True at a certain coordinate,
indicates a veritcal wall to the right of the specified position.
horizontal_walls: (H-1)*W 2D bool numpy array
Data for horizontal walls of the board.
If True at a certain coordinate,
indicates a horizontal wall to the bottom of the specified position.
goals: dict of {(str, str): (int, int)}
Data for all goal tiles.
key[0]: Color of the goal
key[1]: Shape of the goal
value: position of the goal on the board.
fig: Matplotlib Figure()
Figure data to print on screen
ax: Matplotlib subplot
Subplot/Graph data to print on screen
"""
def __init__(self, tiles_names, robots_positions):
"""Init function."""
if len(tiles_names) != 4:
raise Exception('Please specidy 4 tiles names in clockwise manner '
'starting from top left.')
self.robots_positions = robots_positions
if len(robots_positions) == 4:
self.robots_colors = ['RED', 'BLUE', 'GREEN', 'YELLOW']
elif len(robots_positions) == 5:
self.robots_colors = ['RED', 'BLUE', 'GREEN', 'YELLOW', 'KBLACK']
else:
raise Exception('Please enter 4 or 5 initial positions.')
self.robots_tmaps = {i_p: TMap(i_p,
self.robots_positions[i_p],
self.robots_colors)
for i_p in range(len(self.robots_colors))}
self.height = 16
self.width = 16
self.robot_size = 5000/max(self.height, self.width)
self.load_board_walls(tiles_names)
self.load_goals(tiles_names)
def load_board_walls(self, tiles_names):
"""Load board wall data in the class object based on tile data.
Will load self.vertical_walls and self.horizontal_walls.
Parameters
----------
tiles_names: list of str
Tiles that define the board. Tile names correspond to data
in tiles.json.
Order of tiles is clockwise, starting from top left.
"""
self.vertical_walls = np.zeros((self.height, self.width-1),
dtype=bool)
self.horizontal_walls = np.zeros((self.height-1, self.width),
dtype=bool)
for k, tile_name in enumerate(tiles_names):
tile_vertical_walls = np.zeros((8, 8), dtype=bool)
tile_horizontal_walls = np.zeros((8, 8), dtype=bool)
for (i, j) in tiles_data[tile_name]['vertical']:
tile_vertical_walls[i, j] = True
for (i, j) in tiles_data[tile_name]['horizontal']:
tile_horizontal_walls[i, j] = True
if k == 0:
self.vertical_walls[:8, :8] = (
self.vertical_walls[:8, :8] | tile_vertical_walls
)
self.horizontal_walls[:8, :8] = (
self.horizontal_walls[:8, :8] | tile_horizontal_walls
)
elif k == 1:
self.vertical_walls[:8, 7:] = (
self.vertical_walls[:8, 7:] |
np.rot90(tile_horizontal_walls, k=3)
)
self.horizontal_walls[:8, 8:] = (
self.horizontal_walls[:8, 8:] |
np.rot90(tile_vertical_walls, k=3)
)
elif k == 2:
self.vertical_walls[8:, 7:] = (
self.vertical_walls[8:, 7:] |
np.rot90(tile_vertical_walls, k=2)
)
self.horizontal_walls[7:, 8:] = (
self.horizontal_walls[7:, 8:] |
np.rot90(tile_horizontal_walls, k=2)
)
elif k == 3:
self.vertical_walls[8:, :8] = (
self.vertical_walls[8:, :8] |
np.rot90(tile_horizontal_walls, k=1)
)
self.horizontal_walls[7:, :8] = (
self.horizontal_walls[7:, :8] |
np.rot90(tile_vertical_walls, k=1)
)
def load_goals(self, tiles_names):
"""Load goal data in the class object based on tile data.
Will load self.goals.
Parameters
----------
tiles_names: list of str
Tiles that define the board. Tile names correspond to data
in tiles.json.
Order of tiles is clockwise, starting from top left.
"""
shape_list = ["GEAR", "STAR", "MOON", "PLANET"]
self.goals = {}
for k, tile_name in enumerate(tiles_names):
tile_color = tile_name[:max(i for i in range(len(tile_name))
if tile_name[:i].isalpha())]
if tile_color not in self.robots_colors:
raise Exception(f'Tile {tile_name} incompatible with '
'load_goals()')
shift_index = self.robots_colors.index(tile_color)
goal_shapes = shape_list[-shift_index:] + shape_list[:-shift_index]
goal_list = [(self.robots_colors[i], goal_shapes[i])
for i in range(len(self.robots_colors))
if self.robots_colors[i] != 'KBLACK']
if tile_color == 'YELLOW':
goal_list.append(('BLACK', 'HOLE'))
for i, (row, col) in enumerate(tiles_data[tile_name]['goals']):
goal_name = goal_list[i]
if k == 0:
goal_position = [row, col]
elif k == 1:
goal_position = [col, self.width-1-row]
elif k == 2:
goal_position = [self.height-1-row, self.width-1-col]
elif k == 3:
goal_position = [self.height-1-col, row]
self.goals[goal_name] = goal_position
def get_robot_id(self, robot_id):
"""Sanitise robot index.
Will sanitise the robot index to a proper integer
if that was not the case.
Parameters
----------
robot_id: int or str
Returns
-------
int
"""
return get_idx(robot_id, self.robots_colors)
def print(self, goals=True):
"""Print the board on the console.
Parameters
----------
goals: bool, optional
If True, will print goals as well.
Default is True.
"""
self.fig, self.ax = plt.subplots()
self.ax.axis([0, self.width, 0, self.height])
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.print_walls()
self.print_robots()
if goals:
self.print_goals()
self.fig.set_size_inches(6, 6)
# self.fig.show()
def print_walls(self, ax=None):
"""Add wall data to a matplotlib suplot.
Parameters
----------
ax: Matplotlib suplot, optional
If specified, will add the data to this subplot object.
Default is self.ax
"""
if ax is None:
ax = self.ax
for i, j in np.array(np.where(self.vertical_walls)).T:
ax.plot([1+j, 1+j], [self.height-i, self.height-i-1], c='k')
for i, j in np.array(np.where(self.horizontal_walls)).T:
ax.plot([j, 1+j], [self.height-1-i, self.height-1-i], c='k')
def print_robots(self, ax=None):
"""Add robot position's data to a matplotlib suplot.
Parameters
----------
ax: Matplotlib suplot, optional
If specified, will add the data to this subplot object.
Default is self.ax
"""
if ax is None:
ax = self.ax
for i, position in enumerate(self.robots_positions):
ax.scatter([position[1]+0.5],
[self.height - 0.5 - position[0]],
c=self.robots_colors[i][0:1].lower(),
marker='s',
s=self.robot_size)
def print_goals(self, ax=None):
"""Add goals data to a matplotlib suplot.
Parameters
----------
ax: Matplotlib suplot, optional
If specified, will add the data to this subplot object.
Default is self.ax
"""
if ax is None:
ax = self.ax
for name, position in self.goals.items():
color, shape = name
ax.text(position[1]+0.5,
self.height - 0.5 - position[0],
shape,
c=color,
ha='center',
size=80/self.width)
def print_tmap(self, robot_id):
"""Print all TMaps position on the console.
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
"""
self.fig, self.ax = plt.subplots()
self.ax.axis([0, self.width, 0, self.height])
self.ax.xaxis.set_visible(False)
self.ax.yaxis.set_visible(False)
self.print_walls()
self.print_tmap_positions(robot_id)
self.fig.set_size_inches(6, 6)
def print_tmap_positions(self, robot_id, ax=None):
"""Add TMap position data to a matplotlib suplot.
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
ax: Matplotlib suplot, optional
If specified, will add the data to this subplot object.
Default is self.ax
"""
robot_id = self.get_robot_id(robot_id)
robot_tmap = self.robots_tmaps[robot_id]
if ax is None:
ax = self.ax
for position in robot_tmap.get_positions():
ax.scatter([position[1]+0.5],
[self.height - 0.5 - position[0]],
c=self.robots_colors[robot_id][0:1].lower(),
marker='s',
s=self.robot_size)
def move_robot(self, robot_id, direction):
"""Move a robot on the board.
Will handle all collisions. Will update self.robots_positions
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
direction: str
Direction where to move the robot.
Must be within {'U', 'D', 'L', 'R'}
"""
robot_id = self.get_robot_id(robot_id)
direction = direction[0].upper()
if direction == 'U':
self.move_robot_up(robot_id)
elif direction == 'D':
self.move_robot_down(robot_id)
elif direction == 'L':
self.move_robot_left(robot_id)
elif direction == 'R':
self.move_robot_right(robot_id)
else:
raise Exception(f'Direction {direction} not recognised.')
def move_robot_up(self, robot_id):
"""Move a robot up on the board.
Will handle all collisions. Will update self.robots_positions
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
"""
start_row, start_col = self.robots_positions[robot_id]
end_col = start_col
walls = self.horizontal_walls[:start_row, start_col]
walls = np.where(walls)[0]
if len(walls) > 0:
wall_end_row = walls.max()+1
else:
wall_end_row = 0
robots = self.robots_positions[
(self.robots_positions[:, 1] == start_col) &
(self.robots_positions[:, 0] < start_row)
]
if len(robots) > 0:
robots_end_row = robots[:, 0].max()+1
else:
robots_end_row = 0
end_row = max(wall_end_row, robots_end_row)
self.robots_positions[robot_id] = end_row, end_col
def move_robot_down(self, robot_id):
"""Move a robot down on the board.
Will handle all collisions. Will update self.robots_positions
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
"""
start_row, start_col = self.robots_positions[robot_id]
end_col = start_col
walls = self.horizontal_walls[start_row:, start_col]
walls = np.where(walls)[0]
if len(walls) > 0:
wall_end_row = walls.min()+start_row
else:
wall_end_row = self.height-1
robots = self.robots_positions[
(self.robots_positions[:, 1] == start_col) &
(self.robots_positions[:, 0] > start_row)
]
if len(robots) > 0:
robots_end_row = robots[:, 0].min()-1
else:
robots_end_row = self.height-1
end_row = min(wall_end_row, robots_end_row)
self.robots_positions[robot_id] = end_row, end_col
def move_robot_left(self, robot_id):
"""Move a robot left on the board.
Will handle all collisions. Will update self.robots_positions
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
"""
start_row, start_col = self.robots_positions[robot_id]
end_row = start_row
walls = self.vertical_walls[start_row, :start_col]
walls = np.where(walls)[0]
if len(walls) > 0:
wall_end_col = walls.max()+1
else:
wall_end_col = 0
robots = self.robots_positions[
(self.robots_positions[:, 0] == start_row) &
(self.robots_positions[:, 1] < start_col)
]
if len(robots) > 0:
robots_end_col = robots[:, 1].max()+1
else:
robots_end_col = 0
end_col = max(wall_end_col, robots_end_col)
self.robots_positions[robot_id] = end_row, end_col
def move_robot_right(self, robot_id):
"""Move a robot right on the board.
Will handle all collisions. Will update self.robots_positions
Parameters
----------
robot_id: int
Robot index of which to print all attainable positions.
"""
start_row, start_col = self.robots_positions[robot_id]
end_row = start_row
walls = self.vertical_walls[start_row, start_col:]
walls = np.where(walls)[0]
if len(walls) > 0:
wall_end_col = walls.min()+start_col
else:
wall_end_col = self.width-1
robots = self.robots_positions[
(self.robots_positions[:, 0] == start_row) &
(self.robots_positions[:, 1] > start_col)
]
if len(robots) > 0:
robots_end_col = robots[:, 1].min()-1
else:
robots_end_col = self.width-1
end_col = min(wall_end_col, robots_end_col)
self.robots_positions[robot_id] = end_row, end_col
def add_to_tmap(self,
robot_id,
new_position,
tmap_id,
direction,
level,
robot2_id=None,
tmap2_id=None):
"""Add a new position to a TMap.
Will adequately prune the TMap and/or check if the position
is worth adding.
Parameters
----------
robot_id: int
Robot index corresponding to the TMap() on which to add
a new position.
new_position: (int, int)
Coordinates of the position to add.
tmap_id: int
Index of the current TMap() corresponding to the last