-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti_main.py
3449 lines (2987 loc) · 148 KB
/
multi_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
from random import randint, random, choice, shuffle
import socket, time, threading, requests, sys, logging, os
# logging setup
log_filename = 'covid_cover.log'
global_exit = False
if os.path.isfile(log_filename):
try:
os.remove(log_filename)
except PermissionError:
pass
logging.basicConfig(filename=log_filename,
format='%(asctime)s %(levelname)s %(message)s',
level=logging.INFO)
logging.info('game init')
# exit point IN ANY WAY
# is used when game stops
# saves and logs exit code (error_code)
def exit_game(no_player=False):
global global_exit
# setting signal for other threads to stop
global_exit = True
# waiting for threads to stop
time.sleep(0.25)
logging.info(f'exit code: {error_code}')
with open('score.dat', mode='w', encoding='utf-8') as file:
try:
money = player.card_money
except NameError:
money = 0
file.write(str(money) + ' ' + str(error_code))
sys.exit()
error_code = 0
# parsing and amount validation for cmd args
if len(sys.argv) != 5:
error_code = -7
exit_game()
args = sys.argv[1:]
pygame.init()
size = width, height = 1280, 720
screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
# sprite groups set up
all_sprites = pygame.sprite.Group()
player_group = pygame.sprite.Group()
building_group = pygame.sprite.Group()
settings_buttons_group = pygame.sprite.Group()
button_group = pygame.sprite.Group()
terrain_group = pygame.sprite.Group()
background_group = pygame.sprite.Group()
bank_buttons = pygame.sprite.Group()
pharm_buttons = pygame.sprite.Group()
pharm_group = pygame.sprite.Group()
background_pharm = pygame.sprite.Group()
pharm_products = pygame.sprite.Group()
shop_buttons = pygame.sprite.Group()
shop_group = pygame.sprite.Group()
background_shop = pygame.sprite.Group()
shop_products = pygame.sprite.Group()
house_buttons = pygame.sprite.Group()
house_group = pygame.sprite.Group()
background_house = pygame.sprite.Group()
house_products = pygame.sprite.Group()
prog_buttons = pygame.sprite.Group()
prog_group = pygame.sprite.Group()
background_prog = pygame.sprite.Group()
tablet_group = pygame.sprite.Group()
product_buttons = pygame.sprite.Group()
remote_players = pygame.sprite.Group()
npc_group = pygame.sprite.Group()
box_group = pygame.sprite.Group()
# remote players are stored in this dict
online_players = dict()
# other global vars
building_collide_step = 0
near_building_message = None
near_building = None
gravity = 1
menu_is_on = False
music_on = True
effects_on = True
arrested = False
orders = None
# internal_id = input('Enter internal id: ')
# setting vars from args for online mode
host, port, internal_id, player_name = args
port = int(port)
api_port = 8080
# for debug
'''role = 'policeman'
host, port = '127.0.0.1', 9000
player_name = '123456'
internal_id = 'c11cc4ab-492c-424c-aec1-e40b6e5236db'''
# internal_id = 'c3288c7b-acd1-4a6c-8e66-5c9b9c0c6fe0'
# internal_id = '2a288d46-b3bf-4669-a938-dbaa6e8d9126'
# ip = socket.gethostbyname('0.tcp.ngrok.io')
# host = ip
# host = '84.201.168.123'
# once a player is caught his id is added to this list
# this list id transmitted
# if id of client is in the list we procceed this case and arrest him
caught_ids = []
# all sounds for levels (used only in single mode)
speeches = {'intro': pygame.mixer.Sound('data/speech/intro.wav'),
'1': pygame.mixer.Sound('data/speech/1.wav'),
'2': pygame.mixer.Sound('data/speech/2.wav'),
'3': pygame.mixer.Sound('data/speech/3.wav'),
'autro': pygame.mixer.Sound('data/speech/autro.wav'),
'news': pygame.mixer.Sound('data/speech/news.wav')}
music = {'main': pygame.mixer.Sound('data/music/main_music.ogg')}
music['main'].play(-1)
# all objects sounds
sounds = {'apple': pygame.mixer.Sound('data/sounds/apple_crunch.wav'),
'atm_button': pygame.mixer.Sound('data/sounds/atm_button.wav'),
'bottle_open': pygame.mixer.Sound('data/sounds/bottle_open.wav'),
'cashbox': pygame.mixer.Sound('data/sounds/cashbox.wav'),
'close_door': pygame.mixer.Sound('data/sounds/close_door.wav'),
'drink_gulp': pygame.mixer.Sound('data/sounds/drink_gulp.wav'),
'open_door': pygame.mixer.Sound('data/sounds/open_door.wav')}
player_params = dict()
products = dict()
# the heart of multi mode
def operate_player_data():
global global_exit
# always trying to get a connection
while True:
try:
# only sockets (tcp) are used for transmitting coords and other data
con = socket.socket()
try:
con.connect((host, port))
except ConnectionRefusedError:
# if server is too busy to establish a connection we don't mind and catch the exception
con.close()
caught = caught_ids.copy()
# transmitting all necessary vars to the server at once
# raw str '\t' is used to join args
# '%' is used to join caught players id at the end
con.send(
(player.id + r'\t' + player_name + r'\t' + player.get_pos_info() + r'\t' + '%'.join(caught)).encode(
'utf-8'))
# we get data until it ends (and use end flag as a signal)
end = False
while not end:
# get data
data = con.recv(1024).decode('utf-8')
# if that's it but we have the last data
if 'end' in data and len(data) > 3:
# switch flag
end = True
# separate 'end'
data = data[:data.index('end')]
# if that's the end, stop immediatly
elif data == 'end':
break
# by this point we have got remote player params
# firstly, separate id and name
id, name, params = data.split(r'\t')[0], data.split(r'\t')[1], r'\t'.join(data.split(r'\t')[2:])
# if we are NOT drawing this character (it's NOT in the group and dict)
# that character is not the client
if str(id) not in player_params.keys() and id != player.id:
role = params.split(r'\t')[0]
# create instance and add to the group as well as to our dict
player_params[id] = RemotePlayer(str(id), 0, 0, role, name, remote_players)
# if there was an exception in the __init__ or
# in the update_images (explained in the RemotePlayer below)
if len(player_params[id].groups()) == 0:
player_params[id] = RemotePlayer(str(id), 0, 0, role, name, remote_players)
time.sleep(0.002)
# by this point we have already declared needed remote player
# set params to update position direction side etc
player_params[id].set_params(params)
time.sleep(0.002)
# if ANY trouble in the loop
# continue the loop to save connection
# if the wireless connection is weak it happens often, so, we often do not update other players
# and if it happens too often the cleanning thread just delete them
except Exception as e:
# print(e)
continue
finally:
# in any way we check the exit flag
if global_exit:
break
# function in the thread
# deletes and kills all remote players
def clean_params():
global global_exit, player_params, caught_ids
while True:
try:
print(player_params)
for i in player_params:
player_params[i].kill()
player_params = dict()
finally:
caught_ids = []
if global_exit:
break
time.sleep(5)
# to check if order is done (request to server, if not found, it's done)
def check_order_is_done():
global player, error_code
if player.order:
try:
response = requests.get(f'http://{host}:{api_port}/api/orders/{player.order}/token/{internal_id}',
timeout=0.25)
except requests.exceptions.Timeout:
error_code = -6
exit_game()
except requests.exceptions.ConnectionError:
error_code = -5
exit_game()
print(response.status_code)
if response.status_code == 404:
objs = [prod for prod in products.values() if prod.name in player.order_goods]
player.add_objects(*objs)
player.order_goods = None
player.order = 'done'
def count_time():
global global_time
local_clock = pygame.time.Clock()
while not global_exit:
global_time -= 1
if global_time <= 0:
exit_game()
break
try:
if global_time % 2 == 0:
player.satiety -= 1
if player.satiety > Player.satiety:
player.satiety -= 10
if player.satiety < 0:
player.satiety = 0
except NameError:
pass
local_clock.tick(1)
def stop_speeches():
for sound in speeches.values():
sound.stop()
def load_image(path, colorkey=None, size=None) -> pygame.Surface:
image = pygame.image.load(path).convert_alpha()
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey)
if size:
image = pygame.transform.scale(image, size)
return image
def draw_timer():
global global_time, total_game_seconds
current_time = global_time
time_position = (900, 5)
minutes, seconds = str(current_time // 60).rjust(2, '0'), str(current_time % 60).rjust(2, '0')
rect = pygame.Rect((time_position[0] - 5, time_position[1] - 5,
time_position[1] + 100, time_position[1] + 40))
pygame.draw.rect(screen, (236, 222, 181), rect, 0)
if current_time > total_game_seconds // 2:
screen.blit(render_text(f'{minutes}:{seconds}', size=50, color=(0, 255, 0)), time_position)
elif current_time > total_game_seconds // 4:
screen.blit(render_text(f'{minutes}:{seconds}', size=50, color=(255, 255, 0)), time_position)
else:
screen.blit(render_text(f'{minutes}:{seconds}', size=50, color=(255, 0, 0)), time_position)
def distance(first, second):
res = ((second[0] - first[0]) ** 2 + (second[1] - first[1]) ** 2) ** 0.5
return res
def check_collisions(player):
check_near_building(player)
for i in all_sprites:
if id(player) == id(i):
continue
if i.is_obstacle():
if pygame.sprite.collide_mask(player, i):
return True
return False
# if player collides building (logical, not phisical collision))
def check_near_building(player):
global near_building, near_building_message
near_building, near_building_message = None, None
for building in building_group:
if pygame.sprite.collide_mask(player, building):
near_building = building
near_building_message = f'Нажмите [E], чтобы войти в {building.name}'
def render_text(line, size=50, color=(255, 255, 255)):
font = pygame.font.Font(None, size)
text = font.render(line, 1, color)
return text
# main class for all remote players, stores params for drawing
class RemotePlayer(pygame.sprite.Sprite):
def __init__(self, id, x, y, role, name, *groups):
self.id = id # internal id of user
self.name = name # username
self.role = role # policeman, citizen or volunteer
self.scanner_is_on = False # only for policemen
self.side = 'left' # the sidem direction for drawing sprite
self.update_images()
self.image = self.frames['right'][0]
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
self.mask = pygame.mask.from_surface(self.image)
self.is_moving = False
self.clock = pygame.time.Clock()
self.infected = None
self.caught = 0
super().__init__(groups)
def get_coords(self):
return self.rect.x, self.rect.y
def set_position(self, pos):
self.rect.x, self.rect.y = pos
def set_moving(self, value):
self.is_moving = value
def is_obstacle(self):
return False
# main func for remote players
# update all params got from the server
def set_params(self, data):
data = data.split(r'\t')[1:]
# print(123)
# print(data)
# validation of params
try:
# assert len(data) == 5
new_x, new_y = int(data[0]), int(data[1])
moving = True if data[2] == 'True' else False
assert data[3] in ['left', 'right'] and str(data[3]).isalpha()
infected = str(data[4])
except Exception as e:
return
# updating params
self.set_position((new_x + terrain.rect.x, new_y + terrain.rect.y))
self.is_moving = moving
# probably a mistake, but set image can be avaliable only for the second or even third time
# game work better in this way
while True:
try:
self.image = self.frames[data[3]][0]
except IndexError:
continue
break
# if player was caught, proceed the arrest
if internal_id in data[5].split('%'):
global arrested
arrested = True
if infected == 'None':
self.infected = None
elif infected.isdigit():
self.infected = int(infected)
# func for setting next image, animation and changing according to the params from server
def update_images(self):
# if params were damaged and init wasn't finished because of error
# probably fixed
if not self.role:
self.kill()
self.frames = {'left': [], 'right': []}
role = self.role
if self.role == 'volunteer':
role = 'citizen'
self.frames['left'].append(
pygame.transform.flip(load_image(f'data/characters/{role}_right_5.png', size=(80, 110)), 1, 0))
try:
self.frames['left'][0].blit(render_text(self.name, 17, (255, 0, 0)), (0, 0))
except Exception as e:
print(e)
# if client is a policeman and the scanner is on: draw the infected state
if self.scanner_is_on:
if self.infected == 1:
self.frames['left'][0].blit(load_image('data/characters/not_stated.png', size=(20, 20)), (60, 0))
elif self.infected == 2:
self.frames['left'][0].blit(load_image('data/characters/ok.png', size=(20, 20)), (60, 0))
elif self.infected == 3:
self.frames['left'][0].blit(load_image('data/characters/infected.png', size=(20, 20)), (60, 0))
self.frames['right'].append(
load_image(f'data/characters/{role}_right_5.png', size=(80, 110)))
try:
self.frames['right'][0].blit(render_text(self.name, 17, (255, 0, 0)), (0, 0))
except Exception as e:
print(e)
if self.scanner_is_on:
if self.infected == 1:
self.frames['right'][0].blit(load_image('data/characters/not_stated.png', size=(20, 20)), (60, 0))
elif self.infected == 2:
self.frames['right'][0].blit(load_image('data/characters/ok.png', size=(20, 20)), (60, 0))
elif self.infected == 3:
self.frames['right'][0].blit(load_image('data/characters/infected.png', size=(20, 20)), (60, 0))
# setting prepared image
self.image = self.frames[self.side][0]
def update(self, *args):
if not args:
return
scanner_on = args[0]
if scanner_on != self.scanner_is_on:
# func is called again if scanner state was changed
self.scanner_is_on = scanner_on
self.update_images()
# main class for client
# drawing; storing vars, products, etc; moving; changing health, money, infection % etc
# is declared before the menu (game startup)
class Player(pygame.sprite.Sprite):
speed = 13
jump_power = 15
satiety = 100
def __init__(self, x, y, role, *groups):
# set role value as an attr
self.role = role
# citizen and volunteer each has the same sprite, so, we can change local var after its value is stored
if role == 'volunteer':
role = 'citizen'
# flag: if the player is inside any building
self.inside = False
self.frames = {'left': [], 'right': []}
self.frames['left'].append(
pygame.transform.flip(load_image(f'data/characters/{role}_right_5.png', size=(80, 110)), 1, 0))
self.frames['right'].append(
load_image(f'data/characters/{role}_right_5.png', size=(80, 110)))
self.image = self.frames['right'][0]
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
self.prev_coords = x, y
self.is_moving = False
self.grav = 0
self.is_jumping = False
self.clock = pygame.time.Clock()
self.side = 'left'
self.health = 100
self.hazard_risk = 0
self.danger_level = 1
self.hazard_timer = 0
self.id = None
self.speed = Player.speed
self.satiety = Player.satiety
self.card_money = 2500
self.cash = 5000
self.profit = 0.1
self.profit_timer = pygame.time.Clock()
self.profit_num = 0
# generating pin
self.objects = []
pin = str(randint(1000, 9999))
products['card'].description = (r'Пин код:\n' + str(pin)).split(r'\n')
products['card'].pin = pin
self.objects.append(products['card'])
self.infected = 1
# if self.role == 'citizen':
# self.infection_rate = 1250
# else:
self.infection_rate = 2000
self.order = None
self.order_goods = None
self.id = None
self.name = None
super().__init__(groups)
def get_objects(self):
return self.objects
def add_objects(self, *objects):
self.speed = Player.speed
player.card_money += 10 * len(objects)
names = ['Редактор презентаций', 'Текстовый редактор', 'Математический помощник']
for i in objects:
self.objects.append(i)
if i.name == names[0]:
self.profit += 0.2
elif i.name == names[1]:
self.profit += 0.4
elif i.name == names[2]:
self.profit += 0.7
def get_cash(self):
return self.cash
def set_cash(self, value):
self.cash = value
def give_money(self, amount):
if amount <= self.cash:
self.cash -= amount
return True
return False
def set_card_money(self, value):
self.card_money = value
def get_card_money(self):
return self.card_money
def spend_money(self, amount):
if amount <= self.card_money:
self.card_money -= amount
return True
return False
def set_position(self, pos):
self.rect.x, self.rect.y = pos
def set_moving(self, value):
self.is_moving = value
def get_coords(self):
return self.rect.x, self.rect.y
def get_card_balance(self):
return self.card_money
def is_obstacle(self):
return False
def move_left(self):
self.side = 'left'
self.image = self.frames[self.side][0]
self.prev_coords = self.get_coords()
self.rect.x -= self.speed
# it's the "auto jumping"
# if we can jums so that move further, we just jump
if check_collisions(self):
self.rect.y -= 5
if check_collisions(self):
self.rect.y -= 10
if check_collisions(self):
self.rect.y -= 15
if check_collisions(self):
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
def move_right(self):
self.side = 'right'
self.image = self.frames[self.side][0]
self.rect.x += self.speed
if check_collisions(self):
self.rect.y -= 5
if check_collisions(self):
self.rect.y -= 10
if check_collisions(self):
self.rect.y -= 15
if check_collisions(self):
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
def move_down(self, value):
self.prev_coords = self.get_coords()
self.rect.y -= value
if check_collisions(self):
if self.grav < -20:
self.health -= abs(self.grav) - 10
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
self.grav = -5
self.is_jumping = False
def jump(self):
if not self.is_jumping:
self.grav = Player.jump_power
self.is_jumping = True
def render_info(self, color=(255, 255, 255), background=(0, 0, 0)):
canvas = pygame.Surface((width // 2 + 350, 20))
canvas.fill(background)
font = pygame.font.Font(None, 30)
canvas.blit(
font.render(
f'Здоровье: {int(self.health)}% Заражение: {self.hazard_risk}% Наличные: {self.cash} Р На карте: {self.card_money} Р Сытость: {self.satiety} %',
1, color), (0, 0))
return canvas
# is called to get params of local client for transmittion
def get_pos_info(self):
x, y = str(self.rect.x - terrain.rect.x), str(self.rect.y - terrain.rect.y)
if self.inside:
x, y = '0', '0'
res = self.role + r'\t' + x + r'\t' + y + r'\t' + str(
self.is_moving) + r'\t' + self.side + r'\t' + str(self.infected)
# print(res)
return res
# reducing health, increasing danger_level (risk of infection)
def update_params(self, at_work=False):
if self.satiety < Player.satiety // 3:
self.health -= (1 - self.satiety / Player.satiety) * 0.02
if at_work and self.role == 'citizen':
self.profit_num += self.profit_timer.tick()
if self.profit_num >= 1000:
self.profit_num = 0
self.card_money = int(self.card_money + 10 * self.profit)
return
self.speed = Player.speed * self.health / 100
if self.speed <= self.speed // 2:
self.speed //= 2
prev_infect = self.infection_rate
self.danger_level = 1 - (100 - self.health) / 100
self.hazard_timer += self.clock.tick()
for i in npc_group:
if distance(self.get_coords(), i.get_coords()) < 150:
self.infection_rate -= 450
if self.infection_rate < 350:
self.infection_rate = 350
if self.hazard_timer > self.infection_rate * self.danger_level:
self.hazard_risk += 1
self.hazard_timer = 0
self.infection_rate = prev_infect
if self.health <= 0:
self.health = 0
if self.hazard_risk >= 100:
self.hazard_risk = 100
# cheking dead state (added gravity here, in this way we check if player is falling too fast)
if self.health <= 0 or self.grav < -50:
screen.fill((0, 0, 0))
# background_group.draw(screen)
screen.blit(self.render_info(), (0, 0))
text = render_text('Вы мертвы!!!')
screen.blit(text, (width // 2 - text.get_width() // 2, height // 2))
pygame.display.flip()
for i in range(5):
self.clock.tick(1)
exit_game()
elif self.hazard_risk == 100:
self.infected = 3
def update(self, *args):
self.move_down(self.grav)
self.grav -= gravity
self.update_params()
class Character(pygame.sprite.Sprite):
speed = 12
jump_power = 17
def __init__(self, *groups):
self.first_update = True
role = 'citizen'
self.frames = {'left': [], 'right': []}
for i in range(6):
self.frames['left'].append(
pygame.transform.flip(load_image(f'data/characters/citizen_right_{i + 1}.png',
size=(80 + randint(-10, 10), 110 + randint(-10, 10))), 1, 0))
for i in range(6):
self.frames['right'].append(
load_image(f'data/characters/citizen_right_{i + 1}.png',
size=(80 + randint(-10, 10), 110 + randint(-10, 10))))
self.image = self.frames['right'][0]
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
if random() > 0.5:
self.rect.x, self.rect.y = randint(100, 4000) + terrain.rect.x, randint(200, 300) + terrain.rect.y
else:
self.rect.x, self.rect.y = randint(4000, 7500) + terrain.rect.x, randint(100, 200) + terrain.rect.y
self.image_num = 0
self.prev_coords = 0, 0
self.is_moving = False
self.grav = 0
self.is_jumping = False
self.clock = pygame.time.Clock()
self.side = 'left'
self.health = 1000
self.hazard_risk = 0
self.danger_level = 1
self.hazard_timer = 0
self.infected = 1
self.infection_rate = 1250
self.direction = True
self.speed = Player.speed
super().__init__(groups)
def set_position(self, pos):
self.rect.x, self.rect.y = pos
def set_moving(self, value):
self.is_moving = value
def get_coords(self):
return self.rect.x, self.rect.y
def is_obstacle(self):
return False
def move_left(self):
self.side = 'left'
self.image = self.frames[self.side][0]
self.prev_coords = self.get_coords()
self.rect.x -= self.speed
if check_collisions(self):
self.rect.y -= 5
if check_collisions(self):
self.rect.y -= 10
if check_collisions(self):
self.rect.y -= 15
if check_collisions(self):
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
def move_right(self):
self.side = 'right'
self.image = self.frames[self.side][0]
self.rect.x += self.speed
if check_collisions(self):
self.rect.y -= 5
if check_collisions(self):
self.rect.y -= 10
if check_collisions(self):
self.rect.y -= 15
if check_collisions(self):
# self.jump()
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
def move_down(self, value):
self.prev_coords = self.get_coords()
self.rect.y -= value
if check_collisions(self):
if self.grav < -20:
self.health -= abs(self.grav) - 10
self.rect.x = self.prev_coords[0]
self.rect.y = self.prev_coords[1]
self.grav = -5
self.is_jumping = False
def jump(self):
if not self.is_jumping:
self.grav = Character.jump_power
self.is_jumping = True
# reducing health, increasing hazard_risk (risk of infection)
def update_params(self):
self.danger_level = 1 - (100 - self.health) / 100
self.hazard_timer += self.clock.tick()
if self.hazard_timer > self.infection_rate * self.danger_level:
self.hazard_risk += 1
self.hazard_timer = 0
if self.health <= 0:
self.health = 0
if self.hazard_risk >= 100:
self.hazard_risk = 100
# checking dead state (added gravity here, in this way we check if player is falling too fast)
if self.health == 0 or self.grav < -50:
Character(npc_group, all_sprites)
self.kill()
elif self.hazard_risk == 100:
self.infected = 3
def update(self, *args):
if self.first_update:
if check_collisions(self) or (0 < self.rect.x < width and 0 < self.rect.y < height):
Character(npc_group, all_sprites)
self.kill()
return
else:
self.first_update = False
if self.direction:
self.move_left()
else:
self.move_right()
if random() > 0.5:
self.image_num += 1
if random() > 0.75:
self.jump()
if random() < 0.25:
self.speed = Character.speed + randint(-5, 5)
if self.image_num >= len(self.frames['right']) * 6:
self.image_num = 0
# if effects_on:
# sounds['step'].play()
self.image = self.frames[self.side][self.image_num // 6]
self.move_down(self.grav)
self.grav -= gravity
self.update_params()
class Terrain(pygame.sprite.Sprite):
def __init__(self, x, y, *groups):
super().__init__(groups)
self.image = load_image('data/textures/city_platforms.png')
self.mask = pygame.mask.from_surface(self.image)
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
def is_obstacle(self):
return True
# building
# such mark (comment above) is used to tip the class is:
# class contains main func enter, called when player enters the building
# inside the method is big loop with its own groups, sprites, gameplay etc
class Bank(pygame.sprite.Sprite):
def __init__(self, x, y, *groups):
super().__init__(groups)
self.image = load_image('data/buildings/bank.png', size=(300, 250))
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = x, y
self.mask = pygame.mask.from_surface(self.image)
# name is displayed when player is near
self.name = 'Банк'
self.was_visited = False
def is_obstacle(self):
return False
def enter(self):
if not self.was_visited:
player.profit += 0.1
self.was_visited = True
logging.info('enter Bank')
button_group.empty()
pause_button = Button(width - 50, 0, 50, 50, images['pause_button'], menu, None, button_group)
running = True
mode = ''
right_pin = products['card'].pin
current_pin = ''
deposit_summ = ''
main_display = pygame.Surface((width // 2, height // 3 + 150))
main_display.fill((0, 0, 0))
card_size = (100, 150)
card = Button(width - card_size[0], height - card_size[1], *card_size,
load_image('data/objects/bank_card.png', size=card_size), None, 'card', bank_buttons)
card_moving = False
hole_rect = pygame.Rect(888, 107, 300, 20)
# buttons adding eith specific ids and mainly with None instead of func
Button(width - images['exit_sign'].get_width(), height - images['exit_sign'].get_height(),
100, 50, images['exit_sign'], lambda: False, None, bank_buttons)
Button(50, 100, 50, 50, images['right_arrow'], None, 'first', bank_buttons)
Button(50, 200, 50, 50, images['right_arrow'], None, 'second', bank_buttons)
Button(50, 300, 50, 50, images['right_arrow'], None, 'third', bank_buttons)
Button(100 + main_display.get_width(), 100, 50, 50, images['left_arrow'], None, 'fourth', bank_buttons)
Button(100 + main_display.get_width(), 200, 50, 50, images['left_arrow'], None, 'fifth', bank_buttons)
Button(100 + main_display.get_width(), 300, 50, 50, images['left_arrow'], None, 'sixth', bank_buttons)
# buttons with special images
image = load_image('data/objects/digit_button.png')
image.blit(render_text('1', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4, 470, 50, 50, image, None, '1', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('2', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75, 470, 50, 50, image, None, '2', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('3', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75 * 2, 470, 50, 50, image, None, '3', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('4', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4, 545, 50, 50, image, None, '4', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('5', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75, 545, 50, 50, image, None, '5', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('6', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75 * 2, 545, 50, 50, image, None, '6', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('7', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4, 620, 50, 50, image, None, '7', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('8', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75, 620, 50, 50, image, None, '8', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('9', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75 * 2, 620, 50, 50, image, None, '9', bank_buttons)
image = load_image('data/objects/digit_button.png')
image.blit(render_text('0', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75, 670, 50, 50, image, None, '0', bank_buttons)
image = load_image('data/objects/long_button.png')
image.blit(render_text('Enter', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75 * 3, 620, 208, 47, image, None, 'enter', bank_buttons)
image = load_image('data/objects/long_button.png')
image.blit(render_text('Clear', color=(0, 0, 0)), (10, 5))
Button(100 + main_display.get_width() // 4 + 75 * 3, 545, 208, 47, image, None, 'clear', bank_buttons)
# strucrure: in case of game button is pressed, we check id and change mode var
# in the drawing section we draw all bank sprites according to the mode var
# so, we can devide interface in several stages
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit_game()
if event.type == pygame.MOUSEMOTION:
if card_moving:
card.rect.x, card.rect.y = event.pos
if card.rect.colliderect(hole_rect):
mode = 'pin'
bank_buttons.remove(card)
if event.type == pygame.MOUSEBUTTONDOWN:
for btn in bank_buttons:
if btn.rect.collidepoint(event.pos):
if not btn.id:
running = btn.run()
elif btn.id == 'card':
card_moving = True
card.rect.x, card.rect.y = event.pos
elif btn.id == 'clear':