-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1705 lines (1455 loc) · 68.7 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
import pygame
import os
import threading
import time
import tkinter as tk
import math
from math import atan2 # degrees
import pandas as pd
import numpy as np
root = tk.Tk()
# screen variables
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
WIDTH, HEIGHT = screen_width, screen_height
# ship variables
ship_list = []
team_1_ship_list = []
team_1_ship_waiting_list = []
team_2_ship_list = []
team_2_ship_waiting_list = []
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 70, 70
# player stats
PLAYER_CREDITS: float
PLAYER_MAX_BULLETS: float
PLAYER_LASER_RECHARGE_TIME: float
PLAYER_HEALTH: float
PLAYER_FUEL: float
PLAYER_MAX_TORPEDOES: int
def initialize_player_stats():
"""
Resets the player stats to default.
This function runs once at the beginning, and then
again each time the player loses and returns to round 1.
"""
global PLAYER_CREDITS, PLAYER_MAX_BULLETS, PLAYER_LASER_RECHARGE_TIME
global PLAYER_HEALTH, PLAYER_FUEL, PLAYER_MAX_TORPEDOES
PLAYER_CREDITS = 1000
PLAYER_MAX_BULLETS = 3
PLAYER_LASER_RECHARGE_TIME = 1
PLAYER_HEALTH = 5
PLAYER_FUEL = 1500
PLAYER_MAX_TORPEDOES = 0
initialize_player_stats()
# game variables
FPS = 60
TIME_TO_BUY_UPGRADES = False
keys_pressed = []
ROUND_COUNT = 1
round_is_ongoing = False
run = True
version = 2.14
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Game")
BORDER = pygame.Rect(WIDTH//2 - 5, 0, 10, HEIGHT)
event_ID = 1
explosion_group = pygame.sprite.Group()
projectile_list = []
show_targets = False
ship_id = 0 # used for generating a name for the ship
UPGRADE_BUTTON_LIST = []
UPGRADE_WINDOW: object
NUMBER_OF_CHANNELS = 10
current_channel = 1
pygame.font.init()
pygame.mixer.init()
pygame.mixer.set_num_channels(NUMBER_OF_CHANNELS)
# colors
GREY = (100, 100, 100)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
UPGRADE_WINDOW_BACKGROUND = (56, 54, 84)
SELECTED = (47, 85, 151)
ACTIVE = (143, 170, 220)
INACTIVE = (214, 220, 229)
INACTIVE_TEXT = (127, 127, 127)
GREEN = (56, 87, 35)
# sound effects taken from https://mixkit.co/free-sound-effects/
# also https://pixabay.com/sound-effects
BULLET_HIT_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'war_field_explosion.wav'))
BULLET_HIT_SOUND_PLAYER = pygame.mixer.Sound(os.path.join('Assets', 'explosion_in_battle.wav'))
BULLET_FIRE_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'laser.wav'))
BULLET_FIRE_SOUND_PLAYER = pygame.mixer.Sound(os.path.join('Assets', 'laser_2.mp3'))
BULLET_FIRE_SOUND_ALLY = pygame.mixer.Sound(os.path.join('Assets', 'laser_4.mp3'))
SEISMIC_CHARGE_SOUND= pygame.mixer.Sound(os.path.join('Assets', 'seismic_charge.wav'))
TORPEDO_LAUNCH_SOUND= pygame.mixer.Sound(os.path.join('Assets', 'torpedo_launch.wav'))
EXPLOSION_AND_SCREAMING_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'ship_explodes.wav'))
VICTORY_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'drums.wav'))
ENGINE_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'fuel_burn.wav'))
OUT_OF_FUEL_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'emf_shutdown.mp3'))
EXPLOSION_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'car_explosion_debris.wav'))
SUCCESS_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'success.wav'))
DENIED_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'denied.wav'))
NEXT_ROUND_SOUND = pygame.mixer.Sound(os.path.join('Assets', 'next_round.wav'))
HEALTH_FONT = pygame.font.Font(os.path.join('Assets', 'Roboto-Light.ttf'), 40)
WEAPON_FONT = pygame.font.Font(os.path.join('Assets', 'Roboto-Light.ttf'), 20)
BANNER_FONT = pygame.font.Font(os.path.join('Assets', 'Roboto-Medium.ttf'), 60)
DIAGNOSTICS_FONT = pygame.font.Font(os.path.join('Assets', 'Roboto-Light.ttf'), 15)
UPGRADE_BUTTON_FONT = pygame.font.Font(os.path.join('Assets', 'Roboto-Light.ttf'), 20)
# images
X_WING_IMAGE = pygame.image.load(os.path.join('Assets', 'xwing.png')).convert_alpha()
X_WING_IMAGE = pygame.transform.scale(X_WING_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
X_WING_IMAGE = pygame.transform.rotate(X_WING_IMAGE, 270)
OLD_REPUBLIC_FIGHTER = pygame.image.load(os.path.join('Assets', 'old_republic_fighter.png')).convert_alpha()
OLD_REPUBLIC_FIGHTER = pygame.transform.scale(OLD_REPUBLIC_FIGHTER, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
OLD_REPUBLIC_FIGHTER = pygame.transform.rotate(OLD_REPUBLIC_FIGHTER, 270)
TIE_FIGHTER_IMAGE = pygame.image.load(os.path.join('Assets', 'tiefighter.png')).convert_alpha()
TIE_FIGHTER_IMAGE = pygame.transform.scale(TIE_FIGHTER_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
TIE_FIGHTER_IMAGE = pygame.transform.rotate(TIE_FIGHTER_IMAGE, 90)
BLUE_ORB_IMAGE = pygame.image.load(os.path.join('Assets', 'blue_orb.png')).convert_alpha()
BLUE_ORB_IMAGE = pygame.transform.scale(BLUE_ORB_IMAGE, (15, 15))
BLUE_ORB_IMAGE_DISABLED = pygame.image.load(os.path.join('Assets', 'blue_orb_disabled.png')).convert_alpha()
BLUE_ORB_IMAGE_DISABLED = pygame.transform.scale(BLUE_ORB_IMAGE_DISABLED, (15, 15))
RED_LASER_IMAGE = pygame.image.load(os.path.join('Assets', 'red_laser.png')).convert_alpha()
RED_LASER_IMAGE = pygame.transform.scale(RED_LASER_IMAGE, (15, 15))
RED_LASER_IMAGE = pygame.transform.rotate(RED_LASER_IMAGE, 90)
BLUE_LASER_IMAGE = pygame.image.load(os.path.join('Assets', 'blue_laser.png')).convert_alpha()
BLUE_LASER_IMAGE = pygame.transform.scale(BLUE_LASER_IMAGE, (15, 15))
BLUE_LASER_IMAGE = pygame.transform.rotate(BLUE_LASER_IMAGE, 90)
GREEN_LASER_IMAGE = pygame.image.load(os.path.join('Assets', 'green_laser.png')).convert_alpha()
GREEN_LASER_IMAGE = pygame.transform.scale(GREEN_LASER_IMAGE, (15, 15))
GREEN_LASER_IMAGE = pygame.transform.rotate(GREEN_LASER_IMAGE, 90)
GREEN_LASER_IMAGE_DISABLED = pygame.image.load(os.path.join('Assets', 'green_laser_disabled.png')).convert_alpha()
GREEN_LASER_IMAGE_DISABLED = pygame.transform.scale(GREEN_LASER_IMAGE_DISABLED, (15, 15))
GREEN_LASER_IMAGE_DISABLED = pygame.transform.rotate(GREEN_LASER_IMAGE_DISABLED, 90)
RED_ARROW_WIDTH, RED_ARROW_HEIGHT = 100, 100
RED_ARROW_IMAGE = pygame.image.load(os.path.join('Assets', 'red_arrow.png')).convert_alpha()
RED_ARROW_IMAGE = pygame.transform.scale(RED_ARROW_IMAGE, (RED_ARROW_WIDTH, RED_ARROW_HEIGHT))
RED_ARROW_IMAGE = pygame.transform.rotate(RED_ARROW_IMAGE, 180)
RED_ARROW_IMAGE_DOWN = pygame.transform.rotate(RED_ARROW_IMAGE, 90)
RED_ARROW_IMAGE_UP = pygame.transform.rotate(RED_ARROW_IMAGE, 270)
RED_ARROW_IMAGE_UP_LEFT = pygame.transform.rotate(RED_ARROW_IMAGE, 315)
RED_ARROW_IMAGE_DOWN_LEFT = pygame.transform.rotate(RED_ARROW_IMAGE, 45)
RED_ARROW = pygame.Rect(WIDTH//4, HEIGHT//2, RED_ARROW_WIDTH, RED_ARROW_HEIGHT)
TARGET_IMAGE = pygame.image.load(os.path.join('Assets', 'red_target_2.png')).convert_alpha()
TARGET_IMAGE = pygame.transform.scale(TARGET_IMAGE, (200, 200))
SPACE = pygame.image.load(os.path.join('Assets', 'space.png')).convert_alpha()
SPACE = pygame.transform.scale(SPACE, (WIDTH, HEIGHT))
pygame.display.set_icon(X_WING_IMAGE)
# read the game controller from the csv
game_controller = pd.read_csv("game_controller.csv")
print(game_controller)
# events
bullet_sound_event = pygame.USEREVENT + 1
bullet_hit_sound_event = pygame.USEREVENT + 2
engine_sound_event = pygame.USEREVENT + 3
screaming_sound_event = pygame.USEREVENT + 4
toggle_target_event = pygame.USEREVENT + 5
# quadrants
quadrant_6 = ((0, WIDTH//2), (0, HEIGHT))
quadrant_7 = ((WIDTH//2, WIDTH), (0, HEIGHT))
quadrant_14 = ((-1 * WIDTH//2, 0), (-1 * HEIGHT//2, 1.5 * HEIGHT))
quadrant_15 = ((WIDTH, 1.5 * WIDTH), (-1 * HEIGHT//2, 1.5 * HEIGHT))
# entire_playable_area_quadrant = ((.1 * WIDTH, .9 * WIDTH), (.1 * HEIGHT, .9 * HEIGHT)) # smaller playable area for testing
entire_playable_area_quadrant = ((-1 * WIDTH, 2 * WIDTH), (-1 * HEIGHT, 2 * HEIGHT))
# sprites
explosion_image_list = []
for num in range(1, 6):
img = pygame.image.load(os.path.join('Assets', f'exp{num}.png'))
img = pygame.transform.scale(img, (100, 100))
explosion_image_list.append(img)
green_explosion_image_list = []
for num in range(1, 6):
img = pygame.image.load(os.path.join('Assets', f'exp{num}_green.png'))
img = pygame.transform.scale(img, (100, 100))
green_explosion_image_list.append(img)
# general functions
def get_angle(p1, p2):
"""
Determines the angle of a straight line drawn between point one and two.
In radians.
REFERENCE: WikiCode, http://wikicode.wikidot.com/get-angle-of-line-between-two-points
"""
xDiff = p2[0] - p1[0]
yDiff = p2[1] - p1[1]
radians = atan2(yDiff, xDiff)
return radians
def get_distance(p1, p2):
"""calculates the distance between two points"""
xDiff = p2[0] - p1[0]
yDiff = p2[1] - p1[1]
distance = math.sqrt(xDiff ** 2 + yDiff **2)
return distance
def simplify_angle(angle):
"""
takes and angle and returns simplied angle in radians.
no negatives or angles greater than 6.28319 radians.
for example:
-5 degrees -> 355 degress
400 degress -> 340 degress
"""
full_rotation = 6.28319 # 360 degrees in radians
while angle > full_rotation:
angle -= full_rotation
if angle < 0:
angle += full_rotation
return angle
def play_sound_and_increment_channel(sound):
"""
chooses the next channel and then plays the sound on that channel
prevents sounds from overlapping and causing conflicts
"""
global current_channel
if current_channel == NUMBER_OF_CHANNELS:
current_channel = 1
else:
current_channel += 1
pygame.mixer.Channel(current_channel).play(sound)
class upgrade_button:
def __init__(self):
"""
type: Laser Capacity, Laser Recharge Time, Health, Fuel, Next Round
"""
global UPGRADE_WINDOW
button_width = 400
button_height = 50
button_padding = 5
if len(UPGRADE_BUTTON_LIST) == 0:
self.blit_coord = (WIDTH/2 - button_width/2, HEIGHT/2 - 200)
else:
previous_x = UPGRADE_BUTTON_LIST[-1].blit_coord[0]
previous_y = UPGRADE_BUTTON_LIST[-1].blit_coord[1]
previous_height = UPGRADE_BUTTON_LIST[-1].button_rect.height
self.blit_coord = (previous_x, previous_y + previous_height + button_padding)
self.button_rect = pygame.Rect(self.blit_coord[0], self.blit_coord[1], button_width, button_height)
self.status = "active"
self.color = GREY
self.text_color = WHITE
UPGRADE_BUTTON_LIST.append(self)
# re-define UPGRADE_WINDOW
blit_x = WIDTH / 2 - button_width / 2 - button_padding
blit_y = UPGRADE_BUTTON_LIST[0].button_rect.y - button_padding # HEIGHT / 2 - 400
width = button_width + (2 * button_padding)
height = len(UPGRADE_BUTTON_LIST) * (button_height + button_padding) + button_padding
UPGRADE_WINDOW = pygame.Rect(blit_x, blit_y, width, height)
def check_status(self):
"""
checks the status of the upgrade buttons and updates their color accordingly
"""
if self.status not in ["selected", "active", "inactive"]:
return
if self.status == "selected":
self.color = SELECTED
self.text_color = WHITE
elif PLAYER_CREDITS >= self.cost:
self.status = "active"
self.color = ACTIVE
self.text_color = WHITE
elif PLAYER_CREDITS < self.cost:
self.status = "inactive"
self.color = INACTIVE
self.text_color = INACTIVE_TEXT
def is_pressed(self):
"""
defines what happens when upgrade button is clicked
"""
global player_ship, PLAYER_MAX_BULLETS, PLAYER_CREDITS, TIME_TO_BUY_UPGRADES
global PLAYER_LASER_RECHARGE_TIME
if self.status == "active":
self.status = "selected"
PLAYER_CREDITS -= self.cost
self.price_text = "Purchased"
self.perform_action()
elif self.status == "next button":
self.perform_action()
else:
DENIED_SOUND.play()
print("insufficient funds")
def blit(self):
pygame.draw.rect(WIN, self.color, self.button_rect)
text_buffer = 10
self.text_rendered = UPGRADE_BUTTON_FONT.render(self.text, 1, self.text_color)
self.price_text_rendered = UPGRADE_BUTTON_FONT.render(self.price_text, 1, self.text_color)
self.text_blit_x = self.button_rect.x + text_buffer
self.text_blit_y = self.button_rect.y + self.button_rect.height / 2 - self.text_rendered.get_height() / 2
self.price_text_blit_x = self.button_rect.x + self.button_rect.width - self.price_text_rendered.get_width() - text_buffer
self.price_text_blit_y = self.text_blit_y
WIN.blit(self.text_rendered, (self.text_blit_x, self.text_blit_y))
WIN.blit(self.price_text_rendered, (self.price_text_blit_x, self.price_text_blit_y))
class upgrade_button_laser_capacity(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.cost = 3000
self.text = f"Laser Capacity +1"
self.price_text = f"{self.cost} Credits"
def perform_action(self):
global PLAYER_MAX_BULLETS
PLAYER_MAX_BULLETS += 1
player_ship.available_bullets = PLAYER_MAX_BULLETS # this is to ensure display is instantly updated
print("upgrading laser capacity")
SUCCESS_SOUND.play()
class upgrade_button_laser_time(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.cost = 4000
self.text = "Laser Recharge Time -10%"
self.price_text = f"{self.cost} Credits"
def perform_action(self):
global PLAYER_LASER_RECHARGE_TIME
previous_time = PLAYER_LASER_RECHARGE_TIME
PLAYER_LASER_RECHARGE_TIME *= .9
print(f"upgrading laser recharge time from {previous_time} to {PLAYER_LASER_RECHARGE_TIME}")
SUCCESS_SOUND.play()
class upgrade_button_health(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.cost = 4000
self.text = "Health +1"
self.price_text = f"{self.cost} Credits"
def perform_action(self):
global PLAYER_HEALTH
PLAYER_HEALTH += 1
player_ship.health = PLAYER_HEALTH # this is to ensure display is instantly updated
SUCCESS_SOUND.play()
class upgrade_button_fuel(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.cost = 2500
self.text = "Fuel +500"
self.price_text = f"{self.cost} Credits"
def perform_action(self):
global PLAYER_FUEL
PLAYER_FUEL += 500
player_ship.fuel = PLAYER_FUEL # this is to ensure display is instantly updated
SUCCESS_SOUND.play()
class upgrade_torpedo(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.cost = 5000
self.text = "Proton Torpedo"
self.price_text = f"{self.cost} Credits"
def perform_action(self):
global PLAYER_MAX_TORPEDOES
PLAYER_MAX_TORPEDOES += 1
player_ship.maximum_torpedoes = PLAYER_MAX_TORPEDOES # this is to ensure display is instantly updated
player_ship.available_torpedoes = PLAYER_MAX_TORPEDOES
SUCCESS_SOUND.play()
class next_round_button(upgrade_button):
def __init__(self):
upgrade_button.__init__(self)
self.status = "next button" # this prevents the check_status function from altering this button
self.cost = 0
self.text = "Next Round"
self.price_text = ""
self.color = GREEN
def blit(self):
pygame.draw.rect(WIN, self.color, self.button_rect)
self.text_rendered = UPGRADE_BUTTON_FONT.render(self.text, 1, self.text_color)
self.text_blit_x = self.button_rect.x + self.button_rect.width / 2 - self.text_rendered.get_width() / 2
self.text_blit_y = self.button_rect.y + self.button_rect.height / 2 - self.text_rendered.get_height() / 2
WIN.blit(self.text_rendered, (self.text_blit_x, self.text_blit_y))
def perform_action(self):
global TIME_TO_BUY_UPGRADES
TIME_TO_BUY_UPGRADES = False
NEXT_ROUND_SOUND.play()
main()
class ship_1:
def __init__(self, image, team, is_ai = True,
health=5, fuel=2000, maximum_torpedoes=0,
maximum_bullets=3, bullet_recharge_time=1,
acceleration=.261, accuracy=50):
global event_ID, ship_id
# image
self.image = image
self.width = 70
self.height = 70
# general characteristics
self.ship_id = ship_id
ship_id += 1
self.team = team
self.is_ai = is_ai
self.acceleration = acceleration
self.health = health
self.fuel = fuel
self.out_of_fuel = False
self.max_speed = 3.5
self.vel_x = 0
self.vel_y = 0
self.selected_weapon = 'Laser'
self.maximum_bullets = maximum_bullets
self.available_bullets = maximum_bullets
self.maximum_torpedoes = maximum_torpedoes
self.available_torpedoes = self.maximum_torpedoes
self.bullet_recharge_time = bullet_recharge_time # in seconds
self.hit_event = pygame.USEREVENT + 5 + event_ID
event_ID += 1
self.is_off_screen = False
self.quadrant = ''
self.accuracy = accuracy
# sounds
if self.team == 1 and self.is_ai == False:
self.laser_sound = BULLET_FIRE_SOUND_PLAYER
elif self.team == 1 and self.is_ai:
self.laser_sound = BULLET_FIRE_SOUND_ALLY
elif self.team == 2:
self.laser_sound = BULLET_FIRE_SOUND
# controls
self.up = False
self.down = False
self.left = False
self.right = False
self.fire = False
self.engine_on = False
self.change_target = False
# movement
self.x_vel = 0
self.y_vel = 0
self.target_point_x, self.target_point_y = self.select_starting_position()
self.rectangle = pygame.Rect(self.target_point_x, self.target_point_y, self.width, self.height)
self.target_rectangle = pygame.Rect(-100, -100, 70, 70)
self.target_ship = self
# team 1 bots start in random movement mode
# team 2 bots start in pursue target mode
if self.team == 1:
self.ai_mode = 0
elif self.team == 2:
self.ai_mode = 1
if self.team == 2: # if enemy, rotate the image to face the left side of the screen
self.image = pygame.transform.rotate(self.image, 180)
def check_fuel(self):
"""
checks if ship is out of fuel
when fuel reaches 0, a sound plays, 10 seconds passes, and then the ship's health is set to zero
"""
def thread():
global FPS
if self.out_of_fuel == False and self.fuel <= 0:
OUT_OF_FUEL_SOUND.play()
self.out_of_fuel = True
clock = pygame.time.Clock()
frame = 0
while run and round_is_ongoing and self in ship_list:
clock.tick(FPS)
frame += 1
if frame > 10 * FPS:
self.health = 0
break
threading.Thread(target=thread).start()
def select_starting_position(self):
"""
selects a random starting position for the beginning of the round.
"""
global player_ship
buffer = .75 * self.width # some buffer so that ships don't get placed on the edge of the screen.
if self.team == 2:
target_point_x = np.random.randint(quadrant_15[0][0] + buffer , quadrant_15[0][1] - buffer)
target_point_y = np.random.randint(quadrant_15[1][0] + buffer , quadrant_15[1][1] - buffer)
elif self. team == 1 and self.is_ai == False:
target_point_x = np.random.randint(quadrant_6[0][0] + buffer , quadrant_6[0][1] - buffer)
target_point_y = np.random.randint(quadrant_6[1][0] + buffer , quadrant_6[1][1] - buffer)
elif self.team == 1:
target_point_x = np.random.randint(quadrant_14[0][0] + buffer , quadrant_14[0][1] - buffer)
target_point_y = np.random.randint(quadrant_14[1][0] + buffer , quadrant_14[1][1] - buffer)
return target_point_x, target_point_y
def select_random_position(self):
"""
selects a random position within its own quadrant
used by the ai for randomly moving around during the round.
"""
buffer = .75 * self.width # some buffer so that ships don't get placed on the edge of the screen.
if self.team == 2:
target_point_x = np.random.randint(quadrant_7[0][0] + buffer , quadrant_7[0][1] - buffer)
target_point_y = np.random.randint(quadrant_7[1][0] + buffer , quadrant_7[1][1] - buffer)
elif self.team == 1:
target_point_x = np.random.randint(quadrant_6[0][0] + buffer , quadrant_6[0][1] - buffer)
target_point_y = np.random.randint(quadrant_6[1][0] + buffer , quadrant_6[1][1] - buffer)
self.define_target_rectangle()
return target_point_x, target_point_y
def check_controls(self, events):
"""
checks the buttons the user is pressing.
only for the human player.
ai equivalent is ai_move_to_target()
"""
global keys_pressed, team_2_ship_list
if self.is_ai == False:
self.up = keys_pressed[pygame.K_w]
self.down = keys_pressed[pygame.K_s]
self.left = keys_pressed[pygame.K_a]
self.right = keys_pressed[pygame.K_d]
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.fire = True
else:
self.fire = False
increment = 0
# changing target_ship
if event.type == pygame.KEYDOWN: # and self.change_target == False:
if event.key == pygame.K_UP:
team_2_ship_list.sort(key=lambda ship: ship.rectangle.y)
increment = -1
if event.key == pygame.K_DOWN:
team_2_ship_list.sort(key=lambda ship: ship.rectangle.y)
increment = 1
if event.key == pygame.K_LEFT:
team_2_ship_list.sort(key=lambda ship: ship.rectangle.x)
increment = -1
if event.key == pygame.K_RIGHT:
team_2_ship_list.sort(key=lambda ship: ship.rectangle.x)
increment = 1
if increment != 0:
if self.target_ship == self:
self.target_ship = team_2_ship_list[0]
else:
index = team_2_ship_list.index(self.target_ship)
try:
self.target_ship = team_2_ship_list[index + increment]
except:
self.target_ship = team_2_ship_list[0]
# changing weapon
if event.key == pygame.K_1:
self.selected_weapon = "Laser"
if event.key == pygame.K_2 and self.available_torpedoes > 0:
self.selected_weapon = "Torpedo"
else:
pass
if self.available_torpedoes <= 0:
self.selected_weapon = "Laser"
def run_ai(self):
def thread():
global run, round_is_ongoing, player_ship, ship_list, PLAYER_CREDITS
self.ai_move_to_target()
self.manage_firing()
if self.ai_mode == 0:
self.random_movement()
self.select_target_ship()
elif self.ai_mode == 1:
self.pursue_target()
self.randomize_ai_mode()
clock = pygame.time.Clock()
while run and round_is_ongoing and self in ship_list and self.health > 0:
clock.tick(FPS)
# when the ship's target ship dies, choose a new target
# do not select any dead ships or ai ships that are off screen
target_is_off_screen, _ = self.target_ship.determine_off_screen()
if self.target_ship not in ship_list or (target_is_off_screen and self.target_ship != player_ship):
self.select_target_ship()
# seek vengeance on attacker, unless self is low on health
for laser in projectile_list:
if self.rectangle.colliderect(laser.rectangle) and laser.team != self.team:
random_chance = np.random.randint(100)
if random_chance > 50 and self.health > 2: # randomly choose whether to retaliate against attacker
self.pursue_target(laser.parent)
else:
self.random_movement()
# don't pursue target ship off screen unless it is the player ship
is_off_screen, _ = self.target_ship.determine_off_screen()
if is_off_screen and self.target_ship != player_ship:
self.random_movement()
# pause the run_ai function to give the ship time to re-enter the screen.
# otherwise it will calculate a bunch of new random positions unnecessarily
time.sleep(3)
# if the bot's target is the player and the player is offscreen, change bot's ai_mode to pursue target
# this is to ensure the player can't hide offscreen from bots
if self.target_ship.is_ai == False and self.target_ship.determine_off_screen()[0] and self.ai_mode != 1:
self.pursue_target(provided_target=self.target_ship)
threading.Thread(target=thread).start()
def randomize_ai_mode(self):
"""
runs a looping thread that waits a random number of seconds and then
randomly selects a new ai mode
"""
def thread():
global run, round_is_ongoing, ship_list
fps = 10
clock = pygame.time.Clock()
while run and round_is_ongoing and self in ship_list and self.health > 0:
clock.tick(fps)
random_wait_time = np.random.randint(20, 60) # random wait time in seconds
fps = 10
clock = pygame.time.Clock()
n = 0
while run and round_is_ongoing and self in ship_list and self.health > 0 and n < random_wait_time * fps:
clock.tick(fps)
n += 1
original_ai_mode = self.ai_mode
self.ai_mode = np.random.randint(2)
if self.ai_mode == 0:
self.random_movement()
elif self.ai_mode == 1:
self.pursue_target()
threading.Thread(target=thread).start()
def select_target_ship(self):
global team_1_ship_list, team_2_ship_list
"""randomly selects a new target ship"""
if self.team == 1 and len(team_2_ship_list) != 0:
index = np.random.randint(len(team_2_ship_list))
self.target_ship = team_2_ship_list[index]
elif self.team == 2 and len(team_1_ship_list) != 0:
index = np.random.randint(len(team_1_ship_list))
self.target_ship = team_1_ship_list[index]
else:
self.target_ship = self
return self.target_ship
def define_target_rectangle(self):
"""
when the target coordinates change,
use this function to update the target rectangle's position
"""
plot_point_x = self.target_point_x - self.target_rectangle.width//2
plot_point_y = self.target_point_y - self.target_rectangle.height//2
self.target_rectangle = pygame.Rect(plot_point_x, plot_point_y, 70, 70)
def random_movement(self):
""""mode 0"""
def thread():
global run, round_is_ongoing
# generate a new target rectangle
self.ai_mode = 0
self.target_point_x, self.target_point_y = self.select_random_position()
self.define_target_rectangle()
clock = pygame.time.Clock()
while run and round_is_ongoing and self.ai_mode == 0:
clock.tick(10)
if self.rectangle.colliderect(self.target_rectangle):
# when it reaches its target rectangle, select a new target rectangle
self.target_point_x, self.target_point_y = self.select_random_position()
self.define_target_rectangle()
threading.Thread(target=thread).start()
def pursue_target(self, provided_target=""):
"""
mode 1
if there is no provided_target, one will be chosen randomly
"""
self.ai_mode = 1
if provided_target == "":
self.select_target_ship()
else:
self.target_ship = provided_target
self.target_point_x, _ = self.select_random_position()
def thread():
clock = pygame.time.Clock()
while run and round_is_ongoing and self.ai_mode == 1:
clock.tick(10)
# time it will take bullet to reach x coordinate of target
bullet_time = abs((self.rectangle.x - self.target_ship.rectangle.x) / 20) # 20 is the speed of bullets
# distance the enemy will travel in bullet_time
enemy_distance = self.target_ship.y_vel * bullet_time
# the distance that the ship should trail behind its target_ship on the y axis
# don't trail at all if the target_ship is moving slowly
if abs(self.target_ship.y_vel) < 2:
self.target_point_y = self.target_ship.rectangle.center[1]
if abs(self.target_ship.y_vel) > 2:
trailing_distance = enemy_distance
self.target_point_y = self.target_ship.rectangle.center[1] - trailing_distance
self.define_target_rectangle()
if self.rectangle.colliderect(self.target_rectangle):
self.target_point_x, _ = self.select_random_position()
self.target_point_y = self.target_ship.rectangle.center[1]
self.define_target_rectangle()
threading.Thread(target=thread).start()
def hold_position(self):
"""
mode 2
move to a randomly selected position and hold it
"""
# generate a new target rectangle
self.ai_mode = 2
self.target_point_x, self.target_point_y = self.select_random_position()
self.define_target_rectangle()
def ai_move_to_target(self):
"""
meant to run perpetuately during each round, regardless of the ship's current ai_mode
cause the ship to direct itself to its current target
"""
# manage directional keys (new way)
# not as fuel efficient as the old way
if self.ship_id % 2 == 0:
p1 = self.rectangle.center
p2 = self.target_rectangle.center
angle = get_angle(p1, p2)
angle = simplify_angle(angle)
goal_vel_x = math.cos(angle) * self.max_speed
goal_vel_y = math.sin(angle) * self.max_speed
if self.vel_x < goal_vel_x:
self.right = True
else:
self.right = False
if self.vel_x > goal_vel_x:
self.left = True
else:
self.left = False
if self.vel_y < goal_vel_y:
self.down = True
else:
self.down = False
if self.vel_y > goal_vel_y:
self.up = True
else:
self.up = False
else:
# manage directional keys (old way)
# more fuel efficient than the new way
buffer = self.target_rectangle.width//2
my_x, my_y = self.rectangle.center
if my_x < self.target_point_x - buffer:
self.right = True
else:
self.right = False
if my_x > self.target_point_x + buffer:
self.left = True
else:
self.left = False
if my_y < self.target_point_y - buffer:
self.down = True
else:
self.down = False
if my_y > self.target_point_y + buffer:
self.up = True
else:
self.up = False
# threading.Thread(target=thread).start()
def manage_firing(self):
"""
initiates a thread that continously loops to determine when the ship should fire
"""
def caculate_miss_margin():
"""
in between each shot fired, this function calculates
the margin by which the next shot will miss its target
this is determined by self.accuracy
"""
rand_chance = np.random.randint(0, 100)
if rand_chance > self.accuracy:
miss_above = np.random.randint(0, 2)
miss_margin = np.random.randint(70, 180)
if miss_above:
pass
else:
miss_margin = miss_margin * -1
else:
miss_margin = 0
return miss_margin
def thread():
global ship_list
miss_margin = caculate_miss_margin()
clock = pygame.time.Clock()
target_still_count = 0
while run and round_is_ongoing and self in ship_list and self.health > 0:
clock.tick(60)
# if the target comes to a stop, calculate a new miss margin
if -1 < self.target_ship.y_vel < 1:
target_still_count += 1
if target_still_count > 200:
# print('target is staying still. setting miss margin to 0')
miss_margin = 0
target_still_count = 0
if self.ai_mode == 0 or self.ai_mode == 1:
buffer = 10
# calculate the distance_between_ships_x, given the point where the bullet is fired and
# where it will impact on the target
# this value is calculated differently based on team, because each team faces opposite directions
if self.team == 1:
point_of_bullet_fire_x = self.rectangle.x + self.rectangle.width
point_of_bullet_impact_x = self.target_ship.rectangle.x
elif self.team == 2:
point_of_bullet_fire_x = self.rectangle.x
point_of_bullet_impact_x = self.target_ship.rectangle.x + self.target_ship.rectangle.width
distance_between_ships_x = abs(point_of_bullet_fire_x - point_of_bullet_impact_x)
# calculate bullet velocity based on team
if self.team == 1:
bullet_velocity = 20
elif self.team == 2:
bullet_velocity = -20
# time it will take bullet to reach x coordinate of the leading edge of the target
# this may not be a perfect way of calcuating the time, but it seems very close, the ai's shooting seems to be 100% accurate
bullet_time = (distance_between_ships_x) / abs(self.target_ship.x_vel - bullet_velocity)
# distance the enemy will travel in bullet_time
enemy_distance_y = self.target_ship.y_vel * bullet_time
if self.rectangle.center[1] - buffer < self.target_ship.rectangle.center[1] + enemy_distance_y + miss_margin < self.rectangle.center[1] + buffer:
bullets_to_fire = np.random.randint(1, 6)
fire_speed = np.random.randint(5, 50) / 100 # random firing speed between .05 and .5 seconds
for _ in range(bullets_to_fire):
self.fire = True
time.sleep(fire_speed)
self.fire = False
thread() # start the thread over so that a new miss_margin can be randomly calculated
break # break out of the loop so the current thread ends
threading.Thread(target=thread).start()
def handle_movement(self):
global keys_pressed, entire_playable_area_quadrant
global team_1_ship_list, team_2_ship_list
# SHIP MOVEMENT
team_1_center_boundary = BORDER.x - 5
team_2_center_boundary = BORDER.x + BORDER.width + 5
if self.team == 1 and self.rectangle.x + self.width >= team_1_center_boundary:
self.x_vel = 0
self.rectangle.x = team_1_center_boundary - self.width - 1
elif self.team ==2 and self.rectangle.x <= team_2_center_boundary:
self.x_vel = 0
self.rectangle.x = team_2_center_boundary + 1
else:
pass
self.rectangle.x += self.x_vel
self.rectangle.y += self.y_vel
# ENGINES
if self.fuel > 0:
if self.left and self.x_vel > (-1 * self.max_speed):
self.x_vel -= self.acceleration
self.try_engine_fire()
if self.fuel > 0:
self.fuel -= 1
else:
self.fuel = 0
if self.right and self.x_vel < self.max_speed:
self.x_vel += self.acceleration
self.try_engine_fire()
if self.fuel > 0:
self.fuel -= 1
else:
self.fuel = 0
if self.up and self.y_vel > (-1 * self.max_speed):
self.y_vel -= self.acceleration
self.try_engine_fire()
if self.fuel > 0:
self.fuel -= 1
else:
self.fuel = 0
if self.down and self.y_vel < self.max_speed:
self.y_vel += self.acceleration
self.try_engine_fire()
if self.fuel > 0:
self.fuel -= 1
else:
self.fuel = 0
else:
pass
# enforcement of boundaries
if self.rectangle.x <= entire_playable_area_quadrant[0][0]:
self.x_vel = 0
self.rectangle.x = entire_playable_area_quadrant[0][0] + 1
if self.rectangle.x >= entire_playable_area_quadrant[0][1]:
self.x_vel = 0
self.rectangle.x = entire_playable_area_quadrant[0][1] -1
if self.rectangle.y <= entire_playable_area_quadrant[1][0]:
self.y_vel = 0
self.rectangle.y = entire_playable_area_quadrant[1][0] + 1
if self.rectangle.y >= entire_playable_area_quadrant[1][1]:
self.y_vel = 0
self.rectangle.y = entire_playable_area_quadrant[1][1] - 1
# turn of the engine if none of the directional keys are pressed
if self.left == False and \
self.right == False and \
self.up == False and \
self.down == False:
self.engine_on = False
else:
pass
# assign a new target_ship if the current target_ship dies
if self.team == 1:
enemy_list = team_2_ship_list
elif self.team == 2:
enemy_list = team_1_ship_list