0

I have hosted a multiplayer game which runs on python, and i wanted to edit the script in such a way that when i join a message showing that i am playing is displayed on everyone's screen. i was able to do this but the message is shown in the start of every match, i tried to fix it but i'm getting a problem. This is the python script i'm trying to edit:

def onPlayerJoin(self,player):
    'Called for all new bs.Players (including the initial set of them).'
    if player.getName(full=True,icon=False) == "AwesomeLogic":
        if g == 0:
            bs.screenMessage("AwesomeLogic is playing")
            g = 1


def onPlayerLeave(self,player):
    'Called when a player is leaving the activity.'
    g = 0

But this gives me an error:

 if g == 0: UnboundLocalError: local variable 'g' referenced before assignment

Can anyone please tell me what i'm doing wrong?

  • you have to define ```g``` as global variable else it assumes it as the local variable. – Manoj Jadhav Dec 21 '17 at 06:44
  • Possible duplicate of [Why can't I set a global variable in Python?](https://stackoverflow.com/questions/1281184/why-cant-i-set-a-global-variable-in-python) – Julien Dec 21 '17 at 06:45

1 Answers1

0

Read about variable scope: all variables (re)assigned within a function are considered local by default. This is the case for your g, thus g is considered local and not defined yet at if g == 0:.

You can use global g to define g as a global variable within your function, although use of global variables is strongly discouraged...

Julien
  • 13,986
  • 5
  • 29
  • 53