Sure, let's create a simple game called "Fruit Collector" using the Pygame library. This game will involve a moving character collecting fruits as they appear on the screen. Here's the code:
python
import pygame
import random
pygame.init()
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Set the dimensions of the screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# Set the title of the screen
pygame.display.set_caption("Fruit Collector")
# Create the player
player_image = pygame.image.load("player.png")
player_x = 370
player_y = 500
player_speed = 5
# Create the fruit
fruit_image = pygame.image.load("fruit.png")
fruit_x = random.randint(0, screen_width - fruit_image.get_width())
fruit_y = random.randint(0, screen_height - fruit_image.get_height())
fruit_speed_x = 5
fruit_speed_y = 5
# Create the score
score = 0
font = pygame.font.Font(None, 30)
text = font.render("Score: " + str(score), True, WHITE)
text_x = 10
text_y = 10
# Game loop
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Move the player left/right
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
# Check for fruit collision
if player_x < fruit_x + fruit_image.get_width() and \
player_x + player_image.get_width() > fruit_x and \
player_y < fruit_y + fruit_image.get_height() and \
player_y + player_image.get_height() > fruit_y:
score += 1
fruit_x = random.randint(0, screen_width - fruit_image.get_width())
fruit_y = random.randint(0, screen_height - fruit_image.get_height())
# Move the player
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= player_speed
if keys[pygame.K_RIGHT]:
player_x += player_speed
player_y += 1
# Move the fruit
fruit_x += fruit_speed_x
fruit_y += fruit_speed_y
# Draw everything
screen.fill(BLACK)
screen.blit(player_image, (player_x, player_y))
screen.blit(fruit_image, (fruit_x, fruit_y))
screen.blit(text, (text_x, text_y))
pygame.display.update()
pygame.quit()
To run the game, save the code in a Python file (e.g., "fruit_collector.py") and make sure you have the "player.png" and "fruit.png" image files in the same directory. Then, open a terminal or command prompt, navigate to the directory containing the Python file, and run the following command:
code
python fruit_collector.py
This will start the game, and you can use the left and right arrow keys to move the player character and collect the fruits for points. The game will continue until you quit the game by clicking the "X" button on the window or pressing the "ESC" key.