I'm having difficulty understanding why expqueue keeps changing to multiple iterations of state, I've tried everything I have looked up from [:] to deep copy. Can someone explain whats wrong? The code is for a 8 puzzle game, and if I could get a running list going of all the different combinations I'm sure I could complete this myself, and yes, it is homework.
import copy
init = [[2,0,3], [1,5,6],[4,7,8]]
goal = [[1,2,3], [4,5,6],[7,8,0]]
expqueue = []
tempqueue = []
depth = 0
def myappend(lst1, lst2):
new = list(lst1)
new2 = list(lst2)
new.append(new2)
global expqueue
expqueue = new
def makeState(state):
for x in range(0,3):
for i in range(0,3):
print state[x][i],
print "\n"
def locate(state):
for x in range(0,3):
for y in range(0,3):
if state[x][y] == 0:
return [x, y]
def moveU(state):
location = locate(state)
x = location[0]
y = location[1]
s = x-1
if x>0:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def moveL(state):
location = locate(state)
x = location[0]
y = location[1]
s = y-1
if y>0:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveR(state):
location = locate(state)
x = location[0]
y = location[1]
s = y+1
if y<2:
swap = state[x][y]
state[x][y] = state[x][s]
state[x][s] = swap
myappend(expqueue, state)
def moveD(state):
location = locate(state)
x = location[0]
y = location[1]
s = x+1
if x<2:
swap = state[x][y]
state[x][y] = state[s][y]
state[s][y] = swap
myappend(expqueue, state)
def expand(lst):
tempqueue = lst[:]
while tempqueue != []:
state = tempqueue[0]
current = state[:]
moveU(current)
moveL(current)
moveR(current)
moveD(current)
del tempqueue[0]
return expqueue
def solve(queue, initial, solution, level):
length = len(queue)
for x in range(length):
if queue[x] == solution:
return "This works!"
return solve(expand(queue), initial, solution, level+1)
print solve([init], init, goal, 0)
I've since added deepcopy over the initial slices, and I've noticed the ID's are coming back the same after the copy. Does anyone know why?
Apparently I don't have enough street cred to post a screen shot so here's a link to it: Matching id's after copy