Good day to all. I am trying to build a game called 2048.I made a variable named box and added 4 lists each list containing a 4 empty values to be replaced later.Then I declared it global(tried reverse too:declared global and then made the values inside them).when I call global box in one function(to do changes to the box),it works.then I called another function which changes position of box and it too passed without a error.but the third where I assign the box to another variable with list comphrehension like this:
box = [[[]]*4 for i in range(4)] # this is box
box1 = [box[i][::-1] for i in range(4)] # tried to do this
the second function didn't require box1 but I called it to see if any error occurs.Nothing occurs. but when I do same with the next function error "NameError:free variable box referenced before assignment in enclosing scope" occurs.
why is that.what did I do wrong? here is the code
import random
global box
box = [[[]]*4 for i in range(4)]
def adding():
digit = random.choice([2,4])
empty = [index for index,i in enumerate(box[0]) if i==[]]
add = random.choice(empty)
try:
for i in range(3):
if box[i][add] == [] and box[i+1][add] != []:
box[i][add] = digit
break
elif box[-1][add] == []:
box[-1][add] = digit
break
except:
print('Error Occured')
def right():
box1=[box[i][::-1] for i in range(4)]
for i in range(4):
take = box[i]
box[i]=[[] for x in take if x ==[]]
for j in [x for x in take if x != []]:
box[i].append(j)
def left():
box1 = [box[i][::-1] for i in range(4)]
right()
box1 = [box[i][::-1] for i in range(4)]
box= box1
error occurs at function left()
tried in different os too.
thanks.works when I declared global inside function but ca anyone explain why did it work for right() but not for left()?
globaloutside a function and fix your indentationglobal boxinside your function