Skip to main content
 首页 » 编程设计

python之如何在 Python 中同时运行两个 while 循环

2024年10月25日10zlslch

我是 Python 的新手,使用 Zelle 的图形来创建游戏。我需要下面的两个 while 循环同时运行,但是我遇到了困难。我尝试嵌套 while 循环,但只有单击鼠标时马和平民才会移动,这是我不想要的。我想要的是马匹和平民一直在移动,而公主只有在点击鼠标时才移动,当她拯救了 10 个平民时,“游戏结束”结束游戏。

    # animation loop. 
while True==True: 
 
    for horse in horseList: 
        if horse.leg.getX() > -187: 
            horse.move( -1, 20 ) 
        else: 
            horse.move( 5, 28 ) 
 
    for civilian in civiliansList: 
 
        if civilian.getX() < 800: 
            civilian.move( 20, 0 ) 
        else: 
            civilian.move( -100, 0 ) 
 
while civiliansSaved != 10: 
 
    mouse = win.getMouse() 
 
    princess.move( mouse, civilianCounter) 
 
    civilianCounter = princess.move( mouse, civilianCounter) 
    # move is a method that will return an updated civilianCounter ( it is initially 0 and defined outside of the while loop ), depending on whether princess runs into civilians 
 
else: 
    print( "Game over" ) 
    win.getMouse() 
    win.close() 

请您参考如下方法:

只需在动画循环中使用 checkMouse() 而不是 getMouse()。

我想,就这么简单。

while civiliansSaved < 11: 
 
    for horse in horseList: 
        if horse.leg.getX() > -187       
            horse.move( -1, 20 ) 
        else: 
            horse.move( 5, 28 ) 
 
    for civilian in civiliansList: 
        if civilian.getX() < 800: 
            civilian.move( 20, 0 ) 
        else: 
            civilian.move( -100, 0 ) 
 
    mouse = win.checkMouse() 
 
    if mouse: 
        princess.move( mouse, civilianCounter) 
        civilianCounter = princess.move( mouse, civilianCounter) 
 
print( "Game over" ) 
win.getMouse() 
win.close() 

多科:

checkMouse() Similar to getMouse, but does not pause for a user click. Returns the latest point where the mouse was clicked or None if the window as not been clicked since the previous call to checkMouse or getMouse. This is particularly useful for controlling simple animation loops.