Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.9 kB
0
Indexable
Never
import pygame
import random

# Initialize the game
pygame.init()

# Set up the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Cars Game")

# Set up the car
car_width = 50
car_height = 100
car_img = pygame.image.load("car.png")  # Replace "car.png" with your car image file
car_img = pygame.transform.scale(car_img, (car_width, car_height))
car_x = screen_width // 2 - car_width // 2
car_y = screen_height - car_height - 10
car_speed = 5

# Set up the enemy car
enemy_width = 50
enemy_height = 100
enemy_img = pygame.image.load("enemy_car.png")  # Replace "enemy_car.png" with your enemy car image file
enemy_img = pygame.transform.scale(enemy_img, (enemy_width, enemy_height))
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = -enemy_height
enemy_speed = 3

def draw_car(x, y):
    screen.blit(car_img, (x, y))

def draw_enemy_car(x, y):
    screen.blit(enemy_img, (x, y))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and car_x > 0:
        car_x -= car_speed
    if keys[pygame.K_RIGHT] and car_x < screen_width - car_width:
        car_x += car_speed

    # Update enemy car position
    enemy_y += enemy_speed
    if enemy_y > screen_height:
        enemy_x = random.randint(0, screen_width - enemy_width)
        enemy_y = -enemy_height

    # Check for collision
    if car_x < enemy_x + enemy_width and car_x + car_width > enemy_x and car_y < enemy_y + enemy_height and car_y + car_height > enemy_y:
        running = False

    # Clear the screen
    screen.fill((255, 255, 255))

    # Draw the car and enemy car
    draw_car(car_x, car_y)
    draw_enemy_car(enemy_x, enemy_y)

    # Update the display
    pygame.display.update()

# Quit the game
pygame.quit()
Leave a Comment