Python creating a game pygame

Tell us what’s happening:
How do I add the up/down key functions, my object the racecar only moves right and left

Your code so far

import pygame

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

car_width = 73

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption(‘Zelda Racing’)
clock = pygame.time.Clock()

carImg = pygame.image.load(‘racecar.png’)

def car(x,y):
gameDisplay.blit(carImg,(x,y))

def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()

def message_display(text):
largeText = pygame.font.Font(‘freesansbold.ttf’,100)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)

pygame.display.update()

time.sleep(2)

game_loop()

def crash():
message_display(‘Game Over’)

def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)

x_change = 0

gameExit = False

while not gameExit:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            if event.key == pygame.K_RIGHT:
                x_change = 5

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    x += x_change

    gameDisplay.fill(white)
    car(x,y)

    if x > display_width - car_width or x < 0:
        crash()
        
    pygame.display.update()
    clock.tick(60)

def on_cleanup(self):
pygame.quit()

game_loop()
pygame.quit()

  • List item

Hello, I’ll try to help you, but first, need to say some stuff:

I never created any game with PyGame, but I use something called GdScript over Godot OpenSource IDE and its similar to Python, strongly encourage you to check it out if you want to create games.

But let’s jump straight to the point:
you said:

my object the racecar only moves right and left

So, you can extend your KEYDOWN event handle to work with your K_UP and K_DOWN key:


if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        x_change = -5
    if event.key == pygame.K_RIGHT:
        x_change = 5
    if event.key == pygame.K_DOWN:
        y_change = +5
    if event.key == pygame.K_UP:
        y_change = -5

Maybe this solves your problem.

Some tips for you:

  • Use 4 space indentation instead of tabs if the case.
  • Try to break your code into different files with a specific purpose. A file for the core Scene and another for movement and other stuff event handling, this will help to maintain.

Wish this could help you.

1 Like