 


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


      IF INKEY(-256)=77 OR (INKEY(-256) AND &F0)=&A0 THEN MODE 1: COLOUR 0: COLOUR 143: *FX4,1
 
      SIZE=4 : DIFFICULTY=3
 
      MAX=SIZE * SIZE - 1
      DIM Board(MAX)
      FOR I%=1 TO MAX : Board(I% - 1)=I% : NEXT
      Gap=MAX
      WHILE N% < DIFFICULTY ^ 2 PROCSlide(RND(4)) : ENDWHILE : REM Shuffle
      N%=0
 
      @%=2 + LOG(MAX + 1)
      PROCShowAndTest
      WHILE NOT Solved
        PRINT "Use arrow keys to move the gap around. Moves taken: ";N%
        PROCSlide(GET - 135)
        PROCShowAndTest
      ENDWHILE
      PRINT "Solved after ";N% LEFT$(" moves", 6 + (N% = 1)) "."
      END
 
      DEF PROCSlide(dir%)
      NewGap=Gap
      CASE dir% OF
        WHEN 1: IF Gap MOD SIZE > 0        NewGap=Gap - 1    : N%+=1 : REM Left
        WHEN 2: IF Gap MOD SIZE < SIZE - 1 NewGap=Gap + 1    : N%+=1 : REM Right
        WHEN 3: IF Gap < MAX - SIZE + 1    NewGap=Gap + SIZE : N%+=1 : REM Down
        WHEN 4: IF Gap > SIZE - 1          NewGap=Gap - SIZE : N%+=1 : REM Up
      ENDCASE
      SWAP Board(Gap), Board(NewGap)
      Gap=NewGap
      ENDPROC
 
      DEF PROCShowAndTest
      CLS
      Solved=TRUE
      FOR I%=0 TO MAX
        COLOUR 12 : COLOUR 135
        IF I% = Gap COLOUR 1 : COLOUR 129
        IF I% MOD SIZE = SIZE - 1 PRINT Board(I%) ELSE PRINT Board(I%),;
        IF Solved IF I% < MAX - 1 IF Board(I%) > Board(I% + 1) OR I% = Gap Solved=FALSE
      NEXT
      COLOUR 0 : COLOUR 143
      PRINT
      ENDPROC