 


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


 
#difficulty=10 ;higher is harder
#up="u"
#down="d"
#left="l"
#right="r"
OpenConsole("15 game"):EnableGraphicalConsole(1)
Global Dim Game.i(3,3)
Global hole.point
 
Procedure NewBoard()
    num.i=0
    For j=0 To 3
        For i=0 To 3
            Game(i,j)=num
            num+1
        Next i
    Next j
EndProcedure
Procedure.s displayBoard()
    For j=0 To 3
        For i=0 To 3
            ConsoleLocate(i,j)
            If Game(i,j)=0:Print(" "):Continue:EndIf
            Print(Hex(Game(i,j)))
        Next i
    Next j
    PrintN("")
    Print("Your Choice Up :"+#up+", Down :"+#down+", Left :"+#left+" Or Right :"+#right+" ")
    Repeat
        keypress$=Inkey()
    Until keypress$<>""
    keypress$=LCase(keypress$)
    ProcedureReturn keypress$
EndProcedure
Procedure UpdateBoard(key$)
    If key$=#up And hole\y<3
        Swap game(hole\x,hole\y),game(hole\x,hole\y+1):hole\y+1
    ElseIf key$=#down And hole\y
        Swap game(hole\x,hole\y),game(hole\x,hole\y-1):hole\y-1
    ElseIf key$=#left And hole\x<3
        Swap game(hole\x,hole\y),game(hole\x+1,hole\y):hole\x+1
    ElseIf key$=#right And hole\x
        Swap game(hole\x,hole\y),game(hole\x-1,hole\y):hole\x-1
    EndIf
EndProcedure
Procedure TestGameWin()
    For j=0 To 3
        For i=0 To 3
            num+1
            If game(i,j)=num:win+1:EndIf
        Next i
    Next j
    If win=15:ProcedureReturn 1:EndIf
EndProcedure
Procedure ShuffleBoard(difficulty.i)
    Dim randomKey$(3)
    randomkey$(0)=#up:randomkey$(1)=#down:randomkey$(2)=#left:randomkey$(3)=#right
    For i=1 To difficulty
       UpdateBoard(randomKey$(Random(3))) 
    Next i
EndProcedure
NewBoard()
ShuffleBoard(#difficulty)
Repeat
    choice$=displayBoard()
    UpdateBoard(choice$)
Until TestGameWin()
Print("Won !")
CloseConsole()
 