如何在 pygame 中获取键盘输入?
- 2024-11-22 08:47:00
- admin 原创
- 217
问题描述:
我正在用 pygame 1.9.2 制作一款游戏。这是一款非常简单的游戏,一艘船在五列坏人之间移动,坏人通过缓慢向下移动进行攻击。我试图让船用左右箭头键左右移动。这是我的代码:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
location-=1
if location==-1:
location=0
if keys[K_RIGHT]:
location+=1
if location==5:
location=4
效果太好了。船移动得太快了。让它只移动一个位置几乎是不可能的,左或右。我怎样才能让船每次按下键时只移动一次?
解决方案 1:
您可以从 pygame 获取事件,然后留意该KEYDOWN
事件,而不是查看返回的键get_pressed()
(它会给出当前按下的键,而事件会显示在该帧KEYDOWN
上按下了哪些键)。
现在您的代码发生的情况是,如果您的游戏以 30fps 的速度渲染,并且您按住左箭头键半秒钟,那么您将更新位置 15 次。
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
location -= 1
if event.key == pygame.K_RIGHT:
location += 1
为了支持按住某个按键时的连续移动,您必须建立某种限制,要么基于游戏循环的强制最大帧速率,要么通过一个计数器(仅允许您在循环的每隔一定数量的滴答声中移动一次)。
move_ticker = 0
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if move_ticker == 0:
move_ticker = 10
location -= 1
if location == -1:
location = 0
if keys[K_RIGHT]:
if move_ticker == 0:
move_ticker = 10
location+=1
if location == 5:
location = 4
然后在游戏循环中的某个时候你会做这样的事情:
if move_ticker > 0:
move_ticker -= 1
这只允许您每 10 帧移动一次(因此,如果您移动,则标记将设置为 10,并且在 10 帧之后它将允许您再次移动)
解决方案 2:
pygame.key.get_pressed()
返回包含每个键的状态的列表。如果按住某个键,则该键的状态为1
,否则为0
。这是该时刻键的快照 必须在每一帧中连续检索键的新状态。用于pygame.key.get_pressed()
评估按钮的当前状态并获得连续运动:
while True:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
x -= speed
if keys[pygame.K_RIGHT]:
x += speed
if keys[pygame.K_UP]:
y -= speed
if keys[pygame.K_DOWN]:
y += speed
可以通过从“右”中减去“左”、从“下”中减去“上”来简化此代码:
while True:
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * speed
键盘事件(参见pygame.event模块)仅在按键状态改变时发生一次。KEYDOWN
每次按下按键时,事件都会发生一次。KEYUP
每次释放按键时,事件都会发生一次。使用键盘事件执行单个动作或移动:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x -= speed
if event.key == pygame.K_RIGHT:
x += speed
if event.key == pygame.K_UP:
y -= speed
if event.key == pygame.K_DOWN:
y += speed
另请参阅键和键盘事件
连续运动的最小示例: replit.com/@Rabbid76/PyGame-ContinuousMovement
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(0, 0, 20, 20)
rect.center = window.get_rect().center
vel = 5
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
print(pygame.key.name(event.key))
keys = pygame.key.get_pressed()
rect.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel
rect.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel
rect.centerx = rect.centerx % window.get_width()
rect.centery = rect.centery % window.get_height()
window.fill(0)
pygame.draw.rect(window, (255, 0, 0), rect)
pygame.display.flip()
pygame.quit()
exit()
单个动作的最小示例: replit.com/@Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()
解决方案 3:
import pygame
pygame.init()
pygame.display.set_mode()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); #sys.exit() if sys is imported
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_0:
print("Hey, you pressed the key, '0'!")
if event.key == pygame.K_1:
print("Doing whatever")
请注意,K_0 和 K_1 不是唯一的键,要查看所有键,请参阅 pygame 文档,否则,请tab
在输入后点击
pygame。
(注意 pygame 后面的 .)进入空闲程序。注意 K 必须大写。还要注意,如果您没有为 pygame 指定显示大小(不传递任何参数),那么它将自动使用计算机屏幕/显示器的大小。祝您编码愉快!
解决方案 4:
我认为你可以使用:
pygame.time.delay(delayTime)
以毫秒为单位delayTime
。
将其放在事件之前。
解决方案 5:
尝试一下:
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
if count == 10:
location-=1
count=0
else:
count +=1
if location==-1:
location=0
if keys[K_RIGHT]:
if count == 10:
location+=1
count=0
else:
count +=1
if location==5:
location=4
这意味着你只移动了 1/10 的时间。如果它仍然移动得太快,你也可以尝试增加你设置的“计数”值。
解决方案 6:
其背后的原因是 pygame 窗口以 60 fps(每秒帧数)运行,当您按下按键约 1 秒时,它会根据事件块的循环更新 60 帧。
clock = pygame.time.Clock()
flag = true
while flag :
clock.tick(60)
请注意,如果您的项目中有动画,那么图像的数量将决定 中的值的数量tick()
。假设您有一个角色,它需要 20 组图像来行走和跳跃,那么您必须制作tick(20)
这些图像才能以正确的方式移动角色。
解决方案 7:
仅供参考,如果你想确保飞船不会飞出屏幕
location-=1
if location==-1:
location=0
你也许可以更好地使用
location -= 1
location = max(0, location)
这样,如果它跳过 -1,你的程序就不会中断
解决方案 8:
做类似的事情,但基于时间延迟。我第一次立即调用我的函数,然后是午餐计时器,当按钮被按下时,我每隔 button_press_delta 秒调用它一次
from time import time
before main loop:
button_press_delta = 0.2
right_button_pressed = 0
while not done:
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT]:
if not right_button_pressed:
call_my_function()
right_button_pressed = 1
right_button_pressed_time_start = time()
if right_button_pressed:
right_button_pressed_time = (
time() - right_button_pressed_time_start)
if right_button_pressed_time > button_press_delta:
call_my_function()
right_button_pressed_time_start = time()
else:
right_button_pressed = 0
解决方案 9:
Pygames tick 函数 ( clock.tick(5)
),返回自上一帧以来的时间 (deltatime)。您可以将所有移动乘以该值,这样无论帧速率如何,角色都会以相同的速度移动。您还需要再次将其乘以一个数字(例如 50),这样它就不会太慢。
解决方案 10:
您应该按照文档clock.tick(10)
中所述使用。
解决方案 11:
要减慢游戏速度,请使用pygame.clock.tick(10)
解决方案 12:
以上所有答案都太复杂了。我只需将变量改为 0.1 而不是 1,这会使飞船速度慢 10 倍。
如果还是太快,你可以将其改为 0.01,这会使船速慢 100 倍
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
location -= 0.1 #or 0.01
if location==-1:
location=0
if keys[K_RIGHT]:
location += 0.1 #or 0.01
if location==5:
location=4
扫码咨询,免费领取项目管理大礼包!