pygame小游戏代码
时间: 2023-07-09 07:49:48 浏览: 122
Python小游戏源码大全,40个小游戏源代码.zip
5星 · 资源好评率100%
以下是一个用Pygame编写的简单的打砖块游戏的代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置游戏界面大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏标题
pygame.display.set_caption("打砖块游戏")
# 定义颜色变量
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
# 定义小球变量
ball_size = 10
ball_speed = [5, 5]
ball_pos = [screen_width // 2, screen_height // 2]
# 定义挡板变量
paddle_width = 75
paddle_height = 15
paddle_speed = 0
paddle_pos = [(screen_width - paddle_width) // 2, screen_height - paddle_height - 10]
# 定义砖块变量
brick_width = 60
brick_height = 15
brick_gap = 5
brick_colors = [red, blue]
brick_rows = 5
brick_cols = 8
bricks = []
# 创建砖块
for row in range(brick_rows):
row_bricks = []
for col in range(brick_cols):
brick_x = col * (brick_width + brick_gap)
brick_y = row * (brick_height + brick_gap)
brick_color = brick_colors[row // (brick_rows // 2)]
row_bricks.append(pygame.Rect(brick_x, brick_y, brick_width, brick_height))
bricks.append(row_bricks)
# 定义游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
paddle_speed = -5
elif event.key == pygame.K_RIGHT:
paddle_speed = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
paddle_speed = 0
# 移动挡板
paddle_pos[0] += paddle_speed
if paddle_pos[0] < 0:
paddle_pos[0] = 0
elif paddle_pos[0] > screen_width - paddle_width:
paddle_pos[0] = screen_width - paddle_width
# 移动小球
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
if ball_pos[0] < ball_size or ball_pos[0] > screen_width - ball_size:
ball_speed[0] = -ball_speed[0]
if ball_pos[1] < ball_size:
ball_speed[1] = -ball_speed[1]
elif ball_pos[1] > screen_height - ball_size:
game_over = True
# 检测小球是否碰到挡板
if ball_pos[1] > screen_height - ball_size - paddle_height and \
paddle_pos[0] <= ball_pos[0] <= paddle_pos[0] + paddle_width:
ball_speed[1] = -ball_speed[1]
# 检测小球是否碰到砖块
for row in range(brick_rows):
for col in range(brick_cols):
brick_rect = bricks[row][col]
if ball_pos[1] - ball_size < brick_rect.bottom and \
ball_pos[1] + ball_size > brick_rect.top and \
ball_pos[0] + ball_size > brick_rect.left and \
ball_pos[0] - ball_size < brick_rect.right:
ball_speed[1] = -ball_speed[1]
bricks[row][col] = None
# 绘制游戏界面
screen.fill(black)
pygame.draw.circle(screen, white, ball_pos, ball_size)
pygame.draw.rect(screen, white, (paddle_pos[0], paddle_pos[1], paddle_width, paddle_height))
for row in range(brick_rows):
for col in range(brick_cols):
if bricks[row][col]:
pygame.draw.rect(screen, brick_colors[row // (brick_rows // 2)], bricks[row][col])
pygame.display.update()
# 退出Pygame
pygame.quit()
```
运行代码后,可以控制挡板左右移动并击打小球,尝试打掉所有砖块即可获胜。
阅读全文