 


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


'Charlie Ogier (C) 15PuzzleGame 24/04/2017 V0.1.0 Licenced under MIT
'Inspiration came from: -
''http://rosettacode.org/wiki/15_Puzzle_Game
''Bugs or comments to bugs@cogier.com
'Written in Gambas 3.9.2 - Updated on the Gambas Farm 01/05/2017
'Updated so that the message and the Title show the same amount of moves 01/06/2017
'Form now expandable. Font height automated. Form size and position saved 06/06/2107
 
'Simulate playing the 15 - game(puzzle)         Yes in GUI
'Generate a random start position               Yes
'Prompt the user for which piece To move        No
'Validate if the move is legal(possible)        Yes
'Display the game(puzzle) as pieces are moved   Yes in GUI
'Announce when the puzzle is solved             Yes
'Possibly keep track of the number of moves     Yes
 
byPos As New Byte[]                                             'Stores the position of the 'Tiles'
siMoves As Short                                                'Stores the amount of moves
hTimer As Timer                                                 'Timer
dTimerStart As Date                                             'Stores the start time 
dTimerDiff As Date                                              'Stores the time from the start to now
bTimerOn As Boolean                                             'To know if the Timer is running
 
Public Sub Form_Open()                                          'Form opens
 
Settings.read(Me, "Window")                                     'Get details of the last window position and size
With Me                                                         'With the Form..
  .Padding = 5                                                  'Pad the edges
  .Arrangement = Arrange.Row                                    'Arrange the Form
  .Title = "15PuzzleGame v0.3.0"                                'Set the Form Title
End With
 
BuildForm                                                       'Go to the BuildForm routine
 
End
 
Public Sub BuildForm()                                          'To add items to the Form
Dim hButton As Button                                           'We need some Buttons
Dim byRand, byTest As Byte                                      'Various variables
Dim bOK As Boolean                                              'Used to stop duplicate numbers being added
Dim bSolvable As Boolean
 
Repeat                                                          'Repeat until the puzzle is solvable    
  Do                                                            'Start of a Do loop to create 0 to 15 in random order
    byRand = Rand(0, 15)                                        'Get a random number between 0 and 15
    If byRand = 0 Then byRand = 99                              'Change 0 to 99 for the Blank space
    bOK = True                                                  'Set bOK to True
    For Each byTest In byPos                                    'For each number stored in the array byPos
      If byRand = byTest Then bOK = False                       'Check to see if it already exists, if it does set bOK to False
    Next
    If bOK Then byPos.Add(byRand)                               'If not a duplicate then add it to the array
    If byPos.max = 15 Then Break                                'Once the array has 16 numbers get out of here. 99 is used for the blank space
  Loop
  bSolvable = IsItSolvable()                                    'Go to the 'check if puzzle is solvable' routine
  If Not bSolvable Then byPos.clear                             'If it's not solvable then clear byPos
Until bSolvable = True                                          'Repeat until the puzzle is solvable
 
For byRand = 0 To 15                                            'Loop
  If byPos[byRand] = 99 Then                                    'Check if value is 99 as this is where the blank space will go
    AddPanel                                                    'Go to the AddPanel routine to add the blank space
    Continue                                                    'Skip to the end of the loop
  Endif
  hButton = New Button(Me) As "AllButtons"                      'Add a new button to the Form, all buttons grouped as 'AllButtons'
  With hButton                                                  'With the following properties
    .Text = Str(byPos[byRand])                                  'Add Button text 
    .Tag = Str(byPos[byRand])                                   'Add a Tag
    .Height = (Me.Height - 10) / 4                              'Set the Button height
    .Width = (Me.Width - 10) / 4                                'Set the Button width
    .Font.Bold = True                                           'Set the font to Bold
    .Font.Size = 16                                             'Set Font size
  End With
Next
 
AddTimer                                                        'Go to the AddTimer routine
 
End
 
 
Public Sub AddPanel()                                           'Routine to add an invisible panel that is the blank area
Dim hPanel As Panel                                             'We need a Panel
 
HPanel = New Panel(Me)                                          'Add the Panel to the Form
With HPanel                                                     'With the following Properties
  .Tag = 99                                                     'Set a Tag to 99
  .Height = (Me.Height - 10) / 4                                'Set the height
  .Width = (Me.Width - 10) / 4                                  'Set the width
