After our introduction of pygame python module Here's an example of a simple game using the Pygame module in Python. This game is a basic "catch the falling objects" game, where the player controls a paddle at the bottom of the screen to catch falling balls.
```python
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up the game window
window_width = 800
window_height = 600
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Falling Balls Game")
# Set up colors
black = (0, 0, 0)
white = (255, 255, 255)
# Set up the paddle
paddle_width = 100
paddle_height = 20
paddle_x = (window_width - paddle_width) // 2
paddle_y = window_height - paddle_height - 10
paddle_speed = 5
# Set up the ball
ball_radius = 10
ball_x = random.randint(ball_radius, window_width - ball_radius)
ball_y = 50
ball_speed = 3
# Game loop
running = True
clock = pygame.time.Clock()
while running:
# Process events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Move the paddle
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle_x -= paddle_speed
if keys[pygame.K_RIGHT]:
paddle_x += paddle_speed
# Update the ball position
ball_y += ball_speed
# Check collision with the paddle
if ball_y + ball_radius >= paddle_y and paddle_x - ball_radius <= ball_x <= paddle_x + paddle_width + ball_radius:
ball_speed = -ball_speed
# Check if the ball falls off the screen
if ball_y > window_height:
ball_x = random.randint(ball_radius, window_width - ball_radius)
ball_y = 50
# Clear the screen
window.fill(black)
# Draw the paddle
pygame.draw.rect(window, white, (paddle_x, paddle_y, paddle_width, paddle_height))
# Draw the ball
pygame.draw.circle(window, white, (ball_x, ball_y), ball_radius)
# Update the display
pygame.display.update()
# Limit the frame rate
clock.tick(60)
# Quit the game
pygame.quit()
```
This code sets up a game window, a paddle, and a ball. The player controls the paddle using the left and right arrow keys, and the goal is to catch the falling ball with the paddle. If the ball falls off the screen, a new ball is randomly positioned at the top. The game loop updates the positions of the paddle and the ball, checks for collisions, and redraws the game objects on the screen. The frame rate is limited to 60 frames per second.
0 Comments