pygame 文字输入交互,如何在pygame中获得键盘输入?

I am making a game in pygame 1.9.2.

It's a faily simple game in which a ship moves between five columns of bad guys who attack by moving slowly downward. I am attempting to make it so that the ship moves left and right with the left and right arrow keys. Here is my code:

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

It works too well. The ship moves too fast. It is near impossible to have it move only one location, left or right. How can i make it so the ship only moves once every time the key is pressed?

解决方案

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.

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

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.

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

Then somewhere during the game loop you would do something like this:

if move_ticker > 0:

move_ticker -= 1

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值