0

I'm making a game with pygame, and I ran into a problem. The function below is supposed to make a list of lists, containing 1s and 0s according to wall/floor. However, when I try to edit a single tile, an entire column is changed.

def createDefault(width,height,tileW,tileH):
    level = []
    mid = []
    level.append([1]*(width/tileW))
    mid.append(1)
    for i in range((width - (tileW * 2)) / tileW):
        mid.append(0)
    mid.append(1)
    for i in range((height - (tileH * 2)) / tileH):
        level.append((mid))
    level.append([1]*(width/tileW))
    return level

level = createDefault(640,640,64,64)
level[2][4] = 1
print level  

prints (prettified):

[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 0, 0, 0, 1, 0, 0, 0, 0, 1],
 [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]  

As you can see, in every list in the array, value 4 has been changed to 1. How can I make only the value in list 2, character 4 be edited?

sloth
  • 99,095
  • 21
  • 171
  • 219
Shadow Man
  • 23
  • 3
  • You may want to read this: https://docs.python.org/2/library/copy.html – Svalorzen May 25 '14 at 21:52
  • You probably need to indent things a little more; the `mid` handling code looks under-indented to me. – Martijn Pieters May 25 '14 at 21:55
  • 1
    Other questions concerning this problem: [1](http://stackoverflow.com/q/18946728/1258041), [2](http://stackoverflow.com/q/13058458/1258041), [3](http://stackoverflow.com/questions/240178/python-list-of-lists-changes-reflected-across-sublists-unexpectedly), ... – Lev Levitsky May 25 '14 at 21:59

1 Answers1

0

You are appending the same single mid list to level over and over again:

for i in range((height - (tileH * 2)) / tileH):
    level.append((mid))

Append a (shallow) copy instead:

for i in range((height - (tileH * 2)) / tileH):
    level.append(list(mid))

where list() creates a new list object with the values copied.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343