Simple brick breaker
Here's a simple implementation of the classic game Brick Breaker in Python using the Pygame library:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH = 800
HEIGHT = 600
BALL_RADIUS = 20
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 20
BRICK_WIDTH = 80
BRICK_HEIGHT = 30
BRICKS_PER_ROW = 10
BRICKS_PER_COLUMN = 5
BRICKS_COLOR = (255, 0, 0)
PADDLE_COLOR = (0, 0, 0)
BALL_COLOR = (255, 255, 255)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Set up the font
font = pygame.font.Font(None, 36)
# Set up the ball
ball_x = WIDTH / 2
ball_y = HEIGHT / 2
ball_speed_x = 5
ball_speed_y = 5
# Set up the paddle
paddle_x = (WIDTH - PADDLE_WIDTH) / 2
paddle_y = HEIGHT - PADDLE_HEIGHT - 20
# Set up the bricks
bricks = []
for i in range(BRICKS_PER_COLUMN):
row = []
for j in range(BRICKS_PER_ROW):
row.append((j * (BRICK_WIDTH + 5) + 5, i * (BRICK_HEIGHT + 5) + 5))
bricks.append(row)
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Move the paddle
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
paddle_x -= 5
if keys[pygame.K_RIGHT]:
paddle_x += 5
# Move the ball
ball_x += ball_speed_x
ball_y += ball_speed_y
# Check for collisions with the paddle
if ball_y + BALL_RADIUS > paddle_y and ball_x > paddle_x and ball_x < paddle_x + PADDLE_WIDTH:
ball_speed_y = -ball_speed_y
# Check for collisions with the top of the screen
if ball_y - BALL_RADIUS < 0:
ball_speed_y = -ball_speed_y
# Check for collisions with the bottom of the screen
if ball_y + BALL_RADIUS > HEIGHT:
print("Game Over")
pygame.quit()
sys.exit()
# Check for collisions with the left or right of the screen
if ball_x - BALL_RADIUS < 0 or ball_x + BALL_RADIUS > WIDTH:
ball_speed_x = -ball_speed_x
# Check for collisions with the bricks
for row in bricks:
for brick in row:
if ball_x - BALL_RADIUS < brick[0] + BRICK_WIDTH and ball_x + BALL_RADIUS > brick[0] and ball_y - BALL_RADIUS < brick[1] + BRICK_HEIGHT and ball_y + BALL_RADIUS > brick[1]:
ball_speed_y = -ball_speed_y
bricks.remove([brick])
break
if not bricks:
break
# Draw everything
screen.fill((0, 0, 0))
for row in bricks:
for brick in row:
pygame.draw.rect(screen, BRICKS_COLOR, (brick[0], brick[1], BRICK_WIDTH, BRICK_HEIGHT))
pygame.draw.rect(screen, PADDLE_COLOR, (paddle_x, paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT))
pygame.draw.circle(screen, BALL_COLOR, (int(ball_x), int(ball_y)), BALL_RADIUS)
pygame.display.flip()
This code creates a window with a paddle at the bottom and a ball bouncing around. The ball will bounce off the paddle and the top and bottom of the screen, and it will also destroy bricks when it hits them. The game ends when the ball hits the bottom of the screen.