给我写一段地铁跑酷python代码
时间: 2023-10-18 14:17:39 浏览: 180
Python+地铁跑酷地图+源代码
好的,以下是一个简单的地铁跑酷的Python代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("地铁跑酷")
# 加载背景图片和主角图片
bg_image = pygame.image.load("background.png")
player_image = pygame.image.load("player.png")
# 设置主角的初始位置和移动速度
player_x = 50
player_y = screen_height - player_image.get_height() - 50
player_speed = 5
# 设置障碍物的初始位置和移动速度
obstacle_x = screen_width
obstacle_y = screen_height - 100
obstacle_speed = 10
obstacle_width = 50
obstacle_height = 50
# 设置得分和字体
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
# 渲染背景和主角
screen.blit(bg_image, (0, 0))
screen.blit(player_image, (player_x, player_y))
# 移动主角
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player_y -= player_speed
if keys[pygame.K_DOWN]:
player_y += player_speed
# 移动障碍物
obstacle_x -= obstacle_speed
# 如果障碍物移出屏幕,重新设置位置和速度
if obstacle_x < -obstacle_width:
obstacle_x = screen_width
obstacle_y = random.randint(0, screen_height - obstacle_height - 50)
obstacle_speed += 1
score += 1
# 渲染障碍物
pygame.draw.rect(screen, (255, 0, 0), (obstacle_x, obstacle_y, obstacle_width, obstacle_height))
# 检测碰撞
player_rect = pygame.Rect(player_x, player_y, player_image.get_width(), player_image.get_height())
obstacle_rect = pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height)
if player_rect.colliderect(obstacle_rect):
running = False
# 渲染得分
score_text = font.render("得分:" + str(score), True, (255, 255, 255))
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.update()
# 退出Pygame
pygame.quit()
```
这段代码会创建一个简单的地铁跑酷游戏,你需要使用方向键控制主角上下移动,并躲避障碍物。每次成功避开障碍物,你的得分会加一。如果撞到障碍物,游戏就会结束。
阅读全文