Untitled

mail@pastecode.io avatar
unknown
plain_text
5 days ago
1.7 kB
3
Indexable
Never
import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up some constants
WIDTH, HEIGHT = 800, 600
CAR_SIZE = 50
CAR_SPEED = 5

# Set up some colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))

# Set up the car
car_x, car_y = WIDTH / 2, HEIGHT / 2
car_speed_x, car_speed_y = 0, 0

# Game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                car_speed_y = -CAR_SPEED
            elif event.key == pygame.K_DOWN:
                car_speed_y = CAR_SPEED
            elif event.key == pygame.K_LEFT:
                car_speed_x = -CAR_SPEED
            elif event.key == pygame.K_RIGHT:
                car_speed_x = CAR_SPEED
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                car_speed_y = 0
            elif event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                car_speed_x = 0

    # Move the car
    car_x += car_speed_x
    car_y += car_speed_y

    # Keep the car on the screen
    if car_x < 0:
        car_x = 0
    elif car_x > WIDTH - CAR_SIZE:
        car_x = WIDTH - CAR_SIZE
    if car_y < 0:
        car_y = 0
    elif car_y > HEIGHT - CAR_SIZE:
        car_y = HEIGHT - CAR_SIZE

    # Draw everything
    screen.fill(WHITE)
    pygame.draw.rect(screen, RED, (car_x, car_y, CAR_SIZE, CAR_SIZE))

    # Update the display
    pygame.display.flip()

    # Cap the frame rate
    pygame.time.Clock().tick(60)
Leave a Comment