Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Tutorials listed in this section have not been reviewed nor are affliated by Code Forum. It is the sole responsbility of the authour to properly maintain and ensure information is accurate.

Python Simple pygame dodge car game - pygame window

The directory structure I'm using:
  • car
    • media
      • images
        • cars
    • car.py
car being the main folder, media to hold all the media types folders, images, and then the folder holding car images

car.py should be something like:
Python:
# Do the imports
import pygame
import os

'''
 Get the path of the working directory
 Should get the correct path in console or editor
 We will use this to access directories containing
 images and sound
'''
path = os.path.realpath(os.path.dirname(__file__))

'''
 Initiate pygame to acces all classes and functions
'''

pygame.init()

'''
 Setup the pygame time clock.
 We will use this to set the framerate
'''
clock = pygame.time.Clock()

# Set the framerate
fps = 60

'''
 Setup our screen window. A tuple is needed for setting width and height
 I'm going to use a 1280 width and 720 height
'''
screen_size = (1280, 720)
screen = pygame.display.set_mode(screen_size)

# Set the caption for the window
pygame.display.set_caption('Dodge Car')

running = True

# Start the game loop
while running:

    # Set background color
    screen.fill('seagreen')

    '''
     Get pygame events. There is 2 ways to do this.
     We can use pygame.event.poll() - return one event or
     we can use a loop and get all events. We will use the latter -
     pygame.event.get()
    '''

    # Get keys that are pressed
    key = pygame.key.get_pressed()

    for event in pygame.event.get():

        # A way to exit pygame
        if event.type == pygame.QUIT:
            running = False

        # Can press the esc key and exit the game
        if key[pygame.K_ESCAPE]:
            running = False

   
    # Update the screen
    pygame.display.update()

    # Set our framerate
    clock.tick(fps)
pygame.quit()

This should give a pygame window like this

1736739234156.webp
 
Back
Top Bottom