[英]pygame key detect not detecting keypresses
我試圖讓 pygame 檢測我的按鍵並將背景更改為隨機顏色,但每次按下所選鍵時,沒有任何變化。 window 的背景顏色保持不變。
import pygame
import random
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
detect=True
keys=pygame.key.get_pressed()
while detect:
pygame.event.pump()
keys = pygame.key.get_pressed()
if keys[pygame.K_0]:
screen.fill((random.randint(0, 255)), (random.randint(0, 255)), (random.randint(0, 255)))
pygame.display.update()
if keys[pygame.K_1]:
screen.fill((random.randint(0, 255)), (random.randint(0, 255)), (random.randint(0, 255)))
pygame.display.update()
這里的問題是程序永遠不會到達代碼的后半部分。
第一個while True
語句,它對屏幕沒有任何作用,但等待用戶關閉 window 一直運行 - 應該檢測按鍵的代碼僅在接收到pygame.QUIT
事件時執行(然后是 Z025B8C74DEZCBD902FFFB4C1A352702FBFFBsclose )。
程序的工作方式,它們運行一個循環,其中包含所有語句 - while
循環不會並行運行 - 你必須這樣做:
import pygame
import random
running = True
screen = pygame.display.set_mode((800, 600))
while running:
pygame.event.pump()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_0]:
screen.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
pygame.display.update()
if keys[pygame.K_1]:
screen.fill((random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)))
pygame.display.update()
pygame.time.delay(30)
pygame.quit()
(還要注意對“pygame.time.delay”的調用,否則 while 循環將使用所有 CPU 資源運行,試圖以比它們到達的速度更快的速度獲取事件,並且對此無能為力 - 您的簡單示例將以 100% 的速度燒毀中央處理器)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.