NIMU 'S CAR RACING GAME
import pygame
import random
# Initialize Pygame
pygame.init()
# Set display size
width, height = 800, 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Racing Game")
# Load car image
car_img = pygame.image.load("car.png") # Replace with your own image if needed
car_width = 50
car_height = 100
# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (200, 0, 0)
# Clock
clock = pygame.time.Clock()
# Function to draw the player's car
def draw_car(x, y):
win.blit(pygame.transform.scale(car_img, (car_width, car_height)), (x, y))
# Function to draw obstacles
def draw_obstacle(x, y, w, h, color):
pygame.draw.rect(win, color, [x, y, w, h])
# Main game loop
def game_loop():
x = (width * 0.45)
y = (height * 0.8)
x_change = 0
speed = 5
# Obstacle settings
obs_width = 100
obs_height = 100
obs_x = random.randrange(0, width - obs_width)
obs_y = -600
obs_speed = 7
crashed = False
while not crashed:
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 = -speed
elif event.key == pygame.K_RIGHT:
x_change = speed
if event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
x_change = 0
x += x_change
win.fill(white)
# Draw obstacle and car
draw_obstacle(obs_x, obs_y, obs_width, obs_height, red)
obs_y += obs_speed
draw_car(x, y)
# Collision detection
if y < obs_y + obs_height:
if (x > obs_x and x < obs_x + obs_width) or (x + car_width > obs_x and x + car_width < obs_x + obs_width):
print("Crashed!")
crashed = True
# Respawn obstacle
if obs_y > height:
obs_y = 0 - obs_height
obs_x = random.randrange(0, width - obs_width)
# Boundaries
if x < 0 or x > width - car_width:
crashed = True
pygame.display.update()
clock.tick(60)
pygame.quit()
# Run the game
game_loop()
Comments
Post a Comment