4

I've been having trouble with the "def" function. I know this question has already been asked, but the answer didn't satisfy me and I didn't see how to apply it to my code. I'm trying to make the the popular game 2048 in Python. Basically, when I define the function that makes the entire board move left, it bites me with the error: UnboundLocalError: local variable referenced before assignment. It seems that I have to define the variables "bone" and "btwo" in somewhere that isn't, like, global. But I am yet to figure out how to get that working. Setting parameters in my moveleft() function isn't working, e.g moveleft(bone,btwo). So I'm at my wit's end.

Now, I'll include the entire code, all commented up, but the part I think has the problem is where I define the function moveleft(). Also, if there are any outstanding stupid bits of code, please tell me. Also, try and keep it simple, I'm pretty rubbish with programming and its associated phrases and terms. This is only my 3rd attempt at a code.

I realise I'm asking a lot, but I would really, really, appreciate help with this.

Code: http://pastebin.ca/2824228

Minimized version:

bone, btwo = 1, 2

def move_left():
    if bone == 1: print("bone is 1")
    if btwo == 2: print("btwo is 2")

    btwo = 3 
    bone = 2 

move_left()
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Nikachuu
  • 81
  • 2
  • 7
  • It would be much better to minimize your code without losing the error and put the minimized version here. – perreal Jul 22 '14 at 06:22
  • 2
    As you noted, there are many other questions about this problem on StackOverflow. What, precisely, do you want to know that those questions don't already answer? – BrenBarn Jul 22 '14 at 06:26

1 Answers1

3

If you are writing to a global variable inside a function, then you need to explicitly say that you are referring to a global variable. So put this as the first line in your function:

global bone, btwo, bthree, bfour, bfive, bsix, bseven, beight, bnine

And, why don't you use a list instead of defining 9 variables?

perreal
  • 94,503
  • 21
  • 155
  • 181
  • Thanks heaps! And I just realised how stupid I've been with hours and hours of bloody typing - I'll use lists from now on. – Nikachuu Jul 22 '14 at 20:58