import pygame, random, sys # Initialize pygame pygame.init() # Game constants SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 WHITE = (255, 255, 255) RED = (200, 0, 0) BLUE = (0, 0, 255) ROAD_COLOR = (50, 50, 50) # Set up display screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Traffic Rider") clock = pygame.time.Clock() # Load assets player_img = pygame.image.load('Pygame Tasks/pikachu.png') # Load a bike image player_img = pygame.transform.scale(player_img, (50, 100)) # Player setup player = pygame.Rect(375, 500, 50, 100) player_speed = 5 # Traffic setup traffic_cars = [] car_width, car_height = 50, 100 car_speed = 5 spawn_timer = 0 spawn_delay = 30 # Frames before a new car spawns # Score setup score = 0 font = pygame.font.Font(None, 36) def draw_objects(): screen.fill(ROAD_COLOR) screen.blit(player_img, (player.x, player.y)) for car in traffic_cars: pygame.draw.rect(screen, RED, car) score_text = font.render(f"Score: {score}", True, WHITE) screen.blit(score_text, (10, 10)) def move_traffic(): global score for car in traffic_cars: car.y += car_speed if car.top > SCREEN_HEIGHT: traffic_cars.remove(car) score += 1 # Increase score when a car passes def check_collisions(): for car in traffic_cars: if player.colliderect(car): return True return False # Game loop running = True while running: clock.tick(60) # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Player movement keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and player.left > 200: player.x -= player_speed if keys[pygame.K_RIGHT] and player.right < 600: player.x += player_speed # Spawn traffic cars spawn_timer += 1 if spawn_timer >= spawn_delay: spawn_timer = 0 car_x = random.choice([250, 350, 450, 550]) traffic_cars.append(pygame.Rect(car_x, -100, car_width, car_height)) move_traffic() if check_collisions(): print("Game Over!") pygame.quit() sys.exit() draw_objects() pygame.display.update() pygame.quit()