Here's a simple 2D game in Python using the Pygame library. The game has a background with random colors, with a random path of lower color strength. The player can control a square using the arrow keys.
Please note that this is a very basic game and doesn't include advanced features like collision detection or a scoring system.
Here is the code:
import pygame
import random
# Initialize Pygame
pygame.init()
# Set the window size
WINDOW_SIZE = (800, 600)
# Set the colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# Create the window
screen = pygame.display.set_mode(WINDOW_SIZE)
# Set the title of the window
pygame.display.set_caption("Random Color Game")
# Set the player's starting position
player_position = [WINDOW_SIZE[0] / 2, WINDOW_SIZE[1] / 2]
# Set the player's size
player_size = 50
# Set the player's speed
player_speed = 5
# Set the path's size
path_size = 20
# Set the path's speed
path_speed = 2
# Set the path's direction
path_direction = "right"
# Set the path's starting position
path_position = [WINDOW_SIZE[0] - path_size, WINDOW_SIZE[1] / 2]
# Set the path's color
path_color = (255, 0, 0)
# Set the background color
background_color = (0, 0, 0)
# Set the game loop
run = True
while run:
# Fill the screen with the background color
screen.fill(background_color)
# Draw the player
pygame.draw.rect(screen, WHITE, pygame.Rect(player_position[0] - player_size / 2, player_position[1] - player_size / 2, player_size, player_size))
# Draw the path
pygame.draw.rect(screen, path_color, pygame.Rect(path_position[0] - path_size / 2, path_position[1] - path_size / 2, path_size, path_size))
# Update the path's position
if path_direction == "right":
path_position[0] -= path_speed
else:
path_position[0] += path_speed
# Check if the path has reached the edge of the screen
if path_position[0] < -path_size / 2 or path_position[0] > WINDOW_SIZE[0] + path_size / 2:
# Change the path's direction
path_direction = "left" if path_direction == "right" else "right"
# Handle events
for event in pygame.event.get():
# Check if the user has closed the window
if event.type == pygame.QUIT:
run = False
# Check if the user has pressed a key
if event.type == pygame.KEYDOWN:
# Check if the user has pressed the left arrow key
if event.key == pygame.K_LEFT:
player_position[0] -= player_speed
# Check if the user has pressed the right arrow key
if event.key == pygame.K_RIGHT:
player_position[0] += player_speed
# Check if the user has pressed the up arrow key
if event.key == pygame.K_UP:
player_position[1] -= player_speed
# Check if the user has pressed the down arrow key
if event.key == pygame.K_DOWN:
player_position[1] += player_speed
# Update the screen
pygame.display.update()
# Quit Pygame
pygame.quit()
This code creates a window with a random background color and a path moving from left to right. The player can control a square using the arrow keys. The path changes direction when it reaches the edge of the window. The game ends when the user closes the window.