python写一个地铁跑酷小游戏,要求:有九个不同位置的障碍物,越过九个障碍物才能到达终点。固定地点生产金币,每收获一枚金币获得50积分,到达终点并且累计收集999积分以上即为游戏胜利,否则游戏失败。
时间: 2023-11-11 21:03:20 浏览: 106
好的,这是一个满足要求的地铁跑酷小游戏的Python代码:
```python
import pygame
import random
# 初始化pygame模块
pygame.init()
# 设置游戏窗口大小
WIDTH = 800
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置游戏标题
pygame.display.set_caption("地铁跑酷")
# 加载游戏素材
player_img = pygame.image.load("player.png").convert_alpha()
player_rect = player_img.get_rect()
player_rect.bottom = HEIGHT - 50
player_rect.left = 50
obstacle_img = pygame.image.load("obstacle.png").convert_alpha()
coin_img = pygame.image.load("coin.png").convert_alpha()
# 设置游戏参数
score = 0
obstacle_list = []
passed_obstacle = 0
coin_rect = coin_img.get_rect()
coin_rect.bottom = HEIGHT - 100
coin_rect.left = WIDTH
# 设置游戏字体
font = pygame.font.SysFont(None, 48)
# 游戏主循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player_rect.top -= 100
# 更新游戏状态
score += 1
# 添加障碍物
if len(obstacle_list) < 9:
if random.randint(1, 100) > 90:
obstacle_rect = obstacle_img.get_rect()
obstacle_rect.bottom = HEIGHT - 50
obstacle_rect.left = WIDTH
obstacle_list.append(obstacle_rect)
else:
if random.randint(1, 100) > 80:
obstacle_rect = obstacle_img.get_rect()
obstacle_rect.bottom = HEIGHT - 50
obstacle_rect.left = WIDTH
obstacle_list.append(obstacle_rect)
# 添加金币
if coin_rect.right < 0:
coin_rect.bottom = random.randint(HEIGHT // 2, HEIGHT - 50)
coin_rect.left = WIDTH
# 移动障碍物和金币
coin_rect.left -= 5
for obstacle_rect in obstacle_list:
obstacle_rect.left -= 5
if obstacle_rect.right < 0:
obstacle_list.remove(obstacle_rect)
elif obstacle_rect.left < player_rect.right and obstacle_rect.right > player_rect.left and obstacle_rect.bottom > player_rect.top:
passed_obstacle += 1
score += 50
# 碰撞检测
for obstacle_rect in obstacle_list:
if player_rect.colliderect(obstacle_rect):
running = False
if player_rect.colliderect(coin_rect):
score += 50
coin_rect.right = 0
# 绘制游戏场景
screen.fill((255, 255, 255))
screen.blit(player_img, player_rect)
for obstacle_rect in obstacle_list:
screen.blit(obstacle_img, obstacle_rect)
screen.blit(coin_img, coin_rect)
# 绘制分数
score_text = font.render("得分:" + str(score), True, (0, 0, 0))
screen.blit(score_text, (20, 20))
# 判断游戏胜利或失败
if passed_obstacle == 9 and score >= 999:
result_text = font.render("游戏胜利!", True, (0, 255, 0))
screen.blit(result_text, (WIDTH // 2 - 150, HEIGHT // 2 - 50))
running = False
elif score < 999 and (player_rect.right < 0 or player_rect.top > HEIGHT):
result_text = font.render("游戏失败!", True, (255, 0, 0))
screen.blit(result_text, (WIDTH // 2 - 150, HEIGHT // 2 - 50))
running = False
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
同样需要准备三张PNG格式的图片:`player.png`、`obstacle.png`和`coin.png`,放在代码同一目录下。
这个游戏在上一个游戏的基础上又进行了改进,增加了一个金币,增加了金币的收集和对应的积分。每次收集到一个金币可以获得50分。如果收集到所有障碍物,且分数达到999以上,即为游戏胜利;如果分数不足999分,或者玩家掉出屏幕或者撞到障碍物,即为游戏失败。
阅读全文