gpt4 book ai didi

python - 只要按下键,如何让游戏对象连续移动?

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:29 25 4
gpt4 key购买 nike

只要按下键盘上的,我就会尝试让游戏对象(这里是欢迎文字)移动。但是在我的这段代码中,

import pygame , sys
from pygame.locals import *

pygame.init()

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

DISPLAYSURF = pygame.display.set_mode((800 , 400))
pygame.display.set_caption('Welcome Tanks')

#render(text, antialias, color, background=None)
fontObj = pygame.font.SysFont('serif' , 40)
text = fontObj.render('Welcome Folks' , True , RED )

x = 150
y = 29

while True:
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(text ,(x , y))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit(0)
elif event.type == KEYDOWN or event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)
elif event.key == K_DOWN:
y += 15
elif event.key == K_UP:
y -= 15
elif event.key == K_RIGHT:
x += 14
elif event.key == K_LEFT:
x -= 15
else:
x = 150
y = 29
pygame.display.update()

对象只移动一次,即使 key 被连续按下很长时间。换句话说,对象仅在按下键盘按钮时改变其位置一次。我希望它在我按住键时连续移动。

我应该寻找哪个事件而不是 event.KEYDOWN

最佳答案

我建议你使用key.get_pressed(),例如

while True:
DISPLAYSURF.fill(WHITE)
DISPLAYSURF.blit(text ,(x , y))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit(0)
elif event.type == KEYDOWN or event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit(0)

if pygame.key.get_pressed()[K_LEFT]:
x -= 15

if pygame.key.get_pressed()[K_RIGHT]:
x += 14

if pygame.key.get_pressed()[K_UP]:
y -= 15

if pygame.key.get_pressed()[K_DOWN]:
y += 15
pygame.display.update()

pygame.key.get_pressed()

Returns a sequence of boolean values representing the state of every key on the keyboard. Use the key constant values to index the array. A True value means the that button is pressed.

Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. You have no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the event queue for this functionality.

你也可以看看doc

关于python - 只要按下键,如何让游戏对象连续移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33254809/

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