首页 > 解决方案 > 无法在 Pygame 无尽的跳线中使角色跳跃

问题描述

我正在尝试从谷歌重新创建恐龙游戏,我正处于让我的角色跳跃的阶段,但我无法让它工作,所以我想知道是否有人可以帮助我让我的角色跳跃。我试图做的是使用一个for循环让播放器上升然后等待然后使用另一个for循环让它下降但是当我按下向上键让它跳转时它不会做任何事情也给我一个错误。这是我尝试跳转代码

for x in range(0, 60):
    player_y -= player_vel
    time.sleep(0.5)
for x in range(0, 60):
    player_y += player_vel
            

标签: pythonpygame

解决方案


不要尝试在应用程序循环中使用附加循环来控制游戏。使用应用程序循环。添加变量is_jumpingadn jump_count

is_jumping = False
jump_count = 0

用于pygame.time.Clock控制每秒帧数,从而控制游戏速度。

对象的方法tick()pygame.time.Clock这种方式延迟游戏,循环的每次迭代消耗相同的时间段。见pygame.time.Clock.tick()

此方法应每帧调用一次。

这意味着循环:

clock = pygame.time.Clock()
run = True
while run:
   clock.tick(50)

每秒运行 50 次。

使用KEYDOWN事件而不是pygame.key.get_pressed()跳转:

run = True
while run:
    clock.tick(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and not is_jumping:
                is_jumping = True
                jump_count = 30

pygame.key.get_pressed()返回一个包含每个键状态的列表。如果按住某个键,则该键的状态为True,否则为False。用于pygame.key.get_pressed()评估按钮的当前状态并获得连续移动。
键盘事件(参见pygame.event模块)仅在按键状态更改时发生一次。KEYDOWN每次按下某个键时,该事件发生一次。KEYUP每次释放键时发生一次。将键盘事件用于单个操作。

根据应用循环中的is_jumpingadn改变播放器的位置:jump_count

while run:
    # [...]

    #movement code
    if is_jumping and jump_count > 0:
        if jump_count > 15:
            player_y -= player_vel
            jump_count -= 1
        elif jump_count > 0:
            player_y += player_vel  
            jump_count -= 1 
        is_jumping = jump_count > 0    

完整示例:

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Infinite Runner")

#defines the paremeters for the wall
wall_x = 800
wall_y = 300
wall_width = 20
wall_height = 20

score = 0

player_x = 400
player_y = 300
player_width = 40
player_height = 60
player_vel = 5

is_jumping = False
jump_count = 0

#where the main code is run
print(score)
clock = pygame.time.Clock()
run = True
while run:
    clock.tick(50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP and not is_jumping:
                is_jumping = True
                jump_count = 30

    #movement code
    if is_jumping and jump_count > 0:
        if jump_count > 15:
            player_y -= player_vel
            jump_count -= 1
        elif jump_count > 0:
            player_y += player_vel  
            jump_count -= 1 
        is_jumping = jump_count > 0    
   
    #draws the player and the coin
    screen.fill((0,0,0))
    wall = pygame.draw.rect(screen, (244, 247, 30), (wall_x, wall_y, wall_width, wall_height))
    player = pygame.draw.rect(screen, (255, 255, 255), (player_x, player_y, player_width, player_height))     
    pygame.display.update()

pygame.quit()

推荐阅读