Pygame 中未检测到空格键

问题描述 投票:0回答:1

我正在使用 Python 和 Pygame 制作 2d Minecraft 克隆。除了一件事之外,一切都正常。当我按空格键时,应该通过从“positions”变量中删除所有位置来清除屏幕。它不起作用。我在那里放了一个“print(”hello”)”,但它不起作用。我不知道为什么它不起作用,因为它没有出现任何错误。我对 python 和 Stackoverflow 相当陌生,所以非常感谢您的帮助。这是代码。

import pygame

pygame.init()
win = pygame.display.set_mode((480,320))
pygame.display.set_caption(("Mini Minecraft"))
block = pygame.image.load("Stone.png")
background = pygame.image.load("Background.png")
running = True

positions = []

def roundToMultiple(n, m):
    return round(n / m) * m

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

        if event.type == pygame.K_SPACE:
            positions = []

        if event.type == pygame.MOUSEBUTTONDOWN:
            posX, posY = event.pos  
            posXRound = roundToMultiple(posX, 32)
            posYRound = roundToMultiple(posY, 32)
            positions.append((posXRound, posYRound))
        
    mouseX, mouseY = pygame.mouse.get_pos()

    mouseXRound = roundToMultiple(mouseX, 32)
    mouseYRound = roundToMultiple(mouseY, 32)

    if mouseXRound > 448:
        mouseXRound = 448
    if mouseYRound > 288:
        mouseYRound = 288
    
    win.blit(background, (0,0))
    for pos in positions:
        win.blit(block, pos)
    win.blit(block, (mouseXRound, mouseYRound))
    pygame.display.update()
python pygame
1个回答
0
投票

您需要检查事件类型是否为按键

pygame.KEY_DOWN
,然后检查事件键是否为空格
pygame.K_SPACE

        if event.type == pygame.KEY_DOWN:
            if event.key == pygame.K_SPACE:
                positions = []
© www.soinside.com 2019 - 2024. All rights reserved.