python - pygame中的不断运动

标签 python pygame

这是我的第一个 pygame 代码,内容不多,非常简单。当我想移动我的播放器时,它可以工作,但我希望移动平稳。就像当我向左按时,我希望它向左移动。目前,每次我都必须按下左按钮,以便播放器向左移动。您对如何做到这一点有什么建议吗?

import pygame, sys

pygame.init()

window_size = ( 400, 400 )

white = ( 255, 255, 255 )

class Player():
  image = pygame.image.load( 'foo.png')
  rect = image.get_rect()

player = Player()

screen = pygame.display.set_mode( window_size )

done = False

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()

    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_LEFT:
        move = (-10, 0 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_RIGHT:
        move = ( 10, 0 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_UP:
        move = ( 0,-10 )
        player.rect = player.rect.move(move)
      if event.key == pygame.K_DOWN:
        move = ( 0, 10 )
        player.rect = player.rect.move(move)

  screen.fill( white )
  screen.blit( player.image, player.rect )

  pygame.display.flip()

编辑 我对亚伦回答的态度:

while not done:

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()

  pressed = pygame.key.get_pressed()
  if pressed[pygame.K_LEFT]:
    move = ( 2, 0 )
    player.rect = player.rect.move(move)
  if pressed[pygame.K_RIGHT]:
    move = ( 2, 0 )
    player.rect = player.rect.move(move)
  if pressed[pygame.K_UP]:
    move = ( 0,-2 )
    player.rect = player.rect.move(move)
  if pressed[pygame.K_DOWN]:
    move = ( 0, 2 )
    player.rect = player.rect.move(move)

最佳答案

您可以跟踪 KEYUPKEYDOWN 事件,然后为您跟踪的每个键存储按下状态。

现在,不是在用户按下某个键时移动播放器,而是测试键的状态以查看它是否被按下,如果是则向播放器应用移动。

举个简单的例子:

pressed_keys = {
    'left': false,
    ...define other keys...
}

while not done:

    # Check for key events
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                pressed_keys['left'] = True
            ...check other keys...

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                pressed_keys['left'] = False
            ...check other keys...

   # Move the player
   if pressed_keys['left']:
       ...move player left...

关于python - pygame中的不断运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799865/

相关文章:

python - 什么时候应该在 Django 中使用自定义管理器而不是自定义查询集?

python - Pandas to_datetime 不适用于空值

python - 使用 Python 逐 block 加载 Excel 文件而不是将整个文件加载到内存中

python - 为什么这个循环不能正常运行?

python - 有什么东西可以影响 time.sleep() 比我需要的更早发生吗?

python - 每次我的字符串从文本更改为数字时,如何插入字符 ('-"),反之亦然?

python - 在 zip 对象列表上执行 len 会清除 zip

python - python 3.5 的 Pygame 安装

python - 游戏错误 : 'pygame' has no attribute 'init'

python - Pygame 中的箭头键移动