-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEnemy.py
More file actions
54 lines (44 loc) · 2.49 KB
/
Copy pathEnemy.py
File metadata and controls
54 lines (44 loc) · 2.49 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
import pygame
from random import randint, randrange, sample
import asteroids as M
class Enemy(pygame.sprite.Sprite):
""" Enemy object class for the asteroids game. """
def __init__(self, diff, scale):
""" Initialize an asteroid object. """
super().__init__()
# Randomly scale the enemy (small, medium or large) and assign speed accordingly
self.scale = scale
self.speed = (1 if self.scale == 150 else 2 if self.scale == 100 else 3) * diff
# Asteroid: https://www.flaticon.com/free-icon/meteorite_4260653?term=asteroids&related_id=4260653
self.img = pygame.image.load("images/meteorite.png")
self.img = pygame.transform.scale(self.img, (self.scale, self.scale))
# Get initial random spawn position of enemy around the screen
self.pos_x = randint(-self.scale, 0) if randint(0,1) == 0 \
else randint(M.WIDTH, M.WIDTH + self.scale)
self.pos_y = randint(-self.scale, 0) if randint(0,1) == 0 \
else randint(M.HEIGHT, M.HEIGHT + self.scale)
# Moving direction: move to the right (down) if spawned on the left (top) and vice versa
self.dir_x = 1 if self.pos_x <= M.WIDTH//2 else -1
self.dir_y = 1 if self.pos_y <= M.HEIGHT//2 else -1
# Collision rectangle
self.rect = self.img.get_rect(center=(self.pos_x, self.pos_y))
def move(self):
""" Method to update the enemy position. """
# Remove object at borders
if (self.pos_x <= 0 - self.scale//2 and self.dir_x == -1):
self.pos_x = M.WIDTH + self.scale//2
self.pos_y = M.HEIGHT - self.pos_y
if (self.pos_x >= M.WIDTH + self.scale//2 and self.dir_x == 1):
self.pos_x = 0 - self.scale//2
self.pos_y = M.HEIGHT - self.pos_y
if (self.pos_y <= 0 - self.scale//2 and self.dir_y == -1):
self.pos_x = M.WIDTH - self.pos_x
self.pos_y = M.HEIGHT + self.scale//2
if (self.pos_y >= M.HEIGHT + self.scale//2 and self.dir_y == 1):
self.pos_x = M.WIDTH - self.pos_x
self.pos_y = 0 - self.scale//2
# Update position with according direction (depends on spawn pos)
# Get some randomness into asteroid's speed
self.pos_x += self.dir_x * self.speed * randrange(1,2)
self.pos_y += self.dir_y * self.speed * randrange(1,2)
self.rect = self.img.get_rect(center=(self.pos_x, self.pos_y))