1

I'll preface by saying that I'm new to Python. I appologize if this should be extremely simple...

I'm working on "Maze" world on reeborg.ca trying to fix a bug where if your sprite starts with no walls around it, it could loop in a circle. I tried to create an init cycle called "init_homing" where it tests to see if the condition of being in a space with no walls surrounding the sprite is true. If it does, it will move and then run the "init_homing" function again until it has a wall adjacent to it. Once it has this adjacent wall, it should change the seek_goal value to True, which should break the "init_homing" function and continue on to the primary part of the program..

The issue is, is that even though it gets to the else statements which should change the value of seek_goal to True, the seek_goal value remains as False

Thank you in advanced:

seek_goal = False
def turn_right():
    turn_left()
    turn_left()
    turn_left()
def turn_around():
    turn_left()
    turn_left()
def init_homing():
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True
        
while seek_goal == False:
    init_homing()

while at_goal() == False and seek_goal == True:
    if right_is_clear():
        turn_right()
        move()
    elif front_is_clear():
        move()
    else:
        turn_left()
Velexter
  • 19
  • 1
  • 1
    The `seek_goal` variable is local to the function. So your `while` loop is infinite. The values should be returned from the `init_homing` function to be used in the `while` loop. – S3DEV Aug 17 '22 at 15:44

1 Answers1

2

If you assign to a variable inside of a function, it's treated as a local variable. The seek_goal variable inside init_homing has no relation to the global one at the top of your file, despite seeming to have the same name.

To demand that Python use the global variable instead, use the global keyword.

def init_homing():
    global seek_goal
    if right_is_clear() and front_is_clear():
        turn_around()
        if right_is_clear() and front_is_clear():
            turn_right()
            move()
        else:
            seek_goal = True
    else:
        seek_goal = True
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • 2
    Please clarify in the answer why the use of a global is being recommended, rather than using a returned value. It feels that we are setting a new programmer on a slippery course of using globals ... – S3DEV Aug 17 '22 at 15:46