What I want is two things: count the number of enemies on the screen. And remove all enemies from the screen with a contion. The second chose is to allow enemies to shoot randomly
class Enemy(Particle):
active = False
tex_name = 'ufo'
v = 0
def reset(self, created=False):
self.active = False
self.x = -100
self.y = -100
self.v = 0
def advance(self, nap):
if self.active:
if self.check_hit():
self.reset()
return
self.x -= 200 * nap
if self.x < -50:
self.reset()
return
self.y += self.v * nap
if self.y <= 0:
self.v = abs(self.v)
elif self.y >= self.parent.height:
self.v = -abs(self.v)
elif self.parent.spawn_delay <= 0:
self.active = True
self.x = self.parent.width + 50
self.y = self.parent.height * random()
self.v = randint(-100, 100)
self.parent.spawn_delay += 1
def check_hit(self):
if math.hypot(self.parent.player_x - self.x,
self.parent.player_y - self.y) < 60:
return True
for b in self.parent.bullets:
if not b.active:
continue
if math.hypot(b.x - self.x, b.y - self.y) < 30:
b.reset()
return True
What I want is two things: count the number of enemies on the screen. And remove all enemies from the screen with a contion. The second chose is to allow enemies to shoot randomly
Advertisement
Answer
You can accomplish the first two of your questions by modifying the PSWidget
class. By adding two attributes enemy_count
and killall
to the class:
class PSWidget(Widget):
indices = []
vertices = []
particles = []
enemy_count = 0
killall = False
And using those attributes in the update_glsl()
method:
def update_glsl(self, nap):
self.enemy_count = 0 # initialize enemy count
for p in self.particles:
if isinstance(p, Enemy) and p.active:
if self.killall:
p.reset() # kill this enemy
else:
self.enemy_count += 1 # increment enemy count
p.advance(nap)
p.update()
self.canvas.clear()
with self.canvas:
Mesh(fmt=self.vfmt, mode='triangles',
indices=self.indices, vertices=self.vertices,
texture=self.texture)
# reset killall
self.killall = False
So, anytime you want the count of active enemies, just use the enemy_count
attribute of the PSWidget
instance. And whenever you want to kill all the active enemies, just set the killall
attribute of the PSWidget
instance.
As far as your third question, show us your attempt at coding that.
If you are using an answer that I gave in another question, where I suggested using the on_enter()
method to start the game updates, then you can use on_leave()
to stop the updates. The game movements are faster every time you enter MainScreen
because more updates are scheduled on each entry. Here is a modified MainScreen
that handles that handles that issue:
class MainScreen(Screen):
started = BooleanProperty(False)
def on_enter(self, *args):
if not self.started:
self.ids.game.initialize()
self.started = True
self.update_event = Clock.schedule_interval(self.ids.game.update_glsl, 1.0/60.0)
def on_leave(self, *args):
if self.update_event is not None:
self.update_event.cancel()