-
Notifications
You must be signed in to change notification settings - Fork 0
/
enemy.py
88 lines (69 loc) · 3 KB
/
enemy.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
import pygame
class Enemy(pygame.sprite.Sprite):
def __init__(self, health, animation_list, x, y, speed):
pygame.sprite.Sprite.__init__(self)
self.alive = True
self.speed = speed
self.health = health
self.last_attack = pygame.time.get_ticks()
self.attack_cooldown = 1000
self.animation_list = animation_list
self.frame_index = 0
self.action = 0#0==walk, 1==attack, 2==death
self.update_time = pygame.time.get_ticks()
#select starting image
self.image = self.animation_list[self.action][self.frame_index]
self.rect = pygame.Rect(0, 0, 25, 40)
self.rect.center = (x, y)
def update(self, surface, target, bullet_comp):
if self.alive:
#check for collision with bullets
if pygame.sprite.spritecollide(self, bullet_comp, True):
#lower enemy health
self.health -= 25
#check if enemy has reached the castle
if self.rect.right > target.rect.left -130:
self.update_action(1)
#move enemy
if self.action == 0:
#update rectangle position
self.rect.x += self.speed
#attack
if self.action == 1:
#check if enough time has passed since last attack
if pygame.time.get_ticks() - self.last_attack > self.attack_cooldown:
target.health -= 25
if target.health < 0:
target.health = 0
self.last_attack = pygame.time.get_ticks()
#check if health has dropped to zero
if self.health <= 0:
target.money += 100
target.score += 100
self.update_action(2)#death
self.alive = False
self.update_animation()
#draw image on screen
surface.blit(self.image, (self.rect.x - 10, self.rect.y - 15))
def update_animation(self):
#define animation cooldown
animation_cooldown = 250
#update image depending on current action
self.image = self.animation_list[self.action][self.frame_index]
#check if enough time has passed since the last update
if pygame.time.get_ticks() - self.update_time > animation_cooldown:
self.update_time = pygame.time.get_ticks()
self.frame_index += 1
#if the animation has run out then reset back to the start
if self.frame_index >= len(self.animation_list[self.action]):
if self.action == 2:
self.frame_index = len(self.animation_list[self.action]) - 1
else:
self.frame_index = 0
def update_action(self, new_action):
#check if the new action is different to the previous one
if new_action != self.action:
self.action = new_action
#update the animation settings
self.frame_index = 0
self.update_date = pygame.time.get_ticks()