user10567555
user10567555

Reputation:

Randomly spawning an enemy

I am in the progress of making a small 2d game where the objective is to eat as much poop as possible, but I'm having trouble spawning the poop at random times. I want the poop to spawn at the enemy's y location but then shoot forwards like an rpg.

import pygame
from pygame.locals import *
from numpy.random import rand

pygame.init()
pygame.display.set_caption('STINKY BEETLE')

screen_width = 800
screen_height = 600
game_running = True
pl_x = int(screen_width/10)
pl_y = int(screen_height/2)
pl_width = 80
pl_height = 40
pl_vel = 30
en_width = 80
en_height = 40
en_x = screen_width - screen_width/10 - en_width
en_y = int(screen_height/2)
en_yvel = -10
po_width = 50
po_height = 30
po_x = 720
po_y = en_y
po_xvel = 15

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

while game_running:
    clock.tick(10)

    po_delay = rand(1)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False

        if event.type == MOUSEBUTTONDOWN:
            if event.button == 4 and pl_y > pl_vel:
                pl_y -= pl_vel

            elif event.button == 5 and pl_y < screen_height - pl_width:
                pl_y += pl_vel

    if po_delay < 0.01:
        poop(po_x, po_y)

    en_y += en_yvel
    if en_y <= 0 or en_y >= screen_height - en_height:
        en_yvel =- en_yvel

    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, (105, 255, 125), (pl_x, pl_y, pl_width, pl_height))
    pygame.display.update()

    pygame.draw.rect(screen, (255, 125, 115), (en_x, en_y, en_width, en_height))
    pygame.display.update()

pygame.quit()

Upvotes: 3

Views: 180

Answers (2)

Rabbid76
Rabbid76

Reputation: 210909

If you want to mange multiple "poops", then you have to create a list. And each "poop" is an object (an instance of a class).

Crate a class Poop, which can update the position and draw the poop:

class Poop:
    def __init__(self, x, y, w, h):
        self.rect = pygame.Rect(x, y-h//2, w, h)
        self.vel = -15
    def update(self):
        self.rect.x += self.vel
    def draw(self, surf):
        pygame.draw.rect(surf, (255, 200, 125), self.rect)

poops = []

Use a timer event to spawn the poops. Use pygame.time.set_timer() to repeatedly create an USEREVENT. The time is set in milliseconds. Set a random time by random.randint(a, b) e.g. set a time between 0.5 and 4 seconds (of course you can choose your own time interval):

min_time, max_time = 500, 4000 # 0.5 seconds to to 4 seconds
spawn_event = pygame.USEREVENT + 1
pygame.time.set_timer(spawn_event, random.randint(min_time, max_time))

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to start at pygame.USEREVENT. In this case pygame.USEREVENT+1 is the event id for the timer event, which spawns the poops.

Create a new poop when the event occurs in the event loop and set a new random time:

for event in pygame.event.get():
    # [...]
    if event.type == spawn_event:
        pygame.time.set_timer(spawn_event, random.randint(min_time, max_time))
        poops.append(Poop(en_x, en_y+en_yvel+en_height//2, 50, 30))

Change the positions of the poops in a loop and remove them from the list, if they leave the window on the left:

for poop in poops[:]:
    poop.update()
    if poop.rect.right <= 0:
        poops.remove(poop)

Draw them ina loop

for poop in poops:
    poop.draw(screen)

See the example:

import pygame
from pygame.locals import *
import random

pygame.init()
pygame.display.set_caption('STINKY BEETLE')

class Poop:
    def __init__(self, x, y, w, h):
        self.rect = pygame.Rect(x, y-h//2, w, h)
        self.vel = -15
    def update(self):
        self.rect.x += self.vel
    def draw(self, surf):
        pygame.draw.rect(surf, (255, 200, 125), self.rect)

screen_width = 800
screen_height = 600
game_running = True
pl_x, pl_y = screen_width//10, screen_height//2
pl_width, pl_height, pl_vel = 80, 40, 30
en_width, en_height, en_yvel = 80, 40, -10
en_x, en_y,  = screen_width - screen_width//10 - en_width, screen_height//2

screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()

min_time, max_time = 500, 4000 # 0.5 seconds up to 4 seconds 
spawn_event = pygame.USEREVENT + 1
pygame.time.set_timer(spawn_event, random.randint(min_time, max_time))
poops = []

while game_running:
    clock.tick(10)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_running = False

        if event.type == MOUSEBUTTONDOWN:
            if event.button == 4 and pl_y > pl_vel:
                pl_y -= pl_vel
            elif event.button == 5 and pl_y < screen_height - pl_width:
                pl_y += pl_vel

        if event.type == spawn_event:
            pygame.time.set_timer(spawn_event, random.randint(min_time, max_time))
            poops.append(Poop(en_x, en_y+en_yvel+en_height//2, 50, 30))

    en_y += en_yvel
    if en_y <= 0 or en_y >= screen_height - en_height:
        en_yvel =- en_yvel

    for poop in poops[:]:
        poop.update()
        if poop.rect.right <= 0:
            poops.remove(poop)

    screen.fill((0, 0, 0))
    for poop in poops:
        poop.draw(screen)
    pygame.draw.rect(screen, (105, 255, 125), (pl_x, pl_y, pl_width, pl_height))
    pygame.draw.rect(screen, (255, 125, 115), (en_x, en_y, en_width, en_height))
    pygame.display.update()

pygame.quit()

Upvotes: 2

user12291970
user12291970

Reputation:

You can use pygame's time module to randomly spawn enemies. I am assuming you are using OOP for this. Firstly, when initializing your enemy class record the time when it first spawns.

class Enemy:
    def __init__(self):
        self.start = time.time()
        # other code

Then you can calculate the amount of time that has passed since your enemy last spawened. You can do something like now = time.time() in your main game loop and get the difference.

enemy = Enemy()
while True:
    now = time.time()
    time_passed = now - enemy.start()

Now you can use this time_passed as an argument to your spawn_enemy() function that you might create which might look something like this:

def spawn(self, t):
   counter = t % random.randint(1, 10)
   if counter >= 0 and counter <=  0.2:
       #spawn enemy

Call this function as spawn(time_passed)

Upvotes: 0

Related Questions