New to Python trying to make game with pygame

Viewed 125

I made some code for my game using PyGame to spawn an obstacle and im new to coding. It wouldn't spawn the obstacles and so i put a print statement to see when it spawns and it does print but doesn't show up on screen. This is not all the code but instead a minimalistic version of it that only shows the problematic code. no errors show up when running the code

import pygame as pg
import random
pg.init()
obstacle1 = pg.image.load('download1.jpeg')
obstacley = 600#tells object to spawn at top of screen
spawn = random.randint(1,10)
spawned = 0
if spawn == 1 and spawned == 0:
    spawn = 0
    Obstaclex = random.randint(600,800)#determines where on the top of the screen it spawns with rng
    obstaclesize = random.randint(1,5)# determines obstacletype because there are 5 obstacle types that i havent included in this to be as simple as possbile
    obstaclespeed = random.randint(3,8)#determines obstaclespeed using rng
    spawned = 1
    if obstaclesize == 1:       
        gameDisplay.blit(obstacle1,(obstacley,Obstaclex))
        obstacley -= obstaclespeed #changes y position to lower it down the screen to hit player
        print ("i have spawned")
1 Answers

You have to blit all the existing obstacles in the game loop in ever frame, not just when creating a new obstacle.

Create an obstacle list (obstacle_list) and append the coordinates of the new obstacle to the list. Draw all the obstacles in the main application loop:

obstacle_list = []

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # [...]

    if len(obstacle_list) < spawn:
        x = random.randint(600,800)
        y = 600
        size = random.randint(1,5)
        speed = random.randint(3,8)
        obstacle_list.append((x, y, size, speed))

    # [...]

    # move obstacles
    for i in range(len(obstacle_list)):
        x, y, size, speed = obstacle_list[i]
        new_y = y - speed
        obstacle_list[i] = (x, new_y, size, speed)

    # [...]

    # draw obstacles
    for x, y, size, speed in obstacle_list:
        gameDisplay.blit(obstacle1, (x, y))

    # [...]
Related