gpt4 book ai didi

python - 结束程序后发生的奇怪的键盘中断错误

转载 作者:行者123 更新时间:2023-12-04 18:39:39 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to get if a key is pressed pygame [duplicate]

(1 个回答)


1年前关闭。




我可以运行游戏并且所有的图形都可以正常工作,但我无法让键盘输入正常工作,即使我第一次使用它时它可以短暂工作。此外,它只在我关闭程序后给出错误。其他 pygame 功能,例如用红色 x 关闭程序也不起作用

import pygame
from essentials import *
import random

pygame.init()

screen_height = 640
screen_width = 640

win = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption("The Room")


# button class
class button:
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text


player_width = 25
player_height = 25
player_pos_x = 600
player_pos_y = 600
vel = 40 # set to ten for release

keys = pygame.key.get_pressed()
run2 = True

while run2:
win.fill((0, 0, 0))
# the circle
circle = pygame.draw.circle(win, GREEN, (50, 50), 5)
# the player square
player = pygame.draw.rect(win, RED, (player_pos_x, player_pos_y, player_width, player_height))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if keys[pygame.K_LEFT] and player_pos_x > vel:
player_pos_x -= vel
if keys[pygame.K_RIGHT] and player_pos_x < screen_width - player_width - vel:
player_pos_x += vel
if keys[pygame.K_UP] and player_pos_y > vel:
player_pos_y -= vel
if keys[pygame.K_DOWN] and player_pos_y < screen_height - player_height - vel:
player_pos_y += vel
if isOver(player, (50, 50)):
print("Ding!")
pygame.display.update()

结束了:
def isOver(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True

*请注意,我使用的是 Ubuntu,并且对它相当陌生

最佳答案

keys = pygame.key.get_pressed()返回键的当前状态。您必须在主应用程序循环中连续检索键的状态,而不是在循环之前一次:

# keys = pygame.key.get_pressed() <--- REMOVE

while run2:

keys = pygame.key.get_pressed() # <--- INSERT

此外还有一种类型。在 while 循环的条件下,变量 run2被评估,但在事件循环中 run设置:

关于python - 结束程序后发生的奇怪的键盘中断错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60911755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com