用Python写一个地铁跑酷
时间: 2024-03-06 22:05:07 浏览: 535
好的,下面是一个简单的地铁跑酷游戏的 Python 代码示例:
```python
import pygame
import random
pygame.init()
# 游戏窗口大小
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Subway Surfers")
# 玩家角色
player_img = pygame.image.load("player.png")
player_rect = player_img.get_rect()
player_rect.bottomleft = (50, HEIGHT - 50)
player_speed = 5
# 障碍物
obstacle_imgs = [pygame.image.load("obstacle1.png"), pygame.image.load("obstacle2.png"), pygame.image.load("obstacle3.png")]
obstacle_rects = []
obstacle_speed = 5
obstacle_spawn_rate = 30
obstacle_spawn_counter = 0
# 分数
score = 0
font = pygame.font.SysFont("Arial", 30)
# 主游戏循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 玩家移动
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and player_rect.top > 0:
player_rect.top -= player_speed
if keys[pygame.K_DOWN] and player_rect.bottom < HEIGHT:
player_rect.bottom += player_speed
# 障碍物移动和生成
obstacle_spawn_counter += 1
if obstacle_spawn_counter >= obstacle_spawn_rate:
obstacle_spawn_counter = 0
obstacle_img = random.choice(obstacle_imgs)
obstacle_rect = obstacle_img.get_rect()
obstacle_rect.topright = (WIDTH, random.randint(0, HEIGHT - obstacle_rect.height))
obstacle_rects.append(obstacle_rect)
for obstacle_rect in obstacle_rects:
obstacle_rect.left -= obstacle_speed
if obstacle_rect.right < 0:
obstacle_rects.remove(obstacle_rect)
# 碰撞检测
if player_rect.colliderect(obstacle_rect):
running = False
# 计分
if obstacle_rect.right <= player_rect.left:
score += 1
# 显示分数和角色
screen.fill((255, 255, 255))
screen.blit(player_img, player_rect)
for obstacle_rect in obstacle_rects:
screen.blit(obstacle_img, obstacle_rect)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.update()
pygame.quit()
```
请注意,这只是一个简单的示例,您可以根据自己的需求进行修改和扩展。同时,您需要自己准备玩家和障碍物的图片,并将其命名为 "player.png"、"obstacle1.png"、"obstacle2.png" 和 "obstacle3.png"。
阅读全文