Skip to content

Commit 323119d

Browse files
committed
add enemies
1 parent 788c142 commit 323119d

File tree

1 file changed

+43
-14
lines changed

1 file changed

+43
-14
lines changed

src/game/game.py

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python3
22
import pyxel
3+
from copy import copy
34

45

56
class Bullet:
@@ -10,11 +11,7 @@ def __init__(self, cords, rotate):
1011

1112
@classmethod
1213
def from_player(cls, player):
13-
x, y = player.cords
14-
w = player.WIDTH_SPRITE
15-
h = player.HEIGHT_SPRITE
16-
cords = [x + w / 2, y + h / 2]
17-
return cls(cords, player.rotate)
14+
return cls(copy(player.cords), player.rotate)
1815

1916
def update(self):
2017
if self.rotate == 'u':
@@ -38,28 +35,29 @@ def draw(self):
3835
pyxel.circ(x, y, 2, 10)
3936

4037

41-
class Player:
38+
class Ship:
4239
WIDTH_SPRITE = 32
4340
HEIGHT_SPRITE = 32
44-
4541
ROTATE_INDEXES = {
4642
'u': 0,
4743
'l': 1,
4844
'd': 2,
4945
'r': 3,
5046
}
5147

52-
def __init__(self, cords):
53-
self.score = 0
48+
def __init__(self, cords, rotate, img_index):
5449
self.cords = cords
55-
self.rotate = 'u'
50+
self.rotate = rotate
51+
self.img_index = img_index
5652

5753
def draw(self):
58-
x, y = self.cords
5954
w = self.WIDTH_SPRITE
6055
h = self.HEIGHT_SPRITE
6156
u = self.ROTATE_INDEXES[self.rotate] * w
62-
pyxel.blt(x, y, 0, u, 0, w, h, 11)
57+
v = self.img_index * h
58+
x = self.cords[0] - w / 2
59+
y = self.cords[1] - h / 2
60+
pyxel.blt(x, y, 0, u, v, w, h, 11)
6361

6462
def move_up(self):
6563
self.cords[1] -= 5
@@ -78,6 +76,28 @@ def move_right(self):
7876
self.rotate = 'r'
7977

8078

79+
class Player(Ship):
80+
81+
def __init__(self, cords):
82+
super().__init__(cords=cords, rotate='u', img_index=0)
83+
self.score = 0
84+
85+
86+
class EnemyShip(Ship):
87+
88+
def __init__(self, cords):
89+
super().__init__(cords=cords, rotate='u', img_index=3)
90+
91+
def update(self):
92+
self.move_up()
93+
94+
def is_alive(self):
95+
x, y = self.cords
96+
return (
97+
x > 0 and x < 256
98+
and y > 0 and y < 256
99+
)
100+
81101
class App:
82102

83103
def run(self):
@@ -89,10 +109,15 @@ def setup(self):
89109

90110
self.player = Player([128, 128])
91111
self.bullets = []
112+
self.enemies = [
113+
EnemyShip([20 + 50 * i, 250])
114+
for i in range(4)
115+
]
92116

93117
def update(self):
94118
self.keyboard()
95119
self.bullets = self.update_objs(self.bullets)
120+
self.enemies = self.update_objs(self.enemies)
96121

97122
def update_objs(self, objs):
98123
survived_objs = []
@@ -125,5 +150,9 @@ def draw(self):
125150
pyxel.cls(0)
126151
pyxel.text(0, 0, "Score: %d" % self.player.score, 7)
127152
self.player.draw()
128-
for bullet in self.bullets:
129-
bullet.draw()
153+
self.draw_objs(self.bullets)
154+
self.draw_objs(self.enemies)
155+
156+
def draw_objs(self, objs):
157+
for obj in objs:
158+
obj.draw()

0 commit comments

Comments
 (0)