按下时会出现Sprite

时间:2014-06-12 01:14:15

标签: python

我想要的代码是,当我按向上箭头键时,它应该将精灵blit到屏幕上,但事实并非如此。有什么想法吗?

(无需帮助)

while 1:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit(0)
    elif event.type == pygame.K_a:
        screen.blit(image05,(75,50))
        pygame.display.flip()

while True:
    event = pygame.event.poll()
    if event.type == pygame.QUIT:
    pygame.quit()
    sys.exit(0)

2 个答案:

答案 0 :(得分:4)

我希望你能原谅我对第一部分的直言不讳,但你的while循环是流量控制领域中一些主要的复制/粘贴无知的证据。那些循环也是问题所在,这就是我提到它们的原因。

  1. 您将需要只有一个 while循环来轮询不等于quit事件的输入。
  2. 然后,那个循环中你想要定义你的输入案例(if语句)
  3. 将输入发送到您自己的代码,以便您选择响应或操作 - 在这种情况下,在该向上箭头键上移动精灵。
  4. 始终允许以某种方式关闭循环。
  5. 简短回答: 它无效,因为您只允许程序在响应其他输入事件之前退出。

    请阅读关于while,for,foreach,do / until的文章。我会找到一个并通过链接更新这个答案。

    1. 这是关于loop usage and syntax
    2. 的python文档
    3. 这里control flow from the wikipedia绝对会让您的旅程变得轻松。

答案 1 :(得分:0)

事实上。不要在无限循环或sys.exit()语句之后放置代码。正确的方法是:

while 1:
    event = pygame.event.wait() #use wait to prevent busy loop
    if event.type == pygame.QUIT:
       pygame.quit()
       sys.exit(0)
    elif event.type == pygame.KEYDOWN && event.key == pygame.K_a:
         screen.blit(draw_me1,(25,25))
    pygame.display.flip()

这将触发“a”键,而不是向上箭头。要使其在向上箭头键上触发,请使用不同的键常量。