Home > Net >  Part of code in python game project not working?
Part of code in python game project not working?

Time:11-26

in my Python game code i made a function that's meant to return another function once the requirements have been completed but it doesn't seem to work and i'm not sure what else to try? her's that bit of code:

def Allfightcoords():
global xpos, ypos
if xpos == 1 and ypos == 7:
    return event_2()
elif xpos == 4 and ypos == 3:
    return event_2()
elif xpos == 5 and ypos == 5:
    return event_2()
elif xpos == 7 and ypos == 2:
    return event_2()
elif xpos == 8 and ypos == 4:
    return event_2()

Allfightcoords()

the xpos and ypos commands are just the coords the player should be on to trigger a certain event, in this case event 2. Any advice on what to change or what i've done wrong? Much appreciated.

CodePudding user response:

If you want to return the function "event_2", just write

return event_2

without parentheses. This will actually return the function object.

CodePudding user response:

To fetch a function which you want to later invoke, you return the reference to the function itself without braces.

return myFunction

This is different to what you are doing, where including braces will call the function and then return the value from the function call.

def Allfightcoords():
    global xpos, ypos
    if xpos == 1 and ypos == 7:
        return event_1
    elif xpos == 4 and ypos == 3:
        return event_2
    elif xpos == 5 and ypos == 5:
        return event_3
    elif xpos == 7 and ypos == 2:
        return event_4
    elif xpos == 8 and ypos == 4:
        return event_5

functionToInvoke = Allfightcoords() # Fetch the function.
functionToInvoke() # Call the function here.
  • Related