-
Notifications
You must be signed in to change notification settings - Fork 4
/
Main.py
2413 lines (2178 loc) · 149 KB
/
Main.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
from pyswip import *
import pygame
from guizero import App, ListBox, PushButton, Box, Text, info, Slider
import random
from os import listdir
from os.path import isfile, join
import math
import json
import datetime
from SLAMRobot import SLAMAgent
import numpy
#inizializzazione pygame
pygame.init()
pygame.display.set_caption("Environment Generator")
#Costanti tipi Gameobject
BEDROOM = "bedroom"
BATHROOM = "bathroom"
KITCHEN = "kitchen"
HALL = "hall"
BED = "bed"
BEDSIDE = "bedside"
WARDROBE = "wardrobe"
SINK = "sink"
SHOWER = "shower"
TOILET = "toilet"
TABLE = "table"
CHAIR = "chair"
DESK = "desk"
SOFA = "sofa"
HALL_TABLE = "hallTable"
CUPBOARD = "cupboard"
DOOR = "door"
FLOOR = "floor"
AGENT = "agent"
OBJECTIVE = "objective"
#Colori PyGame (mockup, verranno sostituite dalle sprite)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
ORANGE = (255, 200, 140)
BLACK = ( 0, 0, 0)
PINK = (255, 210, 210)
BANANA = (255, 255, 150)
GREY = (150, 150, 150)
LIGHT_GREEN = (150, 255, 150)
class Vertex():
def __init__(self, x , y):
self.x = x
self.y = y
class Gameobject():
#orientation può valere N, E, W, S
orientation = ""
def __init__(self, x, y, width, height, sprite, type):
self.x = x
self.y = y
self.width = width
self.height = height
self.sprite = sprite
self.children = []
self.type = type
class Agent(Gameobject):
def __init__(self, x, y, width, height, sprite, type, rot):
Gameobject.__init__(self, x, y, width, height, sprite, type)
self.rot = rot
self.targetRot = rot #serve per calcolare di quanto roteare (e.g. targetRot - rot = gradi di rotazione)
self.image = 0
class Room(Gameobject):
vertex1 = Vertex(0, 0)
vertex2 = Vertex(0, 0)
vertex3 = Vertex(0, 0)
vertex4 = Vertex(0, 0)
door = Gameobject(0, 0, 0, 0, 0, DOOR)
def __init__(self, x, y, width, height, index, sprite, type):
Gameobject.__init__(self, x, y, width, height, sprite, type)
self.index = index
class Environment():
floor = Gameobject(0, 0, 0, 0, 0, FLOOR)
agentStartX = 198 #per il reset quando muore
agentStartY = 268 #per il reset quando muore
agent = Agent(9999, 9999, 8, 8, 0, AGENT, 90)
objectivePositions1 = [(160,240),(220,240),(230,280),(170, 320)]
objectivePositions2 = [(270,190),(250,325),(110,290),(160,170)]
objectivePositions3 = [(270,190),(250,325),(110,290),(160,170),(160,240),(220,240),(230,280),(170, 320)]
objective = Gameobject(9800, 9800, 15, 15, 0, OBJECTIVE)
isAgentLookingAtObjective = False
spritesLoaded = False
def __init__(self, envWidth, envHeight, multiplier, fakeCollisionMeter, doorFakeCollisionMeter):
self.envWidth = envWidth * multiplier
self.envHeight = envHeight * multiplier
self.multiplier = multiplier
self.prolog = Prolog()
self.fakeCollisionMeter = fakeCollisionMeter
self.doorFakeCollisionMeter = doorFakeCollisionMeter
self.rooms = []
prologQuery = "use_module(library(clpr))"
for solution in self.prolog.query(prologQuery):
print("CLPR loaded.")
def testGuizero(self):
app = App(title="Tesi Addestramento Robot 2019", width = 600, height = 600)
menuBox = Box(app, layout="grid", width=600, height=250)
def goToVistaAmbienti_cmd():
menuBox.hide()
vistaAmbientiBox.show()
def goToVistaGenerazione_cmd():
menuBox.hide()
vistaGenerazioneAmbientiBox.show()
generazioneAmbientiBox1.show()
generazioneAmbientiBox2.show()
generazioneAmbientiButtonBox.show()
def goToAddestraAgente_cmd():
menuBox.hide()
vistaAddestramentoBox.show()
Box(menuBox, height=50, width=600, grid=[0,0])
Box(menuBox, height=20, grid=[0,2])
Box(menuBox, height=20, grid=[0,4])
PushButton(menuBox, command=goToVistaAmbienti_cmd, text="Visualizza ambienti generati", width=18, height=1, grid=[0, 1])
PushButton(menuBox, command=goToVistaGenerazione_cmd, text="Genera nuovi ambienti", width=18, height=1, grid=[0, 3])
PushButton(menuBox, command=goToAddestraAgente_cmd, text="Addestra Agente", width=18, height=1, grid=[0, 5])
vistaAmbientiBox = Box(app, visible=False, layout="grid")
envFiles = [f for f in listdir("./environments") if isfile(join("./environments", f))]
listbox = ListBox(vistaAmbientiBox, items = envFiles, scrollbar = True, width = 350, height = 350, grid=[0,1])
def visualizza_cmd():
self.loadModel(listbox.value)
self.drawModel()
self.displayEnvironment()
def vistaAmbientiBack_cmd():
vistaAmbientiBox.hide()
menuBox.show()
Box(vistaAmbientiBox, height=40, grid=[0,0])
visualizzaButtonBox = Box(vistaAmbientiBox, layout="grid", grid=[0,2])
PushButton(visualizzaButtonBox, command=visualizza_cmd, text = "Visualizza", grid=[0,0])
PushButton(visualizzaButtonBox, command=vistaAmbientiBack_cmd, text="Indietro", grid=[1,0])
vistaGenerazioneAmbientiBox = Box(app, visible=False, layout="grid")
generazioneAmbientiBox1 = Box(vistaGenerazioneAmbientiBox, visible=False, layout="grid", grid=[0, 1])
generazioneAmbientiBox2 = Box(vistaGenerazioneAmbientiBox, visible=False, layout="grid", grid=[1, 1])
generazioneAmbientiButtonBox = Box(vistaGenerazioneAmbientiBox, visible=False, layout="grid", grid=[0,3])
def vistaGenerazioneAmbientiBack_cmd():
vistaGenerazioneAmbientiBox.hide()
generazioneAmbientiBox1.hide()
generazioneAmbientiBox2.hide()
generazioneAmbientiButtonBox.hide()
menuBox.show()
def generate_cmd():
info("Utilizzare il Generatore", "- Durante la generazione ambienti, premere il tasto \n'S' per salvare un ambiente e generare il successivo.\n\n- Premere il tasto 'N' per generare un nuovo ambiente\n scartando quello precedente.\n\n- Chiudere PyGame per tornare al menu.")
#avvia generazione ambienti
self.generateEnvironment(self.sliderBAR.value, self.sliderBR.value, self.sliderKI.value, self.sliderHA.value)
self.drawModel()
self.displayEnvironment(mode="generate")
Box(vistaGenerazioneAmbientiBox, height=40, grid=[0,0])
Text(generazioneAmbientiBox1, text="Numero camere da letto:", grid=[0,0], size=10, bg=LIGHT_GREEN)
self.sliderBR = Slider(generazioneAmbientiBox1, horizontal=True, end=2, grid=[1,0])
self.sliderBR.__setattr__("bg", LIGHT_GREEN)
Text(generazioneAmbientiBox2, text="MAX letti:", grid=[0,0], size=10, bg=LIGHT_GREEN)
self.sliderBR_B = Slider(generazioneAmbientiBox2, horizontal=True, end=2, grid=[1,0])
Text(generazioneAmbientiBox2, text="MAX armadi:", grid=[0,1], size=10, bg=LIGHT_GREEN)
self.sliderBR_W = Slider(generazioneAmbientiBox2, horizontal=True, end=2, grid=[1,1])
Box(generazioneAmbientiBox1, height=40, grid=[0,1])
Text(generazioneAmbientiBox1, text="Numero bagni:", grid=[0,2], size=10, bg=PINK)
self.sliderBAR = Slider(generazioneAmbientiBox1, horizontal=True, end=2, grid=[1,2])
self.sliderBAR.__setattr__("bg", PINK)
Text(generazioneAmbientiBox2, text="MAX water:", grid=[0,2], size=10, bg=PINK)
self.sliderBAR_T = Slider(generazioneAmbientiBox2, horizontal=True, end=1, grid=[1,2])
Text(generazioneAmbientiBox2, text="MAX docce:", grid=[0,3], size=10, bg=PINK)
self.sliderBAR_S = Slider(generazioneAmbientiBox2, horizontal=True, end=1, grid=[1,3])
Text(generazioneAmbientiBox2, text="MAX lavandini:", grid=[0,4], size=10, bg=PINK)
self.sliderBAR_SI = Slider(generazioneAmbientiBox2, horizontal=True, end=1, grid=[1,4])
Box(generazioneAmbientiBox1, height=40, grid=[0,3])
Text(generazioneAmbientiBox1, text="Numero cucine:", grid=[0,4], size=10, bg=BANANA)
self.sliderKI = Slider(generazioneAmbientiBox1, horizontal=True, end=2, grid=[1,4])
self.sliderKI.__setattr__("bg", BANANA)
Text(generazioneAmbientiBox2, text="MAX tavoli:", grid=[0,5], size=10, bg=BANANA)
self.sliderKI_KTA = Slider(generazioneAmbientiBox2, horizontal=True, end=1, grid=[1,5])
Text(generazioneAmbientiBox2, text="MAX banconi:", grid=[0,6], size=10, bg=BANANA)
self.sliderKI_D = Slider(generazioneAmbientiBox2, horizontal=True, end=3, grid=[1,6])
Box(generazioneAmbientiBox1, height=40, grid=[0,5])
Text(generazioneAmbientiBox1, text="Numero saloni:", grid=[0,6], size=10, bg=ORANGE)
self.sliderHA = Slider(generazioneAmbientiBox1, horizontal=True, end=2, grid=[1,6])
self.sliderHA.__setattr__("bg", ORANGE)
Text(generazioneAmbientiBox2, text="MAX tavoli:", grid=[0,7], size=10, bg=ORANGE)
self.sliderHA_HT = Slider(generazioneAmbientiBox2, horizontal=True, end=1, grid=[1,7])
Text(generazioneAmbientiBox2, text="MAX divani:", grid=[0,8], size=10, bg=ORANGE)
self.sliderHA_SO = Slider(generazioneAmbientiBox2, horizontal=True, end=2, grid=[1,8])
Text(generazioneAmbientiBox2, text="MAX scaffali:", grid=[0,9], size=10, bg=ORANGE)
self.sliderHA_CB = Slider(generazioneAmbientiBox2, horizontal=True, end=2, grid=[1,9])
Box(vistaGenerazioneAmbientiBox, height=40, grid=[0,2])
PushButton(generazioneAmbientiButtonBox, command=generate_cmd, text = "Genera Ambienti", grid=[0,0])
PushButton(generazioneAmbientiButtonBox, command=vistaGenerazioneAmbientiBack_cmd, text = "Indietro", grid=[1,0])
vistaAddestramentoBox = Box(app, visible=False, layout="grid")
envFiles = [f for f in listdir("./environments") if isfile(join("./environments", f))]
listbox2 = ListBox(vistaAddestramentoBox, items = envFiles, scrollbar = True, width = 350, height = 350, grid=[0,1])
def addestra_cmd():
self.loadModel(listbox2.value)
self.runTraining()
def vistaAddestramentoBack_cmd():
vistaAddestramentoBox.hide()
menuBox.show()
Box(vistaAddestramentoBox, height=40, grid=[0,0])
visualizzaButtonBox2 = Box(vistaAddestramentoBox, layout="grid", grid=[0,2])
PushButton(visualizzaButtonBox2, command=addestra_cmd, text = "Addestra", grid=[0,0])
PushButton(visualizzaButtonBox2, command=vistaAddestramentoBack_cmd, text="Indietro", grid=[1,0])
app.display()
def displayEnvironment(self, mode="view"):
running = True
clock = pygame.time.Clock()
pygame.init()
pygame.display.set_caption("Environment Generator")
frames = 1500
score = 0
while running:
self.screen.fill((30,30,30))
self.drawModel()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
self.reset()
if not running:
break
pressed = pygame.key.get_pressed()
if pressed[pygame.K_s] and mode == "generate":
self.saveGeneratedModel()
self.reset()
self.generateEnvironment(self.sliderBAR.value, self.sliderBR.value, self.sliderKI.value, self.sliderHA.value)
self.drawModel()
if pressed[pygame.K_n] and mode == "generate":
self.reset()
self.generateEnvironment(self.sliderBAR.value, self.sliderBR.value, self.sliderKI.value, self.sliderHA.value)
self.drawModel()
if pressed[pygame.K_UP] and pressed[pygame.K_RIGHT]:
self.agent.targetRot = 45
self.agent.x += 2
self.agent.y -= 2
elif pressed[pygame.K_UP] and pressed[pygame.K_LEFT]:
self.agent.targetRot = 135
self.agent.x -= 2
self.agent.y -= 2
elif pressed[pygame.K_DOWN] and pressed[pygame.K_RIGHT]:
self.agent.targetRot = 315
self.agent.x += 2
self.agent.y += 2
elif pressed[pygame.K_DOWN] and pressed[pygame.K_LEFT]:
self.agent.targetRot = 225
self.agent.x -= 2
self.agent.y += 2
elif pressed[pygame.K_UP]:
self.agent.targetRot = 90
self.agent.y -= 2
elif pressed[pygame.K_DOWN]:
self.agent.targetRot = 270
self.agent.y += 2
elif pressed[pygame.K_LEFT]:
self.agent.targetRot = 180
self.agent.x -= 2
elif pressed[pygame.K_RIGHT]:
self.agent.targetRot = 0
self.agent.x += 2
elif pressed[pygame.K_SPACE]:
#proiettiamo i 120 segmenti dall'occhio del robot
angleRange = 120
step = 3
eyePoint = self.agent.sprite.rect.center
# if self.agent.targetRot == 0:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width, self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)
# pygame.draw.circle(self.screen, (255,0,0), (self.agent.sprite.rect.x + self.agent.sprite.rect.width, int(self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)), 2)
# elif self.agent.targetRot == 90:
# eyePoint = (self.agent.x + self.agent.width/2, self.agent.y)
# pygame.draw.circle(self.screen, (255,0,0), (int(self.agent.x + self.agent.width/2), self.agent.y), 2)
# elif self.agent.targetRot == 180:
# eyePoint = (self.agent.sprite.rect.x, self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)
# pygame.draw.circle(self.screen, (255,0,0), (self.agent.sprite.rect.x, int(self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)), 2)
# elif self.agent.targetRot == 270:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width/2, self.agent.sprite.rect.y + self.agent.sprite.rect.height)
# pygame.draw.circle(self.screen, (255,0,0), (int(self.agent.sprite.rect.x + self.agent.sprite.rect.width/2), self.agent.sprite.rect.y + self.agent.sprite.rect.height), 2)
slope = (self.agent.targetRot + angleRange/2) % 360
testDistances = []
for i in range(0, angleRange, step):
x = math.cos(math.radians(slope)) * 220
y = math.sin(math.radians(slope)) * 220
viewPoint = (eyePoint[0] + x, eyePoint[1] - y) #punto di fine del segmento i
slope = (slope - step) % 360
#collision check
intersectionPoints = []
intersectionPointsDistances = []
for room in self.rooms:
intersectionPoint = self.checkLineRoomCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), room)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
for roomChild in room.children:
intersectionPoint = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), roomChild.sprite.rect)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
for child in roomChild.children:
intersectionPoint = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), child.sprite.rect)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
intersectionPointFloor = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), self.floor.sprite.rect)
if intersectionPointFloor is not None:
anyRoomContainsPoint = False
for room in self.rooms:
if self.checkRectContainsPoint(room.sprite.rect, intersectionPointFloor):
anyRoomContainsPoint = True
break
if not anyRoomContainsPoint:
intersectionPoints.append(intersectionPointFloor)
intersectionPointObjective = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), self.objective.sprite.rect)
if intersectionPointObjective is not None:
intersectionPoints.append(intersectionPointObjective)
for point in intersectionPoints:
intersectionPointsDistances.append(self.pointPointDistance(eyePoint, point))
if len(intersectionPoints) > 0:
testDistances.append(min(intersectionPointsDistances)/220)
chosenIndex = numpy.argmin(intersectionPointsDistances)
chosenPoint = intersectionPoints[chosenIndex]
if i/step >= 10 and i/step <= 30:
pygame.draw.circle(self.screen, (255,0,0), chosenPoint, 2)
if min(testDistances) < 0.049:
print("attivazione avoidance")
if self.agent.sprite.rect.colliderect(self.objective.sprite.rect):
self.resetObjective()
score += 1
pygame.display.update()
clock.tick(100)
frames -= 1
if frames == 0:
running = False
print("punteggio ottenuto: " + str(score))
pygame.quit()
def runTraining(self):
state_size = 40
slamAgent = SLAMAgent(state_size, 3)
#slamAgent.load("test", 0.19)
speed = 2
frames = 1500
for i in range(1,10001): #10k episodi
self.screen = pygame.display.set_mode((int(self.envWidth), int(self.envHeight)))
#pygame.init()
#self.reset()
#self.generateEnvironment(2, 2, 2, 2)
#self.drawModel()
#pygame.display.set_caption("Agent Training Episode {}/{}".format(i,10000))
done = False
frameCount = 0
self.resetAgent()
self.resetObjective()
state = numpy.reshape(self.projectSegments(), [1,state_size,3])
lastDistFromSpawn = 0
randomActions = 0
score = 0
while not done:
#renderOn = (i-1) % 100 == 0 #renderizzo un episodio ogni 100
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
slamAgent.save("test")
renderOn = True
if renderOn:
frameCount += 1
if frameCount == frames: #episodi lunghi massimo 10 secondi
done = True
self.screen.fill((30,30,30))
action, wasItRandom = slamAgent.act(state)
if wasItRandom:
randomActions += 1
if action == 0: #LOOK RIGHT
self.agent.targetRot = (self.agent.targetRot + 45) % 360
elif action == 1: #LOOK LEFT
self.agent.targetRot = (self.agent.targetRot - 45) % 360
elif action == 2: #GO FORWARD
if self.agent.targetRot == 90:
self.agent.y -= speed
elif self.agent.targetRot == 270:
self.agent.y += speed
elif self.agent.targetRot == 180:
self.agent.x -= speed
elif self.agent.targetRot == 0:
self.agent.x += speed
elif self.agent.targetRot == 45:
self.agent.y -= speed
self.agent.x += speed
elif self.agent.targetRot == 135:
self.agent.x -= speed
self.agent.y -= speed
elif self.agent.targetRot == 225:
self.agent.x -= speed
self.agent.y += speed
elif self.agent.targetRot == 315:
self.agent.x += speed
self.agent.y += speed
self.drawModel()
pygame.display.update()
if self.isAgentColliding():
currentMinDistance = state[0][0][1]
print("len(state[0]): " + str(len(state[0])))
for k in range(len(state[0])):
if state[0][k][1] < currentMinDistance and not state[0][k][2]:
print("state[0][k][1]: " + str(state[0][k][1]))
currentMinDistance = state[0][k][1]
print("currentMinDistance: " + str(currentMinDistance))
print("distanze: " + str(state))
done = True
currentDistFromSpawn = self.pointPointDistance((self.agent.sprite.rect.x, self.agent.sprite.rect.y), (self.agentStartX, self.agentStartY))
if currentDistFromSpawn > lastDistFromSpawn:
lastDistFromSpawn = currentDistFromSpawn
wasDistFromSpawnUpdated = 1
else:
wasDistFromSpawnUpdated = 0
#assegno reward
reward = 0
if self.agent.sprite.rect.colliderect(self.objective.sprite.rect): #spostato da isAgentColliding per cambiare reward
self.resetObjective()
reward += 1
next_state = numpy.reshape(self.projectSegments(), [1,state_size,3])
#reward += wasDistFromSpawnUpdated
score += reward
slamAgent.remember(state, action, reward, next_state, done)
state = next_state
else:
frameCount += 1
if frameCount == 600: #episodi lunghi massimo 10 secondi
done = True
reward = 0
action = slamAgent.act(state)
if action == 0: #UP
self.agent.targetRot = 90
self.agent.y -= 2
elif action == 1: #DOWN
self.agent.targetRot = 270
self.agent.y += 2
elif action == 2: #LEFT
self.agent.targetRot = 180
self.agent.x -= 2
elif action == 3: #RIGHT
self.agent.targetRot = 0
self.agent.x += 2
if self.isAgentColliding():
done = True
#sta sopravvivendo, 1 punto di reward
reward += 1
next_state = numpy.reshape(self.projectSegments(), [1,state_size,2])
if self.isAgentLookingAtObjective:
reward += 3
newDistToObjective = self.pointPointDistance((self.agent.x, self.agent.y), (self.objective.x, self.objective.y))
if newDistToObjective < distToObjective:
distToObjective = newDistToObjective
reward += 5
slamAgent.remember(state, action, reward, next_state, done)
state = next_state
if done:
break
print("Episodio {}/{}: fine al frame {}/{}, score: {}, random: {}%".format(i,10000,frameCount,frames, score, int((randomActions * 100)/frameCount)))
print("Inizio replay agente.")
slamAgent.replay(500)
print("Replay agente completato.")
print("Salvataggio pesi...")
slamAgent.save("test")
print("Salvataggio pesi completato.")
pygame.quit()
def isAgentColliding(self):
isAgentInRoom = False
for room in self.rooms:
if not room.sprite.rect.contains(self.agent.sprite.rect):
if self.agent.sprite.rect.colliderect(room.sprite.rect):
if room.door.width == 0:
if not (self.agent.sprite.rect.y >= room.door.sprite.rect.y and self.agent.sprite.rect.y+self.agent.sprite.rect.height <= room.door.sprite.rect.y+room.door.sprite.rect.height):
print("Collisione con stanza con porta verticale")
return True
else:
if not (self.agent.sprite.rect.x >= room.door.sprite.rect.x and self.agent.sprite.rect.x+self.agent.sprite.rect.width <= room.door.sprite.rect.x+room.door.sprite.rect.width):
print("Collisione con stanza con porta orizzontale")
return True
else:
isAgentInRoom = True
for roomChild in room.children:
if self.agent.sprite.rect.colliderect(roomChild.sprite.rect):
print("Collisione a causa di un oggetto della stanza")
return True
for child in roomChild.children:
if self.agent.sprite.rect.colliderect(child.sprite.rect):
print("Collisione a causa di un oggetto di un oggetto")
return True
if not isAgentInRoom:
if not self.floor.sprite.rect.contains(self.agent.sprite.rect):
print("Collisione con il floor")
return True
return False
def resetAgent(self):
self.agent.targetRot = 90
self.agent.x = self.agentStartX
self.agent.y = self.agentStartY
self.agent.sprite.rect.x = self.agentStartX
self.agent.sprite.rect.y = self.agentStartY
def resetObjective(self):
randomNextX = self.objective.sprite.rect.x
randomNextY = self.objective.sprite.rect.y
while randomNextX == self.objective.sprite.rect.x and randomNextY == self.objective.sprite.rect.y:
randomNextPosition = self.objectivePositions3[random.randrange(0,len(self.objectivePositions3))]
randomNextX = randomNextPosition[0]
randomNextY = randomNextPosition[1]
self.objective.sprite.rect.x = randomNextX
self.objective.sprite.rect.y = randomNextY
def projectSegments(self):
#proiettiamo i angleRange/step segmenti dall'occhio del robot
angleRange = 120
step = 3
eyePoint = self.agent.sprite.rect.center #punto di partenza dei segmenti
# if self.agent.targetRot == 0:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width, self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)
# elif self.agent.targetRot == 90:
# eyePoint = (self.agent.x + self.agent.width/2, self.agent.y)
# elif self.agent.targetRot == 180:
# eyePoint = (self.agent.sprite.rect.x, self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)
# elif self.agent.targetRot == 270:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width/2, self.agent.sprite.rect.y + self.agent.sprite.rect.height)
# elif self.agent.targetRot == 45:
# eyePoint = (self.agent.x + self.agent.width/2, self.agent.y)
# elif self.agent.targetRot == 180:
# eyePoint = (self.agent.sprite.rect.x, self.agent.sprite.rect.y + self.agent.sprite.rect.height/2)
# elif self.agent.targetRot == 270:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width/2, self.agent.sprite.rect.y + self.agent.sprite.rect.height)
# elif self.agent.targetRot == 270:
# eyePoint = (self.agent.sprite.rect.x + self.agent.sprite.rect.width/2, self.agent.sprite.rect.y + self.agent.sprite.rect.height)
slope = (self.agent.targetRot + angleRange/2) % 360
points = []
self.isAgentLookingAtObjective = False
for i in range(0, angleRange, step):
isAgentLookingAtObjective = False
x = math.cos(math.radians(slope)) * 220
y = math.sin(math.radians(slope)) * 220
viewPoint = (eyePoint[0] + x, eyePoint[1] - y) #punto di fine del segmento i
slope = (slope - step) % 360
#collision check
intersectionPoints = []
intersectionPointsDistances = []
for room in self.rooms:
intersectionPoint = self.checkLineRoomCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), room)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
for roomChild in room.children:
intersectionPoint = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), roomChild.sprite.rect)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
for child in roomChild.children:
intersectionPoint = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), child.sprite.rect)
if intersectionPoint is not None:
intersectionPoints.append(intersectionPoint)
intersectionPointFloor = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), self.floor.sprite.rect)
if intersectionPointFloor is not None:
anyRoomContainsPoint = False
for room in self.rooms:
if self.checkRectContainsPoint(room.sprite.rect, intersectionPointFloor):
anyRoomContainsPoint = True
break
if not anyRoomContainsPoint:
intersectionPoints.append(intersectionPointFloor)
intersectionPointObjective = self.checkLineRectCollision((eyePoint[0], eyePoint[1], viewPoint[0], viewPoint[1]), self.objective.sprite.rect)
if intersectionPointObjective is not None:
intersectionPoints.append(intersectionPointObjective)
for point in intersectionPoints:
intersectionPointsDistances.append(self.pointPointDistance(eyePoint, point))
if len(intersectionPoints) > 0:
chosenIndex = numpy.argmin(intersectionPointsDistances)
chosenPoint = intersectionPoints[chosenIndex]
if chosenPoint == intersectionPointObjective:
isAgentLookingAtObjective = True
self.isAgentLookingAtObjective = True
points.append((slope / 359, intersectionPointsDistances[chosenIndex] / 220, isAgentLookingAtObjective))
else:
points.append((slope / 359, 1, False)) #il raggio non ha colpito nulla, torno una tupla con distanza massima
return points
def checkLineRectCollision(self, line, rect): #line è (x1,y1,x2,y2) e rect il rect di pygame
intersectionPoints = []
eyePoint = (line[0], line[1])
point1 = self.checkLineLineCollision(line, (rect.x, rect.y, rect.x, rect.y+rect.height)) #lato ovest
point2 = self.checkLineLineCollision(line, (rect.x, rect.y+rect.height, rect.x+rect.width, rect.y+rect.height)) #lato nord
point3 = self.checkLineLineCollision(line, (rect.x+rect.width, rect.y+rect.height, rect.x+rect.width, rect.y)) #lato est
point4 = self.checkLineLineCollision(line, (rect.x, rect.y, rect.x+rect.width, rect.y)) #lato sud
if point1 is not None:
intersectionPoints.append(point1)
if point2 is not None:
intersectionPoints.append(point2)
if point3 is not None:
intersectionPoints.append(point3)
if point4 is not None:
intersectionPoints.append(point4)
intersectionPointsDistances = []
for point in intersectionPoints:
intersectionPointsDistances.append(self.pointPointDistance(eyePoint, point))
if len(intersectionPoints) > 0:
return intersectionPoints[numpy.argmin(intersectionPointsDistances)]
else:
return None
def checkLineRoomCollision(self, line, room): #ho differenziato i metodi per evitare il calcolo relativo alla door a tutti i rect non room
intersectionPoints = []
eyePoint = (line[0], line[1])
rect = room.sprite.rect
point1 = self.checkLineLineCollision(line, (rect.x, rect.y, rect.x, rect.y+rect.height)) #lato ovest
point2 = self.checkLineLineCollision(line, (rect.x, rect.y+rect.height, rect.x+rect.width, rect.y+rect.height)) #lato nord
point3 = self.checkLineLineCollision(line, (rect.x+rect.width, rect.y+rect.height, rect.x+rect.width, rect.y)) #lato est
point4 = self.checkLineLineCollision(line, (rect.x, rect.y, rect.x+rect.width, rect.y)) #lato sud
if point1 is not None:
if not room.door.sprite.rect.collidepoint(point1):
intersectionPoints.append(point1)
if point2 is not None:
if not room.door.sprite.rect.collidepoint(point2):
intersectionPoints.append(point2)
if point3 is not None:
if not room.door.sprite.rect.collidepoint(point3):
intersectionPoints.append(point3)
if point4 is not None:
if not room.door.sprite.rect.collidepoint(point4):
intersectionPoints.append(point4)
intersectionPointsDistances = []
for point in intersectionPoints:
intersectionPointsDistances.append(self.pointPointDistance(eyePoint, point))
if len(intersectionPoints) > 0:
return intersectionPoints[numpy.argmin(intersectionPointsDistances)]
else:
return None
def checkRectContainsPoint(self, rect, point):
return point[0] >= rect.x and point[0] <= rect.x+rect.width and point[1] >= rect.y and point[1] <= rect.y+rect.height
def pointPointDistance(self, point1, point2): #point1 è (x1,y1) -- point2 è (x2,y2)
return math.sqrt((point1[0]-point2[0])**2 + (point1[1]-point2[1])**2)
def checkLineLineCollision(self, line1, line2): #line1 = (x1,y1,x2,y2) -- line2 = (x3,y3,x4,y4)
x1 = line1[0]
y1 = line1[1]
x2 = line1[2]
y2 = line1[3]
x3 = line2[0]
y3 = line2[1]
x4 = line2[2]
y4 = line2[3]
try:
uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))
except ZeroDivisionError:
uA = 2 #di modo che non collida; tanto se il denominatore tende a zero la frazione tende a +inf
try:
uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1))
except ZeroDivisionError:
uB = 2 #di modo che non collida; tanto se il denominatore tende a zero la frazione tende a +inf
if uA >= 0 and uA <= 1 and uB >= 0 and uB <= 1:
return (int(x1 + (uA * (x2-x1))), int(y1 + (uA * (y2-y1))))
else:
return None
def reset(self):
self.envWidth = 15.0 * self.multiplier
self.envHeight = 15.0 * self.multiplier
self.floor = Gameobject(0, 0, 0, 0, 0, FLOOR)
self.rooms = []
def generateRoomsAndDoors(self, bathroomNumber, bedroomNumber, kitchenNumber, hallNumber):
#Numero stanze totali
roomNumber = bedroomNumber + kitchenNumber + bathroomNumber + hallNumber
roomDistanceThreshold = 10.0 + 3 * roomNumber
self.envWidth = self.envWidth + (8.0 * roomNumber * self.multiplier)
self.envHeight = self.envHeight + (8.0 * roomNumber * self.multiplier)
self.screen = pygame.display.set_mode((int(self.envWidth), int(self.envHeight)))
#Carichiamo le sprite in memoria
#---------------------------------------------------------------------
self.HALL_IMAGE = pygame.image.load('textures/hall_texture.png').convert_alpha()
self.KITCHEN_IMAGE = pygame.image.load('textures/kitchen_texture.png').convert_alpha()
self.BEDROOM_IMAGE = pygame.image.load('textures/bedroom_texture.png').convert_alpha()
self.BATHROOM_IMAGE = pygame.image.load('textures/bathroom_texture.png').convert_alpha()
self.SOFA_IMAGE = pygame.image.load('textures/sofa_texture.png').convert_alpha()
self.HALL_TABLE_IMAGE = pygame.image.load('textures/hall_table_texture.png').convert_alpha()
self.TABLE_IMAGE = pygame.image.load('textures/table_texture.png').convert_alpha()
self.CHAIR_IMAGE = pygame.image.load('textures/chair_texture.png').convert_alpha()
self.DESK_IMAGE = pygame.image.load('textures/desk_texture.png').convert_alpha()
self.BED_IMAGE = pygame.image.load('textures/green_bed_texture.png').convert_alpha()
self.BEDSIDE_IMAGE = pygame.image.load('textures/bedside_texture.png').convert_alpha()
self.WARDROBE_IMAGE = pygame.image.load('textures/wardrobe_texture.png').convert_alpha()
self.TOILET_IMAGE = pygame.image.load('textures/toilet_texture.png').convert_alpha()
self.SHOWER_IMAGE = pygame.image.load('textures/shower_texture.png').convert_alpha()
self.SINK_IMAGE = pygame.image.load('textures/sink_texture.png').convert_alpha()
self.DOOR_IMAGE = pygame.image.load('textures/door_texture.png').convert_alpha()
self.FLOOR_IMAGE = pygame.image.load('textures/floor_texture.png').convert_alpha()
self.AGENT_IMAGE = pygame.image.load('textures/agent_texture_mockup.png').convert_alpha()
self.OBJECTIVE_IMAGE = pygame.image.load('textures/objective_texture_mockup.png').convert_alpha()
#---------------------------------------------------------------------
self.typeToSprite = {
BEDROOM : self.BEDROOM_IMAGE,
BATHROOM : self.BATHROOM_IMAGE,
KITCHEN : self.KITCHEN_IMAGE,
HALL : self.HALL_IMAGE,
SOFA : self.SOFA_IMAGE,
HALL_TABLE : self.HALL_TABLE_IMAGE,
TABLE : self.TABLE_IMAGE,
CHAIR: self.CHAIR_IMAGE,
DESK: self.DESK_IMAGE,
BED: self.BED_IMAGE,
BEDSIDE : self.BEDSIDE_IMAGE,
WARDROBE : self.WARDROBE_IMAGE,
CUPBOARD : self.WARDROBE_IMAGE,
TOILET : self.TOILET_IMAGE,
SHOWER : self.SHOWER_IMAGE,
SINK : self.SINK_IMAGE,
DOOR : self.DOOR_IMAGE,
FLOOR : self.FLOOR_IMAGE,
AGENT: self.AGENT_IMAGE,
OBJECTIVE: self.OBJECTIVE_IMAGE
}
#Inizializzazione rect e image dell'agente
agentSprite = pygame.sprite.Sprite()
agentSprite.image = pygame.transform.scale(self.typeToSprite[AGENT], (int(self.agent.width), int(self.agent.height)))
agentSprite.rect = pygame.Rect(self.agent.x, self.agent.y, self.agent.width, self.agent.height)
self.agent.sprite = agentSprite
self.agent.image = self.agent.sprite.image
#Inizializzazione rect e image dell'obiettivo
objectiveSprite = pygame.sprite.Sprite()
objectiveSprite.image = pygame.transform.scale(self.typeToSprite[OBJECTIVE], (int(self.objective.width), int(self.objective.height)))
objectiveSprite.rect = pygame.Rect(self.objective.x, self.objective.y, self.objective.width, self.objective.height)
self.objective.sprite = objectiveSprite
headVariables = ""
predicateHead = "generateEnvironment(EnvWidth, EnvHeight, "
queryStart = "generateEnvironment("+str(self.envWidth)+", "+str(self.envHeight)+", "
for i in range(0, roomNumber):
headVariables += "R"+str(i)+"X"+", "
headVariables += "R"+str(i)+"Y"+", "
headVariables += "R"+str(i)+"W"+", "
headVariables += "R"+str(i)+"H"+", "
headVariables = headVariables[:-2]
predicateHead = predicateHead + headVariables
predicateHead += ") "
query = queryStart + headVariables + ") "
predicateBody = ":- repeat, "
roomType = []
for i in range(0, bedroomNumber):
roomType.append(BEDROOM)
for i in range(0, bathroomNumber):
roomType.append(BATHROOM)
for i in range(0, kitchenNumber):
roomType.append(KITCHEN)
for i in range(0, hallNumber):
roomType.append(HALL)
#generazione stanze (vuote)
for i in range(0, roomNumber):
if roomType[i] == BEDROOM:
predicateBody += "random("+str(12.0*self.multiplier)+", "+str(17.0*self.multiplier)+", R"+str(i)+"W), "
predicateBody += "random("+str(12.0*self.multiplier)+", "+str(17.0*self.multiplier)+", R"+str(i)+"H), "
predicateBody += "WSUB"+str(i)+" is EnvWidth - R"+str(i)+"W, random(0.0, WSUB"+str(i)+", R"+str(i)+"X), "
predicateBody += "HSUB"+str(i)+" is EnvHeight - R"+str(i)+"H, random(0.0, HSUB"+str(i)+", R"+str(i)+"Y), "
if roomType[i] == BATHROOM:
predicateBody += "random("+str(8.0*self.multiplier)+", "+str(12.0*self.multiplier)+", R"+str(i)+"W), "
predicateBody += "random("+str(8.0*self.multiplier)+", "+str(12.0*self.multiplier)+", R"+str(i)+"H), "
predicateBody += "WSUB"+str(i)+" is EnvWidth - R"+str(i)+"W, random(0.0, WSUB"+str(i)+", R"+str(i)+"X), "
predicateBody += "HSUB"+str(i)+" is EnvHeight - R"+str(i)+"H, random(0.0, HSUB"+str(i)+", R"+str(i)+"Y), "
if roomType[i] == KITCHEN:
predicateBody += "random("+str(10.0*self.multiplier)+", "+str(15.0*self.multiplier)+", R"+str(i)+"W), "
predicateBody += "random("+str(10.0*self.multiplier)+", "+str(15.0*self.multiplier)+", R"+str(i)+"H), "
predicateBody += "WSUB"+str(i)+" is EnvWidth - R"+str(i)+"W, random(0.0, WSUB"+str(i)+", R"+str(i)+"X), "
predicateBody += "HSUB"+str(i)+" is EnvHeight - R"+str(i)+"H, random(0.0, HSUB"+str(i)+", R"+str(i)+"Y), "
if roomType[i] == HALL:
predicateBody += "random("+str(15.0*self.multiplier)+", "+str(20.0*self.multiplier)+", R"+str(i)+"W), "
predicateBody += "random("+str(15.0*self.multiplier)+", "+str(20.0*self.multiplier)+", R"+str(i)+"H), "
predicateBody += "WSUB"+str(i)+" is EnvWidth - R"+str(i)+"W, random(0.0, WSUB"+str(i)+", R"+str(i)+"X), "
predicateBody += "HSUB"+str(i)+" is EnvHeight - R"+str(i)+"H, random(0.0, HSUB"+str(i)+", R"+str(i)+"Y), "
#collision detection
for i in range(0, roomNumber):
for j in range(i+1, roomNumber):
predicateBody += "{(R"+str(i)+"X + R"+str(i)+"W + "+str(self.fakeCollisionMeter*self.multiplier)+" =< R"+str(j)+"X ; R"+str(j)+"X + R"+str(j)+"W + "+str(self.fakeCollisionMeter*self.multiplier)+" =< R"+str(i)+"X) ; (R"+str(i)+"Y + R"+str(i)+"H + "+str(self.fakeCollisionMeter*self.multiplier)+" =< R"+str(j)+"Y ; R"+str(j)+"Y + R"+str(j)+"H + "+str(self.fakeCollisionMeter*self.multiplier)+" =< R"+str(i)+"Y)}, "
#distanza stanze generate dal centro "di massa"
if(roomNumber > 1):
predicateBody += "CentroX is ("
for i in range(0, roomNumber):
predicateBody += "R"+str(i)+"X + "
predicateBody = predicateBody[:-3]
predicateBody += ") / "+str(roomNumber)+", "
predicateBody += "CentroY is ("
for i in range(0, roomNumber):
predicateBody += "R"+str(i)+"Y + "
predicateBody = predicateBody[:-3]
predicateBody += ") / "+str(roomNumber)+", "
for i in range(0, roomNumber):
predicateBody += "DistanzaRoom"+str(i)+" is "
predicateBody += "sqrt(((R"+str(i)+"X + R"+str(i)+"W/2) - (CentroX))^2 + ((R"+str(i)+"Y + R"+str(i)+"H/2) - (CentroY))^2), "
predicateBody += "{DistanzaRoom"+str(i)+" =< "+str(roomDistanceThreshold*self.multiplier)+"}, "
predicateBody = predicateBody[:-2]
predicateBody += ", !"
# print("Il predicato per generare l'ambiente è:")
print(predicateHead + predicateBody)
# print("La query è: ")
# print(query)
self.prolog.assertz(predicateHead + predicateBody)
prologQuery = query
rooms = []
for sol in self.prolog.query(prologQuery):
# print("La soluzione alla generazione dell'ambiente è:")
# print(sol)
for i in range(0, roomNumber):
roomSprite = pygame.sprite.Sprite()
if roomType[i] == BATHROOM:
roomSprite.image = pygame.transform.scale(self.BATHROOM_IMAGE, (int(sol["R"+str(i)+"W"]), int(sol["R"+str(i)+"H"])))
elif roomType[i] == KITCHEN:
roomSprite.image = pygame.transform.scale(self.KITCHEN_IMAGE, (int(sol["R"+str(i)+"W"]), int(sol["R"+str(i)+"H"])))
elif roomType[i] == BEDROOM:
roomSprite.image = pygame.transform.scale(self.BEDROOM_IMAGE, (int(sol["R"+str(i)+"W"]), int(sol["R"+str(i)+"H"])))
else:
roomSprite.image = pygame.transform.scale(self.HALL_IMAGE, (int(sol["R"+str(i)+"W"]), int(sol["R"+str(i)+"H"])))
roomSprite.rect = pygame.Rect(sol["R"+str(i)+"X"], sol["R"+str(i)+"Y"], sol["R"+str(i)+"W"], sol["R"+str(i)+"H"])
room = Room(sol["R"+str(i)+"X"], sol["R"+str(i)+"Y"], sol["R"+str(i)+"W"], sol["R"+str(i)+"H"], i, roomSprite, roomType[i])
room.vertex1 = Vertex(room.x, room.y + room.height)
room.vertex2 = Vertex(room.x + room.width, room.y + room.height)
room.vertex3 = Vertex(room.x + room.width, room.y)
room.vertex4 = Vertex(room.x, room.y)
rooms.append(room)
self.rooms = rooms
self.prolog.retract(predicateHead + predicateBody)
#Generazione baricentro delle stanze
barycenterX = 0
barycenterY = 0
for room in self.rooms:
barycenterX += room.x + room.width/2
barycenterY += room.y + room.height/2
barycenterX /= len(self.rooms)
barycenterY /= len(self.rooms)
self.barycenter = Vertex(barycenterX, barycenterY)
#generazione floor (quadratone)
vertexesXs = []
vertexesYs = []
for room in self.rooms:
vertex1Distance = math.sqrt((room.vertex1.x - self.barycenter.x)**2 + (room.vertex1.y - self.barycenter.y)**2)
vertex2Distance = math.sqrt((room.vertex2.x - self.barycenter.x)**2 + (room.vertex2.y - self.barycenter.y)**2)
vertex3Distance = math.sqrt((room.vertex3.x - self.barycenter.x)**2 + (room.vertex3.y - self.barycenter.y)**2)
vertex4Distance = math.sqrt((room.vertex4.x - self.barycenter.x)**2 + (room.vertex4.y - self.barycenter.y)**2)
minDistance = min(vertex1Distance, vertex2Distance, vertex3Distance, vertex4Distance)
if minDistance == vertex1Distance:
vertexesXs.append(room.vertex1.x)
vertexesYs.append(room.vertex1.y)
elif minDistance == vertex2Distance:
vertexesXs.append(room.vertex2.x)
vertexesYs.append(room.vertex2.y)
elif minDistance == vertex3Distance:
vertexesXs.append(room.vertex3.x)
vertexesYs.append(room.vertex3.y)
else:
vertexesXs.append(room.vertex4.x)
vertexesYs.append(room.vertex4.y)
spaceMultiplier = (random.random()*3 + 3)*self.multiplier
floorSprite = pygame.sprite.Sprite()
floorSprite.image = self.FLOOR_IMAGE
floorSprite.image = pygame.transform.scale(floorSprite.image, (int(max(vertexesXs)-min(vertexesXs) + spaceMultiplier*2), int(max(vertexesYs)-min(vertexesYs) + spaceMultiplier*2)))
floorSprite.rect = pygame.Rect(min(vertexesXs) - spaceMultiplier, min(vertexesYs) - spaceMultiplier, max(vertexesXs)-min(vertexesXs) + spaceMultiplier*2, max(vertexesYs)-min(vertexesYs) + spaceMultiplier*2)
self.floor = Gameobject(min(vertexesXs) - spaceMultiplier, min(vertexesYs) - spaceMultiplier, max(vertexesXs)-min(vertexesXs) + spaceMultiplier*2, max(vertexesYs)-min(vertexesYs) + spaceMultiplier*2, floorSprite, FLOOR)
for room in self.rooms:
lato1 = (room.vertex1, room.vertex4)
lato2 = (room.vertex1, room.vertex2)
lato3 = (room.vertex2, room.vertex3)
lato4 = (room.vertex3, room.vertex4)
distanzaLato1 = math.sqrt((((lato1[0].x + lato1[1].x)/2) - self.barycenter.x)**2 + (((lato1[0].y + lato1[1].y)/2) - self.barycenter.y)**2)
distanzaLato2 = math.sqrt((((lato2[0].x + lato2[1].x)/2) - self.barycenter.x)**2 + (((lato2[0].y + lato2[1].y)/2) - self.barycenter.y)**2)
distanzaLato3 = math.sqrt((((lato3[0].x + lato3[1].x)/2) - self.barycenter.x)**2 + (((lato3[0].y + lato3[1].y)/2) - self.barycenter.y)**2)
distanzaLato4 = math.sqrt((((lato4[0].x + lato4[1].x)/2) - self.barycenter.x)**2 + (((lato4[0].y + lato4[1].y)/2) - self.barycenter.y)**2)
distanzaMinima = min(distanzaLato1, distanzaLato2, distanzaLato3, distanzaLato4)
if distanzaMinima == distanzaLato1:
constraintsSatisfied = False
while not constraintsSatisfied:
doorY = random.random() * (room.height - 2.5*self.multiplier) + room.y
if doorY >= self.floor.y and doorY + 2.5*self.multiplier <= self.floor.y + self.floor.height:
constraintsSatisfied = True
doorSprite = pygame.sprite.Sprite()
doorSprite.image = self.DOOR_IMAGE
doorSprite.image = pygame.transform.scale(doorSprite.image, (int(1.0*self.multiplier), int(2.5*self.multiplier)))
#doorSprite.rect = pygame.Rect(room.x, doorY, 0.5*self.multiplier, 2.5*self.multiplier)
room.door = Gameobject(room.x, doorY, 0, 2.5*self.multiplier, doorSprite, DOOR)
elif distanzaMinima == distanzaLato2:
constraintsSatisfied = False
while not constraintsSatisfied:
doorX = random.random() * (room.width - 2.5*self.multiplier) + room.x
if doorX >= self.floor.x and doorX + 2.5*self.multiplier <= self.floor.x + self.floor.width:
constraintsSatisfied = True
doorSprite = pygame.sprite.Sprite()
doorSprite.image = self.DOOR_IMAGE
doorSprite.image = pygame.transform.rotate(doorSprite.image, 90)
doorSprite.image = pygame.transform.scale(doorSprite.image, (int(2.5*self.multiplier), int(1.0*self.multiplier)))
#doorSprite.rect = pygame.Rect(doorX, room.y + room.height, 2.5*self.multiplier, 0.5*self.multiplier)
room.door = Gameobject(doorX, room.y + room.height, 2.5*self.multiplier, 0, doorSprite, DOOR)
elif distanzaMinima == distanzaLato3:
constraintsSatisfied = False
while not constraintsSatisfied:
doorY = random.random() * (room.height - 2.5*self.multiplier) + room.y
if doorY >= self.floor.y and doorY + 2.5*self.multiplier <= self.floor.y + self.floor.height:
constraintsSatisfied = True
doorSprite = pygame.sprite.Sprite()
doorSprite.image = self.DOOR_IMAGE
doorSprite.image = pygame.transform.scale(doorSprite.image, (int(1.0*self.multiplier), int(2.5*self.multiplier)))
#doorSprite.rect = pygame.Rect(room.x + room.width, doorY, 0.5*self.multiplier, 2.5*self.multiplier)
room.door = Gameobject(room.x + room.width, doorY, 0, 2.5*self.multiplier, doorSprite, DOOR)
else:
constraintsSatisfied = False
while not constraintsSatisfied:
doorX = random.random() * (room.width - 2.5*self.multiplier) + room.x
if doorX >= self.floor.x and doorX + 2.5*self.multiplier <= self.floor.x + self.floor.width:
constraintsSatisfied = True
doorSprite = pygame.sprite.Sprite()
doorSprite.image = self.DOOR_IMAGE
doorSprite.image = pygame.transform.rotate(doorSprite.image, 90)
doorSprite.image = pygame.transform.scale(doorSprite.image, (int(2.5*self.multiplier), int(1.0*self.multiplier)))
#doorSprite.rect = pygame.Rect(doorX, room.y, 2.5*self.multiplier, 0.5*self.multiplier)
room.door = Gameobject(doorX, room.y, 2.5*self.multiplier, 0, doorSprite, DOOR)
return rooms
def drawModel(self):
if len(self.rooms) > 1:
#Quadrato dell'area relativa ai corridoi
self.screen.blit(self.floor.sprite.image, self.floor.sprite.rect)
pygame.draw.rect(self.screen, WHITE, self.floor.sprite.rect, 2)
for room in self.rooms:
self.screen.blit(room.sprite.image, room.sprite.rect)
pygame.draw.rect(self.screen, WHITE, room.sprite.rect, 2)
if room.door.width == 0:
blitRect = pygame.Rect(room.door.x - 0.5*self.multiplier, room.door.y, 1.0*self.multiplier, room.door.height)
self.screen.blit(room.door.sprite.image, blitRect)
room.door.sprite.rect = blitRect