0

I am changing the value of a global variable inside a function, but as soon as I get out of that function it is changing back to its previous value. I have created a game in which a rabbit(represented by "r") is moving on a path, whenever it sees a hole("O") it jumps and if it see carrot("c"), it eat and the r is changed to "R". I have functions for left move, right move and for picking a carrot. Now whenever it picks carrot I am changing the global variable to "R" but whenever it moves again it is keeping it "r"

This is my code

import random
c="r"

def left_move(track):
    i=track.index(c)
    if (i>0):
        next=i-1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "a", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track
        
def right_move(track):
    i=track.index(c)
    if (i<50):
        next=i+1
        if (track[next]=="c"):
            track = pick_carrot(track, next, i)
            return track
        if (track[next]=="O"):
            track=jump_hole(track, next, "d", i)
            return track
        track[next]=c
        track[i]="-"
        print(i)
        return track
        
def string_track(track):
    string_track = '[' + ' '.join(track) + ']'
    return(string_track)
 
def pick_carrot(track, carrot, rabit, c):
    c="R"
    print("The value of c is now ")
    print(c)
    track[rabit]="-"
    track[carrot]="R"
    print("carrot picked")
    return track,c
    
def jump_hole(track, hole, direction, current):
    if (direction=="a"):
        next=hole-1
    if (direction=="d"):
        next=hole+1
    track[next]=c
    track[current]="-"
    print("hole jumped")
    return track
    
track=["-","-","-","-","-","-","r","-","-","-","-","c","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","-","O"]

random.shuffle(track)
print(string_track(track))
print(track.index("r"))
val=input()
while val!="0":
    if val=="a":
        track=left_move(track)
        print(c)
    if val=="d":
        track=right_move(track)
        print(c)
    if val=="0":
        break
    else:
        val=input()
print(string_track(track))
  • Actually you are changing the local `c`, not the global one. Remove the `c` parameter and use `global` keyword. – Guy Dec 06 '22 at 05:39
  • @Guy better yet, don't rely on global variables and just return data from your function to the caller – juanpa.arrivillaga Dec 06 '22 at 05:56
  • Now i want another help, can you pls In this i want that list is always visible on screen and whatever action i perform it is visiblle on that list – Samit Singhvi Dec 06 '22 at 06:28

0 Answers0