 


Task

Implement the Fifteen Puzzle Game.



The   15-puzzle   is also known as:

   Fifteen Puzzle
   Gem Puzzle
   Boss Puzzle
   Game of Fifteen
   Mystic Square
   14-15 Puzzle
   and some others.


Related Tasks

   15 Puzzle Solver
   16 Puzzle Game


background 432
textsize 13
len f[] 16
func draw . .
  clear
  for i range 16
    h = f[i]
    if h < 16
      x = i mod 4 * 24 + 3
      y = i div 4 * 24 + 3
      color 210
      move x y
      rect 22 22
      move x + 4 y + 5
      if h < 10
        move x + 6 y + 5
      .
      color 885
      text h
    .
  .
.
global done .
func init . .
  done = 0
  for i range 16
    f[i] = i + 1
  .
  # shuffle
  for i = 14 downto 1
    r = random (i + 1)
    swap f[r] f[i]
  .
  # make it solvable
  inv = 0
  for i range 15
    for j range i
      if f[j] > f[i]
        inv += 1
      .
    .
  .
  if inv mod 2 <> 0
    swap f[0] f[1]
  .
  textsize 12
  call draw
.
func move_tile . .
  c = mouse_x div 25
  r = mouse_y div 25
  i = r * 4 + c
  if c > 0 and f[i - 1] = 16
    swap f[i] f[i - 1]
  elif r > 0 and f[i - 4] = 16
    swap f[i] f[i - 4]
  elif r < 3 and f[i + 4] = 16
    swap f[i] f[i + 4]
  elif c < 3 and f[i + 1] = 16
    swap f[i] f[i + 1]
  .
  call draw
  done = 1
  for i range 15
    if f[i] > f[i + 1]
      done = 0
    .
  .
  if done = 1
    clear
    move 10 30
    text "Well done!"
  .
.
on mouse_down
  if done = 1
    call init
  else
    call move_tile
  .
.
call init