End With
 
End
 
Public Sub AddTimer()                                           'To add a Timer
 
hTimer = New Timer As "MyTimer"                                 'Add a Timer
hTimer.Delay = 1000                                             'Set the timer delay 
 
End
 
Public Sub MyTimer_Timer()                                      'Timer
 
Me.Title = siMoves & " Moves "                                  'Set the Form Title to show the amount of moves taken
 
If dTimerStart Then                                             'If a start time has been set then
  dTimerDiff = Time(Now) - dTimerStart                          'Calculate the time difference between StartTime and Now
  Me.Title &= " - " & Str(dTimerDiff)                           'Add the time taken to the Form Title
End If
 
End
 
Public Sub AllButtons_Click()                                   'What to do when a Button is clicked
Dim byLast As Byte = Last.Tag                                   'Get the Tag of the Button clicked
Dim byTemp, byCount As Byte                                     'Various variables
Dim byCheck As Byte[] = [88, 88, 88, 88]                        'Used for checking for the blank space
Dim byWChgeck As New Byte[16, 4]
Dim oObj As Object                                              'We need to enumerate Objects
 
For Each oObj In Me.Children                                    'For each Object (Buttons in this case) that are Children of the Form..
  If oObj.Tag = byLast Then Break                               'If the Tag of the Button matches then we know the position of the Button on the form so get out of here
  Inc byCount                                                   'Increase the value of byCount
Next
 
Select Case byCount                                             'Depending on the position of the Button
  Case 0                                                        'e.g 0 then we need to check positions 1 & 4 for the blank
    byCheck[0] = 1
    byCheck[1] = 4
  Case 1
    byCheck[0] = 0
    byCheck[1] = 2
    byCheck[2] = 5
  Case 2
    byCheck[0] = 1
    byCheck[1] = 3
    byCheck[2] = 6
  Case 3
    byCheck[0] = 2
    byCheck[1] = 7
  Case 4
    byCheck[0] = 0
    byCheck[1] = 5
    byCheck[2] = 8
  Case 5                                                        'e.g 5 then we need to check positions 1, 4, 6 & 9 for the blank
    byCheck[0] = 1
    byCheck[1] = 4
    byCheck[2] = 6
    byCheck[3] = 9
  Case 6
    byCheck[0] = 2
    byCheck[1] = 5
    byCheck[2] = 7
    byCheck[3] = 10
  Case 7
    byCheck[0] = 3
    byCheck[1] = 6
    byCheck[2] = 11
  Case 8
    byCheck[0] = 4
    byCheck[1] = 9
    byCheck[2] = 12
  Case 9
    byCheck[0] = 5
    byCheck[1] = 8
    byCheck[2] = 10
    byCheck[3] = 13
  Case 10
    byCheck[0] = 6
    byCheck[1] = 9
    byCheck[2] = 11
    byCheck[3] = 14
  Case 11
    byCheck[0] = 7
    byCheck[1] = 10
    byCheck[2] = 15
  Case 12
    byCheck[0] = 8
    byCheck[1] = 13
  Case 13
    byCheck[0] = 9
    byCheck[1] = 12
    byCheck[2] = 14
  Case 14
    byCheck[0] = 10
    byCheck[1] = 13
    byCheck[2] = 15
  Case 15
    byCheck[0] = 11
    byCheck[1] = 14
End Select
 
For Each byTemp In byCheck                                      'For each value in byCheck
  If byTemp = 88 Then Break                                     'If byTemp = 88 then get out of here
  If byPos[byTemp] = 99 Then                                    'If the position checked is 99 (the blank) then..
    byPos[byTemp] = Last.Text                                   'Set the new position of the Tile in byPos
    byPos[byCount] = 99                                         'Set the existing Tile position to = 99 (blank)
    Inc siMoves                                                 'Inc the amount of moves made
    If Not bTimerOn Then                                        'If the Timer is now needed then 
      dTimerStart = Time(Now)                                   'Set the Start time to NOW
      hTimer.start                                              'Start the Timer
      bTimerOn = True                                           'Set bTimerOn to True 
    Endif
    Break                                                       'Get out of here
  End If
Next
 
