簡體   English   中英

為什么循環不會通過任何按鍵來停止?

[英]Why won't the loop take any keystroke to stop?

我正在嘗試使用 while 語句創建一個在屏幕上移動的無限循環,我想知道如何使用擊鍵來激活中斷命令以停止循環?

while run_me:
    clock.tick(fps_limit) 

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run_me = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                T = 1
                while T == 1:
                    posx = posx - 1
                    screen.fill(black)
                    pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
                    pygame.display.flip()
                    if posx == 0:
                        posx = posx + 600

問題是無限的內循環。 一旦進入這個循環,它就永遠不會終止。 切勿在主應用程序循環中實現游戲循環。 使用主應用程序循環並使用pygame.key.get_pressed()來實現連續移動。

while run_me:
    clock.tick(fps_limit) 

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run_me = False
    
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:    
        posx = posx - 1
        if posx == 0:
            posx = posx + 600
    
    screen.fill(black)
    pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
    pygame.display.flip()

您可能不希望有兩個循環。 目前你沒有在你的內部循環中做任何事件處理,這意味着沒有好的方法來阻止它。 但是,與其在其中添加額外的pygame.event東西,為什么不直接重用主循環中的代碼呢?

這里的代碼可能非常接近工作(它不完整,所以我沒有測試它)。 大多數更改只是取消縮進你已經擁有的東西。

while run_me:
    clock.tick(fps_limit) 

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run_me = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                T = 1
            elif event.key == pygame.K_RIGHT:   # add some code to stop drawing
                T = 0

    if T == 1:               # change this to an `if` rather than a `while`, and unindent
        posx = posx - 1
        screen.fill(black)
        pygame.draw.circle(screen, colorcircle, (posx, posy), 50)
        pygame.display.flip()
        if posx == 0:
            posx = posx + 600

您可能應該使用比T更好的變量名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM