Untitled
unknown
plain_text
2 years ago
2.2 kB
5
Indexable
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
screen_width = 800
screen_height = 600
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
# Car settings
car_width = 50
car_height = 60
# Initialize the screen
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Car Game")
# Load car image
car_img = pygame.image.load('car.png')
car_img = pygame.transform.scale(car_img, (car_width, car_height))
clock = pygame.time.Clock()
def draw_car(x, y):
screen.blit(car_img, (x, y))
def draw_obstacle(obs_x, obs_y, obs_w, obs_h, color):
pygame.draw.rect(screen, color, [obs_x, obs_y, obs_w, obs_h])
def game_loop():
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
obs_start_x = random.randrange(0, screen_width)
obs_start_y = -600
obs_speed = 7
obs_width = 100
obs_height = 100
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = 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.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
screen.fill(white)
draw_obstacle(obs_start_x, obs_start_y, obs_width, obs_height, black)
obs_start_y += obs_speed
draw_car(x, y)
if x > screen_width - car_width or x < 0:
print("You crashed!")
game_exit = True
if obs_start_y > screen_height:
obs_start_y = 0 - obs_height
obs_start_x = random.randrange(0, screen_width)
if y < obs_start_y + obs_height:
if x > obs_start_x and x < obs_start_x + obs_width or x + car_width > obs_start_x and x + car_width < obs_start_x + obs_width:
print("You crashed!")
game_exit = True
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
game_loop()Editor is loading...
Leave a Comment