#!/usr/bin/python3

license = '''sliding puzzle
By: Pedro Izecksohn
Version: 2013-Nov-11 04:12
License: If and only if this program is unmodified then it may be distributed.

Move the characters using one of w a s d followed by Enter.
'''

def build_square (square):
  l = []
  for i in range(square):
    l.append(i)
  l[0] = ' '
  return l

from cmath import sqrt

def print_square (l):
  side = sqrt(len(l)).real
  sidemax = 6
  if (side>sidemax):
    raise Exception ('print_square was not implemented for a side so big.')
  si = ''
  s = ''
  for i in l:
    if i == ' ':
      si = i
    elif i > 9:
      si = str (bytearray ([ord('a')+(i-10)]).decode())
    else:
      si = str (i)
    if len(s) == side:
      print(s)
      s = si
    else:
      s = (s + si)
  print(s)

def print_help (side):
  print('The target format is')
  print_square (build_square (side*side))
  print()

from sys import argv
from sys import exit
from sys import stdin
import random

class XY:
  def __init__ (self, l, desired):
    self.side = sqrt(len(l)).real
    for i in range(len(l)):
      if l[i] == desired:
        self.x = int((i % side).real)
        self.y = int((i / side).real)
  def ifc (self):
    return (side*self.y)+self.x

def ifc (x, y):
  #print 'ifc (x =',x, ', y =',y, ')'
  return (side*y)+x

def apply_command (c, l):
  #print 'apply_command ('+c
  xy0 = XY (l, ' ')
  max = xy0.side-1
  oi = xy0.ifc()
  if c == 's':
    if xy0.y > 0:
      oi = ifc (xy0.x, xy0.y-1)
  elif c == 'w':
    if xy0.y < max:
      oi = ifc (xy0.x, xy0.y+1)
  elif c == 'a':
    if (xy0.x < max):
      oi = ifc (xy0.x+1, xy0.y)
  elif c == 'd':
    if (xy0.x > 0):
      oi = ifc (xy0.x-1, xy0.y)
  else:
    print('The command '+c+' is not specified.')
  l [xy0.ifc()] = l [oi]
  l [oi] = ' '

verbose=False
help=False
side = 0
i = 0
while (i<len(argv)):
  i+=1
  if i==len(argv):
    break
  if argv[i]=='-h':
    print(license)
    help=True
    continue
  if argv[i]=='-v':
    verbose=True
    continue
  try:
    side = int(argv[i])
    break
  except ValueError:
    print('What is '+argv[i]+' ?')
    exit(2)

ineed = 'I need an integer argument such that 2 <= integer <= 6'
if side>6:
  print(ineed)
  exit(2)

if help:
  if side < 2:
    print_help (2)
    print(ineed)
    exit(2)
  else:
    print_help (side)
    print('Your puzzle is')

if side < 2:
  print(ineed)
  exit(2)

square = side*side
l = build_square (square)
shuffled = list (l)
rtop = int (square + (square/3))
while shuffled == l:
  for i in range(rtop):
    c = random.choice(['w','a','s','d'])
    if verbose: print(i,'= '+c)
    apply_command (c, shuffled)

while (shuffled != l):
  print_square (shuffled)
  command = stdin.readline()
  if 0 == len (command): exit(0)
  c = command[0]
  apply_command (c, shuffled)

print_square(shuffled)

