forked from isabella232/mayhem-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmayhem.py
More file actions
1777 lines (1335 loc) · 65.6 KB
/
mayhem.py
File metadata and controls
1777 lines (1335 loc) · 65.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Because this game never dies and deserved to meet Python and AI.
The original game by Espen Skoglund (http://hol.abime.net/3853) was born in the early 90s on the Commodore Amiga. That was the great time of MC68000 Assembly.
Around 2000 we made a PC version (https://github.com/devpack/mayhem) of the game in C++.
It was then ported to Raspberry Pi by Martin O'Hanlon (https://github.com/martinohanlon/mayhem-pi), even new gfx levels were added.
----
It was early time this game had its own Python version. Pygame (https://www.pygame.org/docs) SDL wrapper has been used as backend.
The ultimate goal porting it to Python is to create a friendly AI environment (like Gym (https://gym.openai.com/envs/#atari)) which could easily be used with Keras (https://keras.io) deep learning framework. AI players in Mayhem are coming !
Anthony Prieur
anthony.prieur@gmail.com
"""
"""
Usage example:
python mayhem.py --width=1500 --height=900 --nb_player=2 --sensor=ray -rm=game
python mayhem.py --width=1500 --height=900 --nb_player=1 --sensor=ray -rm=training
python3 mayhem.py --sensor=ray --motion=gravity
python3 mayhem.py --sensor=ray --motion=thrust
python3 mayhem.py --motion=thrust
python3 mayhem.py -r=played1.dat --motion=gravity
python3 mayhem.py -pr=played1.dat --motion=gravity
"""
import os, sys, argparse, random, math, time, multiprocessing
from random import randint
import numpy as np
import datetime as dt
import pygame
from pygame.locals import *
from pygame import gfxdraw
try:
import cPickle as pickle
except ImportError:
import pickle
try:
import neat
NEAT_FOUND = True
except ImportError:
NEAT_FOUND = False
try:
import cv2
CV2_FOUND = True
except ImportError:
CV2_FOUND = False
try:
from matplotlib import pyplot as plt
MPL_FOUND = True
except ImportError:
MPL_FOUND = False
# -------------------------------------------------------------------------------------------------
# General
global game_window
DEBUG_SCREEN = 1 # print debug info on the screen
DEBUG_TEXT_XPOS = 0
MAX_FPS = 60
MAP_WIDTH = 792
MAP_HEIGHT = 1200
WHITE = (255, 255, 255)
RED = (255, 0, 0)
LVIOLET = (128, 0, 128)
# -------------------------------------------------------------------------------------------------
# Player views
SHIP1_X = 473 # ie left
SHIP1_Y = 303 # ie top
SHIP2_X = 520 # ie left
SHIP2_Y = 955 # ie top
SHIP3_X = 75 # ie left
SHIP3_Y = 1015 # ie top
SHIP4_X = 451 # ie left
SHIP4_Y = 501 # ie top
USE_MINI_MASK = True # mask the size of the ship (instead of the player view size)
# -------------------------------------------------------------------------------------------------
# Sensor
RAY_AMGLE_STEP = 45
RAY_BOX_SIZE = 400
RAY_MAX_LEN = ((RAY_BOX_SIZE/2) * math.sqrt(2)) # for now we are at the center of the ray mask box
# -------------------------------------------------------------------------------------------------
# SHIP dynamics
SLOW_DOWN_COEF = 2.0 # somehow the C++ version is slower with the same physics coef ?
SHIP_MASS = 0.9
SHIP_THRUST_MAX = 0.32 / SLOW_DOWN_COEF
SHIP_ANGLESTEP = 5
SHIP_ANGLE_LAND = 30
SHIP_MAX_LIVES = 100
SHIP_SPRITE_SIZE = 32
iG = 0.07 / SLOW_DOWN_COEF
iXfrott = 0.984
iYfrott = 0.99
iCoeffax = 0.6
iCoeffay = 0.6
iCoeffvx = 0.6
iCoeffvy = 0.6
iCoeffimpact = 0.02
MAX_SHOOT = 20
# -------------------------------------------------------------------------------------------------
# Levels / controls
CURRENT_LEVEL = 1
PLATFORMS_1 = [ ( 464, 513, 333 ),
( 60, 127, 1045 ),
( 428, 497, 531 ),
( 504, 568, 985 ),
( 178, 241, 875 ),
( 8, 37, 187 ),
( 302, 351, 271 ),
( 434, 521, 835 ),
( 499, 586, 1165 ),
( 68, 145, 1181 ) ]
SHIP_1_KEYS = {"left":pygame.K_LEFT, "right":pygame.K_RIGHT, "up":pygame.K_UP, "down":pygame.K_DOWN, \
"thrust":pygame.K_KP_PERIOD, "shoot":pygame.K_KP_ENTER, "shield":pygame.K_KP0}
SHIP_1_JOY = 0 # 0 means no joystick, =!0 means joystck number SHIP_1_JOY - 1
SHIP_2_KEYS = {"left":pygame.K_w, "right":pygame.K_x, "up":pygame.K_UP, "down":pygame.K_DOWN, \
"thrust":pygame.K_v, "shoot":pygame.K_g, "shield":pygame.K_c}
SHIP_2_JOY = 1 # 0 means no joystick, =!0 means joystck number SHIP_1_JOY - 1
SHIP_3_KEYS = {"left":pygame.K_w, "right":pygame.K_x, "up":pygame.K_UP, "down":pygame.K_DOWN, \
"thrust":pygame.K_v, "shoot":pygame.K_g, "shield":pygame.K_c}
SHIP_3_JOY = 2 # 0 means no joystick, =!0 means joystck number SHIP_1_JOY - 1
SHIP_4_KEYS = {"left":pygame.K_w, "right":pygame.K_x, "up":pygame.K_UP, "down":pygame.K_DOWN, \
"thrust":pygame.K_v, "shoot":pygame.K_g, "shield":pygame.K_c}
SHIP_4_JOY = 0 # 0 means no joystick, =!0 means joystck number SHIP_1_JOY - 1
# -------------------------------------------------------------------------------------------------
# Assets
MAP_1 = os.path.join("assets", "level1", "Mayhem_Level1_Map_256c.bmp")
SOUND_THURST = os.path.join("assets", "default", "sfx_loop_thrust.wav")
SOUND_EXPLOD = os.path.join("assets", "default", "sfx_boom.wav")
SOUND_BOUNCE = os.path.join("assets", "default", "sfx_rebound.wav")
SOUND_SHOOT = os.path.join("assets", "default", "sfx_shoot.wav")
SOUND_SHIELD = os.path.join("assets", "default", "sfx_loop_shield.wav")
SHIP_1_PIC = os.path.join("assets", "default", "ship1_256c.bmp")
SHIP_1_PIC_THRUST = os.path.join("assets", "default", "ship1_thrust_256c.bmp")
SHIP_1_PIC_SHIELD = os.path.join("assets", "default", "ship1_shield_256c.bmp")
SHIP_2_PIC = os.path.join("assets", "default", "ship2_256c.bmp")
SHIP_2_PIC_THRUST = os.path.join("assets", "default", "ship2_thrust_256c.bmp")
SHIP_2_PIC_SHIELD = os.path.join("assets", "default", "ship2_shield_256c.bmp")
SHIP_3_PIC = os.path.join("assets", "default", "ship3_256c.bmp")
SHIP_3_PIC_THRUST = os.path.join("assets", "default", "ship3_thrust_256c.bmp")
SHIP_3_PIC_SHIELD = os.path.join("assets", "default", "ship3_shield_256c.bmp")
SHIP_4_PIC = os.path.join("assets", "default", "ship4_256c.bmp")
SHIP_4_PIC_THRUST = os.path.join("assets", "default", "ship4_thrust_256c.bmp")
SHIP_4_PIC_SHIELD = os.path.join("assets", "default", "ship4_shield_256c.bmp")
# -------------------------------------------------------------------------------------------------
# Training
START_POSITIONS = [(430, 730), (473, 195), (647, 227), (645, 600), (647, 950), (510, 1070), (298, 1037), \
(273, 777), (275, 506), (70, 513), (89, 208), (434, 452), (289, 153)]
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
class Shot():
def __init__(self):
self.x = 0
self.y = 0
self.xposprecise = 0
self.yposprecise = 0
self.dx = 0
self.dy = 0
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
class Ship():
def __init__(self, mode, screen_width, screen_height, ship_number, nb_player, xpos, ypos, ship_pic, ship_pic_thrust, ship_pic_shield, keys_mapping, joystick_number, lives):
margin_size = 0
w_percent = 1.0
h_percent = 1.0
if mode == "training":
self.view_width = screen_width
self.view_height = screen_height
self.view_left = margin_size
self.view_top = margin_size
else:
self.view_width = int((screen_width * w_percent) / 2)
self.view_height = int((screen_height * h_percent) / 2)
if ship_number == 1:
self.view_left = margin_size
self.view_top = margin_size
elif ship_number == 2:
self.view_left = margin_size + self.view_width + margin_size
self.view_top = margin_size
elif ship_number == 3:
self.view_left = margin_size
self.view_top = margin_size + self.view_height + margin_size
elif ship_number == 4:
self.view_left = margin_size + self.view_width + margin_size
self.view_top = margin_size + self.view_height + margin_size
self.init_xpos = xpos
self.init_ypos = ypos
self.xpos = xpos
self.ypos = ypos
self.xposprecise = xpos
self.yposprecise = ypos
self.vx = 0.0
self.vy = 0.0
self.ax = 0.0
self.ay = 0.0
self.impactx = 0.0
self.impacty = 0.0
self.angle = 0.0
self.thrust = 0.0
self.shield = False
self.shoot = False
self.shoot_delay = False
self.landed = False
self.bounce = False
self.explod = False
self.lives = lives
self.shots = []
# sound
self.sound_thrust = pygame.mixer.Sound(SOUND_THURST)
self.sound_explod = pygame.mixer.Sound(SOUND_EXPLOD)
self.sound_bounce = pygame.mixer.Sound(SOUND_BOUNCE)
self.sound_shoot = pygame.mixer.Sound(SOUND_SHOOT)
self.sound_shield = pygame.mixer.Sound(SOUND_SHIELD)
# ship pic: 32x32, black (0,0,0) background, no alpha
self.ship_pic = pygame.image.load(ship_pic).convert()
self.ship_pic.set_colorkey( (0, 0, 0) ) # used for the mask, black = background, not the ship
self.ship_pic_thrust = pygame.image.load(ship_pic_thrust).convert()
self.ship_pic_thrust.set_colorkey( (0, 0, 0) ) # used for the mask, black = background, not the ship
self.ship_pic_shield = pygame.image.load(ship_pic_shield).convert()
self.ship_pic_shield.set_colorkey( (0, 0, 0) ) # used for the mask, black = background, not the ship
self.image = self.ship_pic
self.mask = pygame.mask.from_surface(self.image)
self.keys_mapping = keys_mapping
self.joystick_number = joystick_number
self.ray_surface = pygame.Surface((RAY_BOX_SIZE, RAY_BOX_SIZE))
def reset(self, env):
if env.mode == "training" and 0:
self.xpos, self.ypos = random.choice(START_POSITIONS)
else:
self.xpos = self.init_xpos
self.ypos = self.init_ypos
self.xposprecise = self.xpos
self.yposprecise = self.ypos
self.vx = 0.0
self.vy = 0.0
self.ax = 0.0
self.ay = 0.0
self.impactx = 0.0
self.impacty = 0.0
self.angle = 0.0
self.thrust = 0.0
self.shield = False
self.shoot = False
self.shoot_delay = False
self.landed = False
self.bounce = False
self.explod = False
self.lives -= 1
if env.render_it:
self.sound_thrust.stop()
self.sound_shoot.stop()
self.sound_shield.stop()
self.sound_bounce.stop()
self.sound_explod.play()
def step(self, env, action):
if not env.play_recorded:
left_pressed = False
right_pressed = False
thrust_pressed = False
up_pressed = False
down_pressed = False
shoot_pressed = False
shield_pressed = False
# -1 for action means random
use_random_walk = False
try:
if action == -1:
use_random_walk = True
except:
pass
if use_random_walk:
if randint(0, 1) == 1:
thrust_pressed = True
v = randint(0, 2)
if v == 1:
right_pressed = True
elif v == 2:
left_pressed = True
else:
# output = 2 nodes
if 0:
if action[0] < -0.33:
left_pressed = True
elif action[0] > 0.33:
right_pressed = True
if action[1] <= 0:
thrust_pressed = True
# output = 3 nodes
else:
if action[0] > 0.8:
thrust_pressed = True
if action[1] > 0.8:
left_pressed = True
elif action[2] > 0.8:
right_pressed = True
# record play ?
if env.record_play:
env.played_data.append((left_pressed, right_pressed, thrust_pressed, shield_pressed, shoot_pressed))
# play recorded
else:
try:
data_i = env.played_data[env.frames]
left_pressed = True if data_i[0] else False
right_pressed = True if data_i[1] else False
thrust_pressed = True if data_i[2] else False
shield_pressed = True if data_i[3] else False
shoot_pressed = True if data_i[4] else False
except:
print("End of playback")
print("Frames=", env.frames)
print("%s seconds" % int(env.frames/MAX_FPS))
sys.exit(0)
self.do_move(env, left_pressed, right_pressed, up_pressed, down_pressed, thrust_pressed, shoot_pressed, shield_pressed)
def update(self, env):
# normal play
if not env.play_recorded:
keys = pygame.key.get_pressed()
left_pressed = keys[self.keys_mapping["left"]]
right_pressed = keys[self.keys_mapping["right"]]
up_pressed = keys[self.keys_mapping["up"]]
down_pressed = keys[self.keys_mapping["down"]]
thrust_pressed = keys[self.keys_mapping["thrust"]]
shoot_pressed = keys[self.keys_mapping["shoot"]]
shield_pressed = keys[self.keys_mapping["shield"]]
if self.joystick_number:
try:
if pygame.joystick.Joystick(self.joystick_number-1).get_button(0):
thrust_pressed = True
else:
thrust_pressed = False
if pygame.joystick.Joystick(self.joystick_number-1).get_button(5):
shoot_pressed = True
else:
shoot_pressed = False
if pygame.joystick.Joystick(self.joystick_number-1).get_button(1):
shield_pressed = True
else:
shield_pressed = False
horizontal_axis = pygame.joystick.Joystick(self.joystick_number-1).get_axis(0)
if int(round(horizontal_axis)) == 1:
right_pressed = True
else:
right_pressed = False
if int(round(horizontal_axis)) == -1:
left_pressed = True
else:
left_pressed = False
except:
pass
# record play ?
if env.record_play:
env.played_data.append((left_pressed, right_pressed, thrust_pressed, shield_pressed, shoot_pressed))
# play recorded
else:
try:
data_i = env.played_data[env.frames]
left_pressed = True if data_i[0] else False
right_pressed = True if data_i[1] else False
thrust_pressed = True if data_i[2] else False
shield_pressed = True if data_i[3] else False
shoot_pressed = True if data_i[4] else False
up_pressed = False
down_pressed = False
except:
print("End of playback")
print("Frames=", env.frames)
print("%s seconds" % int(env.frames/MAX_FPS))
sys.exit(0)
self.do_move(env, left_pressed, right_pressed, up_pressed, down_pressed, thrust_pressed, shoot_pressed, shield_pressed)
def do_move(self, env, left_pressed, right_pressed, up_pressed, down_pressed, thrust_pressed, shoot_pressed, shield_pressed):
if env.motion == "basic":
# pic
if left_pressed or right_pressed or up_pressed or down_pressed:
self.image = self.ship_pic_thrust
else:
self.image = self.ship_pic
#
dx = dy = 0
if left_pressed:
dx = -1
if right_pressed:
dx = 1
if up_pressed:
dy = -1
if down_pressed:
dy = 1
self.xpos += dx
self.ypos += dy
elif env.motion == "thrust":
# pic
if thrust_pressed:
self.image = self.ship_pic_thrust
else:
self.image = self.ship_pic
# angle
if left_pressed:
self.angle += SHIP_ANGLESTEP
if right_pressed:
self.angle -= SHIP_ANGLESTEP
self.angle = self.angle % 360
if thrust_pressed:
coef = 2
self.xposprecise -= coef * math.cos( math.radians(90 - self.angle) )
self.yposprecise -= coef * math.sin( math.radians(90 - self.angle) )
# transfer to screen coordinates
self.xpos = int(self.xposprecise)
self.ypos = int(self.yposprecise)
elif env.motion == "gravity":
self.image = self.ship_pic
self.thrust = 0.0
self.shield = False
# shield
if shield_pressed:
self.image = self.ship_pic_shield
self.shield = True
if env.render_it:
self.sound_thrust.stop()
if env.render_it:
if not pygame.mixer.get_busy():
self.sound_shield.play(-1)
else:
self.shield = False
if env.render_it:
self.sound_shield.stop()
# thrust
if thrust_pressed:
self.image = self.ship_pic_thrust
#self.thrust += 0.1
#if self.thrust >= SHIP_THRUST_MAX:
self.thrust = SHIP_THRUST_MAX
if env.render_it:
if not pygame.mixer.get_busy():
self.sound_thrust.play(-1)
self.landed = False
else:
self.thrust = 0.0
if env.render_it:
self.sound_thrust.stop()
# shoot delay
if shoot_pressed and not self.shoot:
self.shoot_delay = True
else:
self.shoot_delay = False
# shoot
if shoot_pressed:
self.shoot = True
if self.shoot_delay:
if len(self.shots) < MAX_SHOOT:
if env.render_it:
if not pygame.mixer.get_busy():
self.sound_shoot.play()
self.add_shots()
else:
self.shoot = False
if env.render_it:
self.sound_shoot.stop()
#
self.bounce = False
if not self.landed:
# angle
if left_pressed:
self.angle += SHIP_ANGLESTEP
if right_pressed:
self.angle -= SHIP_ANGLESTEP
#
self.angle = self.angle % 360
# https://gafferongames.com/post/integration_basics/
self.ax = self.thrust * -math.cos( math.radians(90 - self.angle) ) # ax = thrust * sin1
self.ay = iG + (self.thrust * -math.sin( math.radians(90 - self.angle))) # ay = g + thrust * (-cos1)
# shoot when shield is on
if self.impactx or self.impacty:
self.ax += iCoeffimpact * self.impactx
self.ay += iCoeffimpact * self.impacty
self.impactx = 0.
self.impacty = 0.
self.vx = self.vx + (iCoeffax * self.ax) # vx += coeffa * ax
self.vy = self.vy + (iCoeffay * self.ay) # vy += coeffa * ay
self.vx = self.vx * iXfrott # on freine de xfrott
self.vy = self.vy * iYfrott # on freine de yfrott
self.xposprecise = self.xposprecise + (iCoeffvx * self.vx) # xpos += coeffv * vx
self.yposprecise = self.yposprecise + (iCoeffvy * self.vy) # ypos += coeffv * vy
else:
self.vx = 0.
self.vy = 0.
self.ax = 0.
self.ay = 0.
# transfer to screen coordinates
self.xpos = int(self.xposprecise)
self.ypos = int(self.yposprecise)
# landed ?
if env.mode != "training": # at the moment no landing in training (because NEAT algo is too lazy !)
self.is_landed(env)
#
# rotate
self.image_rotated = pygame.transform.rotate(self.image, self.angle)
self.mask = pygame.mask.from_surface(self.image_rotated)
rect = self.image_rotated.get_rect()
self.rot_xoffset = int( ((SHIP_SPRITE_SIZE - rect.width)/2) ) # used in draw() and collide_map()
self.rot_yoffset = int( ((SHIP_SPRITE_SIZE - rect.height)/2) ) # used in draw() and collide_map()
def plot_shots(self, map_buffer):
for shot in list(self.shots): # copy of self.shots
shot.xposprecise += shot.dx
shot.yposprecise += shot.dy
shot.x = int(shot.xposprecise)
shot.y = int(shot.yposprecise)
try:
c = map_buffer.get_at((int(shot.x), int(shot.y)))
if (c.r != 0) or (c.g != 0) or (c.b != 0):
self.shots.remove(shot)
#gfxdraw.pixel(map_buffer, int(shot.x) , int(shot.y), WHITE)
pygame.draw.circle(map_buffer, WHITE, (int(shot.x) , int(shot.y)), 1)
#pygame.draw.line(map_buffer, WHITE, (int(self.xpos + SHIP_SPRITE_SIZE/2), int(self.ypos + SHIP_SPRITE_SIZE/2)), (int(shot.x), int(shot.y)))
# out of surface
except IndexError:
self.shots.remove(shot)
if 0:
for i in range(len(self.shots)):
try:
shot1 = self.shots[i]
shot2 = self.shots[i+1]
pygame.draw.line(map_buffer, WHITE, (int(shot1.x), int(shot1.y)), (int(shot2.x), int(shot2.y)))
except IndexError:
pass
def add_shots(self):
shot = Shot()
shot.x = (self.xpos+15) + 18 * -math.cos(math.radians(90 - self.angle))
shot.y = (self.ypos+16) + 18 * -math.sin(math.radians(90 - self.angle))
shot.xposprecise = shot.x
shot.yposprecise = shot.y
shot.dx = 5.1 * -math.cos(math.radians(90 - self.angle))
shot.dy = 5.1 * -math.sin(math.radians(90 - self.angle))
shot.dx += self.vx / 3.5
shot.dy += self.vy / 3.5
self.shots.append(shot)
def is_landed(self, env):
for plaform in PLATFORMS_1:
xmin = plaform[0] - (SHIP_SPRITE_SIZE - 23)
xmax = plaform[1] - (SHIP_SPRITE_SIZE - 9)
yflat = plaform[2] - (SHIP_SPRITE_SIZE - 2)
#print(self.ypos, yflat)
if ((xmin <= self.xpos) and (self.xpos <= xmax) and
((self.ypos == yflat) or ((self.ypos-1) == yflat) or ((self.ypos-2) == yflat) or ((self.ypos-3) == yflat) ) and
(self.vy > 0) and (self.angle<=SHIP_ANGLE_LAND or self.angle>=(360-SHIP_ANGLE_LAND)) ):
self.vy = - self.vy / 1.2
self.vx = self.vx / 1.1
self.angle = 0
self.ypos = yflat
self.yposprecise = yflat
if ( (-1.0/SLOW_DOWN_COEF <= self.vx) and (self.vx < 1.0/SLOW_DOWN_COEF) and (-1.0/SLOW_DOWN_COEF < self.vy) and (self.vy < 1.0/SLOW_DOWN_COEF) ):
self.landed = True
self.bounce = False
else:
self.bounce = True
if env.render_it:
self.sound_bounce.play()
return True
return False
def do_test_collision(self):
test_it = True
for plaform in PLATFORMS_1:
xmin = plaform[0] - (SHIP_SPRITE_SIZE - 23)
xmax = plaform[1] - (SHIP_SPRITE_SIZE - 9)
yflat = plaform[2] - (SHIP_SPRITE_SIZE - 2)
#if ((xmin<=self.xpos) and (self.xpos<=xmax) and ((self.ypos==yflat) or ((self.ypos-1)==yflat) or ((self.ypos-2)==yflat) or ((self.ypos-3)==yflat)) and (self.angle<=SHIP_ANGLE_LAND or self.angle>=(360-SHIP_ANGLE_LAND)) ):
# test_it = False
# break
if (self.shield and (xmin<=self.xpos) and (self.xpos<=xmax) and ((self.ypos==yflat) or ((self.ypos-1)==yflat) or ((self.ypos-2)==yflat) or ((self.ypos-3)==yflat) or ((self.ypos+1)==yflat)) and (self.angle<=SHIP_ANGLE_LAND or self.angle>=(360-SHIP_ANGLE_LAND)) ):
test_it = False
break
if ((self.thrust) and (xmin<=self.xpos) and (self.xpos<=xmax) and ((self.ypos==yflat) or ((self.ypos-1)==yflat) or ((self.ypos+1)==yflat) )):
test_it = False
break
return test_it
def draw(self, map_buffer):
#game_window.blit(self.image_rotated, (self.view_width/2 + self.view_left + self.rot_xoffset, self.view_height/2 + self.view_top + self.rot_yoffset))
map_buffer.blit(self.image_rotated, (self.xpos + self.rot_xoffset, self.ypos + self.rot_yoffset))
def collide_map(self, map_buffer, map_buffer_mask):
# ship size mask
if USE_MINI_MASK:
mini_area = Rect(self.xpos, self.ypos, SHIP_SPRITE_SIZE, SHIP_SPRITE_SIZE)
mini_subsurface = map_buffer.subsurface(mini_area)
mini_subsurface.set_colorkey( (0, 0, 0) ) # used for the mask, black = background
mini_mask = pygame.mask.from_surface(mini_subsurface)
if self.do_test_collision():
offset = (self.rot_xoffset, self.rot_yoffset) # pos of the ship
if mini_mask.overlap(self.mask, offset): # https://stackoverflow.com/questions/55817422/collision-between-masks-in-pygame/55818093#55818093
self.explod = True
# player view size mask
else:
if self.do_test_collision():
offset = (self.xpos + self.rot_xoffset, self.ypos + self.rot_yoffset) # pos of the ship
if map_buffer_mask.overlap(self.mask, offset): # https://stackoverflow.com/questions/55817422/collision-between-masks-in-pygame/55818093#55818093
self.explod = True
#
def collide_ship(self, ships):
for ship in ships:
if self != ship:
offset = ((ship.xpos - self.xpos), (ship.ypos - self.ypos))
if self.mask.overlap(ship.mask, offset):
self.explod = True
ship.explod = True
#
def collide_shots(self, ships):
for ship in ships:
if self != ship:
for shot in self.shots:
try:
if ship.mask.get_at((shot.x - ship.xpos, shot.y - ship.ypos)):
if not ship.shield:
ship.explod = True
return
else:
ship.impactx = shot.dx
ship.impacty = shot.dy
# out of ship mask => no collision
except IndexError:
pass
def ray_sensor(self, env, render_it=True):
# TODO use smaller map masks
# TODO use only 0 to 90 degres ray mask quadran: https://github.com/Rabbid76/PyGameExamplesAndAnswers/blob/master/examples/minimal_examples/pygame_minimal_mask_intersect_surface_line_2.py
# clipping translation for window coordinates
rx = self.xpos - self.view_width/2
ry = self.ypos - self.view_height/2
dx = 0
dy = 0
if rx < 0:
dx = rx
elif rx > (MAP_WIDTH - self.view_width):
dx = rx - (MAP_WIDTH - self.view_width)
if ry < 0:
dy = ry
elif ry > (MAP_HEIGHT - self.view_height):
dy = ry - (MAP_HEIGHT - self.view_height)
#sub_area1 = Rect(rx, ry, self.view_width, self.view_height)
#self.env.game.window.blit(self.env.game.map_buffer, (self.view_left, self.view_top), sub_area1)
# in window coord, center of the player view
ship_window_pos = (int(self.view_width/2) + self.view_left + SHIP_SPRITE_SIZE/2 + dx, int(self.view_height/2) + self.view_top + SHIP_SPRITE_SIZE/2 + dy)
#print("ship_window_pos", ship_window_pos)
ray_surface_center = (int(RAY_BOX_SIZE/2), int(RAY_BOX_SIZE/2))
wall_distances = []
# 30 degres step
for angle in range(0, 359, RAY_AMGLE_STEP):
c = math.cos(math.radians(angle))
s = math.sin(math.radians(angle))
flip_x = c < 0
flip_y = s < 0
filpped_map_mask = env.game.flipped_masks_map_buffer[flip_x][flip_y]
# ray final point
x_dest = ray_surface_center[0] + RAY_BOX_SIZE/2 * abs(c)
y_dest = ray_surface_center[1] + RAY_BOX_SIZE/2 * abs(s)
#x_dest = ray_surface_center[0] + RAY_BOX_SIZE * abs(c)
#y_dest = ray_surface_center[1] + RAY_BOX_SIZE * abs(s)
self.ray_surface.fill((0, 0, 0))
self.ray_surface.set_colorkey((0, 0, 0))
pygame.draw.line(self.ray_surface, WHITE, ray_surface_center, (x_dest, y_dest))
ray_mask = pygame.mask.from_surface(self.ray_surface)
pygame.draw.circle(self.ray_surface, RED, ray_surface_center, 3)
# offset = ray mask (left/top) coordinate in the map (ie where to put our lines mask in the map)
if flip_x:
offset_x = MAP_WIDTH - (self.xpos+SHIP_SPRITE_SIZE/2) - int(RAY_BOX_SIZE/2)
else:
offset_x = self.xpos+SHIP_SPRITE_SIZE/2 - int(RAY_BOX_SIZE/2)
if flip_y:
offset_y = MAP_HEIGHT - (self.ypos+SHIP_SPRITE_SIZE/2) - int(RAY_BOX_SIZE/2)
else:
offset_y = self.ypos+SHIP_SPRITE_SIZE/2 - int(RAY_BOX_SIZE/2)
#print("offset", offset_x, offset_y)
hit = filpped_map_mask.overlap(ray_mask, (int(offset_x), int(offset_y)))
#print("hit", hit)
if hit is not None and (hit[0] != self.xpos+SHIP_SPRITE_SIZE/2 or hit[1] != self.ypos+SHIP_SPRITE_SIZE/2):
hx = MAP_WIDTH-1 - hit[0] if flip_x else hit[0]
hy = MAP_HEIGHT-1 - hit[1] if flip_y else hit[1]
hit = (hx, hy)
#print("new hit", hit)
# go back to screen coordinates
dx_hit = hit[0] - (self.xpos+SHIP_SPRITE_SIZE/2)
dy_hit = hit[1] - (self.ypos+SHIP_SPRITE_SIZE/2)
if render_it:
pygame.draw.line(env.game.window, LVIOLET, ship_window_pos, (ship_window_pos[0] + dx_hit, ship_window_pos[1] + dy_hit))
#pygame.draw.circle(map, RED, hit, 2)
# Note: this is the distance from the center of the ship, not the borders
dist_wall = math.sqrt(dx_hit**2 + dy_hit**2)
# so remove
dist_wall -= (SHIP_SPRITE_SIZE/2 - 1)
# Not hit: too far
else:
dist_wall = RAY_MAX_LEN
if dist_wall < 0:
dist_wall = 0
wall_distances.append(dist_wall)
#print("Sensor for angle=%s, dist wall=%.2f" % (str(angle), dist_wall))
#env.game.window.blit(RAY_SURFACE, (self.view_left + self.view_width, self.view_top))
#map.blit(RAY_SURFACE, (int(offset_x), int(offset_y)))
return wall_distances
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
class MayhemEnv():
def __init__(self, game, render_it, nb_player, mode="game", motion="gravity", sensor="", record_play="", play_recorded=""):
self.myfont = pygame.font.SysFont('Arial', 20)
self.render_it = render_it
self.nb_player = nb_player
# screen
self.game = game
self.game.window.fill((0, 0, 0))
self.mode = mode # training or game
self.motion = motion # basic, thrust, gravity
self.sensor = sensor
# record / play recorded
self.record_play = record_play
self.played_data = [] # [(0,0,0), (0,0,1), ...] (left, right, thrust)
self.play_recorded = play_recorded
if self.play_recorded:
with open(self.play_recorded, "rb") as f:
self.played_data = pickle.load(f)
# FPS
self.clock = pygame.time.Clock()
self.paused = False
self.frames = 0
self.nb_dead = 0
self.ships = []
if self.mode == "game":
self.ship_1 = Ship(self.mode, self.game.screen_width, self.game.screen_height, 1, self.nb_player, SHIP1_X, SHIP1_Y, \
SHIP_1_PIC, SHIP_1_PIC_THRUST, SHIP_1_PIC_SHIELD, SHIP_1_KEYS, SHIP_1_JOY, SHIP_MAX_LIVES - self.nb_dead)
self.ship_2 = Ship(self.mode, self.game.screen_width, self.game.screen_height, 2, self.nb_player, SHIP2_X, SHIP2_Y, \
SHIP_2_PIC, SHIP_2_PIC_THRUST, SHIP_2_PIC_SHIELD, SHIP_2_KEYS, SHIP_2_JOY, SHIP_MAX_LIVES - self.nb_dead)
self.ship_3 = Ship(self.mode, self.game.screen_width, self.game.screen_height, 3, self.nb_player, SHIP3_X, SHIP3_Y, \
SHIP_3_PIC, SHIP_3_PIC_THRUST, SHIP_3_PIC_SHIELD, SHIP_3_KEYS, SHIP_3_JOY, SHIP_MAX_LIVES - self.nb_dead)
self.ship_4 = Ship(self.mode, self.game.screen_width, self.game.screen_height, 4, self.nb_player, SHIP4_X, SHIP4_Y, \
SHIP_4_PIC, SHIP_4_PIC_THRUST, SHIP_4_PIC_SHIELD, SHIP_4_KEYS, SHIP_4_JOY, SHIP_MAX_LIVES - self.nb_dead)
self.ships.append(self.ship_1)
if self.nb_player >= 2:
self.ships.append(self.ship_2)
if self.nb_player >= 3:
self.ships.append(self.ship_3)
if self.nb_player >= 4:
self.ships.append(self.ship_4)
# -- training params
self.done = False
self.frame_pic = None
if self.mode == "training":
self.ship_1 = Ship(self.mode, self.game.screen_width, self.game.screen_height, 1, 1, 430, 730, \
SHIP_1_PIC, SHIP_1_PIC_THRUST, SHIP_1_PIC_SHIELD, SHIP_1_KEYS, SHIP_1_JOY, SHIP_MAX_LIVES)
def main_loop(self):
# exit on Quit
while True:
# real training loop is done in reset() / step() / render()
# practice_loop is just a free flight
if self.mode == "training":
self.practice_loop()
# game
elif self.mode == "game":
self.game_loop()
for ship in self.ships:
ship.sound_thrust.stop()
ship.sound_bounce.stop()
ship.sound_shield.stop()
ship.sound_shoot.stop()
ship.sound_explod.play()
self.nb_dead += 1
# record play ?
self.record_it()
def record_it(self):
if self.record_play:
with open(self.record_play, "wb") as f:
pickle.dump(self.played_data, f, protocol=pickle.HIGHEST_PROTOCOL)
time.sleep(0.1)
print("Frames=", self.frames)
print("%s seconds" % int(self.frames/MAX_FPS))
sys.exit(0)