debugging pygame.key.get_pressed()不工作,为什么?

1cklez4t  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(107)

此问题已在此处有答案

How to get keyboard input in pygame?(12个回答)
How can I make a sprite move when a key is held down?(6个回答)
5天前关闭。
有人可以请帮助我只是新的这一点,不能弄清楚为什么只是没有React,从所有的游戏时,我按下一个或二我使用一些代码形式的YouTube视频技术与蒂姆,我已经完成了视频,并有一个工作的游戏,现在我试图使我自己的东西,但我真的卡住了。

import pygame
import os

WIDTH, HEIGHT = 1440, 900
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("The Game")

background = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'blackish.jpg')), (WIDTH, HEIGHT))
bar = pygame.transform.scale(pygame.image.load(os.path.join("Assets", "bar.png")), (250, 100))
SHIP = pygame.transform.rotate(pygame.transform.scale(pygame.image.load(os.path.join("Assets", "spaceship_red.png")), (100, 100)), 180)

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)

ShipWidth = (200)
ShipHeight = (200)

direction = "left"

def barsleft(BarMove):
    BarMove.x -= 1

def barsright(BarMove):
    BarMove.x += 1

def draw(player, BarMove):
    WIN.blit(background, (0, 0))
    WIN.blit(bar, (BarMove.x, BarMove.y))
    WIN.blit(SHIP, (player.x, player.y))

    pygame.display.update()

def PlayerMove(player, keys_pressed):
     if keys_pressed[pygame.K_a] and player.x > 0: #left
        player.x -= 2
     if keys_pressed[pygame.K_d] and player.x + ShipWidth/2 < WIDTH: #right
        player.x += 2


def game(ShipWidth, ShipHeight):
    player = pygame.Rect(620, 700, ShipWidth, ShipHeight)
    BarMove = pygame.Rect(600, 550, 250, 100)

    keys_pressed = pygame.key.get_pressed()

    edge = False

    run = True
    while run == True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

        
        if BarMove.x > 0 and edge == False:
            barsleft(BarMove)
            if BarMove.x < 50:
                edge = True
        if edge == True:
            barsright(BarMove)
            if BarMove.x > WIDTH - 300:
                edge = False

        
        PlayerMove(player, keys_pressed)
        draw(player, BarMove)

game(ShipWidth, ShipHeight)

我希望能够按住键,所以我不使用获取事件,我试图用不同的功能和东西,但没有什么是工作混乱

jc3wubiy

jc3wubiy1#

我希望能够按住键......但没有任何工作
当然,你只调用了get_pressed()**一次。这很好。但之后你再也不会在游戏循环中调用它了,你需要这样做。

def game
    ...
    keys_pressed = pygame.key.get_pressed()
    ...
    while run == True:
        ...
        PlayerMove(player, keys_pressed)  # which inspects 2nd param for K_{a,d}

只需在循环中向下移动该赋值即可:

while run == True:
        keys_pressed = pygame.key.get_pressed()
        ...

现在,如果键盘的状态在玩游戏的几秒钟内发生变化,该变量也会发生变化,PlayerMove可以做出适当的响应。
我建议您将源代码格式化为“$black *.py”

WIDTH, HEIGHT = 1440, 900
...
WHITE = (255, 255, 255)
...
ShipWidth = (200)
ShipHeight = (200)

WIDTH和HEIGHT是非常好的。同样对于白色,() paren符号恰好匹配python显示元组的方式。
OTOH,ShipWidth和height周围的括号会分散注意力,可能会产生误导。请理解它们是多余的,对你没有任何帮助。特别是,它们不会神奇地产生一个元组,因为那里没有逗号。建议你删除它们。最简单的方法是让black整理你的源代码。

相关问题