Python Shell can not run a module with more than one while loop

1

I have serious problems with building a functional module in which you have to use more than 1 while loop, because the program stops running.

Especially when I use modules like pygame and tkinter, in which my goal is to build a game, but I need to use more than 1 while loop, but if I put it to run it stops working. In this situation I intend to run two loops at the same time, but the window stops responding. Why?

---------------------------- ####### ------------ --------------------------

I also did not understand why my while loop does not exist when I turn the variable 'playing' True? In this situation I only want to run one while loop at a time, and the switch off of the while loop is when the 'playing' variable is True. Here is the code:

playing = False
def play():
    playing = True

def gameloop():
    ...
    play()

while not playing:
    gameloop()

while playing:
    gameDisplay.fill(black)
    pygame.display.update()
    clock.tick(15)

The problem is that the second while loop does not run and the first one does not stop running when I call the play () function, even if I declare the global 'playing' variable. Why?

Using python 3.5.0 with Windows 10

I do not see why windows stop responding when I run more than one while loop, because other people's PCs work perfectly. Will the problem be on my pc?

    
asked by anonymous 09.07.2016 / 20:01

1 answer

2

What you run when you put:

def play():
    playing = True

The interpreter created playing as a local variable, so even if you change the value within play the playing global will remain False .

Global variable declaration

To tell the interpreter that you want to use the global variable, you must pass the global attribute to the variable in the method. If the variable does not exist, it is instantiated. Tested on python3.4 (Gentoo Linux)

def play():
    global playing
    playing = True

Contrary to what many beginners think, to use a global variable is not enough to just declare it at the top of the file, you need to specify in the method that a global variable will use.

If it does not work, you can use alternative methods.

Library

vars.py:

playing = False

main.py:

import vars

...

def play():
    playing = True

...

while not vars.playing:
    ...

This method imports variables from a python file, so when it references the variable, its path is passed so the method does not create a local variable.

Static

def gameloop():
    self.playing = True
gameloop.playing = False

...

while not gameloop.playing:

Dict

conf = {
    'playing' : False,
}

def play():
    conf['playing'] = True

...

while not conf['playing']:
    ...
    
15.07.2016 / 06:58