Home / Python / Block puzzle or jigsaw puzzle program in python

Block puzzle or jigsaw puzzle program in python

This is a program for block puzzle in python. A jigsaw puzzle that can be a 8 block puzzle , 15 block puzzle etc is given here. The puzzle has N – 1 blocks available to solve. All you have to do is to match the broken blocks pattern with the original image. Here is the n block puzzle that can be used to solve sliding block puzzle for N( 3,4,5….) blocks.

from operator import itemgetter
n=int(input("Enter Board Size (For NxN board enter value of N only): "))  //block puzzle solution for n=3(8 blocks) n=4 (15 blocks)
print("Enter number on board row wise and 0 for space")
initialb=[]
for i in range(n*n):
    initialb.append(int(input()))
initialb=tuple(initialb)
#initialb=(1,0,6,3,2,4,7,5,8)
finalb=tuple([i for i in range(n*n)])
oldst=[]
status=0
result=()
pid=0
def isequal(a,b):
    count=0
    for i in range(n*n):
        if(a[i]!=b[i]):
            count+=1
    return count

qu=[]
fres=[]

qu.append((initialb,isequal(initialb,finalb),0,"",pid,0))
while(len(qu) and not status):
    temp=qu[len(qu)-1]
    del(qu[len(qu)-1])
    #print("temp",temp)
    #print ("top",temp)
    z=temp[0].index(0)
    pos=[]
    h=z//n
    #print(z,h)
    if((z+1)//n==h):
        pid+=1
        pos.append((z+1,"RIGHT",pid,temp[4]))
    if((z-1)//n==h):
        pid+=1
        pos.append((z-1,"LEFT",pid,temp[4]))
    if(0<=(z+n)<n*n):
        pid+=1
        pos.append((z+n,"DOWN",pid,temp[4]))
    if(0<=(z-n)<n*n):
        pid+=1
        pos.append((z-n,"TOP",pid,temp[4]))
    #print(pos)
    rt=[]
    for i in range(len(pos)):
        temp2=list(temp[0])
        t=temp2[z]
        temp2[z]=temp2[pos[i][0]]
        temp2[pos[i][0]]=t
        temp2=tuple(temp2)
        if temp2 in oldst:
            continue
        dis=isequal(temp2,finalb)
        if dis==0:
            status=1
            result=temp2
            qu.append((temp2,dis,temp[2]+1,pos[i][1],pos[i][2],pos[i][3]))
            break
        rt.append((temp2,dis,temp[2]+1,pos[i][1],pos[i][2],pos[i][3]))
        #print("add",temp2)
    rt=sorted(rt,key=itemgetter(1),reverse=True)
    for i in range(len(rt)):
        qu.append(rt[i])
    qu=sorted(qu,key=itemgetter(1),reverse=True)
    oldst.append(temp[0])
    fres.append(qu[len(qu)-1]) 

qu=[]
l=len(fres)-1
pid=fres[l][5]
qu.append(fres[l])
l-=1
while l !=-1:
    if(fres[l][4]==pid):
        qu.append(fres[l])
        pid=fres[l][5]
    l-=1

print("Total number of moves required",qu[0][2])
print("Moves are :")
for i in range(len(qu)-1,-1,-1):
    print(qu[i][3])

Tags: Block puzzle program , sliding block puzzle, block puzzle solution.

One comment

  1. I don’t understand the
    //block puzzle solution for n=3(8 blocks) n=4 (15 blocks)
    part.

Leave a Reply

Your email address will not be published. Required fields are marked *

Preventing spam * Time limit is exhausted. Please reload the CAPTCHA.