帮我用python做一个150行代码的跳箱子小游戏
时间: 2024-01-28 13:03:21 浏览: 29
好的,我可以为您提供一个基本的跳箱子小游戏的代码,但是可能需要更多的行数来完善游戏的功能和美化游戏界面。以下是一个简单的跳箱子小游戏的代码:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 定义游戏窗口的大小
WIDTH = 800
HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置游戏窗口标题
pygame.display.set_caption("跳箱子小游戏")
# 加载游戏背景图片
background = pygame.image.load("background.jpg")
# 加载箱子图片
box = pygame.image.load("box.png")
# 设置箱子的初始位置
box_x = 350
box_y = 500
# 设置箱子的大小
box_width = 50
box_height = 50
# 设置箱子的移动速度
box_speed = 10
# 定义跳板类
class Platform:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
# 绘制跳板
def draw(self):
pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.width, self.height))
# 检查箱子是否和跳板碰撞
def collide(self, box_x, box_y, box_width, box_height):
if box_x + box_width > self.x and box_x < self.x + self.width:
if box_y + box_height > self.y and box_y < self.y + self.height:
return True
return False
# 定义跳板列表
platforms = []
# 添加初始的跳板
platforms.append(Platform(300, 400, 200, 20))
# 定义游戏是否结束的变量
game_over = False
# 定义分数变量
score = 0
# 设置游戏字体
font = pygame.font.Font(None, 30)
# 游戏循环
while not game_over:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 绘制游戏背景
screen.blit(background, (0, 0))
# 绘制分数
score_text = font.render("分数:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 绘制箱子
screen.blit(box, (box_x, box_y))
# 检查箱子是否和跳板碰撞
on_platform = False
for platform in platforms:
if platform.collide(box_x, box_y, box_width, box_height):
on_platform = True
break
# 如果箱子在跳板上,则可以跳跃
if on_platform:
if pygame.key.get_pressed()[pygame.K_SPACE]:
box_speed = -20
else:
box_speed += 1
# 移动箱子
box_y += box_speed
# 如果箱子落到了屏幕下面,游戏结束
if box_y > HEIGHT:
game_over = True
# 绘制跳板
for platform in platforms:
platform.draw()
# 添加新的跳板
if len(platforms) < 5:
x = random.randint(0, WIDTH - 100)
y = random.randint(-50, -20)
width = random.randint(50, 150)
height = 20
platforms.append(Platform(x, y, width, height))
# 检查箱子是否和跳板碰撞,如果碰撞了则加分
for platform in platforms:
if platform.collide(box_x, box_y, box_width, box_height):
score += 1
platforms.remove(platform)
break
# 更新游戏窗口
pygame.display.update()
# 退出游戏
pygame.quit()
```
注:此代码仅供参考,可能需要根据您的需求进行修改和完善。