用python写一个跑酷游戏
时间: 2024-05-15 09:18:36 浏览: 164
好的,我可以为你提供一个简单的跑酷游戏的Python代码。这个游戏基于Pygame,可以在Python 3中运行。
首先,你需要安装Pygame库,可以使用以下命令:`pip install pygame`
然后,下面是游戏的代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口的大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 加载游戏图像资源
player_img = pygame.image.load('player.png')
obstacle_img = pygame.image.load('obstacle.png')
# 设置游戏变量
player_x = 50
player_y = 300
player_speed = 5
player_jump = False
player_jump_count = 10
obstacle_x = screen_width
obstacle_y = 450
obstacle_speed = 8
obstacle_passed = False
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
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not player_jump:
player_jump = True
# 更新游戏状态
if player_jump:
if player_jump_count >= -10:
player_y -= (player_jump_count * abs(player_jump_count)) * 0.5
player_jump_count -= 1
else:
player_jump = False
player_jump_count = 10
obstacle_x -= obstacle_speed
if obstacle_x < -obstacle_img.get_width():
obstacle_x = screen_width
obstacle_passed = False
if obstacle_x < player_x < obstacle_x + obstacle_img.get_width() and not obstacle_passed:
obstacle_passed = True
score += 1
# 绘制游戏界面
screen.fill((255, 255, 255))
screen.blit(player_img, (player_x, player_y))
screen.blit(obstacle_img, (obstacle_x, obstacle_y))
score_text = font.render('Score: ' + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.update()
# 判断游戏失败条件
if player_y > obstacle_y - player_img.get_height():
running = False
# 游戏结束
gameover_text = font.render('Game Over. Your score is: ' + str(score), True, (0, 0, 0))
screen.blit(gameover_text, (screen_width // 2 - gameover_text.get_width() // 2, screen_height // 2 - gameover_text.get_height() // 2))
pygame.display.update()
# 等待用户退出游戏
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
```
你需要在同一目录下准备两个PNG格式的图片,一个是玩家的图片(例如player.png),一个是障碍物的图片(例如obstacle.png)。
运行代码后,你的跑酷游戏就可以开始了!
阅读全文