forked from EnJiang/USV-Game
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.py
executable file
·966 lines (678 loc) · 35.7 KB
/
game.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
# coding:utf-8
import pygame
from pygame.locals import *
import copy
from collections import namedtuple
from time import sleep
import numpy as np
from math import sin, cos, pi
import os
from PIL import Image,ImageDraw
import cv2
# import matplotlib
# matplotlib.use('TkAgg')
# import matplotlib.pyplot as plt
# plt.ion()
# fig = plt.figure()
# ax = fig.add_subplot(111)
class BasicGame(object):
"""基本游戏逻辑"""
def __init__(self):
super(BasicGame, self).__init__()
self.is_target_safe = True
def set_map(self, gameMap):
self.map = gameMap
def update(self):
for ship in self.map.ships:
ship.move()
self.check_target()
#print (self.map.str2())
def check_target(self):
target_x, target_y = self.map.target_coordinate()
for ship in self.map.enemy_ships:
ship_x, ship_y = ship.coordinate()
if(ship_x == target_x and ship_y == target_y):
self.is_target_safe = False
def is_game_over(self):
return not self.is_target_safe
def start(self):
while not self.is_game_over():
self.update()
print ('----------------------------------------------------------------------------------------')
print ("press any key to continue")
#raw_input()
input()
print ("you lost!")
class MyGame(BasicGame):
def __init__(self):
super(MyGame, self).__init__()
self.recordlist = []
self.arriveTarget = 0
self.arriveObstacle = 0
def update(self):
# print('update_之前:输出ma.str2()函数的地图形式::')
# print(self.map.str2())
try:
for ship in self.map.friendly_ships:
#if ship.uid == 0: recenv = ship.recordenv()
if not ship.is_enemy: recenv = ship.recordenv()
# if ship.uid == 0: recaction = ship.recordaction()
if not ship.is_enemy: recaction = ship.recordaction()
ship.move()
self.recordlist.append((recenv, recaction))
self.check_target()
self.check_obstacle()
#这里添加enemy_ships的随机变动:上下左右或是原地(在USV.py中添加moverandom()方法)
for ship in self.map.enemy_ships:
ship.moverandom()
except IndexError as e:
self.is_target_safe = False
self.arriveObstacle = True
# print('update_之后:输出ma.str2()函数的地图形式::')
# print(self.map.str2())
def check_target(self):
target_x, target_y = self.map.target_coordinate()
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
if(ship_x == target_x and ship_y == target_y):
self.is_target_safe = True
self.arriveTarget = True
def check_obstacle(self):
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
for obstacle in self.map.enemy_ships:
obstacle_x, obstacle_y = obstacle.coordinate()
if(ship_x == obstacle_x and ship_y == obstacle_y):
self.is_target_safe = False
self.arriveObstacle = True
def is_game_over(self):
return not self.is_target_safe
def start(self):
while not self.is_game_over():
#print('game-start-update前的地图形式:');print(self.map.str2())
self.update()
# print('\n决策链(当前环境env + 采取动作action)',self.recordlist)
print(self.map.env_matrix())
print ('----------------------------------------------------------------------------------------')
#print ("press any key to continue");input()
print ("game over!")
print('是否到达终点:(0表示没,1表示到达)',self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
class BasicGUIGame(BasicGame):
"""基本的GUI引擎, 使用pygame"""
def __init__(self):
super(BasicGUIGame, self).__init__()
self.gui = pygame
self.gui_init()
def gui_init(self):
self.gui_screen = self.gui.display.set_mode((800, 600), 0, 32)
self.gui.display.set_caption("USV")
self.gui_background = self.gui.image.load(
'src/img/bg/seaSurface.png').convert()
self.gui_friendly_ship = self.gui.image.load(
'src/img/usv/friendly.png').convert_alpha()
self.gui_enemy_ship = self.gui.image.load(
'src/img/usv/enemy.png').convert_alpha()
self.gui_target = self.gui.image.load(
'src/img/target/blueTarget.png').convert_alpha()
def update(self):
'''地图里面为了符合人的习惯,定整个矩阵的左下角为(0,0), x轴负方向为0°, y轴正方形为90°
和计算机矩阵左上角为(0,0)的习惯稍微不同. 而且pygame已经做过校正了, x就是水平方向,
所以有(x1, y1)=(x, height-y)
pygame定义,负角度顺时针转动,所以我们角度加个负'''
x_unit = 800.0 / self.map.width
y_unit = 600.0 / self.map.height
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui_screen.blit(self.gui_background, (0, 0))
for ship in self.map.ships:
ship.move()
ship_x, ship_y = ship.coordinate()
ship_w, ship_h = x_unit, y_unit
if(ship.is_enemy):
gui_enemy_ship = self.gui.transform.rotozoom(
self.gui_enemy_ship, -ship.direction, x_unit / 16)
self.gui_screen.blit(
gui_enemy_ship, (ship_x * x_unit - ship_w / 2, (self.map.height - ship_y) * y_unit - ship_h / 2))
else:
gui_friendly_ship = self.gui.transform.rotozoom(
self.gui_friendly_ship, -ship.direction, x_unit / 16)
self.gui_screen.blit(
gui_friendly_ship, (ship_x * x_unit - ship_w / 2, (self.map.height - ship_y) * y_unit - ship_h / 2))
self.check_target()
target_x, target_y = self.map.target_coordinate()
target_w, target_h = x_unit, y_unit
self.gui_screen.blit(
self.gui.transform.rotozoom(self.gui_target, 0, x_unit / 16),
(target_x * x_unit - target_w / 2, (self.map.height - target_y) * y_unit - target_h / 2))
self.gui.display.update()
def start(self):
while not self.is_game_over():
self.update()
sleep(0.01)
self.gui.display.set_caption("Game Over!")
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui.display.update()
class MyContinueGame(BasicGame):
def __init__(self,obsmove):
super(MyContinueGame, self).__init__()
self.arriveTarget = 0
self.arriveObstacle = 0
self.arriveUnlegal = 0
self.obsMoveBool = obsmove #默认false,障碍物不随机移动
#获取船体当前的状态信息 u,v,r(速度信息)
def get_uvr_u(self):
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
return ship.u
def get_uvr_v(self):
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
return ship.v
def get_uvr_r(self):
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
return ship.r
#获取船体当前的航向
def get_xyh_heading(self):
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
return ship.heading
def update(self):
#print('update_之前:输出map.env_matrix()函数的地图形式::')
#np.set_printoptions(threshold=np.nan)
#print(self.map.env_matrix())
# ax.set_xlim(0,100)
# ax.set_ylim(100,0)
#
# import time
# start = time.time()
# temptestoutput = self.map.env_matrix()
# # print('输出值为1的位置:',np.argwhere(temptestoutput == 1))
# # print('输出值为-1的位置:', np.argwhere(temptestoutput == -1))
# # print('输出值为2的位置:', np.argwhere(temptestoutput == 2))
# lines = []
# for i in range(len(np.argwhere(temptestoutput == 1))):
# lines.append(ax.scatter(np.argwhere(temptestoutput == 1)[i][1], np.argwhere(temptestoutput == 1)[i][0], s=6, c='g', marker='.')) #绿色
#
# for i in range(len(np.argwhere(temptestoutput == -1))):
# lines.append(ax.scatter(np.argwhere(temptestoutput == -1)[i][1], np.argwhere(temptestoutput == -1)[i][0], s=60, c='r',marker='*')) #红色终点
# for i in range(len(np.argwhere(temptestoutput == 2))):
# lines.append(ax.scatter(np.argwhere(temptestoutput == 2)[i][1], np.argwhere(temptestoutput == 2)[i][0], s=60, c='b',marker='o')) #蓝色USV
# plt.pause(0.01)
# for each in lines:
# each.remove()
# plt.show()
# print(time.time() - start)
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
ship.move()
self.check_target()
self.check_obstacle()
self.check_legal()
if self.obsMoveBool == False:
pass
else:
#添加圆形障碍物的移动(需在其移动方法中添加对所随机移动的下一位置的合法性判断,若下一位置不合法则保持原位置)
for obstacle in self.map.obs:
obstacle.obsRandomMove()
#print('update_之后:输出ma.env_matrix()函数的地图形式::')
#print(self.map.env_matrix())
#USV是否到达终点
def check_target(self):
target_x, target_y = self.map.target_coordinate()
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
if ((ship_x - target_x)*(ship_x - target_x) + (ship_y - target_y)*(ship_y - target_y)) <= ((ship.radius + self.map.target_radius)*(ship.radius + self.map.target_radius)):
self.is_target_safe = False
self.arriveTarget = 1
break
#USV是否碰到障碍物
def check_obstacle(self):
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
for obstacle in self.map.obs:
if ((ship_x - obstacle.x)*(ship_x - obstacle.x) + (ship_y - obstacle.y)*(ship_y - obstacle.y)) <= ((ship.radius + obstacle.radius)*(ship.radius + obstacle.radius)):
self.is_target_safe = False
self.arriveObstacle = 1
break
#USV是否越界
def check_legal(self):
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
width, height = self.map.width,self.map.height
if ( ship_x < ship.radius or ship_y < ship.radius or ship_x > (width - 1 - ship.radius) or ship_y > (height - 1 - ship.radius)):
self.is_target_safe = False
self.arriveUnlegal = 1
def is_game_over(self):
return not self.is_target_safe
def start(self):
i = 0
while not self.is_game_over():
#print('game-start-update前的地图形式:');#print(self.map.str2())
self.update()
i += 1
# print ('----------------------------------------------------------------------------------------')
#print ("press any key to continue");input()
print ("game over!")
print('是否到达终点:(0表示没,1表示到达)',self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
print('是否走出区域:(0表示没,1表示走出去)', self.arriveUnlegal)
print('game-update次数',i)
class BasicPyGame(MyContinueGame):
"""基本的GUI引擎, 使用pygame"""
def __init__(self, obsmove):
super(BasicPyGame, self).__init__(obsmove)
self.gui = pygame
self.gui_init()
self.obsMoveBool = obsmove # 默认false,障碍物不随机移动
def gui_init(self):
self.gui_screen = self.gui.display.set_mode((800, 800), 0, 32)
self.gui.display.set_caption("USV")
#1.USV的五个定点(头1,左上2,左下3,右上4,右下5)根据中心点即USV位置点和其半径求解
#注意顺序(头1,左上2,右上4,右下5,左下3),连接成一个闭合多边行
#师弟参数格式
# def allPointUSV(self, curPoint, USVradius):
# pointList = []
# halfR = USVradius/2
# pointList.append((curPoint[0], curPoint[1]-USVradius))
#
# pointList.append((curPoint[0] - halfR, curPoint[1]))
#
# pointList.append((curPoint[0] - halfR, curPoint[1] + USVradius))
# pointList.append((curPoint[0] + halfR, curPoint[1] + USVradius))
#
# pointList.append((curPoint[0] + halfR, curPoint[1]))
#
# return pointList
#柯老师版参数
def allPointUSV(self, curPoint, USVradius):
pointList = []
halfR = USVradius/2
pointList.append((curPoint[0] - USVradius, curPoint[1]))
pointList.append((curPoint[0], curPoint[1] + halfR))
pointList.append((curPoint[0] + USVradius, curPoint[1] + halfR))
pointList.append((curPoint[0] + USVradius, curPoint[1] - halfR))
pointList.append((curPoint[0], curPoint[1] - halfR))
return pointList
def transferAngle(self, pointList, point, angle):
angle = 360 - angle
transList = []
for i in range(len(pointList)):
trans_x = (pointList[i][0] - point[0]) * cos(angle*pi/180) + (pointList[i][1] - point[1])*sin(angle*pi/180) + point[0]
trans_y = (pointList[i][0] - point[0]) * sin(angle*pi/180) + (pointList[i][1] - point[1])*cos(angle*pi/180) + point[1]
trans_x = float("%.4f" % trans_x)
trans_y = float("%.4f" % trans_y)
transList.append((trans_x, trans_y))
return transList
#2输入当前点(x,y)的List,所绕点(x0,y0),逆时针旋转的角度数Angle,输出是旋转后的五个点坐标
#所绕点应该是移动后的USV位置,逆时针旋转的角度是USV.heading
#https://www.cnblogs.com/MachineVision/p/5778677.html
# def transferAngle(self, pointList, point, angle):
# transList = []
# for i in range(len(pointList)):
# trans_x = (pointList[i][0] - point[0]) * cos(angle*pi/180) + (pointList[i][1] - point[1])*sin(angle*pi/180) + point[0]
# trans_y = (pointList[i][0] - point[0]) * sin(angle*pi/180) + (pointList[i][1] - point[1])*cos(angle*pi/180) + point[1]
# trans_x = float("%.4f" % trans_x)
# trans_y = float("%.4f" % trans_y)
# transList.append((trans_x, trans_y))
# return transList
#3.将transList中 每一点的坐标(x,y) 换成(y*y_unit,x*unit)
def pyTrans(self, transList, xunit, yunit):
pyTransList = []
for i in range(len(transList)):
px = transList[i][1] * yunit
py = transList[i][0] * xunit
pyTransList.append((px,py))
#print('pygame画图上的坐标:', pyTransList)
return pyTransList
#4.获取当前速度方向:即self.ax 与 self.ay的向量合成,是当前速度方向
def update(self):
x_unit = 800.0 / self.map.width
y_unit = 800.0 / self.map.height
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui_screen.fill((99,184,255)) # (255,255,255)白色填充
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
ship.move()
#USV: ship_x * x_unit, ship_y * y_unit 此时USV的中心在画布的位置\\ship.heading
USVPoint = self.allPointUSV((ship.x,ship.y), ship.radius)
TransUSVPoint = self.transferAngle(USVPoint, (ship.x,ship.y), ship.heading)
PyTransList = self.pyTrans(TransUSVPoint, x_unit, y_unit)
self.gui.draw.polygon(self.gui_screen, (0, 255, 0), PyTransList)
#获取船体当前加速度ship.get_curSpeedDirection(),是左下角是(0,0)的情况,
#但这里计算的坐标是左上角是(0,0)的情况,所以变换关系是:ship.x - speedDirectPosy, ship.y + speedDirectPosx
speedDirectPosx, speedDirectPosy = ship.get_curSpeedDirection()
# af_speedDirectPosx = (ship.x - speedDirectPosy) * x_unit
# af_speedDirectPosy = (ship.y + speedDirectPosx) * y_unit
af_speedDirectPosx = (ship.x - speedDirectPosx) * x_unit
af_speedDirectPosy = (ship.y + speedDirectPosy) * y_unit
#加速度导引线
self.gui.draw.line(self.gui_screen, (0, 255, 0), [ship.y * y_unit, ship.x * x_unit],[af_speedDirectPosy, af_speedDirectPosx], 1)
# af_speedDirectPosx2 = (ship.x + speedDirectPosx) * x_unit
# af_speedDirectPosy2 = (ship.y + speedDirectPosy) * y_unit
# # 加速度导引线
# self.gui.draw.line(self.gui_screen, (0, 255, 0), [ship.y * y_unit, ship.x * x_unit],[af_speedDirectPosy2, af_speedDirectPosx2], 1)
#print('测试速度方向值:',speedDirectPosx, speedDirectPosy)
# speedDirectPosx2, speedDirectPosy2 = ship.get_curSpeedDirection2()
# af_speedDirectPosx2 = (speedDirectPosx2 + ship.x) * x_unit
# af_speedDirectPosy2 = (speedDirectPosy2 + ship.y) * y_unit
# speedDirectPosx3, speedDirectPosy3 = ship.get_curSpeedDirection3()
# af_speedDirectPosx3 = (speedDirectPosx3 + ship.x) * x_unit
# af_speedDirectPosy3 = (speedDirectPosy3 + ship.y) * y_unit
#self.gui.draw.line(self.gui_screen, (0, 0, 0), [ship.y * y_unit, ship.x * x_unit],[af_speedDirectPosy2, af_speedDirectPosx2], 1)
#self.gui.draw.line(self.gui_screen, (255, 0, 0), [ship.y * y_unit, ship.x * x_unit],[af_speedDirectPosy3, af_speedDirectPosx3], 1)
self.check_target()
self.check_obstacle()
self.check_legal()
if self.obsMoveBool == False:
for obstacle in self.map.obs:
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y*y_unit), int(obstacle.x*x_unit)], int(obstacle.radius*x_unit))
pass
else:
#添加圆形障碍物的移动(需在其移动方法中添加对所随机移动的下一位置的合法性判断,若下一位置不合法则保持原位置)
for obstacle in self.map.obs:
obstacle.obsRandomMove()
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y*y_unit), int(obstacle.x*x_unit)], int(obstacle.radius*x_unit))
# 画终点:中心点 + radius
target_x, target_y = self.map.target_coordinate()
self.gui.draw.circle(self.gui_screen, (255, 0, 0), [int(target_y*y_unit), int(target_x*x_unit)], int(self.map.target_radius*x_unit))
#更新
self.gui.display.update()
#print('update_之后:输出ma.env_matrix()函数的地图形式::')
#print(self.map.env_matrix())
def start(self):
i = 0
while not self.is_game_over():
self.update()
i += 1
#print('-----')
#sleep(0.1)
print("game over!")
print('是否到达终点:(0表示没,1表示到达)', self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
print('是否走出区域:(0表示没,1表示走出去)', self.arriveUnlegal)
# #print('FTList:',self.map.friendly_ships[0].FTList)
# print('FTLen:',self.map.friendly_ships[0].FTLen) #等于: print('FTList的长度:', len(self.map.friendly_ships[0].FTList))
# print(self.map.friendly_ships[0].RecordList)
print('game-update次数', i)
self.gui.display.set_caption("Game Over!")
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
#self.gui.display.update()
#地图3*3
class PyGameXSWorld(MyContinueGame):
"""基本的GUI引擎, 使用pygame"""
def __init__(self, obsmove):
super(PyGameXSWorld, self).__init__(obsmove)
self.gui = pygame
self.gui_init()
self.obsMoveBool = obsmove # 默认false,障碍物不随机移动
def gui_init(self):
self.gui_screen = self.gui.display.set_mode((600, 600), 0, 32)
self.gui.display.set_caption("USV")
#柯老师版参数
def allPointUSV(self, curPoint, USVradius):
pointList = []
halfR = USVradius/2
pointList.append((curPoint[0] - USVradius, curPoint[1]))
pointList.append((curPoint[0], curPoint[1] + halfR))
pointList.append((curPoint[0] + USVradius, curPoint[1] + halfR))
pointList.append((curPoint[0] + USVradius, curPoint[1] - halfR))
pointList.append((curPoint[0], curPoint[1] - halfR))
return pointList
def transferAngle(self, pointList, point, angle):
angle = 360 - angle
transList = []
for i in range(len(pointList)):
trans_x = (pointList[i][0] - point[0]) * cos(angle*pi/180) + (pointList[i][1] - point[1])*sin(angle*pi/180) + point[0]
trans_y = (pointList[i][0] - point[0]) * sin(angle*pi/180) + (pointList[i][1] - point[1])*cos(angle*pi/180) + point[1]
trans_x = float("%.4f" % trans_x)
trans_y = float("%.4f" % trans_y)
transList.append((trans_x, trans_y))
return transList
#3.将transList中 每一点的坐标(x,y) 换成(y*y_unit,x*unit)
def pyTrans(self, transList, xunit, yunit):
pyTransList = []
for i in range(len(transList)):
px = transList[i][1] * yunit
py = transList[i][0] * xunit
pyTransList.append((px,py))
#print('pygame画图上的坐标:', pyTransList)
return pyTransList
#4.获取当前速度方向:即self.ax 与 self.ay的向量合成,是当前速度方向
def update(self):
x_unit = 600.0 / self.map.width
y_unit = 600.0 / self.map.height
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui_screen.fill((99,184,255)) # (255,255,255)白色填充
for ship in self.map.friendly_ships:
if ship.getuid() == 0:
ship.move()
#USV: ship_x * x_unit, ship_y * y_unit 此时USV的中心在画布的位置\\ship.heading
USVPoint = self.allPointUSV((ship.x,ship.y), ship.radius)
TransUSVPoint = self.transferAngle(USVPoint, (ship.x,ship.y), ship.heading)
PyTransList = self.pyTrans(TransUSVPoint, x_unit, y_unit)
self.gui.draw.polygon(self.gui_screen, (0, 255, 0), PyTransList)
#获取船体当前加速度ship.get_curSpeedDirection(),是左下角是(0,0)的情况,
#但这里计算的坐标是左上角是(0,0)的情况,所以变换关系是:ship.x - speedDirectPosy, ship.y + speedDirectPosx
speedDirectPosx, speedDirectPosy = ship.get_curSpeedDirection()
af_speedDirectPosx = (ship.x - speedDirectPosx) * x_unit
af_speedDirectPosy = (ship.y + speedDirectPosy) * y_unit
#加速度导引线
self.gui.draw.line(self.gui_screen, (0, 255, 0), [ship.y * y_unit, ship.x * x_unit],[af_speedDirectPosy, af_speedDirectPosx], 1)
self.check_target()
self.check_obstacle()
self.check_legal()
if self.obsMoveBool == False:
for obstacle in self.map.obs:
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y*y_unit), int(obstacle.x*x_unit)], int(obstacle.radius*x_unit))
pass
else:
#添加圆形障碍物的移动(需在其移动方法中添加对所随机移动的下一位置的合法性判断,若下一位置不合法则保持原位置)
for obstacle in self.map.obs:
obstacle.obsRandomMove()
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y*y_unit), int(obstacle.x*x_unit)], int(obstacle.radius*x_unit))
# 画终点:中心点 + radius
target_x, target_y = self.map.target_coordinate()
self.gui.draw.circle(self.gui_screen, (255, 0, 0), [int(target_y*y_unit), int(target_x*x_unit)], int(self.map.target_radius*x_unit))
#更新
self.gui.display.update()
# USV是否越界
def check_legal(self):
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
width, height = self.map.width, self.map.height
if (ship_x < ship.radius or ship_y < ship.radius or ship_x > (width - ship.radius) or ship_y > (
height - ship.radius)):
self.is_target_safe = False
self.arriveUnlegal = 1
def start(self):
i = 0
while not self.is_game_over():
self.update()
i += 1
#print('-----')
sleep(0.1)
print("game over!")
print('是否到达终点:(0表示没,1表示到达)', self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
print('是否走出区域:(0表示没,1表示走出去)', self.arriveUnlegal)
#
# #print('FTList:',self.map.friendly_ships[0].FTList)
print('FTLen:',self.map.friendly_ships[0].FTLen) #等于: print('FTList的长度:', len(self.map.friendly_ships[0].FTList))
print(self.map.friendly_ships[0].RecordList)
print(i)
self.gui.display.set_caption("Game Over!")
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
#self.gui.display.update()
class MyContinueGameModify(MyContinueGame):
"""基本的GUI引擎, 使用pygame"""
#修正了是否越界函数:USV是否越界
def check_legal(self):
for ship in self.map.friendly_ships:
ship_x, ship_y = ship.coordinate()
width, height = self.map.width, self.map.height
if (ship_x < ship.radius or ship_y < ship.radius or ship_x > (width - ship.radius) or ship_y > (
height - ship.radius)):
self.is_target_safe = False
self.arriveUnlegal = 1
#测试DDPG网络的有效性:调3*3地图上,固定angular_speed和固定speed值
#对应continue_obsmap_test_smallmap
#CoutinuePyGame CoutinueNoPyGame MyContinueUSV_SmallMap
class CoutinuePyGame(MyContinueGameModify):
"""基本的GUI引擎, 使用pygame"""
def __init__(self, obsmove):
super(CoutinuePyGame, self).__init__(obsmove)
self.gui = pygame
self.gui_init()
self.obsMoveBool = obsmove # 默认false,障碍物不随机移动
def gui_init(self):
self.gui_screen = self.gui.display.set_mode((600, 600), 0, 32)
self.gui.display.set_caption("USV")
# self.gui_screen是个surface对象,这里获取该对象(因为pygame.image,load得到的也是个Surface对象)
#转为PIL的Image,再转为cv2
def get_imgsurface(self):
tempSurface = self.gui_screen
string_image = pygame.image.tostring(tempSurface, "RGB", False)
im = Image.frombytes("RGB", (600, 600), string_image)
# 转化为PIL中的image对象--》转化为cv2中的对象,查看下isinstance(imgtest,np.ndarray)类型确认下
imgtest = cv2.cvtColor(np.asarray(im), cv2.COLOR_RGB2BGR)
return imgtest
def update(self, i):
x_unit = 600.0 / self.map.width
y_unit = 600.0 / self.map.height
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui_screen.fill((99, 184, 255)) # (255,255,255)白色填充
for ship in self.map.friendly_ships:
ship.move()
self.gui.draw.circle(self.gui_screen, (0, 255, 0), [int(ship.y * y_unit), int(ship.x * x_unit)],
int(ship.radius * x_unit))
self.check_target()
self.check_obstacle()
self.check_legal()
if self.obsMoveBool == False:
for obstacle in self.map.obs:
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y * y_unit), int(obstacle.x * x_unit)],
int(obstacle.radius * x_unit))
pass
else:
# 添加圆形障碍物的移动(需在其移动方法中添加对所随机移动的下一位置的合法性判断,若下一位置不合法则保持原位置)
for obstacle in self.map.obs:
obstacle.obsRandomMove()
# 画障碍物: 中心点 + radius
self.gui.draw.circle(self.gui_screen, (0, 0, 0), [int(obstacle.y * y_unit), int(obstacle.x * x_unit)],
int(obstacle.radius * x_unit))
# 画终点:中心点 + radius
target_x, target_y = self.map.target_coordinate()
self.gui.draw.circle(self.gui_screen, (255, 0, 0), [int(target_y * y_unit), int(target_x * x_unit)],
int(self.map.target_radius * x_unit))
# 更新
self.gui.display.update()
fname = "%s.png" % str(i)
if i == 0:
cur_dir = os.getcwd() # get current path
dir_new = os.path.join(cur_dir, 'img')
os.chdir(dir_new)
#pygame.image.save(self.gui_screen, fname)
def start(self):
i = 0
while not self.is_game_over():
self.update(i)
i += 1
# imgg = self.get_imgsurface()
# print('cv2--', type(imgg))
# cv2.imwrite("test%s.png" % str(i), imgg)
#语句格式:cv2.imwrite(filename, img) filename: 保存文件的路径名;;img: 表示图像的numpy.ndarray对象
print("更新次数:", i)
print("game over!")
print('是否到达终点:(0表示没,1表示到达)', self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
print('是否走出区域:(0表示没,1表示走出去)', self.arriveUnlegal)
self.gui.display.set_caption("Game Over!")
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
self.gui.display.update()
class CoutinueNoPyGame(MyContinueGameModify):
"""3*3小地图上,不使用可视化"""
def __init__(self, obsmove):
super(CoutinueNoPyGame, self).__init__(obsmove)
self.cv_img = None
#获取某次update之后的图(该图是cv2格式imread的格式)
def get_cv_img(self):
return self.cv_img
def update(self,i):
x_unit = 600.0 / self.map.width
y_unit = 600.0 / self.map.height
screen = Image.new("RGB", [600, 600], (99, 184, 255))
drawObject = ImageDraw.Draw(screen)
for ship in self.map.friendly_ships:
ship.move()
templeftup = (int(ship.y * y_unit)-int(ship.radius * x_unit), int(ship.x * x_unit)-int(ship.radius * x_unit))
temprightdown = (int(ship.y * y_unit)+int(ship.radius * x_unit), int(ship.x * x_unit)+int(ship.radius *x_unit))
drawObject.ellipse((templeftup[0],templeftup[1], temprightdown[0],temprightdown[1]), (0,255,0), (0,255,0))
self.check_target()
self.check_obstacle()
self.check_legal()
if self.obsMoveBool == False:
for obstacle in self.map.obs:
templeftup_obs = (int(obstacle.y*y_unit)-int(obstacle.radius*x_unit), int(obstacle.x*x_unit)-int(obstacle.radius*x_unit))
temprightdown_obs = (int(obstacle.y*y_unit)+int(obstacle.radius*x_unit), int(obstacle.x*x_unit)+int(obstacle.radius*x_unit))
drawObject.ellipse((templeftup_obs[0],templeftup_obs[1], temprightdown_obs[0],temprightdown_obs[1]), (0, 0, 0), (0, 0, 0))
pass
else:
#添加圆形障碍物的移动(需在其移动方法中添加对所随机移动的下一位置的合法性判断,若下一位置不合法则保持原位置)
for obstacle in self.map.obs:
obstacle.obsRandomMove()
templeftup_obs = (int(obstacle.y * y_unit) - int(obstacle.radius * x_unit),
int(obstacle.x * x_unit) - int(obstacle.radius * x_unit))
temprightdown_obs = (int(obstacle.y * y_unit) + int(obstacle.radius * x_unit),
int(obstacle.x * x_unit) + int(obstacle.radius * x_unit))
drawObject.ellipse((templeftup_obs[0],templeftup_obs[1], temprightdown_obs[0],temprightdown_obs[1]), (0, 0, 0), (0, 0, 0))
# 画终点:中心点 + radius
target_x, target_y = self.map.target_coordinate()
target_leftup = (int(target_y * y_unit)-self.map.target_radius * x_unit, int(target_x * x_unit)-self.map.target_radius * x_unit)
target_rightdown = (int(target_y * y_unit)+self.map.target_radius * x_unit, int(target_x * x_unit)+self.map.target_radius * x_unit)
drawObject.ellipse((target_leftup[0],target_leftup[1], target_rightdown[0], target_rightdown[1]), (255, 0, 0),
(255, 0, 0))
if i == 0:
cur_dir = os.getcwd() # get current path
dir_new = os.path.join(cur_dir, 'img2')
os.chdir(dir_new)
imgtest = cv2.cvtColor(np.asarray(screen), cv2.COLOR_RGB2BGR)
self.cv_img = imgtest
#screen.save("%s.png" % str(i), 'png')
#语句格式:im.save('/Users/michael/thumbnail.jpg', 'jpeg')
def start(self):
i=0
while not self.is_game_over():
self.update(i)
i += 1
#cv2.imwrite("test%s.png" % str(i), self.cv_img)
print("更新次数:", i)
print ("game over!")
print('是否到达终点:(0表示没,1表示到达)',self.arriveTarget)
print('是否碰到障碍物:(0表示没,1表示碰到)', self.arriveObstacle)
print('是否走出区域:(0表示没,1表示走出去)', self.arriveUnlegal)