-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrule_based_agents.py
1383 lines (891 loc) · 44.9 KB
/
rule_based_agents.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 numpy as np
import random
import math
import networkx as nx
import matplotlib.pyplot as plt
from scipy.spatial import distance
ACTION_LIST = ['n', ' ', 'w', 's', 'a', 'd', 'wa', 'wd', 'sa', 'sd', 'w ', 's ', 'a ', 'd ', 'wa ', 'wd ', 'sa ', 'sd ']
MOVE_LIST = ['n', 'w', 's', 'a', 'd', 'wa', 'wd', 'sa', 'sd']
class PositionError(Exception):
def __init__(self, position):
self.position = position
class WorldExploredError(Exception):
def __init__(self, agent):
agent.world_explored = 1
class BasicAgent:
def __init__(self, world):
self.world = world
self.prefered_direction = 0
self.previous_direction = 0
self.previous_action = 'n'
self.previous_function = None
self.subsequent_function_changes = 0
self.cannot_decide = 0
self.previous_pos_x = self.world.player.imagined_x
self.previous_pos_y = self.world.player.imagined_y
self.stuck_counter = 0
self.world_explored = 0
self.up_unknown = []
self.down_unknown = []
self.left_unknown = []
self.right_unknown = []
self.passed_ticks = 0
self.previous_next_path = None
self.subsequent_same_next_path_ticks = 0
#self.visited_array = [0] * self.world.perceptor.num_directions
# self.direction_array = [None] * self.world.perceptor.num_directions
# for i in range(len(self.direction_array)):
# direct = (i/self.world.perceptor.num_directions)*360 + 180
# if direct >= 360:
# direct -= 360
# self.direction_array[i] = direct
self.last_update_x = None
self.last_update_y = None
self.nav_graph = nx.Graph()
self.collide_graph = nx.Graph()
self.last_print = 0
self.current_path = []
self.chasing_enemy = False
self.chasing_flower = False
self.chasing_coin = False
self.chasing_cake = False
self.tick_interval_to_update_graph = 20
self.positions_list = []
self.positions_list_size = 300
self.function_buffer_number = 0
self.function_in_buffer = None
self.max_function_buffer_number = 5
# self.nav_matrix_size = 30
# self.nav_matrix = np.zeros((self.nav_matrix_size, self.nav_matrix_size))
def check_if_stuck_or_looping(self, chosen_function):
#print("Chosen Function: ", chosen_function)
if self.cannot_decide > 0:
self.cannot_decide -= 1
return True
max_dist = 0
if len(self.positions_list) > self.positions_list_size - 1:
for spot in self.positions_list:
if self.euclidian_distance(spot, self.positions_list[0]) > max_dist:
max_dist = self.euclidian_distance(spot, self.positions_list[0])
if max_dist < 25:
print("STUCK")
self.positions_list = []
self.chasing_enemy = False
self.chasing_coin = False
self.chasing_flower = False
self.chasing_cake = False
self.cannot_decide = 150
return True
# print("subsequent_same_next_path_ticks:", self.subsequent_same_next_path_ticks)
# if self.subsequent_same_next_path_ticks > 100:
# self.subsequent_same_next_path_ticks = 0
# self.subsequent_function_changes = 0
# self.cannot_decide = 150
# return True
# if self.previous_function != chosen_function and self.previous_function != None:
# self.subsequent_function_changes += 1
# else:
# self.subsequent_function_changes = 0
# print("self.subsequent_function_changes: ", self.subsequent_function_changes)
# if self.subsequent_function_changes >= 10:
# self.subsequent_same_next_path_ticks = 0
# self.subsequent_function_changes = 0
# self.cannot_decide = 150
# return True
# if len(self.current_path) > 0:
# print("Path: ", self.current_path[0])
# if self.current_path[0] == self.previous_next_path:
# self.subsequent_same_next_path_ticks += 1
# else:
# self.subsequent_same_next_path_ticks = 0
# if len(self.positions_list) > 100:
# if np.max(distance.cdist(self.positions_list[:-100], self.positions_list[:-2], "euclidean")) < 200:
# self.subsequent_same_next_path_ticks = 0
# self.subsequent_function_changes = 0
# self.cannot_decide = 50
# return True
return False
def unstuck(self, chosen_function):
action = random.choice(MOVE_LIST)
self.current_path = []
return action
def flower_in_view(self):
for flower in self.world.flower_group:
if self.world.in_view(flower):
return True
def sprites_in_view(self, sprite_group):
number_sprites_view = 0
for spritty in sprite_group:
if self.world.in_view(spritty):
number_sprites_view += 1
return number_sprites_view
def enemies_in_view(self):
return self.sprites_in_view(self.world.enemy_group)
def coins_in_view(self):
return self.sprites_in_view(self.world.money_group)
def cakes_in_view(self):
return self.sprites_in_view(self.world.food_group)
def closest_manhattan_sprite(self, sprite_group):
distance_closest = float('inf')
sprite_closest = None
player_x = self.world.player.imagined_x + self.world.screen_width/2
player_y = self.world.player.imagined_y + self.world.screen_height/2
for sprite in sprite_group:
if self.world.in_view(sprite):
try:
distance = len(nx.shortest_path(self.nav_graph, source = self.get_closest_node_to_position(player_x, player_y), target=self.get_closest_node_to_position(sprite.rect.x + self.world.player.imagined_x, sprite.rect.y + self.world.player.imagined_y)))
except PositionError:
continue
except nx.NetworkXNoPath:
continue
if distance < distance_closest:
distance_closest = distance
sprite_closest = sprite
return distance_closest, sprite_closest
def closest_enemy(self):
distance_closest_enemy = float('inf')
direction_closest_enemy = None
position_closest_enemy = None
for enemy in self.world.enemy_group:
if self.world.in_view(enemy):
distance = math.sqrt((self.world.player.rect.x - enemy.rect.x )**2 + (self.world.player.rect.y - enemy.rect.y)**2 )
myradians = math.atan2(enemy.rect.y - self.world.player.rect.y, enemy.rect.x - self.world.player.rect.x)
direction = math.degrees(myradians)
while(direction > 360):
direction -= 360
while(direction < 0):
direction += 360
if distance < distance_closest_enemy:
distance_closest_enemy = distance
direction_closest_enemy = direction
#print("Rect: ", enemy.rect.x, enemy.rect.y)
position_closest_enemy = (enemy.rect.x, enemy.rect.y)
return distance_closest_enemy, direction_closest_enemy, position_closest_enemy
def avoid_closest_enemy(self):
action = self.fight_closest()
return self.negate_action(action)
def fight_closest(self):
distance_closest_enemy, direction_closest_enemy, position_closest_enemy = self.closest_enemy()
#print(direction_closest_enemy)
if distance_closest_enemy < float('inf'):
if distance_closest_enemy < 70:
self.chasing_enemy = False
#move thowards while attacking
self.current_path = []
if (direction_closest_enemy < 22.5 and direction_closest_enemy >= 0) or (direction_closest_enemy <= 360 and direction_closest_enemy > 337.5):
action = 'd '
elif (direction_closest_enemy < 67.5 and direction_closest_enemy >= 22.5):
action = 'sd '
elif (direction_closest_enemy < 112.5 and direction_closest_enemy >= 67.5):
action = 's '
elif (direction_closest_enemy < 157.5 and direction_closest_enemy >= 112.5):
action = 'sa '
elif (direction_closest_enemy < 202.5 and direction_closest_enemy >= 157.5):
action = 'a '
elif (direction_closest_enemy < 247.5 and direction_closest_enemy >= 202.5):
action = 'wa '
elif (direction_closest_enemy < 292.5 and direction_closest_enemy >= 247.5):
action = 'w '
elif (direction_closest_enemy < 337.5 and direction_closest_enemy >= 292.5):
action = 'wd '
else:
print("Error in directions!!!")
exit()
else:
if self.previous_pos_x == self.world.player.imagined_x and self.previous_pos_y == self.world.player.imagined_y:
self.stuck_counter += 1
else:
self.stuck_counter = 0
if self.stuck_counter >= 2:
self.stuck_counter = 0
if self.previous_action == "w" or self.previous_action == "s":
action = "a"
elif self.previous_action == "a" or self.previous_action == "d":
action = "w"
else:
action = random.choice(["a", "w"])
else:
if self.chasing_enemy:
if self.player_arrived_at_next_node():
del[self.current_path[0]]
if len(self.current_path) == 0:
self.current_path = []
self.chasing_enemy = False
action = random.choice(MOVE_LIST)
else:
action = self.go_to_node(self.current_path[0])
else:
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
try:
self.current_path = nx.shortest_path(self.nav_graph, source = self.get_closest_node_to_position(x, y), target=self.get_closest_node_to_position(position_closest_enemy[0] + self.world.player.imagined_x, position_closest_enemy[1] + self.world.player.imagined_y))
self.chasing_enemy = True
self.chasing_coin = False
self.chasing_flower = False
self.chasing_cake = False
action = self.go_to_node(self.current_path[0])
except PositionError:
action = random.choice(MOVE_LIST)
except nx.NetworkXNoPath:
action = random.choice(MOVE_LIST)
# if self.world_explored:
# return self.go_to_flower()
# else:
# try:
# print("Exploring the world!")
# self.chasing_enemy = False
# self.current_path = []
# return self.explore()
# except WorldExploredError:
# self.chasing_flower = False
# return self.go_to_flower()
# if (direction_closest_enemy < 22.5 and direction_closest_enemy >= 0) or (direction_closest_enemy <= 360 and direction_closest_enemy > 337.5):
# action = 'd'
# elif (direction_closest_enemy < 67.5 and direction_closest_enemy >= 22.5):
# action = 'sd'
# elif (direction_closest_enemy < 112.5 and direction_closest_enemy >= 67.5):
# action = 's'
# elif (direction_closest_enemy < 157.5 and direction_closest_enemy >= 112.5):
# action = 'sa'
# elif (direction_closest_enemy < 202.5 and direction_closest_enemy >= 157.5):
# action = 'a'
# elif (direction_closest_enemy < 247.5 and direction_closest_enemy >= 202.5):
# action = 'wa'
# elif (direction_closest_enemy < 292.5 and direction_closest_enemy >= 247.5):
# action = 'w'
# elif (direction_closest_enemy < 337.5 and direction_closest_enemy >= 292.5):
# action = 'wd'
# else:
# print("Error in directions!!!")
# exit()
else:
action = self.explore()
self.previous_pos_x = self.world.player.imagined_x
self.previous_pos_y = self.world.player.imagined_y
return action
def go_to_flower(self):
if self.previous_pos_x == self.world.player.imagined_x and self.previous_pos_y == self.world.player.imagined_y:
self.stuck_counter += 1
else:
self.stuck_counter = 0
if self.stuck_counter >= 3:
self.stuck_counter = 0
action = random.choice(MOVE_LIST)
self.previous_action = action
return action
flower_x = self.world.flower_group.sprites()[0].rect.x
flower_y = self.world.flower_group.sprites()[0].rect.y
try:
self.get_closest_node_to_position(flower_x + self.world.player.imagined_x, flower_y + self.world.player.imagined_y)
except PositionError as er:
#print("Couldn't find a node near position: ", er.position)
if self.world_explored:
return None
else:
return self.explore()
if self.chasing_flower == False or len(self.current_path) == 0:
self.chasing_flower = True
self.chasing_coin = False
self.chasing_enemy = False
self.chasing_cake = False
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
try:
self.current_path = nx.shortest_path(self.nav_graph, source = self.get_closest_node_to_position(x, y), target=self.get_closest_node_to_position(flower_x + self.world.player.imagined_x, flower_y + self.world.player.imagined_y))
except nx.exception.NetworkXNoPath:
return None
if self.player_arrived_at_next_node():
del[self.current_path[0]]
if len(self.current_path) == 0:
self.chasing_flower = False
return random.choice(MOVE_LIST)
action = self.go_to_node(self.current_path[0])
self.previous_pos_x = self.world.player.imagined_x
self.previous_pos_y = self.world.player.imagined_y
return action
def get_closest_sprite_position_and_distance(self, sprite_group):
distance = float('inf')
position = None
for spritty in sprite_group:
prov_distance = math.sqrt((self.world.screen_width/2 - spritty.rect.x)**2 + (self.world.screen_height/2 - spritty.rect.y)**2)
if prov_distance < distance:
distance = prov_distance
position = (self.world.player.imagined_x + spritty.rect.x, self.world.player.imagined_y + spritty.rect.y)
return position, distance
def go_to_closest_coin(self):
#print("Going to coin!")
if self.previous_pos_x == self.world.player.imagined_x and self.previous_pos_y == self.world.player.imagined_y:
self.stuck_counter += 1
else:
self.stuck_counter = 0
#print("Stuck counter: ", self.stuck_counter)
if self.stuck_counter >= 3:
self.stuck_counter = 0
if self.previous_action == "w" or self.previous_action == "s":
action = "a"
elif self.previous_action == "a" or self.previous_action == "d":
action = "w"
else:
action = random.choice(["a", "w"])
return action
if len(self.world.get_all_in_view(self.world.money_group)) == 0:
action = self.explore()
else:
position, distance = self.get_closest_sprite_position_and_distance(self.world.money_group)
try:
self.get_closest_node_to_position(position[0], position[1])
except PositionError as er:
#print("Couldn't find a node near position: ", er.position)
return self.explore()
# print("Current Position: ", self.world.player.imagined_x + self.world.screen_width/2, self.world.player.imagined_y + self.world.screen_height/2)
# print("Closest Coin Position: ", position[0], position[1])
if self.chasing_coin == False or len(self.current_path) == 0:
self.chasing_coin = True
self.chasing_flower = False
self.chasing_enemy = False
self.chasing_cake = False
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
try:
self.current_path = nx.shortest_path(self.nav_graph, source = self.get_closest_node_to_position(x, y), target=self.get_closest_node_to_position(position[0], position[1]))
except nx.exception.NetworkXNoPath:
return self.explore()
if self.player_arrived_at_next_node():
del[self.current_path[0]]
if len(self.current_path) == 0:
self.chasing_coin = False
return random.choice(MOVE_LIST)
action = self.go_to_node(self.current_path[0])
self.previous_pos_x = self.world.player.imagined_x
self.previous_pos_y = self.world.player.imagined_y
return action
def go_to_closest_cake(self):
#print("Going to cake!")
if self.previous_pos_x == self.world.player.imagined_x and self.previous_pos_y == self.world.player.imagined_y:
self.stuck_counter += 1
else:
self.stuck_counter = 0
if self.stuck_counter >= 2:
self.stuck_counter = 0
if self.previous_action == "w" or self.previous_action == "s":
action = "a"
elif self.previous_action == "a" or self.previous_action == "d":
action = "w"
else:
action = random.choice(["a", "w"])
return action
if len(self.world.get_all_in_view(self.world.food_group)) == 0:
action = self.explore()
else:
position, distance = self.get_closest_sprite_position_and_distance(self.world.food_group)
try:
self.get_closest_node_to_position(position[0], position[1])
except PositionError as er:
#print("Couldn't find a node near position: ", er.position)
return self.explore()
if self.chasing_coin == False or len(self.current_path) == 0:
self.chasing_coin = True
self.chasing_flower = False
self.chasing_enemy = False
self.chasing_cake = False
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
try:
self.current_path = nx.shortest_path(self.nav_graph, source = self.get_closest_node_to_position(x, y), target=self.get_closest_node_to_position(position[0], position[1]))
except nx.exception.NetworkXNoPath:
return self.explore()
if self.player_arrived_at_next_node():
del[self.current_path[0]]
if len(self.current_path) == 0:
self.chasing_coin = False
return random.choice(MOVE_LIST)
action = self.go_to_node(self.current_path[0])
self.previous_pos_x = self.world.player.imagined_x
self.previous_pos_y = self.world.player.imagined_y
return action
def euclidian_distance(self, p1, p2):
return math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )
def get_free_directions(self):
perc_vec = self.world.perceptor.get_perception_vec(self.world.collide_group)[0]
if self.previous_action == 'n':
self.visited_array = [0] * self.world.perceptor.num_directions
elif self.previous_action == 'w':
self.visited_array = [0] * int(self.world.perceptor.num_directions/2) + [1] * int(self.world.perceptor.num_directions/2)
elif self.previous_action == 's':
self.visited_array = [1] * int(self.world.perceptor.num_directions/2) + [0] * int(self.world.perceptor.num_directions/2)
elif self.previous_action == 'a':
self.visited_array = [0] * int(self.world.perceptor.num_directions/4) + [1] * int(self.world.perceptor.num_directions/2) + [0] * int(self.world.perceptor.num_directions/4)
elif self.previous_action == 'd':
self.visited_array = [1] * int(self.world.perceptor.num_directions/4) + [0] * int(self.world.perceptor.num_directions/2) + [1] * int(self.world.perceptor.num_directions/4)
elif self.previous_action == 'wa':
self.visited_array = [0] * int(self.world.perceptor.num_directions/8) + [0] * int(self.world.perceptor.num_directions/4) + [1] * int(self.world.perceptor.num_directions/2) + [0] * int(self.world.perceptor.num_directions/8)
elif self.previous_action == 'wd':
self.visited_array = [1] * int(self.world.perceptor.num_directions/8) + [0] * int(self.world.perceptor.num_directions/2) + [1] * int(self.world.perceptor.num_directions/4) + [1] * int(self.world.perceptor.num_directions/8)
elif self.previous_action == 'sa':
self.visited_array = [0] * int(self.world.perceptor.num_directions/8) + [1] * int(self.world.perceptor.num_directions/2) + [0] * int(self.world.perceptor.num_directions/4) + [0] * int(self.world.perceptor.num_directions/8)
elif self.previous_action == 'sd':
self.visited_array = [1] * int(self.world.perceptor.num_directions/8) + [1] * int(self.world.perceptor.num_directions/4) + [0] * int(self.world.perceptor.num_directions/2) + [1] * int(self.world.perceptor.num_directions/8)
#print(self.previous_action)
#print(len(self.visited_array))
#print(perc_vec)
empty_dir = []
weights = []
for i in range(len(perc_vec)):
if perc_vec[i] < 300 and self.visited_array[i] == 0:
empty_dir.append(self.direction_array[i])
weights.append((self.world.perceptor.max_distance - perc_vec[i])**3)
return empty_dir, weights
def create_graphs(self):
for xx in range(0, self.world.screen_width, self.world.iterator_square.granularity):
for yy in range(0, self.world.screen_height, self.world.iterator_square.granularity):
self.world.iterator_square.rect.x = xx
self.world.iterator_square.rect.y = yy
in_view = self.world.get_all_in_view(self.world.collide_group)
collided = False
for dude in in_view:
if self.world.iterator_square.rect.colliderect(dude.rect):
collided = True
if not collided:
self.nav_graph.add_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy), pos=(self.world.player.imagined_x + xx, -(self.world.player.imagined_y + yy)))
if self.nav_graph.has_node((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy)):
self.nav_graph.add_edge((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if self.nav_graph.has_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy - self.world.iterator_square.granularity)):
self.nav_graph.add_edge((self.world.player.imagined_x + xx , self.world.player.imagined_y + yy - self.world.iterator_square.granularity), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
else:
self.collide_graph.add_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy), pos=(self.world.player.imagined_x + xx, -(self.world.player.imagined_y + yy)))
if self.collide_graph.has_node((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy)):
self.collide_graph.add_edge((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if self.collide_graph.has_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy - self.world.iterator_square.granularity)):
self.collide_graph.add_edge((self.world.player.imagined_x + xx , self.world.player.imagined_y + yy - self.world.iterator_square.granularity), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
self.last_update_x = self.world.player.imagined_x
self.last_update_y = self.world.player.imagined_y
def update_connections(self, graph, xx, yy):
if not graph.has_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy)):
graph.add_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy), pos=(self.world.player.imagined_x + xx, -(self.world.player.imagined_y + yy)))
#Check for left connection
if graph.has_node((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy)):
graph.add_edge((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if (self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy) in self.right_unknown:
self.right_unknown.remove((self.world.player.imagined_x + xx - self.world.iterator_square.granularity, self.world.player.imagined_y + yy))
#Check for up connection
if graph.has_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy - self.world.iterator_square.granularity)):
graph.add_edge((self.world.player.imagined_x + xx , self.world.player.imagined_y + yy - self.world.iterator_square.granularity), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy - self.world.iterator_square.granularity) in self.down_unknown:
self.down_unknown.remove((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy - self.world.iterator_square.granularity))
#Check for right connection
if graph.has_node((self.world.player.imagined_x + xx + self.world.iterator_square.granularity, self.world.player.imagined_y + yy)):
graph.add_edge((self.world.player.imagined_x + xx + self.world.iterator_square.granularity, self.world.player.imagined_y + yy), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if (self.world.player.imagined_x + xx + self.world.iterator_square.granularity, self.world.player.imagined_y + yy) in self.left_unknown:
self.left_unknown.remove((self.world.player.imagined_x + xx + self.world.iterator_square.granularity, self.world.player.imagined_y + yy))
#Check for down connection
if graph.has_node((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy + self.world.iterator_square.granularity)):
graph.add_edge((self.world.player.imagined_x + xx , self.world.player.imagined_y + yy + self.world.iterator_square.granularity), (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy))
if (self.world.player.imagined_x + xx, self.world.player.imagined_y + yy + self.world.iterator_square.granularity) in self.up_unknown:
self.up_unknown.remove((self.world.player.imagined_x + xx, self.world.player.imagined_y + yy + self.world.iterator_square.granularity))
def update_nav_graph(self):
#Update the RIGHT side of the screen
if (self.world.player.imagined_x - self.last_update_x) >= self.world.iterator_square.granularity:
x_remainder = self.world.player.imagined_x - self.last_update_x - self.world.iterator_square.granularity
self.last_update_x = self.world.player.imagined_x - x_remainder
yy_beginning = self.last_update_y - self.world.player.imagined_y
xx = self.world.screen_width - self.world.iterator_square.granularity - x_remainder
for yy in range(yy_beginning, self.world.screen_height + yy_beginning, self.world.iterator_square.granularity):
self.world.iterator_square.rect.x = xx
self.world.iterator_square.rect.y = yy
in_view = self.world.get_all_in_view(self.world.collide_group)
collided = False
for dude in in_view:
if self.world.iterator_square.rect.colliderect(dude.rect):
collided = True
if not collided:
self.update_connections(self.nav_graph, xx, yy)
else:
self.update_connections(self.collide_graph, xx, yy)
#Update the LEFT side of the screen
if (self.world.player.imagined_x - self.last_update_x) <= -self.world.iterator_square.granularity:
x_remainder = self.world.player.imagined_x - self.last_update_x + self.world.iterator_square.granularity
self.last_update_x = self.world.player.imagined_x - x_remainder
yy_beginning = self.last_update_y - self.world.player.imagined_y
xx = 0 - x_remainder
for yy in range(yy_beginning, self.world.screen_height + yy_beginning, self.world.iterator_square.granularity):
self.world.iterator_square.rect.x = xx
self.world.iterator_square.rect.y = yy
in_view = self.world.get_all_in_view(self.world.collide_group)
collided = False
for dude in in_view:
if self.world.iterator_square.rect.colliderect(dude.rect):
collided = True
if not collided:
self.update_connections(self.nav_graph, xx, yy)
else:
self.update_connections(self.collide_graph, xx, yy)
#Update the DOWN side of the screen
if (self.world.player.imagined_y - self.last_update_y) >= self.world.iterator_square.granularity:
y_remainder = self.world.player.imagined_y - self.last_update_y - self.world.iterator_square.granularity
self.last_update_y = self.world.player.imagined_y - y_remainder
xx_beginning = self.last_update_x - self.world.player.imagined_x
yy = self.world.screen_height - self.world.iterator_square.granularity - y_remainder
for xx in range(xx_beginning, self.world.screen_width + xx_beginning, self.world.iterator_square.granularity):
self.world.iterator_square.rect.x = xx
self.world.iterator_square.rect.y = yy
in_view = self.world.get_all_in_view(self.world.collide_group)
collided = False
for dude in in_view:
if self.world.iterator_square.rect.colliderect(dude.rect):
collided = True
if not collided:
self.update_connections(self.nav_graph, xx, yy)
else:
self.update_connections(self.collide_graph, xx, yy)
#Update the UP side of the screen
if (self.world.player.imagined_y - self.last_update_y) <= -self.world.iterator_square.granularity:
y_remainder = self.world.player.imagined_y - self.last_update_y + self.world.iterator_square.granularity
self.last_update_y = self.world.player.imagined_y - y_remainder
xx_beginning = self.last_update_x - self.world.player.imagined_x
yy = 0 - y_remainder
for xx in range(xx_beginning, self.world.screen_width + xx_beginning, self.world.iterator_square.granularity):
self.world.iterator_square.rect.x = xx
self.world.iterator_square.rect.y = yy
in_view = self.world.get_all_in_view(self.world.collide_group)
collided = False
for dude in in_view:
if self.world.iterator_square.rect.colliderect(dude.rect):
collided = True
if not collided:
self.update_connections(self.nav_graph, xx, yy)
else:
self.update_connections(self.collide_graph, xx, yy)
##### Uncoment these lines to print the navigational graphs being generated at fixed intervals
# if (self.last_print == 0) or (self.last_print > 100):
# self.last_print = 0
# self.print_connected_components()
# self.last_print += 1
def negate_action(self, action):
negated_actions = ['n', ' ', 's', 'w', 'd', 'a', 'sd', 'sa', 'wd', 'wa', 's', 'w', 'd', 'a', 'sd', 'sa', 'wd', 'wa']
return negated_actions[ACTION_LIST.index(action)]
def get_closest_node_to_position(self, x, y):
possible_x = x - (x % self.world.iterator_square.granularity)
possible_y = y - (y % self.world.iterator_square.granularity)
if (possible_x, possible_y) in self.nav_graph:
return (possible_x, possible_y)
else:
possible_x = x - (x % self.world.iterator_square.granularity) + self.world.iterator_square.granularity
possible_y = y - (y % self.world.iterator_square.granularity)
if (possible_x, possible_y) in self.nav_graph:
return (possible_x, possible_y)
else:
possible_x = x - (x % self.world.iterator_square.granularity) + self.world.iterator_square.granularity
possible_y = y - (y % self.world.iterator_square.granularity) + self.world.iterator_square.granularity
if (possible_x, possible_y) in self.nav_graph:
return (possible_x, possible_y)
else:
possible_x = x - (x % self.world.iterator_square.granularity)
possible_y = y - (y % self.world.iterator_square.granularity) + self.world.iterator_square.granularity
if (possible_x, possible_y) in self.nav_graph:
return (possible_x, possible_y)
else:
raise PositionError((x,y))
def get_collide_neighbors(self, node):
collide_neighbors = []
if (node[0] + self.world.iterator_square.granularity, node[1]) in self.collide_graph:
collide_neighbors.append((node[0] + self.world.iterator_square.granularity, node[1]))
if (node[0] - self.world.iterator_square.granularity, node[1]) in self.collide_graph:
collide_neighbors.append((node[0] - self.world.iterator_square.granularity, node[1]))
if (node[0], node[1] + self.world.iterator_square.granularity) in self.collide_graph:
collide_neighbors.append((node[0], node[1] + self.world.iterator_square.granularity))
if (node[0], node[1] - self.world.iterator_square.granularity) in self.collide_graph:
collide_neighbors.append((node[0], node[1] - self.world.iterator_square.granularity))
return collide_neighbors
def get_unexplored_nodes(self):
unexplored_nodes = []
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
player_node = self.get_closest_node_to_position(x, y)
components = nx.connected_components(self.nav_graph)
player_component = None
for component in components:
if player_node in component:
player_component = component
for n in self.nav_graph:
#print(n)
if len(self.nav_graph[n]) >= 4:
continue
# print("Num Neighbors: ", len(self.nav_graph[n]))
# print("Num Collidables: ", len(self.get_collide_neighbors(n)))
if (len(self.get_collide_neighbors(n)) + len(self.nav_graph[n])) < 4:
#if nx.has_path(self.nav_graph, n, player_node):
if n in player_component:
unexplored_nodes.append(n)
#print("Unexplored nodes: ", unexplored_nodes)
# for node in unexplored_nodes:
# print("Node: ", node)
# print("Path: ", nx.shortest_path(self.nav_graph, source=player_node, target=node))
return unexplored_nodes
def print_connected_components(self):
print("--> Navigation Graphs:")
print("Conected Components: ", nx.number_connected_components(self.nav_graph))
pos = nx.get_node_attributes(self.nav_graph, 'pos')
for h in [self.nav_graph.subgraph(c).copy() for c in nx.connected_components(self.nav_graph)]:
nx.draw(h, pos, node_color='blue', node_size = 20)
plt.show()
print("--> Collision Graphs:")
print("Conected Components: ", nx.number_connected_components(self.collide_graph))
pos = nx.get_node_attributes(self.collide_graph, 'pos')
for h in [self.collide_graph.subgraph(c).copy() for c in nx.connected_components(self.collide_graph)]:
nx.draw(h, pos, node_color='red', node_size = 20)
plt.show()
def get_movement_from_direction(self, direction):
if (direction < 22.5 and direction >= 0) or (direction <= 360 and direction > 337.5):
action = 'd'
elif (direction < 67.5 and direction >= 22.5):
action = 'sd'
elif (direction < 112.5 and direction >= 67.5):
action = 's'
elif (direction < 157.5 and direction >= 112.5):
action = 'sa'
elif (direction < 202.5 and direction >= 157.5):
action = 'a'
elif (direction < 247.5 and direction >= 202.5):
action = 'wa'
elif (direction < 292.5 and direction >= 247.5):
action = 'w'
elif (direction < 337.5 and direction >= 292.5):
action = 'wd'
else:
print("Direction: ", direction)
print("Error in directions!!!")
exit()
return action
def go_to_node(self, node):
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
player_node = self.get_closest_node_to_position(x, y)
myradians = math.atan2(node[1] - player_node[1], node[0] - player_node[0])
direction = math.degrees(myradians)
while(direction > 360):
direction -= 360
while(direction < 0):
direction += 360
action = self.get_movement_from_direction(direction)
# print("Going to Node!")
# print("I'm here: ", player_node)
# print("I want to go: ", node)
# print("So I'm doing: ", action)
return action
def player_arrived_at_next_node(self):
node = self.current_path[0]
x = self.world.player.imagined_x + self.world.screen_width/2
y = self.world.player.imagined_y + self.world.screen_height/2
player_node = self.get_closest_node_to_position(x, y)
distance = math.sqrt((player_node[0] - node[0])**2 + (player_node[1] - node[1])**2 )
if distance < self.world.speed:
return True
else:
return False