-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenemy.py
More file actions
90 lines (77 loc) · 2.98 KB
/
enemy.py
File metadata and controls
90 lines (77 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import pygame
import random
import utils
import math
from bullets import EnemyBullet
SCALE = 6
POSITION_OFFSET = 10
SPEED = 1
ENEMY_PATH = ["Images/enemy.png", "Images/enemy_up.png"]
class Enemies(pygame.sprite.Group):
def __init__(self, num_of_enemies, screen_width, bullets, timer, finish_position):
super().__init__()
self.finish_position = finish_position - 3 * POSITION_OFFSET
self.generate_enemies(num_of_enemies, screen_width, bullets, timer)
def generate_enemies(self, num_of_enemies, screen_width, bullets, timer):
rows = math.ceil(num_of_enemies / 10)
enemy_per_row = math.ceil(num_of_enemies / rows)
enemy_in_row = 0
row = 1
for i in range(num_of_enemies):
if enemy_in_row + 1 > enemy_per_row:
row += 1
enemy_in_row = 0
direction = 1
if row % 2:
width = (enemy_in_row + 1) * 80
else:
width = screen_width - ((enemy_per_row - enemy_in_row) * 80)
direction = -1
height = 70 + row * 55
enemy_in_row += 1
enemy = Enemy(width,
height,
bullets,
direction, timer)
self.add(enemy)
def is_any_down_the_screen(self):
for enemy in self.sprites():
if enemy.rect.y >= self.finish_position:
return True
return False
class Enemy(pygame.sprite.Sprite):
def __init__(self, x, y, enemy_bullets, direction, timer):
super().__init__()
self.image_number = 0
self.image = utils.load_and_scale(ENEMY_PATH[self.image_number], SCALE)
self.rect = self.image.get_rect()
self.rect.center = (x, y - int(self.image.get_height() / 2) - POSITION_OFFSET)
self.mask = pygame.mask.from_surface(self.image)
self.speed = direction * SPEED
self.enemy_bullets = enemy_bullets
self.timer = timer
def animation(self):
if self.image_number == 0:
self.image_number = 1
else:
self.image_number = 0
position = self.rect.center
self.image = utils.load_and_scale(ENEMY_PATH[self.image_number], SCALE)
self.rect = self.image.get_rect()
self.rect.center = position
def change_direction(self):
self.rect.y += 55
self.speed *= -1
def update(self):
self.rect.x += self.speed
if self.rect.x + self.image.get_width() / 2 > 980:
self.change_direction()
if self.rect.x + self.image.get_width() / 2 < 20:
self.change_direction()
if random.randrange(0, 200, 2) == 16 and not self.timer.is_running:
self.shoot_bullet()
self.animation()
def shoot_bullet(self):
bullet = EnemyBullet(self.rect.x + self.image.get_width() / 2,
self.rect.y + self.image.get_height() + POSITION_OFFSET)
self.enemy_bullets.add(bullet)