用python写个弹球小游戏
时间: 2024-01-26 22:12:04 浏览: 210
以下是用Python实现的弹球小游戏的代码和说明:
```python
# 引入必要的库
import pygame
import random
# 初始化pygame
pygame.init()
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (50, 153, 213)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置游戏标题
pygame.display.set_caption("弹球小游戏")
# 定义球的类
class Ball:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.speed_x = random.randint(3, 6)
self.speed_y = random.randint(3, 6)
def draw(self):
pygame.draw.circle(screen, self.color, [self.x, self.y], self.radius)
def move(self):
self.x += self.speed_x
self.y += self.speed_y
# 碰到左右边界反弹
if self.x < self.radius or self.x > SCREEN_WIDTH - self.radius:
self.speed_x = -self.speed_x
# 碰到上边界反弹
if self.y < self.radius:
self.speed_y = -self.speed_y
# 碰到下边界游戏结束
if self.y > SCREEN_HEIGHT - self.radius:
return True
return False
# 定义挡板的类
class Paddle:
def __init__(self, x, y, width, height, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = color
self.speed = 0
def draw(self):
pygame.draw.rect(screen, self.color, [self.x, self.y, self.width, self.height])
def move(self):
self.x += self.speed
# 碰到左右边界停止移动
if self.x < 0:
self.x = 0
elif self.x > SCREEN_WIDTH - self.width:
self.x = SCREEN_WIDTH - self.width
# 创建球和挡板对象
ball = Ball(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, 10, WHITE)
paddle = Paddle(SCREEN_WIDTH // 2 - 50, SCREEN_HEIGHT - 20, 100, 10, GREEN)
# 设置游戏时钟
clock = pygame.time.Clock()
# 游戏循环
done = False
while not done:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = 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
# 清屏
screen.fill(BLACK)
# 移动球和挡板
if ball.move():
done = True
paddle.move()
# 绘制球和挡板
ball.draw()
paddle.draw()
# 碰撞检测
if ball.y + ball.radius >= paddle.y and ball.x >= paddle.x and ball.x <= paddle.x + paddle.width:
ball.speed_y = -ball.speed_y
# 更新屏幕
pygame.display.flip()
# 设置游戏帧率
clock.tick(60)
# 退出游戏
pygame.quit()
```
阅读全文