python - Editing a duplicate list edits the original -
so i've started simple sort of roguelike game project in python, have problems editing duplicate list editing original. code follows:
charx = 1 chary = 1 level = [["#","#","#","#","#","#","#"],["#",".",".",".",".",".","#"],["#",".","#",".",".",".","#"],["#","#","#","#","#","#","#"]] while true: move = raw_input("u,d,l or r: ") if move=="u": if level[chary-1][charx]!="#": chary-=1 elif move=="d": if level[chary+1][charx]!="#": chary+=1 elif move=="r": if level[chary][charx+1]!="#": charx+=1 elif move=="l": if level[chary][charx-1]!="#": charx-=1 display_level=level display_level[chary][charx]="@" row in display_level: print "".join(row) row2 in level: print ",".join(row2)
as can see have created list called level, each list inside list row. characters starting row , column position stated.
then loop asks whether want move up, down left or right. checks see if there wall (the # character) in way , reacts accordingly.
as can see, makes duplicate of level called display_level , puts "@" character onto display level. problem changing display_level changes level no apparent reason, though separate , each time loop runs through makes display_level=level.
display_level , level printed separately , shows level being edited along side display_level shouldn't happen.
so want know why changing part of display_level change level , how can fix it.
much appreciated
you not creating duplicate of level
. create reference same list.
to create copy of list, can slice start end:
display_level = level[:]
but case, not enough. need copy nested lists. in case, list comprehension easiest:
display_level = [l[:] l in level]
a more comprehensive solution use copy.deepcopy()
function make absolutely sure top-level object , contained objects copies:
import copy # ... display_level = copy.deepcopy(level)
Comments
Post a Comment