用python使用pygame写弹珠的小游戏
时间: 2024-01-27 13:04:04 浏览: 159
当然可以!以下是一个简单的弹珠游戏实现代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
WIDTH = 480
HEIGHT = 600
FPS = 60
# 设置屏幕大小
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("弹珠小游戏")
# 设置时钟对象,控制游戏帧率
clock = pygame.time.Clock()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
# 定义球、挡板的属性
BALL_RADIUS = 10
BALL_COLOR = RED
BALL_SPEED = 5
PAD_WIDTH = 80
PAD_HEIGHT = 10
PAD_COLOR = GREEN
PAD_SPEED = 5
# 创建球、挡板对象
ball_pos = [WIDTH/2, HEIGHT/2]
ball_vel = [random.randint(-BALL_SPEED, BALL_SPEED), random.randint(-BALL_SPEED, BALL_SPEED)]
pad_pos = [WIDTH/2 - PAD_WIDTH/2, HEIGHT - PAD_HEIGHT - 10]
pad_vel = [0, 0]
# 定义绘制球的函数
def draw_ball(ball_pos):
pygame.draw.circle(screen, BALL_COLOR, ball_pos, BALL_RADIUS)
# 定义绘制挡板的函数
def draw_pad(pad_pos):
pygame.draw.rect(screen, PAD_COLOR, (pad_pos[0], pad_pos[1], PAD_WIDTH, PAD_HEIGHT))
# 游戏循环
running = True
while running:
# 控制游戏帧率
clock.tick(FPS)
# 处理事件队列
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pad_vel[0] = -PAD_SPEED
elif event.key == pygame.K_RIGHT:
pad_vel[0] = PAD_SPEED
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and pad_vel[0] == -PAD_SPEED:
pad_vel[0] = 0
elif event.key == pygame.K_RIGHT and pad_vel[0] == PAD_SPEED:
pad_vel[0] = 0
# 更新球的位置
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# 碰到边界反弹
if ball_pos[0] < BALL_RADIUS or ball_pos[0] > WIDTH - BALL_RADIUS:
ball_vel[0] = -ball_vel[0]
if ball_pos[1] < BALL_RADIUS:
ball_vel[1] = -ball_vel[1]
if ball_pos[1] > HEIGHT - BALL_RADIUS:
running = False
# 更新挡板的位置
pad_pos[0] += pad_vel[0]
# 碰到边界停止
if pad_pos[0] < 0:
pad_pos[0] = 0
if pad_pos[0] > WIDTH - PAD_WIDTH:
pad_pos[0] = WIDTH - PAD_WIDTH
# 碰到挡板反弹
if ball_pos[1] > HEIGHT - BALL_RADIUS - PAD_HEIGHT and ball_pos[0] >= pad_pos[0] and ball_pos[0] <= pad_pos[0] + PAD_WIDTH:
ball_vel[1] = -ball_vel[1]
# 清屏
screen.fill(BLACK)
# 绘制球、挡板
draw_ball(ball_pos)
draw_pad(pad_pos)
# 更新屏幕
pygame.display.update()
# 退出 Pygame
pygame.quit()
```
运行代码后,你就可以玩到一个简单的弹珠小游戏啦!
阅读全文