首页 > 解决方案 > 如何在 pygame 库中测试持有的密钥

问题描述

我试图在 pygame 中制作一个简单的平台游戏。但是,当我执行移动并按住移动key(d)时,它一次只会将玩家移动到右侧。每当我按住移动键时,它只会移动一次,直到我再次按下它时它会再移动一次。

这是我的代码:

import pygame
import sys

# General setup
pygame.init()
clock = pygame.time.Clock()

# Setting up the main window
screen_width = 1280
screen_height = 920
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('PyPlat')
# Game rects
accelerationY = .164
speedY = 7
speedX = 3
player = pygame.Rect(1, 1, 20, 60)
ground = pygame.Rect(0, screen_height-50, screen_width, 60)
bg_color = pygame.Color('gray12')
light_blue = (62, 175, 250)
grounded = player.colliderect(ground)
while True:
    # Handling inputs
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_d:
                player.x += speedX
    # Handling collisions
    if player.colliderect(ground) == False:
        player.y += speedY
        speedY += accelerationY

    # Visuals
    screen.fill(bg_color)
    pygame.draw.rect(screen, light_blue, player)
    pygame.draw.rect(screen, light_blue, ground)

    # Updating the window
    pygame.display.flip()
    clock.tick(60)

标签: pythonpygame

解决方案


推荐阅读