import pygame import sys import random # Initialize pygame pygame.init() # Set up the screen screen_width = 800 screen_height = 400 screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("2D Drag Racing") # Define colors WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # Define the car car_width = 50 car_height = 100 car_x = 50 car_y = screen_height // 2 - car_height // 2 car_speed = 0 # Define the opponent car opponent_width = 50 opponent_height = 100 opponent_x = screen_width - 50 - opponent_width opponent_y = screen_height // 2 - opponent_height // 2 opponent_speed = random.randint(5, 10) # Define game variables score = 0 clock = pygame.time.Clock() # Load images car_image = pygame.image.load("car.png") car_image = pygame.transform.scale(car_image, (car_width, car_height)) opponent_image = pygame.image.load("opponent_car.png") opponent_image = pygame.transform.scale(opponent_image, (opponent_width, opponent_height)) # Game loop while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Handle key presses if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: car_speed = 5 elif event.key == pygame.K_DOWN: car_speed = -5 # Handle key releases if event.type == pygame.KEYUP: if event.key == pygame.K_UP or event.key == pygame.K_DOWN: car_speed = 0 # Update car position car_y += car_speed # Update opponent car position opponent_y += opponent_speed # Check for collisions if car_y < 0 or car_y + car_height > screen_height: score -= 10 car_y = screen_height // 2 - car_height // 2 if opponent_y < 0 or opponent_y + opponent_height > screen_height: score += 10 opponent_y = screen_height // 2 - opponent_height // 2 opponent_speed = random.randint(5, 10) # Check for overlap if car_x < opponent_x + opponent_width and car_x + car_width > opponent_x and car_y < opponent_y + opponent_height and car_y + car_height > opponent_y: score -= 50 car_y = screen_height // 2 - car_height // 2 # Draw the background screen.fill(WHITE) # Draw the car screen.blit(car_image, (car_x, car_y)) # Draw the opponent car screen.blit(opponent_image, (opponent_x, opponent_y)) # Draw the score font = pygame.font.SysFont(None, 30) score_text = font.render("Score: " + str(score), True, GREEN) screen.blit(score_text, (10, 10)) # Update the display pygame.display.flip() # Set the frame rate clock.tick(60)
Please note that this code assumes you have two images for the car and the opponent car, named "car.png" and "opponent_car.png" respectively, located in the same directory as the Python script. Also, make sure you have the Pygame library installed (pip install pygame) before running the code.
This is a simple implementation to get you started. You can enhance it by adding acceleration, sound effects, lap times, and other features according to your preferences