1

I'm working on a project using python along with the pygame module. I have split the project into 7 files for better code management. Since it would be difficult to describe the issue including all the files. I'll code a similar situation below: (the program starts from file 4)

file1.py

import pygame

running = True

file2.py

from file1 import *

def game_logic():
    global running
    if player.health <= 0:
        running = False

file3.py

from file2 import*

def game():
    global running
    if pygame.key.get_pressed()[K_ESCAPE]:
        running = False

    game_logic()

file4.py

from file3 import *

while running:
    game()

Whenever I press the escape button my program ends without any issue but, whenever the players health falls below 0, the program does not stop and keeps running. I added a print statement inside the if statement which changes the value of running variable, but even after the health becomes negative, the program keeps running and the value of running is not changed.

If anyone wants the .py files do let me know and I'll perhaps email it to you.

Community
  • 1
  • 1
Ontropy
  • 130
  • 1
  • 12

1 Answers1

1

When declared in function, global running creates a new running variable that overrides the imported running. What you want to do here is nonlocal running.

Also, this is typically why global is never recommended. You could achieve the same kind of behavior more securely using a singleton class ; or just import file1 (in file2) then test on file1.running.

Martin
  • 56
  • 3