I have to perform a depth first seach to solve the 8 puzzle game: (-1 represents the empty value)
initialState1 = [[-1,1,2], [7,8,3], [6,5,4]]
finalState1 = [[1,2,3], [8,-1,4], [7,6,5]]
The code I have:
def play(puzzle, direction):
print(puzzle)
if direction == "up":
for i in range(3):
for j in range(3):
if(puzzle[i][j]==-1):
if i!=0:
puzzle[i][j] = puzzle[i-1][j]
puzzle[i-1][j] = -1
return puzzle
if direction=="down":
for i in range(3):
for j in range(3):
if(puzzle[i][j]==-1):
if i!=2:
puzzle[i][j] = puzzle[i+1][j]
puzzle[i+1][j] = -1
return puzzle
if direction == "left":
for i in range(3):
for j in range(3):
if(puzzle[i][j] == -1):
if j!=0:
puzzle[i][j] = puzzle[i][j-1]
puzzle[i][j-1] = -1
return puzzle
if direction == "right":
for i in range(3):
for j in range(3):
if(puzzle[i][j] == -1):
if j!=2:
puzzle[i][j] = puzzle[i][j+1]
puzzle[i][j+1] = -1
return puzzle
def checkBoundaries(puzzle):
possibilities = []
for i in range(3):
for j in range(3):
if(puzzle[i][j]==-1):
if(i == 0):
if(j == 0):
possibilities.append("down")
possibilities.append("right")
elif(j == 1):
possibilities.append("down")
possibilities.append("right")
possibilities.append("left")
elif(j == 2):
possibilities.append("down")
possibilities.append("left")
if(i == 1):
if(j == 0):
possibilities.append("down")
possibilities.append("right")
possibilities.append("up")
elif(j == 1):
possibilities.append("down")
possibilities.append("right")
possibilities.append("left")
possibilities.append("up")
elif(j == 2):
possibilities.append("down")
possibilities.append("left")
possibilities.append("up")
if(i == 2):
if(j == 0):
possibilities.append("up")
possibilities.append("right")
elif(j == 1):
possibilities.append("up")
possibilities.append("right")
possibilities.append("left")
elif(j == 2):
possibilities.append("up")
possibilities.append("left")
return random.choice(possibilities)
def depthFirstSearch():
pathcost=0
queue=[]
initialFormatted=[initialState1,"none"]
queue.append(initialFormatted)
while(True):
puzzle=queue.pop(0)
pathcost=pathcost+1
print(str(puzzle[1])+" --> "+str(puzzle[0]))
if(puzzle[0] == finalState1):
print("Found")
print("Path cost -> "+str(pathcost-1))
break
else:
nextMove=play(puzzle[0], checkBoundaries(puzzle[0]))
if(nextMove!=puzzle[0]):
nextMove=[nextMove,checkBoundaries(puzzle[0])]
queue.insert(0, nextMove)
depthFirstSearch()
But running this code, I receive this error :
puzzle=queue.pop(0) IndexError: pop from empty list
How to handle this? What i'm doing wrong?
And is my code doing the right thing to achieve my goal ? In checkBoudaries method, I'm currently setting a random value (within the possibilities) to return.. Is it right or do I have to prefer some movement based on the last move?