编写一个python跑酷小游戏
时间: 2023-07-18 22:44:29 浏览: 48
好的,以下是一个简单的 Python 跑酷小游戏的示例代码,你可以参考一下:
```python
import pygame
import random
# 游戏初始化
pygame.init()
# 游戏屏幕设置
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Python 跑酷小游戏")
# 游戏时钟设置
clock = pygame.time.Clock()
# 游戏资源加载
player_image = pygame.image.load("player.png").convert_alpha()
player_rect = player_image.get_rect(centerx=screen_width/2, bottom=screen_height-30)
player_speed = 5
player_jump_speed = 20
player_gravity = 1
player_is_jump = False
platform_image = pygame.image.load("platform.png").convert_alpha()
platforms = []
for i in range(10):
platform_x = random.randint(0, screen_width-platform_image.get_width())
platform_y = random.randint(0, screen_height)
platform_rect = platform_image.get_rect(topleft=(platform_x, platform_y))
platforms.append(platform_rect)
# 游戏循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not player_is_jump:
player_is_jump = True
# 玩家移动
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.move_ip(-player_speed, 0)
if keys[pygame.K_RIGHT]:
player_rect.move_ip(player_speed, 0)
if player_is_jump:
player_rect.move_ip(0, -player_jump_speed)
player_jump_speed -= player_gravity
if player_jump_speed <= 0:
player_is_jump = False
player_jump_speed = 20
# 平台移动
for platform_rect in platforms:
platform_rect.move_ip(0, 5)
if platform_rect.top >= screen_height:
platform_x = random.randint(0, screen_width-platform_image.get_width())
platform_y = random.randint(-10, 0)
platform_rect.topleft = (platform_x, platform_y)
# 碰撞检测
for platform_rect in platforms:
if player_rect.colliderect(platform_rect):
if player_rect.bottom <= platform_rect.top+10:
player_is_jump = False
player_jump_speed = 20
player_rect.bottom = platform_rect.top
else:
pygame.quit()
exit()
# 游戏背景绘制
screen.fill((255, 255, 255))
# 平台绘制
for platform_rect in platforms:
screen.blit(platform_image, platform_rect)
# 玩家绘制
screen.blit(player_image, player_rect)
# 屏幕更新
pygame.display.update()
# 游戏时钟更新
clock.tick(60)
```
在这个示例代码中,我们使用 Pygame 模块来实现跑酷小游戏的功能。游戏中,玩家通过方向键控制角色的移动,通过空格键控制角色的跳跃。同时,游戏中有多个不同位置的平台,玩家需要跳跃到平台上避免掉落。游戏中的平台会不断向下移动,如果玩家掉落到屏幕下面,则游戏结束。