```python
import pygame
import sys
import random
初始化pygame
pygame.init()
设置游戏界面大小
size = (640, 480)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("打砖块游戏")
定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
定义挡板
baffle_width = 100
baffle_height = 20
baffle_x = (size - baffle_width) // 2
baffle_y = size - baffle_height
baffle_speed = 5
定义小球
ball_radius = 10
ball_x = (size - ball_radius) // 2
ball_y = (size - ball_radius) // 2
ball_dx = random.randint(-3, 3)
ball_dy = -3
定义砖块
brick_width = 50
brick_height = 20
bricks = []
brick_x = []
brick_y = []
brick_speed = 1
游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
更新挡板位置
baffle_y += baffle_speed
if baffle_y >= size:
baffle_y = size - baffle_height
baffle_x = (size - baffle_width) // 2
更新小球位置
ball_x += ball_dx
ball_y += ball_dy
检测小球与挡板的碰撞
if baffle_x <= ball_x <= baffle_x + baffle_width and baffle_y <= ball_y <= baffle_y + baffle_height:
ball_dx = -ball_dx
ball_dy = -2 * ball_dy
检测小球与砖块的碰撞
for i in range(len(bricks)):
if ball_x + ball_radius >= brick_x[i] and ball_x - ball_radius <= brick_x[i] + brick_width and ball_y + ball_radius >= brick_y[i] and ball_y - ball_radius <= brick_y[i] + brick_height:
bricks.pop(i)
brick_x.pop(i)
brick_y.pop(i)
break
绘制游戏界面
screen.fill(black)
pygame.draw.rect(screen, white, (baffle_x, baffle_y, baffle_width, baffle_height))
pygame.draw.circle(screen, red, (ball_x, ball_y), ball_radius)
for i in range(len(bricks)):
pygame.draw.rect(screen, white, (brick_x[i], brick_y[i], brick_width, brick_height))
pygame.display.update()
```
代码解析:
初始化
初始化Pygame库。
设置游戏界面大小和标题。
定义变量
挡板的位置、宽度、高度和速度。
小球的位置、半径、速度和移动方向。
砖块的位置、宽度、高度和速度。
游戏主循环
处理退出事件。
更新挡板和小球的位置。
检测小球与挡板的碰撞,使小球反弹。
检测小球与砖块的碰撞,消除砖块。
绘制游戏界面。
运行代码:
1. 确保已安装Pygame库,可以使用以下命令安装:
```bash
pip install pygame
```
2. 将上述代码保存为一个Python文件(例如`brick_breaker.py`),然后在命令行中运行:
```bash
python brick_breaker.py
```
这样就可以运行一个简单的打砖