Python小黄狗跑酷游戏,我们通常会用到pygame
库,这是一个用于创建游戏的库。如果你还没有安装pygame
,可以使用pip install pygame
进行安装。
以下是一个简单的跑酷游戏示例:
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
win_height = 800
win_width = 600
win = pygame.display.set_mode((win_width, win_height))
# 主循环
run = True
clock = pygame.time.Clock()
# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
yellow = (255, 255, 102)
# 设置小黄狗属性
dog_width = 50
dog_height = 50
dog_x = win_width // 2
dog_y = win_height - dog_height - 10
dog_velocity = 10
# 设置障碍物属性
obstacle_width = 50
obstacle_height = random.randint(20, 30)
obstacle_x = random.randint(0, win_width-obstacle_width)
obstacle_y = 0 - obstacle_height
obstacle_velocity = 10
while run:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and dog_x - dog_velocity > 0:
dog_x -= dog_velocity
if keys[pygame.K_RIGHT] and dog_x + dog_velocity < win_width - dog_width:
dog_x += dog_velocity
obstacle_y += obstacle_velocity
if obstacle_y > win_height:
obstacle_y = 0 - obstacle_height
obstacle_x = random.randint(0, win_width-obstacle_width)
if obstacle_y + obstacle_height > dog_y and obstacle_x + obstacle_width > dog_x and obstacle_x < dog_x + dog_width:
run = False
win.fill(black)
pygame.draw.rect(win, yellow, (dog_x, dog_y, dog_width, dog_height))
pygame.draw.rect(win, white, (obstacle_x, obstacle_y, obstacle_width, obstacle_height))
pygame.display.update()
pygame.quit()
这个示例非常简单,只包含一个角色(小黄狗)和一种障碍物。你可以按左
和右
键来控制小黄狗移动,避免撞到障碍物。
你可以在这个基础上添加更多功能,比如多个障碍物、得分机制等。