如何在Pygame中获取键盘输入
我正在尝试在程序上获取键盘输入,其中用户必须在屏幕上移动一个点。但是,当我运行该程序时,控制台没有出现。你能帮我解决这个错误吗?这是我的代码:
import pygame
import random
pygame.init()
x=0
y=0
xdir=5
ydir=5
r = random.randint(10,255)
g = random.randint(10,255)
b = random.randint(10,255)
screen = pygame.display.set_mode((500,300))
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
USI = pygame.key.get_pressed()
while True:
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
pygame.display.update()
if USI[pygame.K_LEFT]:
x -= 5
if USI[pygame.K_RIGHT]:
x += 5
if USI[pygame.K_UP]:
y -= 5
if USI[pygame.K_DOWN]:
y += 5
I am trying to get keyboard input on a program where the user has to move a dot around the screen. However when I run the program, the console does not come up. Could you please help me fix this error? Here is my code:
import pygame
import random
pygame.init()
x=0
y=0
xdir=5
ydir=5
r = random.randint(10,255)
g = random.randint(10,255)
b = random.randint(10,255)
screen = pygame.display.set_mode((500,300))
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
USI = pygame.key.get_pressed()
while True:
pygame.draw.circle(screen, (r, g, b), (x,y), 15, 0)
pygame.display.update()
if USI[pygame.K_LEFT]:
x -= 5
if USI[pygame.K_RIGHT]:
x += 5
if USI[pygame.K_UP]:
y -= 5
if USI[pygame.K_DOWN]:
y += 5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
deteck键的示例循环,用pygame按下:
a sample loop to deteck key pressed with pygame:
https://replit.com/@Rabbid76/PyGame-ContinouslyMovement#main.py< /a>
这应该可以帮助你弄清楚 pygame 中的移动。
https://replit.com/@Rabbid76/PyGame-ContinuousMovement#main.py
this should help you figure out movement in pygame.
您可以从pygame获得事件,然后注意键盘事件,而不是查看get_pressed()返回的键那个框架)。
您的代码现在正在发生的事情是,如果您的游戏以30fps渲染,并且您将左箭头键持续半秒,则您将在15次更新位置。
为了支持钥匙的持续移动,您必须建立某种限制,要么基于强制的游戏循环帧速率,要么是由您只允许您移动的每一个如此多的tick的计数器环形。
然后,在游戏循环中的某个地方,您会做这样的事情:
这只会让您每10帧移动一次(因此,如果您移动,则记录器将设置为10帧,并且在10帧后,它将允许您再次移动)
You can get the events from pygame and then watch out for the KEYDOWN event, instead of looking at the keys returned by get_pressed()(which gives you keys that are currently pressed down, whereas the KEYDOWN event shows you which keys were pressed down on that frame).
What's happening with your code right now is that if your game is rendering at 30fps, and you hold down the left arrow key for half a second, you're updating the location 15 times.
To support continuous movement while a key is being held down, you would have to establish some sort of limitation, either based on a forced maximum frame rate of the game loop or by a counter which only allows you to move every so many ticks of the loop.
Then somewhere during the game loop you would do something like this:
This would only let you move once every 10 frames (so if you move, the ticker gets set to 10, and after 10 frames it will allow you to move again)