How to randomly spawn bullets in different directions?

Viewed 40

I've been trying to code a game where a turkey has to dodge bullets, this is a 2d game so it only goes up, down, left, and right. I tried putting in the logic of the game "asteroids" where the asteroids spawn randomly but still no luck.

import pygame
bakcground = pygame.image.load("Bulletspix/Grass BG.png")
PlayerTurk = pygame.image.load ("Bulletspix/turkey.png")
playerTurkx = 450
playerTurky = 800
vel = 1

pygame.display.set_caption("game")
screen = pygame.display.set_mode((800, 900))

playerTurkx = 350
playerTurky = 350
vel = 1

def player():
    screen.blit(PlayerTurk, (playerTurkx , playerTurky))

running = True
while running:
    #Oprion of quitting
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Background
    screen.fill((0, 0, 0))
    screen.blit(bakcground, (0, 0))

    #movement
    Input = pygame.key.get_pressed()
    if Input[pygame.K_LEFT] and playerTurkx >0:
        playerTurkx -= vel
    if Input[pygame.K_RIGHT]and playerTurkx <730:
        playerTurkx += vel
    if Input[pygame.K_UP]and playerTurky >0:
        playerTurky -= vel
    if Input[pygame.K_DOWN]and playerTurky <500:
        playerTurky += vel

    player()
    pygame.display.update()

pygame.quit()
1 Answers

First, create a list to store the bullets.

bullets = []

# And some other necessary variables.
seconds_since_spawn = 0.0
player_lives = 3
BULLET_START_POSITION = (799, 449)

Then, at every iteration in the loop:

  1. Every N iterations/seconds, spawn a bullet at a fixed location (randomize later).
    if seconds_since_spawn >= 1.0:
        seconds_since_spawn = 0.0
        bullets.append(BULLET_START_POSITION)
    
  2. Move all bullets across the screen by a step.
    bullets = [(x - 1, y) for x, y in bullets]
    
  3. Check if any of the bullets collided with player.
    def collided_with_player(x, y):
        return check_collision(
            player.x, player.y, PLAYER_RADIUS, x, y, BULLET_RADIUS
        )
    
    player_lives -= sum(
        1 for x, y in bullets if collided_with_player(x, y)
    )
    
    if player_lives <= 0:
        running = False  # end game
    
  4. Remove any bullets from the list that are not visible on the screen, or collided with player.
    bullets = [
        (x, y)
        for x, y in bullets
        if is_inside_screen(x, y) and not collided_with_player(x, y)
    ]
    
  5. Draw all bullets.
    for x, y in bullets:
        draw_bullet(x, y)
    
Related