用python设计一款基于 Pygame 包的小游戏
时间: 2023-12-19 22:07:46 浏览: 219
基于python+pygame编写的小游戏外星人入侵源码+项目说明+代码注释(课程大作业).zip
5星 · 资源好评率100%
好的,我可以为您提供一个简单的游戏示例,使用 Python 和 Pygame 包开发。这个游戏是一个简单的弹球游戏,玩家需要控制一个板来反弹球,并尽可能地打破所有砖块。下面是游戏的主要代码:
```python
import pygame
import random
# 游戏窗口大小
WINDOW_WIDTH = 480
WINDOW_HEIGHT = 600
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化 Pygame
pygame.init()
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# 设置游戏标题
pygame.display.set_caption('弹球游戏')
# 游戏帧率
clock = pygame.time.Clock()
FPS = 60
# 定义球的属性
ball_pos = [WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2]
ball_radius = 10
ball_color = WHITE
ball_speed = [5, 5]
# 定义板的属性
paddle_pos = [WINDOW_WIDTH // 2, WINDOW_HEIGHT - 50]
paddle_size = [100, 10]
paddle_color = BLUE
paddle_speed = 10
# 定义砖块的属性
brick_width = 60
brick_height = 20
brick_color = GREEN
brick_gap = 10
brick_cols = 7
brick_rows = 5
bricks = []
for i in range(brick_cols):
for j in range(brick_rows):
brick_pos = [i * (brick_width + brick_gap) + brick_gap, j * (brick_height + brick_gap) + brick_gap]
bricks.append(pygame.Rect(brick_pos[0], brick_pos[1], brick_width, brick_height))
# 游戏主循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 移动球
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# 碰撞检测
if ball_pos[0] < ball_radius or ball_pos[0] > WINDOW_WIDTH - ball_radius:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < ball_radius:
ball_speed[1] = -ball_speed[1]
if ball_pos[1] > WINDOW_HEIGHT - ball_radius:
running = False
ball_rect = pygame.Rect(ball_pos[0] - ball_radius, ball_pos[1] - ball_radius, ball_radius * 2, ball_radius * 2)
paddle_rect = pygame.Rect(paddle_pos[0] - paddle_size[0] // 2, paddle_pos[1] - paddle_size[1] // 2, paddle_size[0], paddle_size[1])
if ball_rect.colliderect(paddle_rect):
ball_speed[1] = -ball_speed[1]
ball_pos[1] = paddle_pos[1] - ball_radius - paddle_size[1] // 2
for brick in bricks:
if ball_rect.colliderect(brick):
bricks.remove(brick)
ball_speed[1] = -ball_speed[1]
break
# 移动板
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and paddle_pos[0] > paddle_size[0] // 2:
paddle_pos[0] -= paddle_speed
if keys[pygame.K_RIGHT] and paddle_pos[0] < WINDOW_WIDTH - paddle_size[0] // 2:
paddle_pos[0] += paddle_speed
# 绘制游戏界面
window.fill(BLACK)
pygame.draw.circle(window, ball_color, ball_pos, ball_radius)
pygame.draw.rect(window, paddle_color, (paddle_pos[0] - paddle_size[0] // 2, paddle_pos[1] - paddle_size[1] // 2, paddle_size[0], paddle_size[1]))
for brick in bricks:
pygame.draw.rect(window, brick_color, brick)
pygame.display.update()
# 控制游戏帧率
clock.tick(FPS)
# 退出 Pygame
pygame.quit()
```
这个游戏使用了 Pygame 提供的各种函数和对象,包括游戏窗口、图形绘制、键盘输入、游戏循环等。玩家可以使用左右箭头键控制板的移动,用板来反弹球,并尽可能地打破所有砖块。希望这个示例可以为您提供一些参考!
阅读全文