简体   繁体   English

使用pygame事件突破python for循环

[英]Breaking out of a python for loop using pygame events

I am having an issue breaking out of a for loop in python, using pygame. 我在使用pygame遇到了在python中打破for循环的问题。 Specifically, I'm trying to break out of the loop on release of a key. 具体来说,我正在尝试在释放密钥时打破循环。 For example when key "W" is held down, the code should execute, but then immediately break out of loop when the "W" is released. 例如,当按下键“ W”时,应执行代码,但是当释放“ W”时,则立即退出循环。

I have tried to use pygame.key.get_pressed() and if event.type == KEYUP: but I cannot seem to get it right. 我试图使用pygame.key.get_pressed()if event.type == KEYUP:但是我似乎无法正确地使用它。 Can anyone help? 有人可以帮忙吗?

while 1:
  for event in pygame.event.get():   
    if event.type == pygame.QUIT: 
      doQuitStuff()
    elif event.type == pygame.MOUSEBUTTONDOWN:
      doMouseButtonStuff()
    elif event.type == KEYDOWN:
      if event.key == pygame.K_p:
        doPStuff()
      elif event.key == pygame.K_e:
        doEStuff()
      elif event.key in foo:
        doFooStuff()
        for i in xrange(100):
          doThisStuffOnlyIfKeyInFooIsHeldDown() #This for loop finishes
                                                #execution even if I release the
                                                #key in "foo"      

You have to do without for loop - and while True will do as loop. 您必须没有for循环- while True将作为循环。

run_loop = False
i = 0

while True:

    # - events -

    for event in pygame.event.get():

        if event.type == KEYDOWN:
           if event.key == pygame.K_w:
              # start loop
              run_loop = True
              i = 0

        elif event.type == KEYUP:
           if event.key == pygame.K_w:
              # stop loop
              run_loop = False

    # - updates -

    if run_loop and i < 100:
        i += 1
        doThisStuffOnlyIfKeyInFooIsHeldDown() 

    # - draws -

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM