Cool brick breaker
A classic!
Here's a simple implementation of a Brick Breaker game in Python using the Pygame library:
Code:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH, HEIGHT = 640, 480
BRICK_WIDTH, BRICK_HEIGHT = 60, 20
PADDLE_WIDTH, PADDLE_HEIGHT = 100, 20
BALL_SIZE = 10
# Set up some colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Set up the paddle
paddle = pygame.Rect(WIDTH / 2, HEIGHT - PADDLE_HEIGHT - 20, PADDLE_WIDTH, PADDLE_HEIGHT)
# Set up the ball
ball = pygame.Rect(WIDTH / 2, HEIGHT / 2, BALL_SIZE, BALL_SIZE)
ball_x_speed = 5
ball_y_speed = 5
# Set up the bricks
bricks = []
for i in range(5):
for j in range(10):
brick = pygame.Rect(j * (BRICK_WIDTH + 5), i * (BRICK_HEIGHT + 5), BRICK_WIDTH, BRICK_HEIGHT)
bricks.append(brick)
# Game loop
while True:
# Handle events
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_x_speed
ball.y += ball_y_speed
# Collision with paddle
if ball.colliderect(paddle):
ball_y_speed = -ball_y_speed
# Collision with bricks
for brick in bricks:
if ball.colliderect(brick):
ball_y_speed = -ball_y_speed
bricks.remove(brick)
# Collision with edges
if ball.y < 0:
ball_y_speed = -ball_y_speed
if ball.y > HEIGHT - BALL_SIZE:
ball_y_speed = -ball_y_speed
if ball.x < 0:
ball_x_speed = -ball_x_speed
if ball.x > WIDTH - BALL_SIZE:
ball_x_speed = -ball_x_speed
# Draw everything
screen.fill(WHITE)
pygame.draw.rect(screen, RED, paddle)
pygame.draw.rect(screen, RED, ball)
for brick in bricks:
pygame.draw.rect(screen, RED, brick)
# Update the display
pygame.display.flip()
pygame.time.Clock().tick(60)
How to play:
- Run the code using Python (e.g.,
python brick_breaker.py
). - Use the left and right arrow keys to move the paddle.
- Hit the bricks with the ball to break them.
- Try to clear all the bricks to win!
Note: This is a very basic implementation, and you can add features like scoring, power-ups, and smoother animations to make the game more engaging.