Game
unknown
python
a year ago
2.7 kB
12
Indexable
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# Frame rate
FPS = 60
clock = pygame.time.Clock()
# Load car image
car_img = pygame.image.load('car.png') # Use any simple car image
car_width = car_img.get_width()
# Car class
class Car:
def __init__(self):
self.x = SCREEN_WIDTH // 2 - car_width // 2
self.y = SCREEN_HEIGHT - 100
self.speed = 5
def move_left(self):
if self.x > 0:
self.x -= self.speed
def move_right(self):
if self.x < SCREEN_WIDTH - car_width:
self.x += self.speed
def draw(self):
screen.blit(car_img, (self.x, self.y))
# Obstacle class
class Obstacle:
def __init__(self):
self.x = random.randint(0, SCREEN_WIDTH - 40)
self.y = -100
self.speed = random.randint(4, 8)
self.width = 40
self.height = 60
def move(self):
self.y += self.speed
def draw(self):
pygame.draw.rect(screen, RED, [self.x, self.y, self.width, self.height])
def off_screen(self):
return self.y > SCREEN_HEIGHT
# Function to detect collision
def detect_collision(car, obstacle):
if car.x < obstacle.x + obstacle.width and car.x + car_width > obstacle.x:
if car.y < obstacle.y + obstacle.height and car.y + car_width > obstacle.y:
return True
return False
# Main game loop
def game_loop():
car = Car()
obstacles = []
score = 0
running = True
while running:
screen.fill(WHITE)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move car with keys
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
car.move_left()
if keys[pygame.K_RIGHT]:
car.move_right()
# Create obstacles
if random.randint(1, 60) == 1:
obstacles.append(Obstacle())
# Move and draw obstacles
for obstacle in obstacles[:]:
obstacle.move()
obstacle.draw()
if obstacle.off_screen():
obstacles.remove(obstacle)
score += 1
if detect_collision(car, obstacle):
print(f'Game Over! Your score: {score}')
running = False
# Draw car
car.draw()
# Update the screen
pygame.display.flip()
# Control the frame rate
clock.tick(FPS)
pygame.quit()
# Start the game
game_loop()Editor is loading...
Leave a Comment