RebuildForm                                                     'Go to the RebuilForm routine
CheckIfPuzzleCompleted                                          'Check to see if the puzzle has been solved
 
End
 
Public Sub CheckIfPuzzleCompleted()                             'Is the puzzle is complete
Dim byTest As Byte[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 99] 'byPos will equal this if it is completed
Dim siCount As Short                                            'Counter
Dim bCompleted As Boolean = True                                'Completed?
Dim sMessage As String                                          'String to store the display message
 
For siCount = 0 To 15                                           'Loop through the byPos
  If byPos[siCount] <> byTest[siCount] Then                     'If the position does not match the completed position then..
    bCompleted = False                                          'Set bCompleted to False
    Break                                                       'Get out of here
  Endif
Next
 
If bCompleted Then                                              'If the puzzle is completed then
  hTimer.Stop                                                   'Stop the timer
  Me.Title = siMoves & " Moves "                                'Set the Form Title to show the amount of moves taken
  sMessage = "Congratulations!!\n"                              'Build sMessage
  sMessage &= Str(siMoves) & " Moves\n"                         'Build sMessage
  sMessage &= "Time = " & Str(dTimerDiff)                       'Build sMessage
  Message(sMessage, "OK")                                       'Put up a congratulatory message
  Me.Close                                                      'Close the form
Endif
 
End
 
Public Sub RebuildForm()                                        'To clear the Form and rebuild with the Tiles in the new postion
Dim hButton As Button                                           'We need Buttons
Dim byCount, byTemp As Byte                                     'Various variables
Dim siFontH As Short
 
Me.Children.clear                                               'Clear the Form of all Objects
 
For Each byTemp In byPos                                        'For each 'Position'
  If byTemp = 99 Then                                           'If the Position's value is 99 then it's the space
    AddPanel                                                    'Go to the AddPanel routine
  Else                                                          'If the Position's value is NOT 99 then 
    hButton = New Button(Me) As "AllButtons"                    'Create a new Button
  With hButton                                                  'With the following properties
    .Text = Str(byPos[byCount])                                 'Text as stored in byPos
    .Tag = Str(byPos[byCount])                                  'Tag as stored in byPos
    .Height = (Me.Height - 10) / 4                              'Set the Button height
    .Width = (Me.Width - 10) / 4                                'Set the Button width
    .Font.Bold = True                                           'Set the Font to Bold
      End With
    If Me.Width > Me.Height Then                                'If Form Width is greater than Form Width then..
      siFontH = Me.Height                                       'siFontH = Form Height
    Else                                                        'Else..
      siFontH = Me.Width                                        'siFontH = Form Width
    End If
  hButton.Font.size = siFontH / 16                              'Set Font height
  Endif
 
  Inc byCount                                                   'Increase counter
Next
 
End
 
Public Sub Form_Resize()                                        'If the form is resized
 
RebuildForm                                                     'Rebuild the Form
 
End
 
Public Sub IsItSolvable() As Boolean                            'To check if the puzzle is solvable
Dim bSolvable, bBlankOnEven As Boolean                          'Triggers
Dim siCount0, siCount1, siInversion As Short                    'Counters
 
For siCount0 = 0 To byPos.Max                                   'Loop through the positions
  If byPos[siCount0] = 99 Then                                  'The blank
    If InStr("0,1,2,3,8,9,10,11,", Str(siCount0 & ",")) Then    'Is the blank on an even row (counting from the bottom) if so..
      bBlankOnEven = True                                       'bBlankOnEven = True
    End If
    Continue                                                    'Go to the end of the loop
  End If
  For siCount1 = siCount0 + 1 To byPos.Max                      'Loop through the positions 
    If byPos[siCount0] > byPos[siCount1] Then Inc siInversion   'Counts the inversions
  Next                                                          'See https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
Next
 
If bBlankOnEven And Odd(siInversion) Then bSolvable = True      'Blank is on an even row (counting from the bottom) then the number of inversions in a solvable situation is odd
If Not bBlankOnEven And Even(siInversion) Then bSolvable = True 'Blank is on an odd row (counting from the bottom) then the number of inversions in a solvable situation is even
 
Return bSolvable                                                'Return the value
 
End
 
Public Sub Form_Close()
 
Settings.Write(Me, "Window")                                    'Store the window position and size
 
End
 