''' Write a python code for a simple car racing game. ''' import pygame import random # Initialize pygame pygame.init() # Set screen dimensions screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # Load images car_img = pygame.image.load("car.png") car_width = 80 car_height = 160 # Set up game clock clock = pygame.time.Clock() # Define functions def draw_car(x, y): screen.blit(car_img, (x, y)) def display_score(score): font = pygame.font.SysFont(None, 25) text = font.render("Score: " + str(score), True, (0, 0, 0)) screen.blit(text, (0, 0)) def message_display(text): font = pygame.font.SysFont(None, 50) message = font.render(text, True, (255, 0, 0)) screen.blit(message, (screen_width/2 - message.get_width()/2, screen_height/2 - message.get_height()/2)) pygame.display.update() pygame.time.delay(2000) def game_loop(): # Initialize car position x = screen_width / 2 - car_width / 2 y = screen_height - car_height - 10 # Initialize block position and speed block_width = 100 block_height = 100 block_x = random.randrange(0, screen_width - block_width) block_y = -block_height block_speed = 5 # Initialize score score = 0 # Start game loop game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True # Move car left or right keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and x > 0: x -= 5 if keys[pygame.K_RIGHT] and x < screen_width - car_width: x += 5 # Move block down block_y += block_speed # Check for collision if y < block_y + block_height: if x < block_x + block_width and x + car_width > block_x: message_display("Game Over") game_over = True # If block reaches bottom, reset position and increase score if block_y > screen_height: block_y = -block_height block_x = random.randrange(0, screen_width - block_width) score += 1 block_speed += 1 # Clear screen and draw objects screen.fill((255, 255, 255)) draw_car(x, y) pygame.draw.rect(screen, (0, 0, 0), (block_x, block_y, block_width, block_height)) display_score(score) # Update display and limit to 60 FPS pygame.display.update() clock.tick(60) # Quit pygame and exit pygame.quit() quit() # Start game game_loop()