如何向sprite添加关键命令?

时间:2012-03-31 20:14:08

标签: python pygame

如何向sprite管道工添加关键命令?以下是我到目前为止的尝试,但按下向上按钮没有结果。当按下按钮按钮时,我如何设置ud和ld改变10?

pink = (255, 64, 64)
w = 640
h = 480
ld = 0
ud = 0
screen = pygame.display.set_mode((w, h))
running = 1
def key_event(self, event):

         if event.key == pygame.K_UP:
             ud - 10
             ld  + 10
def show_sprites():
    screen.blit(plumbers,(50+ld ,100+ud ))
def setup_background():
    screen.fill((pink))
    screen.blit(cloud_background,(0,0))
    brick_width, brick_height = brick_tile.get_width(), brick_tile.get_height()
    for x,y in itertools.product(range(0,640,brick_width),
                                 range(390,480,brick_height)):
        screen.blit(brick_tile, (x,y))

 while running:

    setup_background()
    event = pygame.event.poll()
    show_sprites()
    pygame.display.flip()

  if event.type == pygame.QUIT:
        sys.exit()
    for event in pygame.event.get():
         if event.type == pygame.QUIT:
             running = False
         elif event.type == pygame.KEYDOWN:
             w.key_event(event)

1 个答案:

答案 0 :(得分:0)

删除行

event = pygame.event.poll()

的第一次出现
if event.type == pygame.QUIT:
    sys.exit()

问题在于轮询和获取事件队列中的事件,因此您正在丢失轮询调用中的关键事件。

换句话说,会发生什么:

  1. 按UP键
  2. 这会将KEYDOWN事件插入队列
  3. 你调用event = pygame.event.poll()
  4. 返回KEYDOWN事件
  5. 你检查这是否是退出,不是这样你继续
  6. 你调用pygame.event.get(),但队列现在是空的,因此for循环没有输入
  7. 示例代码:

    import pygame
    pink = (255, 64, 64)
    w = 640
    h = 480
    ud = 0
    ld = 0
    screen = pygame.display.set_mode((w, h))
    running = 1
    def key_event(event):
        global ud
        if event.key == pygame.K_UP:
            ud -= 10
            print 'ud',ud           
    
    def setup_background():
        screen.fill((pink))
    
    while running:
    
        setup_background()
        pygame.display.flip()
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                 running = False
            elif event.type == pygame.KEYDOWN:
                 key_event(event)