-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
9229 lines (8182 loc) · 468 KB
/
main.py
File metadata and controls
9229 lines (8182 loc) · 468 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
import json
from math import cos, sin, radians, ceil, floor
from random import randint
from threading import Thread, Event
from time import sleep
import assets.audio_loader as sounds
import assets.font_loader as fonts
import assets.image_loader as assets
import assets.map_loader as maps
try:
import pygame
except ImportError: # Attempt to install pygame if it doesn't exist with tkinter UI
from tkinter import messagebox, Toplevel, Message
import subprocess
import sys
loop = True
confirm = False
user = False
while loop:
if not confirm:
user = messagebox.askyesno('Install Pygame?', 'Pygame is required for this game.\n'
'Would you like to install Pygame?')
if user or confirm:
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'pygame'])
import pygame
messagebox.showinfo('Success', 'Pygame was successfully installed.')
loop = False
user = None
except subprocess.CalledProcessError or ModuleNotFoundError as error:
user = messagebox.askretrycancel('Could not Install', 'There was an error installing pygame.\n'
'If the problem persists, you may have to'
' install it manually.\n\n'
'Would you like to retry?', icon='error')
if not user:
quit()
else:
confirm = messagebox.askyesno('Are you sure?', 'If you do not install pygame,\n'
'you will not be able to play this game!\n'
'Do you want to install pygame?',
icon='warning', default=messagebox.NO)
if not confirm:
quit()
pygame.init() # Initialise all libraries for pygame
pygame.joystick.init()
pygame.mixer.init()
# -------- GLOBAL VARIABLES -------- #
# Menu colour constants
RED = 255, 0, 0
GREEN = 0, 255, 0
WHITE = 255, 255, 255
V_LIGHT_GREY = 200, 200, 200
LIGHT_GREY = 170, 170, 170
GREY = 150, 150, 150
DARK_GREY = 100, 100, 100
BLACK = 0, 0, 0
# Car colour constants
RED_CAR = 232, 106, 23
YELLOW_CAR = 255, 204, 0
GREEN_CAR = 57, 194, 114
BLUE_CAR = 47, 149, 208
BLACK_CAR = 93, 91, 91
# Other variables
Debug = False # Enables Debug mode for detecting issues. (Changes various things other than visual changes)
Race_debug = False # Enables Debug mode and starts game on race settings menu
Force_resolution = [] # Manual window size ([] = Automatic, [width, height] = Forced)
Screen = 0 # If the user has multiple monitors, sets which monitor to use (starts at 0)
Animations = False # Enables animations on the main menu
Mute_volume = False # Set default muted state
Music_volume = 0.5 # Set default Volume level for music
Sfx_volume = 0.5 # Set default Volume level for all sounds effects
FPS = 60 # Controls the speed of the game ***changing from 60 will break EVERYTHING!***
Intro_screen = True # Enables the intro screen on game boot
Countdown = True # Enables the traffic light countdown on game start
Load_settings = True # Enables setting loading + saving
Game_end = False # Lets the game know if the game finished or if the player quit
# -------- SETTINGS FUNCTIONS -------- #
def save_settings():
if Load_settings:
try:
with open('settings.json', 'r+') as file:
data = json.load(file)
data['Debug'] = Debug
if Display_resolution == Desktop_info[Screen]: # If resolution is automatic
data['Resolution'] = 0
else: # If resolution is forced...
data['Resolution'] = Display_resolution
data['Screen'] = Screen
data['Menu animations'] = Animations
data['Mute volume'] = Mute_volume
data['Music volume'] = Music_volume
data['Sfx volume'] = Sfx_volume
file.seek(0)
json.dump(data, file, indent=2)
file.truncate()
print('Successfully saved settings to file.')
except FileNotFoundError:
print("*** ERROR: Failed to save settings -> 'settings.json' not found! ***")
except PermissionError:
print('*** ERROR: Failed to save settings -> permission denied! ***')
def load_settings():
if Load_settings:
global Debug, Force_resolution, Screen, Animations, Mute_volume, Music_volume, Sfx_volume
try:
with open('settings.json') as file:
file = json.load(file)
Debug = file['Debug']
Force_resolution = file['Resolution']
Screen = file['Screen']
Animations = file['Menu animations']
Mute_volume = file['Mute volume']
Music_volume = file['Music volume']
Sfx_volume = file['Sfx volume']
print('Successfully loaded settings from file.')
except FileNotFoundError:
print("*** ERROR: Failed to save settings -> 'settings.json' not found! ***")
print('Creating new settings file...')
try:
with open('settings.json', 'w') as settings:
default_settings = {'Debug': False,
'Resolution': 0,
'Screen': 0,
'Menu animations': True,
'Mute volume': False,
'Music volume': 0.5,
'Sfx volume': 0.5}
json.dump(default_settings, settings, indent=2)
print('Successfully created new settings file.')
except PermissionError:
print('*** ERROR: Failed to save settings -> permission denied! ***')
except PermissionError:
print('*** ERROR: Failed to save settings -> permission denied! ***')
if Load_settings:
load_settings()
Desktop_info = pygame.display.get_desktop_sizes()
if not Force_resolution: # Automatically detect screen resolution and set display size
if len(Desktop_info) < Screen + 1: # Always default to 1st screen if previously set to other and only have one
Screen = 0
Display_resolution = tuple(Desktop_info[Screen])
else:
if len(Desktop_info) < Screen + 1: # Always default to 1st screen if previously set to second and only have one
Screen = 0
save_settings()
Display_resolution = tuple(Force_resolution)
print('Running at ' + str(Display_resolution[0]) + ' x ' + str(Display_resolution[1]))
pygame.display.set_caption('Retro Rampage') # Set display name
try:
icon = pygame.surface.Surface((32, 32))
icon.set_colorkey(BLACK)
icon.blit(pygame.transform.scale(pygame.image.load(assets.car(RED_CAR, 'family car')), (20, 32)), (6, 0))
pygame.display.set_icon(icon) # Set display icon
except FileNotFoundError:
print('*** ERROR: Could not set window icon -> {0} not found! ***'.format(assets.car(RED_CAR, 'family car')))
if Desktop_info[Screen] != Display_resolution:
Display = pygame.display.set_mode(Display_resolution, display=Screen)
Fullscreen = False
else:
Display = pygame.display.set_mode(Display_resolution, display=Screen, flags=pygame.FULLSCREEN)
Fullscreen = True
'''
Create virtual window at 1080p that game writes to, then when screen is updated scale the window
to the size of the screen and write to screen, also scale mouse positions and screen updates
between window and screen. This means that the game will always render at 1080p, however can output
any resolution by scaling. There is also a secondary window for fade effects and visual animations that works the same.
Note: any scaling between any window and the screen (apart from writing directly to it, which this game doesn't do)
is not 100% exact due to rounding! Rounding will always round UP to avoid artifacts, but could overlap pixels
in the process. This usually results in thin lines not showing up or being thinner than they are supposed to.
'''
WIDTH, HEIGHT = 1920, 1080 # System default resolution that will scale to display *MUST BE 1080p!*
CENTRE = WIDTH // 2, HEIGHT // 2 # Calculate centre pixel for reference
Window = pygame.Surface((WIDTH, HEIGHT))
Window_resolution = Window.get_size()
Window_screenshot = Window.copy()
Window_sleep = False # Slow down screen updates when not focused
Secondary_window = pygame.Surface((WIDTH, HEIGHT))
current_window = ''
if Display_resolution != Window_resolution:
Display_scaling = True
else:
Display_scaling = False
Players = []
Selected_player = []
Player_amount = 0
Npc_amount = 3
Map = maps.objs[len(maps.index)//2]()
Track_mask = pygame.mask.Mask((WIDTH, HEIGHT))
Total_laps = 3
Current_lap = 0
Race_time = 0
Player_positions = []
Player_list = []
All_vehicles = []
Npc_names = [['John', False], ['Mark', False], ['Lilly', False], ['Jessica', False], ['Matthew', False],
['James', False], ['Jack', False], ['Holly', False], ['Aimee', False], ['Harrison', False],
['Emily', False], ['Ben', False], ['Tom', False], ['Anthony', False], ['Michael', False],
['Noah', False], ['Oliver', False], ['Jake', False], ['Olivia', False], ['Teddy', False],
['Tyler', False], ['Carmel', False], ['Jeremy', False], ['Joe', False], ['Steven', False],
['Scott', False], ['Keith', False], ['Jules', False], ['Katharine', False], ['Charlotte', False]]
controllers = []
controls = []
controller_prompts = []
Npc_force_veh = 0
Npc_force_colour = None
lightning_frames = []
for frame in range(0, 15):
lightning_frames.append(pygame.transform.scale(pygame.image.load(assets.animation('lightning', frame)), (128, 128)))
smoke_frames = []
for frame in range(0, 7):
smoke_frames.append(pygame.transform.scale(pygame.image.load(assets.animation('smoke', frame)), (64, 64)))
repair_frames = []
for frame in range(0, 11):
repair_frames.append(pygame.transform.scale(pygame.image.load(assets.animation('repair', frame)), (128, 128)))
# Define tile and menu variables
map_preview_size = 974, 600
map_preview_pos = CENTRE[0] - map_preview_size[0] // 2, CENTRE[1] - map_preview_size[1] // 2
map_preview = '', pygame.surface.Surface(map_preview_size)
tile_scale = ceil(WIDTH / 15), ceil(HEIGHT / 10)
menu_scroll_speed = 70 # Default = 20
menu_car_speed = 10 # Default = 6
button_trigger = False # only press single button with single click
selected_text_entry = 0
current_song = ''
Clock = pygame.time.Clock() # Used for timing display updates and keeping constant FPS
music_thread = Thread()
loading_thread = Thread()
loading_thread_event = Event()
music_thread_event = Event()
# Define game variables
powerups = True
Game_paused = False
global_car_rotation_speed = 1
global_car_move_speed = 4
# Define updating and loaded asset lists
screen_updates = []
loaded_assets = []
loaded_sounds = []
loaded_fonts = {}
# -------- CLASSES -------- #
class Object:
def __init__(self, surf: pygame.surface.Surface, rect: pygame.rect.Rect, mask: pygame.mask.Mask):
self.surf = surf
self.rect = rect
self.mask = mask
self.ver = None
self.timeout = None
self.active = None
class Player:
def __init__(self, position: int, is_player=True):
self.id = position
self.is_player = is_player
if 0 > self.id or 5 < self.id:
raise ValueError('Player | self.id can only be between 0 and 5 not ' + str(self.id))
self.name = None
self.veh_name = None
self.veh_image = None
self.veh_colour = None
self.start_pos = self.id + 1
self.controls = None
self.default_controls = None
if self.is_player:
self.load_player()
else:
self.load_npc()
self.update_image()
def load_player(self):
if self.id == 0:
self.veh_name = 'Family Car'
self.veh_colour = RED_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
elif self.id == 1:
self.name = ''
self.veh_name = 'Sports Car'
self.veh_colour = YELLOW_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
elif self.id == 2:
self.veh_name = 'Luxury Car'
self.veh_colour = GREEN_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
elif self.id == 3:
self.veh_name = 'Truck'
self.veh_colour = BLUE_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
elif self.id == 4:
self.veh_name = 'Race Car'
self.veh_colour = BLACK_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
elif self.id == 5:
self.veh_name = 'Family Car'
self.veh_colour = RED_CAR
if 'wasd' not in controls:
self.controls = 'wasd'
elif 'arrows' not in controls:
self.controls = 'arrows'
if self.controls:
controls.append(self.controls)
else:
self.controls = 'controller'
self.name = ''
self.default_controls = self.controls
def load_npc(self):
self.name = Npc_names[randint(0, len(Npc_names) - 1)] # Only use one name per NPC
while self.name[1] or self.name[0].lower() == Players[0].name.lower() or Player_amount >= 2 and \
self.name[0].lower() == Players[1].name.lower() or Player_amount >= 3 and \
self.name[0].lower() == Players[2].name.lower() or Player_amount >= 4 and \
self.name[0].lower() == Players[3].name.lower() or Player_amount >= 5 and \
self.name[0].lower() == Players[4].name.lower() or Player_amount == 6 and \
self.name[0].lower() and Players[5].name.lower():
self.name = Npc_names[randint(0, len(Npc_names) - 1)]
self.name[1] = True
if Npc_force_veh == 1:
self.veh_name = 'Family Car'
elif Npc_force_veh == 2:
self.veh_name = 'Sports Car'
elif Npc_force_veh == 3:
self.veh_name = 'Luxury Car'
elif Npc_force_veh == 4:
self.veh_name = 'Truck'
elif Npc_force_veh == 5:
self.veh_name = 'Race Car'
else:
self.veh_name = rand_vehicle()
if Npc_force_colour:
self.veh_colour = Npc_force_colour
else:
self.veh_colour = rand_color()
def update_image(self):
self.veh_image = pygame.transform.scale(pygame.image.load(assets.car(self.veh_colour, self.veh_name)),
(175, 300))
class MenuCar: # Create car sprite
def __init__(self):
self.scale = 71, 131
self.pos_x = CENTRE[0]
self.pos_y = CENTRE[1]
self.rotation = 0 # Default rotation
self.image = pygame.transform.scale(pygame.image.load(assets.car('red', 'family car')).convert(), self.scale)
self.image.set_colorkey(BLACK) # Remove background from image
self.size = self.image.get_size()
self.rect = self.image.get_rect() # Set surface size to image size
self.scaled_rect = None
self.prev_rect = self.rect
if Debug:
pygame.draw.rect(self.image, WHITE, self.rect, 1) # Draw outline of sprite (debugging)
self.rect.center = self.pos_x, self.pos_y # Centre car on screen
self.speed = menu_car_speed
def rotate(self, degree): # Func to rotate car
if self.rotation != degree: # Only change rotation if it is different from current rotation for efficiency
self.prev_rect = pygame.rect.Rect(self.rect) # Remember previous position as clear rect
self.image = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
assets.car('red', 'family car')).convert(), self.scale), degree) # Rotate image
self.image.set_colorkey(BLACK) # Remove bg from rotated image
self.rotation = degree # Set current rotation as rotation
self.rect = self.image.get_rect() # Set surface size to image size
if Debug:
pygame.draw.rect(self.image, WHITE, self.rect, 1) # Draw outline of sprite (debugging)
self.rect.center = self.pos_x, self.pos_y
self.size = self.image.get_size()
def move(self, x, y):
self.prev_rect = pygame.rect.Rect(self.rect) # Remember previous position as clear rect
screen_updates.append(self.prev_rect) # Add clear rectangle to update list to clear previous pos
self.pos_x = x
self.pos_y = y
self.rect.center = x, y
def draw(self, update=False):
Window.blit(self.image, (self.rect.left, self.rect.top)) # Draw new car on screen
if update:
if Display_scaling:
self.scaled_rect = [self.rect[0], self.rect[1], self.rect[2], self.rect[3]]
update_screen(scale_rect(self.scaled_rect))
self.scaled_rect = [self.prev_rect[0], self.prev_rect[1], self.prev_rect[2], self.prev_rect[3]]
update_screen(scale_rect(self.scaled_rect))
else:
update_screen(rect=self.prev_rect)
update_screen(rect=self.rect)
else:
if Display_scaling:
self.scaled_rect = [self.rect[0], self.rect[1], self.rect[2], self.rect[3]] # Get rect size and pos
screen_updates.append(scale_rect(self.scaled_rect)) # Scale and update to screen
self.scaled_rect = [self.prev_rect[0], self.prev_rect[1], self.prev_rect[2], self.prev_rect[3]]
screen_updates.append(scale_rect(self.scaled_rect))
else:
screen_updates.append(self.prev_rect)
screen_updates.append(self.rect)
def animate(self, direction: str, bg: any):
if direction == 'up':
if self.rotation != 0:
if self.rotation < 180:
for rotation in reversed(range(0, self.rotation, self.speed)):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
else:
for rotation in range(self.rotation, 360 + 1, self.speed):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
self.rotation = 0
elif direction == 'down':
if self.rotation != 180:
if self.rotation < 180:
for rotation in range(self.rotation, 180 + 1, self.speed):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0)) # Draw background and assets to remove old car frame
self.rotate(rotation) # Rotate car by set degree
self.draw(update=True) # Only update area around car
else:
for rotation in reversed(range(180, self.rotation, self.speed)):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0)) # Draw background and assets to remove old car frame
self.rotate(rotation) # Rotate car by set degree
self.draw(update=True) # Only update area around car
elif direction == 'left':
if self.rotation != 90:
if self.rotation > 90:
for rotation in reversed(range(90, self.rotation, self.speed)):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
else:
for rotation in range(self.rotation, 90 + 1, self.speed):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
elif direction == 'right':
if self.rotation != 270:
if self.rotation > 270:
for rotation in reversed(range(270, self.rotation, menu_car_speed)):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
elif self.rotation < 90:
for rotation in reversed(range(-90, self.rotation, menu_car_speed)):
Clock.tick(FPS)
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
self.rotation = 270
else:
for rotation in range(self.rotation, 270 + 1, menu_car_speed):
Clock.tick(FPS) # Ensure constant FPS between animations
Window.blit(bg, (0, 0))
self.rotate(rotation)
self.draw(update=True)
class Car(pygame.sprite.Sprite):
def __init__(self, player: Player):
super().__init__()
self.player = player
self.is_player = self.player.is_player
self.id = self.player.id
if self.id > 6 or self.id < 0:
raise ValueError('Car | self.id should only be between 0 and 5, not ' + str(self.player.id))
# STARTING variables
self.start_pos = self.player.start_pos
self._origin_pos = Map.start_pos(self.start_pos)
self._origin_rotation = self._origin_pos[2] # Original rotation
self._origin_pos = self._origin_pos[:2]
self.vehicle = self.player.veh_name
self._move_speed = global_car_move_speed
self._rotation_speed = global_car_rotation_speed
if self.vehicle == 'Family Car':
self.max_speed = 3
self.max_rotation_speed = 2
self.durability = 4
elif self.vehicle == 'Sports Car':
self.max_speed = 4
self.max_rotation_speed = 3
self.durability = 2
elif self.vehicle == 'Luxury Car':
self.max_speed = 3
self.max_rotation_speed = 3
self.durability = 3
elif self.vehicle == 'Truck':
self.max_speed = 2
self.max_rotation_speed = 2
self.durability = 5
elif self.vehicle == 'Race Car':
self.max_speed = 5
self.max_rotation_speed = 3
self.durability = 1
self.set_move_speed(self.max_speed)
self.set_rotation_speed(self.max_rotation_speed)
# SURFACE variables
self.colour = self.player.veh_colour
self.image_dir = assets.car(self.colour, self.vehicle)
self.image = pygame.transform.scale(pygame.image.load(self.image_dir).convert(), (40, 70))
self.image.set_colorkey(BLACK)
self._origin_img = self.image
self._dmg_img = None
self.damage = 0
self.size = self.image.get_size()
# RECT variables
self.rect = self.image.get_rect()
self.rect.center = self._origin_pos
self.pos_x = self.rect.x
self.pos_y = self.rect.y
self.rotation = self._origin_rotation
# COLLISION variables
self.mask = pygame.mask.from_surface(self.image) # Get mask from image
self.mask_overlap = None # Used for checking collision position
self.mask_area = None # Used to ensure the player cannot get outside the map
self.mask_size = None
self.collision = False
self.finished = False
# MOVEMENT variables
self._up = None
self._down = None
self._left = None
self._right = None
self.input_type = None
self.controller = None
self.set_controls(self.player.controls)
self._allow_forwards = True
self._allow_reverse = True
self._pressed_keys = None
self._boost_timeout = 0
self.bullet_penalty = 0
self._bullet_damage = 0
self._current_speed = 0
self._boost_frames = [] # Boost animation frames stored locally as different versions per car
self._boost_ani_frame = -1
for frames in range(0, 4):
self._boost_frames.append(pygame.transform.scale(pygame.image.load(assets.animation(
'flame', frames, car_num=self.vehicle)), (self.size[0], self.size[1] + 20)))
self._smoke_ani_frame = -1
self._repair_ani_frame = -1
self._ani_frame = None
self._ani_frame_rect = None
self.lightning_animation = False
self.lightning_target = False
self.lightning_indicator = pygame.transform.scale(pygame.image.load(assets.power_up('lightning')), (16, 16))
self._lightning_frame = None
# NAME variables
self.name = self.player.name
self._name_rect = None
# LAP variables
self._lap_halfway = True
self.laps = 0
# CHECKPOINT variables
self.checkpoint_count = -1
self.checkpoint_time = 99999999999
# SOUND variables
self._collision_sound = False
# Move car to starting position
self.move(self._origin_pos[0], self._origin_pos[1])
if self.rotation != 0: # If start rotation is not 0 then rotate
self.rotate(self.rotation)
def set_move_speed(self, speed):
if speed < 1:
speed = 1
if speed != 10: # Save current speed for boost powerup
self._current_speed = speed
self._move_speed = global_car_move_speed + speed
def set_rotation_speed(self, speed):
self._rotation_speed = global_car_rotation_speed + speed
def set_controls(self, control: str or pygame.joystick.Joystick): # Set controls to appropriate keys
if control == 'wasd':
self.input_type = 'wasd'
self._up = pygame.K_w
self._down = pygame.K_s
self._left = pygame.K_a
self._right = pygame.K_d
elif control == 'arrows':
self.input_type = 'arrows'
self._up = pygame.K_UP
self._down = pygame.K_DOWN
self._left = pygame.K_LEFT
self._right = pygame.K_RIGHT
elif control in controllers:
self.input_type = 'controller'
self.controller = control
if not self.controller.get_init():
self.controller.init()
else:
raise ValueError("Car | controls is not == 'wasd' or 'arrows'"
" or controller : {0} as {1}".format(control, type(control)))
def check_checkpoints(self, checkpoint_rectangles):
if not self.finished:
for checkpoint in checkpoint_rectangles: # For each checkpoint
if checkpoint.colliderect(self.rect) and \
self.checkpoint_count != checkpoint_rectangles.index(checkpoint):
self.checkpoint_count = checkpoint_rectangles.index(checkpoint) # Set current checkpoint
self.checkpoint_time = pygame.time.get_ticks() # Set checkpoint time
if not self._lap_halfway and self.checkpoint_count == \
ceil(len(checkpoint_rectangles) / 2): # If hit halfway
self._lap_halfway = True # Set halfway
if self._lap_halfway and checkpoint_rectangles.index(checkpoint) == 0 and \
self.checkpoint_count <= checkpoint_rectangles.index(checkpoint): # If point 0 and halfway
self._lap_halfway = False # Halfway reset
self.laps += 1
def check_track_collisions(self): # Check if there are collisions and take action
if not self.collision or self.collision == 'track':
if Debug: # If debug then outline car mask in red
for pos in self.mask.outline():
pos_x, pos_y = pos
pygame.draw.circle(self.image, RED, (pos_x, pos_y), 1)
self.mask_overlap = self.mask.overlap(Track_mask, (-self.rect.left, -self.rect.top))
if self.mask_overlap:
self.collision = 'track'
if not self._collision_sound:
play_sound('collision')
if self.controller:
self.controller.rumble(0, 0.2, 250)
self._collision_sound = True
if self.damage < self.durability:
self.damage += 1
if self.damage:
self._dmg_img = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
assets.car_damage(self.vehicle, self.damage)), self.size), self.rotation)
self._dmg_img.set_colorkey(WHITE)
self.image.blit(self._dmg_img, (0, 0)) # Overlay damage on top of image
# If there is a collision between masks...
self.mask_area = self.mask.overlap_area(Track_mask, (-self.rect.left, -self.rect.top))
self.mask_size = self.mask.count()
if Debug: # If debug then show collision position via small yellow square
pygame.draw.rect(self.image, YELLOW_CAR, (self.mask_overlap[0], self.mask_overlap[1], 5, 5))
screen_updates.append((self.mask_overlap[0], self.mask_overlap[1], 5, 5))
if self.rotation <= 45 or self.rotation >= 315: # If car is pointing up...
# print('pointing up')
if self.image.get_size()[1] // 2 > self.mask_overlap[1]: # If the collision is on the top half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[1] // 2 < self.mask_overlap[1]: # If the collision is on the bottom half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 45 < self.rotation < 135: # If the car is pointing left...
# print('pointing left')
if self.image.get_size()[0] // 2 > self.mask_overlap[0]: # If the collision is on the left half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[0] // 2 < self.mask_overlap[0]: # If the collision is on the right half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 135 <= self.rotation <= 225: # If the car is pointing down...
# print('pointing down')
if self.image.get_size()[1] // 2 < self.mask_overlap[1]: # If the collision is on the bottom half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[1] // 2 > self.mask_overlap[1]: # If the collision is on the top half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 225 < self.rotation < 315: # If the car is pointing right...
# print('pointing right')
if self.image.get_size()[0] // 2 < self.mask_overlap[0]: # If the collision is on the right half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[0] // 2 > self.mask_overlap[0]: # If the collision is on the left half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
if self.mask_area > self.mask_size // 2: # If over half of the car is colliding with the mask...
self.move(self._origin_pos[0], self._origin_pos[1]) # Reset the car to starting position + rotation
self.rotate(self._origin_rotation)
# print('reset to origin')
else: # If there are no collisions with the track
self.collision = False
self._collision_sound = False
if not self._allow_forwards: # Ensure that the player can move forwards and backwards
self._allow_forwards = True
if not self._allow_reverse:
self._allow_reverse = True
def check_car_collision(self, sprite):
if not self.finished and not sprite.finished and (not self.collision or self.collision == sprite):
self.mask_overlap = pygame.sprite.collide_mask(self, sprite)
if self.mask_overlap:
self.collision = sprite
if not self._collision_sound:
play_sound('collision')
if self.controller:
self.controller.rumble(0, 0.2, 250)
self._collision_sound = True
if self.damage < self.durability:
self.damage += 1
if self.damage:
self._dmg_img = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
assets.car_damage(self.vehicle, self.damage)), self.size), self.rotation)
self._dmg_img.set_colorkey(WHITE)
self.image.blit(self._dmg_img, (0, 0)) # Overlay damage on top of image
# If there is a collision between masks...
self.mask_area = self.mask.overlap_area(sprite.mask, (-self.rect.left, -self.rect.top))
self.mask_size = self.mask.count()
if Debug: # If debug then show collision position via small yellow square
pygame.draw.rect(self.image, YELLOW_CAR, (self.mask_overlap[0], self.mask_overlap[1], 5, 5))
screen_updates.append((self.mask_overlap[0], self.mask_overlap[1], 5, 5))
if self.rotation <= 45 or self.rotation >= 315: # If car is pointing up...
# print('pointing up')
if self.image.get_size()[1] // 2 > self.mask_overlap[1]: # If the collision is on the top half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[1] // 2 < self.mask_overlap[1]: # If the collision is on the bottom half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 45 < self.rotation < 135: # If the car is pointing left...
# print('pointing left')
if self.image.get_size()[0] // 2 > self.mask_overlap[0]: # If the collision is on the left half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[0] // 2 < self.mask_overlap[0]: # If the collision is on the right half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 135 <= self.rotation <= 225: # If the car is pointing down...
# print('pointing down')
if self.image.get_size()[1] // 2 < self.mask_overlap[1]: # If the collision is on the bottom half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[1] // 2 > self.mask_overlap[1]: # If the collision is on the top half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
elif 225 < self.rotation < 315: # If the car is pointing right...
# print('pointing right')
if self.image.get_size()[0] // 2 < self.mask_overlap[0]: # If the collision is on the right half
self._allow_forwards = False # Do not allow forwards
self._allow_reverse = True
# print('do not allow forwards')
elif self.image.get_size()[0] // 2 > self.mask_overlap[0]: # If the collision is on the left half
self._allow_forwards = True # Do not allow reverse
self._allow_reverse = False
# print('do not allow reverse')
if self.mask_area > self.mask_size // 1.5: # If over half of the car is colliding with the mask...
self.move(self._origin_pos[0], self._origin_pos[1]) # Reset the car to starting position + rotation
self.rotate(self._origin_rotation)
# print('reset to origin')
else: # If there are no collisions with the track
self.collision = False
self._collision_sound = False
if not self._allow_forwards: # Ensure that the player can move forwards and backwards
self._allow_forwards = True
if not self._allow_reverse:
self._allow_reverse = True
def move(self, x, y): # Move car to new position
self.pos_x = x
self.pos_y = y
self.rect.center = x, y
def rotate(self, degree): # Rotate car to new angle
self.rotation = degree # Set current rotation as rotation
if global_car_rotation_speed + 1 >= self.rotation: # Create snapping points to drive in straight lines
self.rotation = 360
elif self.rotation >= 360 - (global_car_rotation_speed + 1):
self.rotation = 0
elif 90 - (global_car_rotation_speed + 1) <= self.rotation <= 90 + (global_car_rotation_speed + 1):
self.rotation = 90
elif 180 - (global_car_rotation_speed + 1) <= self.rotation <= 180 + (global_car_rotation_speed + 1):
self.rotation = 180
elif 270 - (global_car_rotation_speed + 1) <= self.rotation <= 270 + (global_car_rotation_speed + 1):
self.rotation = 270
self.image = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
self.image_dir).convert(), self.size), self.rotation) # Rotate image
self.image.set_colorkey(BLACK)
self.mask = pygame.mask.from_surface(self.image) # Update mask to new rotation
if 0 < self.damage <= self.durability:
self._dmg_img = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(
assets.car_damage(self.vehicle, self.damage)), self.size), self.rotation) # Load and rotate damage
self._dmg_img.set_colorkey(WHITE)
self.image.blit(self._dmg_img, (0, 0)) # Overlay damage on top of image
self.rect = self.image.get_rect() # Set surface size to image size
if self.finished:
self.image.set_alpha(150)
if Debug:
pygame.draw.rect(self.image, WHITE, self.rect, 1) # Draw outline of sprite (debugging)
self.rect.center = self.pos_x, self.pos_y
def power_up(self, ver):
if ver == 'repair':
play_sound('repair')
if self.controller:
self.controller.rumble(0, 0.7, 200)
self.damage = 0
self._repair_ani_frame = 0
elif ver == 'boost':
play_sound('boost')
if not self._boost_timeout:
self._boost_timeout = pygame.time.get_ticks() + 2000 + (5000 - self._current_speed * 1000)
self.set_move_speed(10)
self.set_rotation_speed(5)
self._boost_ani_frame = 0
else:
self._boost_timeout += 2000 + (5000 - self._current_speed * 1000)
if self.controller:
self.controller.rumble(0, 0.2, self._boost_timeout - pygame.time.get_ticks())
elif ver == 'bullet':
if self._boost_timeout:
self._boost_timeout = 0
self._boost_ani_frame = -1
play_sound('bullet')
if self.controller:
self.controller.rumble(1, 1, 500)
self._bullet_damage = self.damage
self.bullet_penalty = pygame.time.get_ticks() + 2000 + (5000 - self._current_speed * 1000)
self._smoke_ani_frame = 0
self.damage = self.durability
self.rotate(self.rotation + 1) # Reloads image for damage
self.rotate(self.rotation - 1)
elif ver == 'lightning':
if ver == 'lightning' and not self.collision and not self.bullet_penalty:
self.lightning_animation = pygame.time.get_ticks() // 70
elif ver == 'lightning rumble':
if self.controller:
self.controller.rumble(0.3, 0.5, 700)
def check_inputs(self): # Check all inputs and take action
if self.input_type == 'wasd' or self.input_type == 'arrows':
self._pressed_keys = pygame.key.get_pressed() # Get all pressed keys on keyboard
if self._pressed_keys[self._up] and self._pressed_keys[self._down]: # If up and down pressed at same time
return # Do not move the car
if self._pressed_keys[self._up] and self._allow_forwards: # If up key is pressed
self.move(self.pos_x - round(cos(radians(self.rotation - 90)) * self._move_speed),
self.pos_y + round(sin(radians(self.rotation - 90)) * self._move_speed))
# print('car move: ' + str(self.pos_x) + ', ' + str(self.pos_y))
if self._pressed_keys[self._left]: # If left key is pressed
self.rotate(self.rotation + self._rotation_speed) # Rotate car to new position
# print(self.rotation)
elif self._pressed_keys[self._right]: # If right key is pressed
self.rotate(self.rotation - self._rotation_speed)
# print(self.rotation)
elif self._pressed_keys[self._down] and self._allow_reverse: # If down key is pressed
self.move(self.pos_x + round(cos(radians(self.rotation - 90)) * self._move_speed), # Always move back
self.pos_y - round(sin(radians(self.rotation - 90)) * self._move_speed)) # Despite rotation
# print('car move: ' + str(self.pos_x) + ', ' + str(self.pos_y))
if self._pressed_keys[self._left]: # If left key is pressed
self.rotate(self.rotation - self._rotation_speed) # Rotate car to new position
# print(self.rotation)
elif self._pressed_keys[self._right]: # If right key is pressed
self.rotate(self.rotation + self._rotation_speed)
# print(self.rotation)
elif self.input_type == 'controller' and self.controller.get_init():
if self.controller.get_axis(5) > 0.6 and self.controller.get_axis(4) > 0.6:
return # Do not move the car
if self.controller.get_axis(5) > 0.6 and self._allow_forwards:
self.move(self.pos_x - round(cos(radians(self.rotation - 90)) * self._move_speed),
self.pos_y + round(sin(radians(self.rotation - 90)) * self._move_speed))
if self.controller.get_axis(0) < -0.6: # If left key is pressed
self.rotate(self.rotation + self._rotation_speed) # Rotate car to new position
elif self.controller.get_axis(0) > 0.6: # If right key is pressed
self.rotate(self.rotation - self._rotation_speed)
elif self.controller.get_axis(4) > 0.6 and self._allow_reverse: # If down key is pressed
self.move(self.pos_x + round(cos(radians(self.rotation - 90)) * self._move_speed), # Always move back
self.pos_y - round(sin(radians(self.rotation - 90)) * self._move_speed)) # Despite rotation
if self.controller.get_axis(0) < -0.6: # If left key is pressed
self.rotate(self.rotation - self._rotation_speed) # Rotate car to new position
elif self.controller.get_axis(0) > 0.6: # If right key is pressed
self.rotate(self.rotation + self._rotation_speed)
elif self.controller and not self.controller.get_init():
self.controller.init()
def draw(self, surf=Window):
surf.blit(self.image, (self.rect.left, self.rect.top)) # Car image
draw_triangle((self.rect.centerx, self.rect.top - 14), 'down', # Name
width=10, height=10, border=self.colour, border_width=3, surface=surf)
self._name_rect = draw_text(self.rect.centerx, self.rect.top - 35,
self.name, WHITE, 12, surf=surf, return_rect=True)
if self.lightning_target:
surf.blit(self.lightning_indicator, (self.rect.centerx - self._name_rect.width/2 -
self.lightning_indicator.get_width() - 8, self.rect.top - 38))
if self._boost_ani_frame == 4 and self._boost_timeout: # If boost animation finished
self._boost_ani_frame = 0 # Replay animation
elif not self._boost_timeout and self._boost_ani_frame != -1: # If boost timeout finished
self._boost_ani_frame = -1 # Reset animation
if self._boost_timeout and self._boost_ani_frame >= 0: # If boost animation playing
self._ani_frame = pygame.transform.rotate(self._boost_frames[self._boost_ani_frame], self.rotation)
self._ani_frame_rect = self._ani_frame.get_rect()
self._ani_frame_rect.center = self.rect.center
surf.blit(self._ani_frame, (self._ani_frame_rect.left, self._ani_frame_rect.top))
self._boost_ani_frame += 1 # Increase animation to next frame
if self._smoke_ani_frame >= 14 and self.bullet_penalty: # If smoke animation finished
self._smoke_ani_frame = 0 # Replay animation
elif not self.bullet_penalty and self._smoke_ani_frame >= 14: # If smoke timeout finished
self._smoke_ani_frame = -1 # Reset animation at end of loop
if self._smoke_ani_frame >= 0: # If smoke animation playing
self._ani_frame = smoke_frames[floor(self._smoke_ani_frame / 2)]
self._ani_frame_rect = self._ani_frame.get_rect()
self._ani_frame_rect.centerx = self.rect.centerx
self._ani_frame_rect.bottom = self.rect.centery
surf.blit(self._ani_frame, (self._ani_frame_rect.left, self._ani_frame_rect.top))
self._smoke_ani_frame += 1 # Increase animation to next frame
if self._repair_ani_frame >= 22: # If repair animation finished...
self._repair_ani_frame = -1 # Reset animation
if self._repair_ani_frame >= 0:
self._ani_frame = repair_frames[floor(self._repair_ani_frame / 2)]
self._ani_frame_rect = self._ani_frame.get_rect()
self._ani_frame_rect.center = self.rect.center
surf.blit(self._ani_frame, (self._ani_frame_rect.left, self._ani_frame_rect.top))
self._repair_ani_frame += 1 # Increase animation to next frame