-
Notifications
You must be signed in to change notification settings - Fork 11
/
tanks.py
executable file
·2101 lines (1631 loc) · 55.7 KB
/
tanks.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
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 """
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_SHOVEL, BONUS_STAR, BONUS_TANK, BONUS_TIMER) = range(6)
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_GRENADE,
self.BONUS_HELMET,
self.BONUS_SHOVEL,
self.BONUS_STAR,
self.BONUS_TANK,
self.BONUS_TIMER
])
self.image = sprites.subsurface(16*2*self.bonus, 32*2, 16*2, 15*2)
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 = 5):
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 = 1
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] + 11, position[1] - 8, 6, 8)
elif direction == self.DIR_RIGHT:
self.image = pygame.transform.rotate(self.image, 270)
self.rect = pygame.Rect(position[0] + 26, position[1] + 11, 8, 6)
elif direction == self.DIR_DOWN:
self.image = pygame.transform.rotate(self.image, 180)
self.rect = pygame.Rect(position[0] + 11, position[1] + 26, 6, 8)
elif direction == self.DIR_LEFT:
self.image = pygame.transform.rotate(self.image, 90)
self.rect = pygame.Rect(position[0] - 8 , position[1] + 11, 8, 6)
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
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()
def update(self):
global castle, players, enemies, bullets
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 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-13, self.rect.top-13], 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
self.font = pygame.font.SysFont("Arial", 13)
if duration != None:
gtimer.add(duration, lambda :self.destroy(), 1)
def draw(self):
""" draw label """
global screen
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
# max number of enemies simultaneously being on map
self.max_active_enemies = 4
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(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 = []
# update these tiles
self.updateObstacleRects()
gtimer.add(400, 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()
return True
elif tile.type == self.TILE_STEEL:
if play_sounds and sound:
sounds["steel"].play()
if power == 2:
self.mapr.remove(tile)
self.updateObstacleRects()
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 = [TILE_BRICK, TILE_STEEL, TILE_WATER, TILE_GRASS, 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 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 = 2
# how many bullets can tank fire simultaneously
self.max_active_bullets = 1
# friend or foe
self.side = side
# flashing state. 0-off, 1-on
self.flash = 0
# 0 - no superpowers
# 1 - faster bullets
# 2 - can fire 2 bullets
# 3 - can destroy steel
self.superpowers = 0
# 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
self.shield_images = [
sprites.subsurface(0, 48*2, 16*2, 16*2),
sprites.subsurface(16*2, 48*2, 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, (26, 26))
else:
self.rect = pygame.Rect(0, 0, 26, 26)
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())
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:
screen.blit(self.image, self.rect.topleft)
if self.shielded:
screen.blit(self.shield_image, [self.rect.left-3, self.rect.top-3])
elif self.state == self.STATE_EXPLODING:
self.explosion.draw()
elif self.state == self.STATE_SPAWNING:
screen.blit(self.spawn_image, self.rect.topleft)
def explode(self):
""" start tanks's explosion """
if self.state != self.STATE_DEAD:
self.state = self.STATE_EXPLODING
self.explosion = Explosion(self.rect.topleft)
if self.bonus:
self.spawnBonus()
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_ALIVE:
gtimer.destroy(self.timer_uuid_fire)
return False
if self.paused:
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)
# if superpower level is at least 1
if self.superpowers > 0:
bullet.speed = 8
# if superpower level is at least 3
if self.superpowers > 2:
bullet.power = 2
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:
new_x = self.nearest(self.rect.left, 8) + 3
new_y = self.nearest(self.rect.top, 8) + 3
if (abs(self.rect.left - new_x) < 5):
self.rect.left = new_x
if (abs(self.rect.top - new_y) < 5):
self.rect.top = new_y
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(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:
return True
if not friendly_fire:
self.health -= damage
if self.health < 1:
if self.side == self.SIDE_ENEMY:
tank.trophies["enemy"+str(self.type)] += 1
points = (self.type+1) * 100
tank.score += points
if play_sounds:
sounds["explosion"].play()
labels.append(Label(self.rect.topleft, str(points), 500))
self.explode()
return True
if self.side == self.SIDE_ENEMY:
return False
elif self.side == self.SIDE_PLAYER:
if not self.paralised:
self.setParalised(True)
self.timer_uuid_paralise = gtimer.add(10000, lambda :self.setParalised(False), 1)
return True
def setParalised(self, paralised = True):
""" set tank paralise state
@param boolean paralised
@return None
"""
if self.state != self.STATE_ALIVE:
gtimer.destroy(self.timer_uuid_paralise)
return
self.paralised = paralised
class Enemy(Tank):
(TYPE_BASIC, TYPE_FAST, TYPE_POWER, TYPE_ARMOR) = range(4)
def __init__(self, level, type, position = None, direction = None, filename = None):
Tank.__init__(self, level, type, position = None, direction = None, filename = None)
global enemies, sprites
# if true, do not fire
self.bullet_queued = False
# chose type on random
if len(level.enemies_left) > 0:
self.type = level.enemies_left.pop()
else:
self.state = self.STATE_DEAD
return
if self.type == self.TYPE_BASIC:
self.speed = 1
elif self.type == self.TYPE_FAST:
self.speed = 3
elif self.type == self.TYPE_POWER:
self.superpowers = 1
elif self.type == self.TYPE_ARMOR:
self.health = 400
# 1 in 5 chance this will be bonus carrier, but only if no other tank is
if random.randint(1, 5) == 1:
self.bonus = True
for enemy in enemies:
if enemy.bonus:
self.bonus = False
break
images = [
sprites.subsurface(32*2, 0, 13*2, 15*2),
sprites.subsurface(48*2, 0, 13*2, 15*2),
sprites.subsurface(64*2, 0, 13*2, 15*2),
sprites.subsurface(80*2, 0, 13*2, 15*2),
sprites.subsurface(32*2, 16*2, 13*2, 15*2),
sprites.subsurface(48*2, 16*2, 13*2, 15*2),
sprites.subsurface(64*2, 16*2, 13*2, 15*2),
sprites.subsurface(80*2, 16*2, 13*2, 15*2)
]
self.image = images[self.type+0]
self.image_up = self.image;
self.image_left = pygame.transform.rotate(self.image, 90)
self.image_down = pygame.transform.rotate(self.image, 180)
self.image_right = pygame.transform.rotate(self.image, 270)
if self.bonus:
self.image1_up = self.image_up;
self.image1_left = self.image_left
self.image1_down = self.image_down
self.image1_right = self.image_right
self.image2 = images[self.type+4]
self.image2_up = self.image2;
self.image2_left = pygame.transform.rotate(self.image2, 90)
self.image2_down = pygame.transform.rotate(self.image2, 180)
self.image2_right = pygame.transform.rotate(self.image2, 270)
self.rotate(self.direction, False)
if position == None:
self.rect.topleft = self.getFreeSpawningPosition()
if not self.rect.topleft:
self.state = self.STATE_DEAD
return
# list of map coords where tank should go next
self.path = self.generatePath(self.direction)
# 1000 is duration between shots
self.timer_uuid_fire = gtimer.add(1000, lambda :self.fire())
# turn on flashing
if self.bonus:
self.timer_uuid_flash = gtimer.add(200, lambda :self.toggleFlash())
def toggleFlash(self):
""" Toggle flash state """
if self.state not in (self.STATE_ALIVE, self.STATE_SPAWNING):
gtimer.destroy(self.timer_uuid_flash)
return
self.flash = not self.flash
if self.flash:
self.image_up = self.image2_up
self.image_right = self.image2_right
self.image_down = self.image2_down
self.image_left = self.image2_left
else:
self.image_up = self.image1_up
self.image_right = self.image1_right
self.image_down = self.image1_down
self.image_left = self.image1_left
self.rotate(self.direction, False)
def spawnBonus(self):
""" Create new bonus if needed """
global bonuses
if len(bonuses) > 0:
return
bonus = Bonus(self.level)
bonuses.append(bonus)
gtimer.add(500, lambda :bonus.toggleVisibility())
gtimer.add(10000, lambda :bonuses.remove(bonus), 1)
def getFreeSpawningPosition(self):
global players, enemies
available_positions = [
[(self.level.TILE_SIZE * 2 - self.rect.width) / 2, (self.level.TILE_SIZE * 2 - self.rect.height) / 2],
[12 * self.level.TILE_SIZE + (self.level.TILE_SIZE * 2 - self.rect.width) / 2, (self.level.TILE_SIZE * 2 - self.rect.height) / 2],
[24 * self.level.TILE_SIZE + (self.level.TILE_SIZE * 2 - self.rect.width) / 2, (self.level.TILE_SIZE * 2 - self.rect.height) / 2]
]
random.shuffle(available_positions)
for pos in available_positions:
enemy_rect = pygame.Rect(pos, [26, 26])
# collisions with other enemies
collision = False
for enemy in enemies:
if enemy_rect.colliderect(enemy.rect):
collision = True
continue
if collision:
continue
# collisions with players
collision = False
for player in players:
if enemy_rect.colliderect(player.rect):
collision = True
continue
if collision:
continue
return pos
return False
def move(self):
""" move enemy if possible """
global players, enemies, bonuses
if self.state != self.STATE_ALIVE or self.paused or self.paralised:
return
if self.path == []:
self.path = self.generatePath(None, True)
new_position = self.path.pop(0)
# move enemy
if self.direction == self.DIR_UP:
if new_position[1] < 0:
self.path = self.generatePath(self.direction, True)
return
elif self.direction == self.DIR_RIGHT:
if new_position[0] > (416 - 26):
self.path = self.generatePath(self.direction, True)
return
elif self.direction == self.DIR_DOWN:
if new_position[1] > (416 - 26):
self.path = self.generatePath(self.direction, True)
return
elif self.direction == self.DIR_LEFT:
if new_position[0] < 0:
self.path = self.generatePath(self.direction, True)
return
new_rect = pygame.Rect(new_position, [26, 26])
# collisions with tiles
if new_rect.collidelist(self.level.obstacle_rects) != -1:
self.path = self.generatePath(self.direction, True)
return
# collisions with other enemies
for enemy in enemies: