写一个python跑酷小游戏
时间: 2023-07-18 12:42:48 浏览: 141
使用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("跑酷小游戏")
# 加载游戏资源
player_image = pygame.image.load("player.png").convert_alpha()
bg_image = pygame.image.load("background.png").convert_alpha()
obstacle_image = pygame.image.load("obstacle.png").convert_alpha()
# 定义游戏变量
player_pos = [100, 400]
player_speed = 10
player_jump = False
player_jump_speed = 20
player_gravity = 1
obstacle_pos = [screen_width + 100, 400]
obstacle_speed = 10
score = 0
# 定义游戏函数
def draw_background():
screen.blit(bg_image, (0, 0))
def draw_player():
screen.blit(player_image, player_pos)
def draw_obstacle():
screen.blit(obstacle_image, obstacle_pos)
def update_obstacle():
global obstacle_pos, score
obstacle_pos[0] -= obstacle_speed
if obstacle_pos[0] < -100:
obstacle_pos[0] = screen_width + 100
obstacle_pos[1] = random.randint(200, 500)
score += 1
def check_collision():
global player_pos, score
player_rect = pygame.Rect(player_pos[0], player_pos[1], player_image.get_width(), player_image.get_height())
obstacle_rect = pygame.Rect(obstacle_pos[0], obstacle_pos[1], obstacle_image.get_width(), obstacle_image.get_height())
if player_rect.colliderect(obstacle_rect):
score = 0
player_pos = [100, 400]
obstacle_pos = [screen_width + 100, 400]
def update_score():
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, (255, 255, 255))
screen.blit(text, (screen_width - 150, 20))
# 游戏主循环
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:
player_pos[1] -= player_jump_speed
player_jump_speed -= player_gravity
if player_pos[1] > 400:
player_pos[1] = 400
player_jump = False
player_jump_speed = 20
update_obstacle()
check_collision()
# 游戏画面
draw_background()
draw_player()
draw_obstacle()
update_score()
# 更新屏幕
pygame.display.update()
# 退出游戏
pygame.quit()
```
请注意,此代码仅仅是一个简单的示例,您可以根据自己的需求进行修改和扩展。同时,为了让这个游戏运行起来,您还需要准备好 `player.png`、`background.png` 和 `obstacle.png` 这三个图片资源。
阅读全文