1

I am trying to create a Frog game where a frog will have to dodge cars while moving through roads. I made an user event of car1 which would produce a car after a delay of three seconds. But for some reason it is not being shown on the screen.

I also wanted to know whether how to create multiple car objects moving from left to right, should i store them in variables or is there some other method?

import random
import time
# Initialising the program
pygame.init()
# Creating the screen
screen = pygame.display.set_mode((700,700))
playerImg = pygame.image.load('images/golden-frog.png')
playerX = 330
playerY = 700
playerX_change = 0
playerY_change = 0
cars = {
    1: pygame.image.load('images/police.png'),
    2: pygame.image.load('images/motorcycle.png'),
    3: pygame.image.load('images/sports1.png')
}
road = pygame.image.load('images/road.png')
def car(a,x,y):
    screen.blit(cars.get(a),(x,y))
def player(x,y):
    screen.blit(playerImg,(x,y))
running = True
clock = pygame.time.Clock()
while running:
    screen.fill((0,0,0))
    screen.blit(road,(0,100))

    a = random.randint(1,len(cars.keys()))
    car1 = pygame.USEREVENT + 1
    pygame.time.set_timer(car1, 3000)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == car1:

            car(1,0,120)
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                playerX_change = 30
            if event.key == pygame.K_LEFT:
                playerX_change = -30
            if event.key == pygame.K_DOWN:
                playerY_change = 50
            if event.key == pygame.K_UP:
                playerY_change = -50
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_RIGHT or  event.key == pygame.K_LEFT:
                playerX_change = 0
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                playerY_change = 0
    playerX += playerX_change
    playerY += playerY_change
    if playerX < 0:
        playerX = 0
    if playerX > 674:
        playerX = 674
    if playerY < 0:
        playerY = 0
    if playerY > 674:
        playerY = 674
    player(playerX,playerY)
    clock.tick(11)
    pygame.display.update()```
Azan
  • 35
  • 4

1 Answers1

1

On each iteration of your game loop, you are calling pygame.time.set_timer(). Calling set_timer() discards the old timer for this event, so your car1 timer will never trigger.

Move the call to set_timer before your while statement.

Note also that your car1 event handler will be triggered after three seconds and will blit your car surface to your screen. You'll be able to see the image for one eleventh of a second before your game loop runs again and the background draws over your car. You could do something similar to your player function which is called every loop. Longer term you should investigate sprites.

import random
  • 3,054
  • 1
  • 17
  • 22