-
Notifications
You must be signed in to change notification settings - Fork 0
/
tanks_new.py
executable file
·2706 lines (2135 loc) · 75 KB
/
tanks_new.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
#!/usr/bin/python
# coding=utf-8
import os, pygame, time, random, uuid, sys
from pygame.locals import *
# CHEATS
START_LEVEL = 8
FORTRESS_FOREVER = 0
PLAYER_INFINITE_ARMOR = 0
PLAYER_INFINITE_LIVES = False
INFINITE_HEALTH_FOR_ALL = False # if True overrides PLAYER_INFINITE_ARMOR
INFINITE_BONUSES = False
# GAME MECHANICS
BONUS_FREQ = 4 # every n-th enemy tank will carry a bonus
ALLOW_MULTI_BONUS = True
ENEMY_PICKUP_BONUSES = True
FRIENDLY_FIRE = False
MAX_ACTIVE_ENEMIES = 4
MAX_ACTIVE_ENEMIES_2_PLAYERS = 10
MAX_ACTIVE_ENEMIES_3_PLAYERS = 12
ENEMY_SPAWN_TIMEOUT = 1500
LEVEL_FINISH_TIMEOUT = 4000
BONUS_TIMER_FREEZE_TIMEOUT = 10000
BONUS_FORTRESS_WALLS_TIMEOUT = 15000
BONUS_PLAYER_SHIELD_TIMEOUT = 15000
BONUS_PLAYER_HIDDEN_TIMEOUT = 10000
BONUS_SPAWN_TIMEOUT = 20000
CHANCE_OF_FIRE = 50
ENEMY_FIRE_TIMER = 500
# GAME SPEED
GAME_FRAME_TIMING = 50
DEFAULT_BULLET_SPEED = 4
PLAYER_DEFAULT_SPEED = 2
DEFAULT_ENEMY_SPEED = 1
DEFAULT_ENEMY_SPEED_FAST = 2
# ENEMY
DEFAULT_ENEMY_ARMOR_HEALTH = 600
# PLAYER
PLAYER_START_SUPERPOWER = 1
PLAYER_START_LIFE = 4
PLAYER_START_HEALTH = 100
PLAYER_START_SCORE = 0
PLAYER_START_MAX_ACTIVE_BULLETS = 1
PLAYER_START_SHIELD_TIMEOUT = 4000
# DEBUG
DEBUG_UNFREEZE_PLAYERS_ON_PAUSE = False
DEBUG_SPRITES = False
DEBUG_DRAW_MESH = False
DEBUG_COORDINATES = False
DISABLE_LABELS = True # to avoid bug with delayed font loading
# CONSTANTS
S_SIZE = 4
T_SIZE = 32
class myRect(pygame.Rect):
""" Add type property """
def __init__(self, left, top, width, height, type):
pygame.Rect.__init__(self, left, top, width, height)
self.type = type
class Timer(object):
def __init__(self):
self.timers = []
def add(self, interval, f, repeat = -1):
options = {
"interval" : interval,
"callback" : f,
"repeat" : repeat,
"times" : 0,
"time" : 0,
"uuid" : uuid.uuid4()
}
self.timers.append(options)
return options["uuid"]
def destroy(self, uuid_nr):
for timer in self.timers:
if timer["uuid"] == uuid_nr:
self.timers.remove(timer)
return
def update(self, time_passed):
for timer in self.timers:
timer["time"] += time_passed
if timer["time"] > timer["interval"]:
timer["time"] -= timer["interval"]
timer["times"] += 1
if timer["repeat"] > -1 and timer["times"] == timer["repeat"]:
self.timers.remove(timer)
try:
timer["callback"]()
except:
try:
self.timers.remove(timer)
except:
pass
class Castle():
""" Player's castle/fortress """
(STATE_STANDING, STATE_DESTROYED, STATE_EXPLODING) = range(3)
def __init__(self):
global sprites
# images
self.img_undamaged = sprites.subsurface(0, 15*2, 16*2, 16*2)
self.img_destroyed = sprites.subsurface(16*2, 15*2, 16*2, 16*2)
# init position
self.rect = pygame.Rect(12*16, 24*16, 32, 32)
# start w/ undamaged and shiny castle
self.rebuild()
def draw(self):
""" Draw castle """
global screen
screen.blit(self.image, self.rect.topleft)
if self.state == self.STATE_EXPLODING:
if not self.explosion.active:
self.state = self.STATE_DESTROYED
del self.explosion
else:
self.explosion.draw()
def rebuild(self):
""" Reset castle """
self.state = self.STATE_STANDING
self.image = self.img_undamaged
self.active = True
def destroy(self):
""" Destroy castle """
if play_sounds:
sounds["boom"].play()
self.state = self.STATE_EXPLODING
self.explosion = Explosion(self.rect.topleft)
self.image = self.img_destroyed
self.active = False
class Bonus():
""" Various power-ups
When bonus is spawned, it begins flashing and after some time dissapears
Available bonusses:
grenade : Picking up the grenade power up instantly wipes out ever enemy presently on the screen, including Armor Tanks regardless of how many times you've hit them. You do not, however, get credit for destroying them during the end-stage bonus points.
helmet : The helmet power up grants you a temporary force field that makes you invulnerable to enemy shots, just like the one you begin every stage with.
shovel : The shovel power up turns the walls around your fortress from brick to stone. This makes it impossible for the enemy to penetrate the wall and destroy your fortress, ending the game prematurely. The effect, however, is only temporary, and will wear off eventually.
star : The star power up grants your tank with new offensive power each time you pick one up, up to three times. The first star allows you to fire your bullets as fast as the power tanks can. The second star allows you to fire up to two bullets on the screen at one time. And the third star allows your bullets to destroy the otherwise unbreakable steel walls. You carry this power with you to each new stage until you lose a life.
tank : The tank power up grants you one extra life. The only other way to get an extra life is to score 20000 points.
timer : The timer power up temporarily freezes time, allowing you to harmlessly approach every tank and destroy them until the time freeze wears off.
"""
# bonus types
(BONUS_GRENADE, BONUS_HELMET, BONUS_TIMER, BONUS_SHOVEL, BONUS_TANK, BONUS_STAR, BONUS_PISTOL, BONUS_SHIP) = range(8)
def __init__(self, level):
global sprites
# to know where to place
self.level = level
# bonus lives only for a limited period of time
self.active = True
# blinking state
self.visible = True
self.rect = pygame.Rect(random.randint(0, 416-32), random.randint(0, 416-32), 32, 32)
self.bonus = random.choice([
self.BONUS_STAR,
self.BONUS_STAR,
self.BONUS_GRENADE,
self.BONUS_GRENADE,
self.BONUS_HELMET,
self.BONUS_SHOVEL,
self.BONUS_SHOVEL,
self.BONUS_TANK,
self.BONUS_TIMER
# self.BONUS_PISTOL,
# self.BONUS_SHIP
])
#self.bonus = self.BONUS_GRENADE
# self.image = sprites.subsurface(16*2*self.bonus, 32*2, 16*2, 15*2)
self.image = sprites2.subsurface((7*S_SIZE+2)*T_SIZE, 32*(self.bonus+1), 32, 32)
def draw(self):
""" draw bonus """
global screen
if self.visible:
screen.blit(self.image, self.rect.topleft)
def toggleVisibility(self):
""" Toggle bonus visibility """
self.visible = not self.visible
class Bullet():
# direction constants
(DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT) = range(4)
# bullet's stated
(STATE_REMOVED, STATE_ACTIVE, STATE_EXPLODING) = range(3)
(OWNER_PLAYER, OWNER_ENEMY) = range(2)
def __init__(self, level, position, direction, damage = 100, speed = DEFAULT_BULLET_SPEED, power = 1):
global sprites
self.level = level
self.direction = direction
self.damage = damage
self.owner = None
self.owner_class = None
# 1-regular everyday normal bullet
# 2-can destroy steel
self.power = power
self.image = sprites.subsurface(75*2, 74*2, 3*2, 4*2)
# position is player's top left corner, so we'll need to
# recalculate a bit. also rotate image itself.
if direction == self.DIR_UP:
self.rect = pygame.Rect(position[0] + 12, position[1], 8, 8)
elif direction == self.DIR_RIGHT:
self.image = pygame.transform.rotate(self.image, 270)
self.rect = pygame.Rect(position[0] + 32 - 8, position[1] + 12, 8, 8)
elif direction == self.DIR_DOWN:
self.image = pygame.transform.rotate(self.image, 180)
self.rect = pygame.Rect(position[0] + 12, position[1] + 32 - 8, 8, 8)
elif direction == self.DIR_LEFT:
self.image = pygame.transform.rotate(self.image, 90)
self.rect = pygame.Rect(position[0] + 4 , position[1] + 12, 8, 8)
self.explosion_images = [
sprites.subsurface(0, 80*2, 32*2, 32*2),
sprites.subsurface(32*2, 80*2, 32*2, 32*2),
]
self.speed = speed
self.state = self.STATE_ACTIVE
self.dbg_label = Label(self.rect.bottomleft, str(self.rect.topleft))
def draw(self):
""" draw bullet """
global screen
if self.state == self.STATE_ACTIVE:
screen.blit(self.image, self.rect.topleft)
elif self.state == self.STATE_EXPLODING:
self.explosion.draw()
# debug sprites
if DEBUG_SPRITES:
red = (255,0,0)
pygame.draw.rect(screen, red, self.rect, 1)
self.dbg_label.position = self.rect.bottomleft
self.dbg_label.text = str(self.rect.topleft) + " " + str(self.rect.size)
self.dbg_label.draw()
def update(self):
global castle, players, enemies, bullets, sounds
if self.state == self.STATE_EXPLODING:
if not self.explosion.active:
self.destroy()
del self.explosion
if self.state != self.STATE_ACTIVE:
return
""" move bullet """
if self.direction == self.DIR_UP:
self.rect.topleft = [self.rect.left, self.rect.top - self.speed]
if self.rect.top < 0:
if play_sounds and self.owner == self.OWNER_PLAYER:
sounds["steel"].play()
self.explode()
return
elif self.direction == self.DIR_RIGHT:
self.rect.topleft = [self.rect.left + self.speed, self.rect.top]
if self.rect.left > (416 - self.rect.width):
if play_sounds and self.owner == self.OWNER_PLAYER:
sounds["steel"].play()
self.explode()
return
elif self.direction == self.DIR_DOWN:
self.rect.topleft = [self.rect.left, self.rect.top + self.speed]
if self.rect.top > (416 - self.rect.height):
if play_sounds and self.owner == self.OWNER_PLAYER:
sounds["steel"].play()
self.explode()
return
elif self.direction == self.DIR_LEFT:
self.rect.topleft = [self.rect.left - self.speed, self.rect.top]
if self.rect.left < 0:
if play_sounds and self.owner == self.OWNER_PLAYER:
sounds["steel"].play()
self.explode()
return
has_collided = False
# check for removable tiles
# if bullet is powerfull enough it can clear those tiles
if self.power >= 2:
rects = self.level.removable_rects
removable = self.rect.collidelistall(rects)
if removable != []:
for i in removable:
for tile in self.level.mapr:
if tile.topleft == rects[i].topleft:
if play_sounds:
sounds["brick"].play()
self.level.mapr.remove(tile)
# check for collisions with walls. one bullet can destroy several (1 or 2)
# tiles but explosion remains 1
rects = self.level.obstacle_rects
collisions = self.rect.collidelistall(rects)
if collisions != []:
for i in collisions:
if self.level.hitTile(rects[i].topleft, self.power, self.owner == self.OWNER_PLAYER):
has_collided = True
if has_collided:
self.explode()
return
# check for collisions with other bullets
for bullet in bullets:
if self.state == self.STATE_ACTIVE and bullet.owner != self.owner and bullet != self and self.rect.colliderect(bullet.rect):
self.destroy()
self.explode()
return
# check for collisions with players
for player in players:
if player.state == player.STATE_ALIVE and self.rect.colliderect(player.rect):
if player.bulletImpact(self.owner == self.OWNER_PLAYER, self.damage, self.owner_class):
self.destroy()
return
# check for collisions with enemies
for enemy in enemies:
if enemy.state == enemy.STATE_ALIVE and self.rect.colliderect(enemy.rect):
if enemy.bulletImpact(self.owner == self.OWNER_ENEMY, self.damage, self.owner_class):
self.destroy()
return
# check for collision with castle
if castle.active and self.rect.colliderect(castle.rect):
castle.destroy()
self.destroy()
return
def explode(self):
""" start bullets's explosion """
global screen
if self.state != self.STATE_REMOVED:
self.state = self.STATE_EXPLODING
self.explosion = Explosion([self.rect.left-16, self.rect.top-16], None, self.explosion_images)
def destroy(self):
self.state = self.STATE_REMOVED
class Label():
def __init__(self, position, text = "", duration = None):
self.position = position
self.active = True
self.text = text
if not DISABLE_LABELS:
self.font = pygame.font.SysFont("Arial", 10)
if duration != None:
gtimer.add(duration, lambda :self.destroy(), 1)
def draw(self):
""" draw label """
global screen
if not DISABLE_LABELS:
screen.blit(self.font.render(self.text, False, (200,200,200)), [self.position[0]+4, self.position[1]+8])
def destroy(self):
self.active = False
class Explosion():
def __init__(self, position, interval = None, images = None):
global sprites
self.position = [position[0]-16, position[1]-16]
self.active = True
if interval == None:
interval = 100
if images == None:
images = [
sprites.subsurface(0, 80*2, 32*2, 32*2),
sprites.subsurface(32*2, 80*2, 32*2, 32*2),
sprites.subsurface(64*2, 80*2, 32*2, 32*2)
]
images.reverse()
self.images = [] + images
self.image = self.images.pop()
gtimer.add(interval, lambda :self.update(), len(self.images) + 1)
def draw(self):
global screen
""" draw current explosion frame """
screen.blit(self.image, self.position)
def update(self):
""" Advace to the next image """
if len(self.images) > 0:
self.image = self.images.pop()
else:
self.active = False
class Level():
# tile constants
(TILE_EMPTY, TILE_BRICK, TILE_STEEL, TILE_WATER, TILE_GRASS, TILE_FROZE) = range(6)
# tile width/height in px
TILE_SIZE = 16
def __init__(self, level_nr = None):
""" There are total 35 different levels. If level_nr is larger than 35, loop over
to next according level so, for example, if level_nr ir 37, then load level 2 """
global sprites, game
# max number of enemies simultaneously being on map
self.max_active_enemies = MAX_ACTIVE_ENEMIES
if game.nr_of_players == 1:
self.max_active_enemies = MAX_ACTIVE_ENEMIES
elif game.nr_of_players == 2:
self.max_active_enemies = MAX_ACTIVE_ENEMIES_2_PLAYERS
elif game.nr_of_players == 3:
self.max_active_enemies = MAX_ACTIVE_ENEMIES_3_PLAYERS
tile_images = [
pygame.Surface((8*2, 8*2)),
sprites.subsurface(48*2, 64*2, 8*2, 8*2),
sprites.subsurface(48*2, 72*2, 8*2, 8*2),
sprites.subsurface(56*2, 72*2, 8*2, 8*2),
sprites.subsurface(64*2, 64*2, 8*2, 8*2),
sprites.subsurface(72*2, 64*2, 8*2, 8*2),
sprites.subsurface(64*2, 72*2, 8*2, 8*2)
]
self.tile_empty = tile_images[0]
self.tile_brick = tile_images[1]
self.tile_steel = tile_images[2]
self.tile_grass = tile_images[3]
self.tile_water = tile_images[4]
self.tile_water1= tile_images[4]
self.tile_water2= tile_images[5]
self.tile_froze = tile_images[6]
self.obstacle_rects = []
level_nr = 1 if level_nr == None else level_nr%35
if level_nr == 0:
level_nr = 35
self.loadLevel(level_nr)
# tiles' rects on map, tanks cannot move over
self.obstacle_rects = []
# tiles' rects on map which can be removed by bullets
self.removable_rects = []
# update these tiles
self.updateObstacleRects()
self.updateRemovableRects()
gtimer.add(600, lambda :self.toggleWaves())
def hitTile(self, pos, power = 1, sound = False):
"""
Hit the tile
@param pos Tile's x, y in px
@return True if bullet was stopped, False otherwise
"""
global play_sounds, sounds
for tile in self.mapr:
if tile.topleft == pos:
if tile.type == self.TILE_BRICK:
if play_sounds and sound:
sounds["brick"].play()
self.mapr.remove(tile)
self.updateObstacleRects()
if power >= 4:
return False
return True
elif tile.type == self.TILE_STEEL:
if play_sounds and sound:
sounds["steel"].play()
if power >= 3:
self.mapr.remove(tile)
self.updateObstacleRects()
if power >= 4:
return False
return True
else:
return False
def toggleWaves(self):
""" Toggle water image """
if self.tile_water == self.tile_water1:
self.tile_water = self.tile_water2
else:
self.tile_water = self.tile_water1
def loadLevel(self, level_nr = 1):
""" Load specified level
@return boolean Whether level was loaded
"""
filename = "levels/"+str(level_nr)
if (not os.path.isfile(filename)):
return False
level = []
f = open(filename, "r")
data = f.read().split("\n")
self.mapr = []
x, y = 0, 0
for row in data:
for ch in row:
if ch == "#":
self.mapr.append(myRect(x, y, self.TILE_SIZE, self.TILE_SIZE, self.TILE_BRICK))
elif ch == "@":
self.mapr.append(myRect(x, y, self.TILE_SIZE, self.TILE_SIZE, self.TILE_STEEL))
elif ch == "~":
self.mapr.append(myRect(x, y, self.TILE_SIZE, self.TILE_SIZE, self.TILE_WATER))
elif ch == "%":
self.mapr.append(myRect(x, y, self.TILE_SIZE, self.TILE_SIZE, self.TILE_GRASS))
elif ch == "-":
self.mapr.append(myRect(x, y, self.TILE_SIZE, self.TILE_SIZE, self.TILE_FROZE))
x += self.TILE_SIZE
x = 0
y += self.TILE_SIZE
return True
def draw(self, tiles = None):
""" Draw specified map on top of existing surface """
global screen
if tiles == None:
tiles = [self.TILE_BRICK, self.TILE_STEEL, self.TILE_WATER, self.TILE_GRASS, self.TILE_FROZE]
for tile in self.mapr:
if tile.type in tiles:
if tile.type == self.TILE_BRICK:
screen.blit(self.tile_brick, tile.topleft)
elif tile.type == self.TILE_STEEL:
screen.blit(self.tile_steel, tile.topleft)
elif tile.type == self.TILE_WATER:
screen.blit(self.tile_water, tile.topleft)
elif tile.type == self.TILE_FROZE:
screen.blit(self.tile_froze, tile.topleft)
elif tile.type == self.TILE_GRASS:
screen.blit(self.tile_grass, tile.topleft)
def updateRemovableRects(self):
""" Set self.removable_rects to all tiles' rects that players can drive through and clear
with bullets having enough power """
global castle
self.removable_rects = [castle.rect]
for tile in self.mapr:
if tile.type == self.TILE_GRASS:
self.removable_rects.append(tile)
def updateObstacleRects(self):
""" Set self.obstacle_rects to all tiles' rects that players can destroy
with bullets """
global castle
self.obstacle_rects = [castle.rect]
for tile in self.mapr:
if tile.type in (self.TILE_BRICK, self.TILE_STEEL, self.TILE_WATER):
self.obstacle_rects.append(tile)
def buildFortress(self, tile):
""" Build walls around castle made from tile """
positions = [
(11*self.TILE_SIZE, 23*self.TILE_SIZE),
(11*self.TILE_SIZE, 24*self.TILE_SIZE),
(11*self.TILE_SIZE, 25*self.TILE_SIZE),
(14*self.TILE_SIZE, 23*self.TILE_SIZE),
(14*self.TILE_SIZE, 24*self.TILE_SIZE),
(14*self.TILE_SIZE, 25*self.TILE_SIZE),
(12*self.TILE_SIZE, 23*self.TILE_SIZE),
(13*self.TILE_SIZE, 23*self.TILE_SIZE)
]
obsolete = []
for i, rect in enumerate(self.mapr):
if rect.topleft in positions:
obsolete.append(rect)
for rect in obsolete:
self.mapr.remove(rect)
for pos in positions:
self.mapr.append(myRect(pos[0], pos[1], self.TILE_SIZE, self.TILE_SIZE, tile))
self.updateObstacleRects()
class Tank():
# possible directions
(DIR_UP, DIR_RIGHT, DIR_DOWN, DIR_LEFT) = range(4)
# states
(STATE_SPAWNING, STATE_DEAD, STATE_ALIVE, STATE_EXPLODING) = range(4)
# sides
(SIDE_PLAYER, SIDE_ENEMY) = range(2)
def __init__(self, level, side, position = None, direction = None, filename = None):
global sprites
# health. 0 health means dead
self.health = 100
# tank can't move but can rotate and shoot
self.paralised = False
# tank can't do anything
self.paused = False
# tank is protected from bullets
self.shielded = False
# px per move
self.speed = DEFAULT_ENEMY_SPEED
# friend or foe
self.side = side
# flashing state. 0-off, 1-on
self.flash = 0
self.bullet_speed = DEFAULT_BULLET_SPEED
self.bullet_power = 1
# how many bullets can tank fire simultaneously
self.max_active_bullets = PLAYER_START_MAX_ACTIVE_BULLETS
self.superpowers = 0
# self.updateSuperpowers()
# each tank can pick up 1 bonus
self.bonus = None
# navigation keys: fire, up, right, down, left
self.controls = [pygame.K_SPACE, pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT]
# currently pressed buttons (navigation only)
self.pressed = [False] * 4
# visibility state
self.visible = True
self.shield_images = [
# sprites.subsurface(0, 48*2, 16*2, 16*2),
# sprites.subsurface(16*2, 48*2, 16*2, 16*2)
sprites2.subsurface(7*32+4, 9*32, 16*2, 16*2),
sprites2.subsurface(8*32+4, 9*32, 16*2, 16*2)
]
self.shield_image = self.shield_images[0]
self.shield_index = 0
self.spawn_images = [
sprites.subsurface(32*2, 48*2, 16*2, 16*2),
sprites.subsurface(48*2, 48*2, 16*2, 16*2)
]
self.spawn_image = self.spawn_images[0]
self.spawn_index = 0
self.level = level
if position != None:
self.rect = pygame.Rect(position, (32, 32))
else:
self.rect = pygame.Rect(0, 0, 32, 32)
if direction == None:
self.direction = random.choice([self.DIR_RIGHT, self.DIR_DOWN, self.DIR_LEFT])
else:
self.direction = direction
self.state = self.STATE_SPAWNING
# spawning animation
self.timer_uuid_spawn = gtimer.add(100, lambda :self.toggleSpawnImage())
# duration of spawning
self.timer_uuid_spawn_end = gtimer.add(1000, lambda :self.endSpawning())
self.visibility_timer = None
self.shield_end_timer = None
self.dbg_label = Label(self.rect.bottomleft, str(self.rect.topleft))
def toggleVisibility(self):
""" Toggle tank visibility """
self.visible = not self.visible
def hideTank(self, duration = None):
if self.visibility_timer:
gtimer.destroy(self.visibility_timer)
self.setVisibility(False)
self.visibility_timer = gtimer.add(duration, lambda: self.setVisibility(True))
def setVisibility(self, visible):
""" Set tank visibility """
self.visible = visible
def endSpawning(self):
""" End spawning
Player becomes operational
"""
self.state = self.STATE_ALIVE
gtimer.destroy(self.timer_uuid_spawn_end)
def toggleSpawnImage(self):
""" advance to the next spawn image """
if self.state != self.STATE_SPAWNING:
gtimer.destroy(self.timer_uuid_spawn)
return
self.spawn_index += 1
if self.spawn_index >= len(self.spawn_images):
self.spawn_index = 0
self.spawn_image = self.spawn_images[self.spawn_index]
def toggleShieldImage(self):
""" advance to the next shield image """
if self.state != self.STATE_ALIVE:
gtimer.destroy(self.timer_uuid_shield)
return
if self.shielded:
self.shield_index += 1
if self.shield_index >= len(self.shield_images):
self.shield_index = 0
self.shield_image = self.shield_images[self.shield_index]
def draw(self):
""" draw tank """
global screen
if self.state == self.STATE_ALIVE:
# hidden state
if not self.visible:
return
screen.blit(self.image, self.rect.topleft)
if self.shielded:
screen.blit(self.shield_image, [self.rect.left, self.rect.top])
elif self.state == self.STATE_EXPLODING:
self.explosion.draw()
elif self.state == self.STATE_SPAWNING:
screen.blit(self.spawn_image, self.rect.topleft)
# debug sprites
if DEBUG_SPRITES:
green = (0,255,0)
pygame.draw.rect(screen, green, self.rect, 1)
self.dbg_label.position = self.rect.bottomleft
self.dbg_label.text = str(self.rect.topleft) + " " + str(self.rect.size)
self.dbg_label.draw()
def explode(self):
""" start tanks's explosion """
if self.state != self.STATE_DEAD:
self.state = self.STATE_EXPLODING
self.explosion = Explosion(self.rect.topleft)
def updateSuperpowers(self):
""" update player super powers """
self.updateSprites()
# 0 - no superpowers
if self.superpowers >= 0:
self.bullet_speed = DEFAULT_BULLET_SPEED
self.bullet_power = 1
self.max_active_bullets = PLAYER_START_MAX_ACTIVE_BULLETS
# 1 - faster bullets
if self.superpowers >= 1:
self.bullet_speed = 8
# 2 - can fire 2 bullets
if self.superpowers >= 2:
self.max_active_bullets = 2
# 3 - can clear trees
if self.superpowers >= 3:
self.bullet_power = 2
# 4 - can destroy steel
if self.superpowers >= 4:
self.bullet_power = 3
# 5 - can fire 3 bullets
if self.superpowers >= 5:
self.max_active_bullets = 3
# 6- can clear trees, bricks and steel in 1 shot
if self.superpowers >= 6:
self.bullet_power = 4
def fire(self, forced = False):
""" Shoot a bullet
@param boolean forced. If false, check whether tank has exceeded his bullet quota. Default: True
@return boolean True if bullet was fired, false otherwise
"""
global bullets, labels
if self.state == self.STATE_SPAWNING:
return False
if self.state not in (self.STATE_ALIVE, self.STATE_SPAWNING):
gtimer.destroy(self.timer_uuid_fire)
return False
if self.paused:
return False
if self.side == self.SIDE_ENEMY and random.randint(1, 100) < 100 - CHANCE_OF_FIRE:
return False
if not forced:
active_bullets = 0
for bullet in bullets:
if bullet.owner_class == self and bullet.state == bullet.STATE_ACTIVE:
active_bullets += 1
if active_bullets >= self.max_active_bullets:
return False
bullet = Bullet(self.level, self.rect.topleft, self.direction)
bullet.speed = self.bullet_speed
bullet.power = self.bullet_power
if self.side == self.SIDE_PLAYER:
bullet.owner = self.SIDE_PLAYER
else:
bullet.owner = self.SIDE_ENEMY
self.bullet_queued = False
bullet.owner_class = self
bullets.append(bullet)
return True
def rotate(self, direction, fix_position = True):
""" Rotate tank
rotate, update image and correct position
"""
self.direction = direction
if direction == self.DIR_UP:
self.image = self.image_up
elif direction == self.DIR_RIGHT:
self.image = self.image_right
elif direction == self.DIR_DOWN:
self.image = self.image_down
elif direction == self.DIR_LEFT:
self.image = self.image_left
if fix_position:
#print "Fixing position"
#print "Before fixing: " + str(self.rect.left) + ", " + str(self.rect.top)
SPRITES_FIX = 0
new_x = self.nearest(self.rect.left - SPRITES_FIX, 16) + SPRITES_FIX
new_y = self.nearest(self.rect.top - SPRITES_FIX, 16) + SPRITES_FIX
new_rect = pygame.Rect([new_x, new_y], [32, 32])
collision = False
if new_rect.collidelist(self.level.obstacle_rects) != -1:
collision = True
for enemy in enemies:
if enemy != self and new_rect.colliderect(enemy.rect):
collision = True
for player in players:
if player != self and new_rect.colliderect(player.rect):
collision = True
if collision:
#print "Collision!"
return
self.rect.left = new_x
self.rect.top = new_y
if DEBUG_COORDINATES:
print("After fixing: " + str(self.rect.center))
def turnRandom(self):
""" Turn tank into random direction """
self.direction = random.choice([self.DIR_RIGHT, self.DIR_DOWN, self.DIR_LEFT])
def turnAround(self):
""" Turn tank into opposite direction """
if self.direction in (self.DIR_UP, self.DIR_RIGHT):
self.rotate(self.direction + 2, False)
else:
self.rotate(self.direction - 2, False)
def update(self, time_passed):
""" Update timer and explosion (if any) """
if self.state == self.STATE_EXPLODING:
if not self.explosion.active:
self.state = self.STATE_DEAD
del self.explosion
def nearest(self, num, base):
""" Round number to nearest divisible """
return int(round(float(num) / (base * 1.0)) * base)
def bulletImpact(self, friendly_fire = False, damage = 100, tank = None):
""" Bullet impact
Return True if bullet should be destroyed on impact. Only enemy friendly-fire
doesn't trigger bullet explosion
"""
global play_sounds, sounds
if self.shielded and not friendly_fire:
return True
if not friendly_fire:
if not INFINITE_HEALTH_FOR_ALL:
self.health -= damage
self.updateSprites()
# restore health if infinite armor
if PLAYER_INFINITE_ARMOR > 0 and self.side == self.SIDE_PLAYER:
self.health += damage
# if Tank has a bonus display it
if self.bonus:
if not INFINITE_BONUSES:
self.removeBonusLoad()
# If bonus already exit on screen, remove it
if len(bonuses) > 0 and not ALLOW_MULTI_BONUS: