pygame103.py

#! /usr/bin/python3
# ==================================================================
# From: pythonprogramming.net/pygame-python-3-part-1-intro/
# ==================================================================

# ----- initialize pygame

import pygame

pygame.init()

# ----- pygame display

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A Bit Racey')

# ----- set car location function

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

# ----- define some colors

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

# ----- car image, etc.

carImg = pygame.image.load('racecar_green.png')
car_width = carImg.get_width()
car_height = carImg.get_height()

# ----- initial car position and movement values

x = display_width * 0.45
y = display_height * 0.8
x_change = 0
y_change = 0

# ----- runtime "stuff"

print('-----Runtime------------------------')
print('Display X = ',display_width)
print('Display Y = ',display_height)
print('Car     X = ',car_width)
print('Car     Y = ',car_height)
print('------------------------------------')

# ----- event loop

clock = pygame.time.Clock()
crashed = False

while not crashed:

    # ----- process events

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
            if event.key == pygame.K_DOWN:
                y_change = 5
            elif event.key == pygame.K_UP:
                y_change = -5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or pygame.K_RIGHT or \
                            pygame.K_DOWN or pygame.K_UP:
                x_change = 0
                y_change = 0

    # ----- car's location, do not go outside the display boundry 

    x += x_change
    y += y_change

    if x < 0:
        x = 0
    elif x > (display_width - car_width):
        x = display_width - car_width

    if y < 0:
        y = 0
    elif y > (display_height - car_height):
        y = display_height - car_height

    # ----- referesh display

    gameDisplay.fill(white)
    car(x,y)
    pygame.display.update()
    clock.tick(60)

# ----- end progrm

pygame.quit()
quit()