My code:
class World:
def __init__(self, _map, pos):
self.orig_map = _map
self.map = self.orig_map[:]
self.orig_pos = pos
self.pos = list(self.orig_pos)
def reset(self):
self.map = self.orig_map[:]
self.pos = list(self.orig_pos)
def left(self):
if self.pos[1]>0:
self.pos[1]-=1
def right(self):
if not self.pos[1]+1>=len(self.map[0]):
self.pos[1]+=1
def up(self):
if self.pos[0]>0:
self.pos[0]-=1
def down(self):
if not self.pos[0]+1>=len(self.map):
self.pos[0]+=1
def eat(self):
if self.map[self.pos[0]][self.pos[1]]==1:
self.map[self.pos[0]][self.pos[1]]=0
return True
What is supposed to happen:
>>> w=World([[0,0,0],[0,1,0],[0,0,0]],(0,0))
>>> w.right()
>>> w.down()
>>> w.eat()
True
>>> w.reset()
>>> w.map
>>> [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
What happens:
>>> w=World([[0,0,0],[0,1,0],[0,0,0]],(0,0))
>>> w.right()
>>> w.down()
>>> w.eat()
True
>>> w.reset()
>>> w.map
>>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Where it probably goes wrong: self.map = self.orig_map[:]
The above would have worked (tried and tested) for a single list, however, it doesn't seem to work for nested lists.
2 Answers 2
By saying self.map = self.orig_map[:]
you are indeed making a copy of self.orig_map
. However, this is a shallow copy, and the elements within self.map
will still be the same objects as the elements within self.orig_map
.
What you need to do instead is make self.map
a deep copy of self.orig_map
in your __init__
. E.g.
import copy
...
self.map = copy.deepcopy(self.orig_map)
You should use deepcopy
import copy
cop2 = copy.deepcopy(origin)
It will recursively copy your object.
Explore related questions
See similar questions with these tags.
deep_copy
it. See thisw.orig_map
in the last step? You could in this case use thecopy
module'sdeepcopy
function.w.map
. However, at that step, they should be equal (value wise) but be different objects.reset()
call.self.orig_map
contains,deepcopy
may not work stackoverflow.com/questions/1601269/…