# SlidePuzzle
#   implements a slide-puzzle game.
# assumed input: a series of integers between 1 and 15, 
#   which indicate the pieces to move in the slide puzzle
# output: the slide puzzle, as it appears after each move

import string   # required later to use  zfill  function to print

PUZZLE_SIZE = 4  # the puzzle's size

# Data structure: The puzzle, where 0 marks the empty space/cell:
puzzle = [ [15, 14, 13, 12],
           [11, 10,  9,  8],
	   [ 7,  6,  5,  4],
	   [ 3,  2,  1,  0] ]

# It is convenient to remember which cell is empty:
empty_space = (3, 3)

# loop forever to move the pieces dictated by the user:

while True :

    # print the puzzle:
    for row in puzzle :
        for item in row :
            if item == 0 :
                print "  ",
            else :
                print string.zfill(item, 2), # print two-symbol number
        print

    # ask for the next move:
    num = int(raw_input("\nType number of piece to move: "))

    # search the puzzle for the piece numbered  num:
    piece = ()  # will remember the cell coordinates where  num  rests
    for i in range(PUZZLE_SIZE):
        for j in range(PUZZLE_SIZE) :
	    if num == puzzle[i][j] :
	        piece = (i, j)  # we found  num  at coordinates  i,j

    # did we find the piece ?
    if piece == () :
        print "illegal move --- try again"
    else :  # we did find it, so let's try to move it:
        # check if the piece is adjacent to the empty space: 
	i = piece[0] 
	j = piece[1]
	if (empty_space == (i-1, j))    \
	   or (empty_space == (i+1, j)) \
	   or (empty_space == (i, j-1)) \
	   or (empty_space == (i, j+1)) :
	    # if True, it's ok to move  num  into the empty space:
            puzzle[empty_space[0]][empty_space[1]] = num
	    # remember that the former cell holding  num  is now empty:
	    puzzle[i][j] = 0
	    empty_space = (i, j)
        else : # False, so it's not ok to move  num:
	    print "illegal move --- try again"
