I am currently working on a space inavders game in kivy. I have a spaceship and it shoots bullets to the enemies. The enemies move to the right and when they hit the border they turn left and it happens again and again. Everything works perfect. I can shoot and enemy is moving. But the problem is I cant create multiple enemies. I have to put a own class for every enemy and write the same code again and again. My idea was that I will create a enemy list and then display them from the list . So that it looks like there are multiple enemies. But I have no ideas how I could do it and I am failing to do it from one day.Also when you another ideas, it would be great if you suggest them. Here is my code.
The enemy class:
class Enemy(Widget):
def collision(self,ball,enemy,enemy1):
if self.collide_widget(ball):
enemy.y = randint(300,500)
enemy1.y = randint(300,500)
ball.x = -1000
ball.y = self.height / self.width
My Main Game Class:
class SapceGame(Widget):
enemy = ObjectProperty(None)
enemy = ObjectProperty(None)
x_change = NumericProperty(3)
y_change = NumericProperty(-50)
def enemy_movement(self, *args):
self.enemy.x -= self.x_change
if self.enemy.x >= self.width -64:
self.x_change = 3
self.enemy.y += self.y_change
elif self.enemy.x <=0:
self.x_change = -3
self.enemy.y += self.y_change
elif self.enemy.y < 0:
print('Game Over')
def update(self,dt):
self.enemy_movement()
My kv file:
<Enemy>:
size: 64,64
canvas:
Rectangle:
pos:self.pos
size: self.size
source:'alien.png'
<SpaceGame>:
ball: pong_ball
ship: space_ship
enemy: enemy_ship
Enemy:
id:enemy_ship
x:root.random_generator(2,root.width-64)
y:root.random_generator(300,550)
the App class
class SpaceApp(App):
def build(self):
game = PongGame()
# pro second 60 frames are shown
Clock.schedule_interval(game.update, 1.0/60.0)
return game
SpaceApp().run()
Now when I want to create more enemies I have to write the same code again and again.