不要尝试在应用程序循环中使用附加循环来控制游戏。使用应用程序循环。
添加变量is_jumping和jump_count:
is_jumping = False
jump_count = 0
使用pygame.time.Clock 控制每秒帧数,从而控制游戏速度。
pygame.time.Clock 对象的方法tick() 以这种方式延迟游戏,即循环的每次迭代消耗相同的时间段。见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_jumping和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()