1

So, I am developing this game where the graphics is made entirely of text.

This prototype looks right but there are some errors in the program.

If anyone has any solutions to the problem please, tell me.

global tiles
tiles = ["=","#"," "]
st1 = [1,1,1,1,1]
global pcx
global pcy
global lcx
global lcy
pcx = 3
pcy = 3
lcx = 3
lcy = 3

#makes 1 charecter on the screen
def j1t(ps):
    ltr = ""
    if pcx == lcx and lcy == pcy: # error "UnboundLocalError: local variable 'pcx' referenced before assignment""
        ltr = "@"
    else:
        ltr = tiles[ps[pcx]]
    if pcx == 5:
        pcx -= 4
    else:
        pcx += 1
    return ltr
print(j1t(st1)) # error "line 25, in <module> print(j1t(st1))"

1 Answers1

1

Functions do not see global variables by default. You have to use the global statement inside a function to tell it to see the global variable. Otherwise, any reference to that variable is actually an attempt to reference a function local variable by that name. And since you don't have a variable called pcx inside that function, you get the UnboundLocalError.

Add global to the beginning of your function as below, so that it can access the global variables.

def j1t(ps):
    global pcx, pcy, lcx, lcy  # Add this line
    ltr = ""
    if pcx == lcx and lcy == pcy:
        ltr = "@"
    else:
        ltr = tiles[ps[pcx]]
    if pcx == 5:
        pcx -= 4
    else:
        pcx += 1
    return ltr
Steven
  • 1,733
  • 2
  • 16
  • 30
  • You can also use comma-separated variables if you need to reference multiple global variables: `global pcx, pcy` for example. – Brian Rodriguez May 15 '22 at 00:11
  • Yes, thank you for reminding me to include the remaining variables. – Steven May 15 '22 at 00:14
  • _Functions do not see global variables by default_ This is true if the function _assigns_ to the variable. If the function only _reads_ the variable, it is visible without a `global` statement. – John Gordon May 15 '22 at 00:19
  • @JohnGordon how do you explain the OP's error, then? If they hadn't assigned to `pcx` at all, then they wouldn't have gotten it? – Brian Rodriguez May 15 '22 at 00:45
  • @BrianRodriguez I believe JohnGordon was refining the accuracy of my statement in a more general sense, which I appreciate. Since assignment occurs in this example as you say, my statement remains correct for this instance. – Steven May 15 '22 at 01:09