The procedure CheckPositions() determines whether, after a swap, all puzzle pieces are arranged correctly:
Sub CheckPositions()
Dim i As Integer
Dim j As Integer
Dim Name1 As String
Dim Name2 As String
Dim Piece1 As Shape
Dim Piece2 As Shape
Dim AllCorrect As Boolean
AllCorrect = True
' Check horizontal order (row-wise)
For i = 1 To 5
For j = 1 To 4
Name1 = "P" & i & j
Name2 = "P" & i & (j + 1)
Set Piece1 = ActiveSheet.Shapes(Name1)
Set Piece2 = ActiveSheet.Shapes(Name2)
If Piece1.Left >= Piece2.Left Then
AllCorrect = False
Exit For
End If
Next j
If Not AllCorrect Then Exit For
Next i
If Not AllCorrect Then Exit Sub
' Check vertical order (column-wise)
For i = 1 To 4
For j = 1 To 5
Name1 = "P" & i & j
Name2 = "P" & (i + 1) & j
Set Piece1 = ActiveSheet.Shapes(Name1)
Set Piece2 = ActiveSheet.Shapes(Name2)
If Piece1.Top >= Piece2.Top Then
AllCorrect = False
Exit For
End If
Next j
If Not AllCorrect Then Exit For
Next i
If Not AllCorrect Then Exit Sub
' If all pieces are correctly positioned, end the game
GameActive = False
Application.OnTime Now + TimeValue("00:00:01"), _
"PromptNewGame"
Set Piece1 = Nothing
Set Piece2 = Nothing
End Sub
Explanation:
- Initially, the code assumes all puzzle pieces are correctly positioned:
AllCorrect = True. - Horizontal check (row-wise):
- For each row (
ifrom 1 to 5), it compares horizontally adjacent pieces (jfrom 1 to 4). - It checks that piece
"P" & i & jis strictly to the left of"P" & i & (j+1)using the.Leftproperty. - If this condition fails,
AllCorrectis set toFalseand the loop exits early.
- For each row (
- Vertical check (column-wise):
- For each column (
jfrom 1 to 5), it compares vertically adjacent pieces in rows (ifrom 1 to 4). - It verifies that piece
"P" & i & jis above"P" & (i+1) & jusing the.Topproperty. - If any piece is vertically out of order,
AllCorrectis set toFalse, and the procedure exits.
- For each column (
- If any check fails, the game continues (i.e., it does not mark the puzzle as solved).
- If all pieces are correctly placed:
GameActiveis set toFalseto signal the game has ended.- The procedure
PromptNewGame()is scheduled to run one second later usingApplication.OnTime. This ensures visual updates finish before prompting the player.
- Finally, shape references
Piece1andPiece2are cleared from memory.