TutorialsCocktail Shaker Sort

Appendix A — Logic Reference

Every Logic Component and Function in Picture Puzzle, as it is in the finished game. Each entry stands on its own: read what it does, see what it needs, and build it from its card into your own game. A card’s Shared Variables and Per Instance Variables are the values you can change. A Shared Variable holds one value for the whole Object, under Variables in its Properties. A Per Instance Variable holds one for each placement in the Scene.

A.1 Arrange Board

Built in Chapter 1, The Picture and the Board.

Logic ComponentArrange BoardAttach to: Puzzle Rules

Lays out a whole new arrangement when it is asked: Reset puts the starting arrangement back, Shuffle makes a new one, and so does a new piece count or a new picture. Then it tells every Piece that the board was arranged.

Attach toAny Object
On Reset Requested
WhenresetRequestedCustom Event
1Restore Start ArrangementFunction
2Change Variable
Variable
$message
Value
data('Messages', 'reset', 'words')
3Start Cooldown
Cooldown Key
"pieceSlide"
Seconds
0
4Trigger Custom Event
Custom Event
boardArranged
On Shuffle Requested
WhenshuffleRequestedCustom Event
1Shuffle BoardFunction
2Change Variable
Variable
$message
Value
""
3Start Cooldown
Cooldown Key
"pieceSlide"
Seconds
0
4Trigger Custom Event
Custom Event
boardArranged
On Piece Count Chosen
WhenpieceCountChosenCustom Event
1Trigger Custom Event on Object
Custom Event
shuffleRequested
On Picture Chosen
WhenpictureChosenCustom Event
1Trigger Custom Event on Object
Custom Event
shuffleRequested

A.2 Button Action

Built in Chapter 1, The Picture and the Board.

Logic ComponentButton ActionAttach to: Puzzle Button, Sort Button

Clicking or tapping a Puzzle Button runs the Request Function of its command: Reset, Shuffle, Step, Sort, Upload or Lesson. Each placement sets its own command and its own text. While the How it works panel is open, the Button does nothing.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
PER INSTANCE VARIABLES
NameTypeStarting Value
commandTextReset
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
puzzleControlsOn
Input Context
Puzzle Controls
2IfpuzzleControlsOn.value == true
Then
3Ifself.command == "Reset"
Then
4Request ResetFunction
puzzleRules
@self.puzzleRules
5Ifself.command == "Shuffle"
Then
6Request ShuffleFunction
puzzleRules
@self.puzzleRules
7Ifself.command == "Step"
Then
8Request StepFunction
puzzleRules
@self.puzzleRules
9Ifself.command == "Sort"
Then
10Request SortFunction
puzzleRules
@self.puzzleRules
11Ifself.command == "Upload"
Then
12Request UploadFunction
puzzleRules
@self.puzzleRules
13Ifself.command == "Lesson"
Then
14Request LessonFunction
puzzleRules
@self.puzzleRules

A.3 Count Pieces Home (Function)

Built in Chapter 1, The Picture and the Board.

FunctionCount Pieces Home

Counts the pieces that are home (a piece is home when its ID equals its slot's row index) and stores the count in $piecesHome, which the Board Caption shows.

ACTIONS
1Change Variable
Variable
$piecesHome
Value
0
2Repeat$gridSize * $gridSizetimes
Each time
3Ifdata('Board Slots', local.index, 'piece') == local.index
Then
4Change Variable
Variable
$piecesHome
Operator
+=
Value
1

A.4 Exchange Slots (Function)

Built in Chapter 1, The Picture and the Board.

FunctionExchange Slots

Trades the pieces of two slots of Board Slots. Every piece is still on the board exactly once afterwards. Slots are row indices, 0 for the top-left slot.

PARAMETERS
NameTypeStarts at
firstSlotNumber0
secondSlotNumber0
ACTIONS
1Declare Variable
Name
firstPiece
Value
0
2Change Variable
Variable
firstPiece
Value
data('Board Slots', firstSlot, 'piece')
3Set Data Cell
Table
Board Slots
Row
firstSlot
Column
"piece"
Value
data('Board Slots', secondSlot, 'piece')
4Set Data Cell
Table
Board Slots
Row
secondSlot
Column
"piece"
Value
firstPiece

A.5 Lay Out Slot

Built in Chapter 1, The Picture and the Board.

Logic ComponentLay Out SlotAttach to: Piece Outline, Piece

Places this Piece or Outline for the board's piece count: on its slot's center and sized to the slot when the slot is on the board, hidden when it is not. drawnSlotSide is the slot side, in screen pixels, that the Object fits at scale 1 (70, a slot of the 64-piece board).

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
SHARED VARIABLES
NameTypeKindStarting Value
drawnSlotSideNumberConstant70
On Placed on Board
WhenplacedOnBoardCustom Event
1Lay Out One SlotFunction
slotObject
self
drawnSlotSide
@self.drawnSlotSide
On Board Arranged
WhenboardArrangedCustom Event
1Lay Out One SlotFunction
slotObject
self
drawnSlotSide
@self.drawnSlotSide

A.6 Make Board

Built in Chapter 1, The Picture and the Board.

Logic ComponentMake BoardAttach to: Puzzle Rules

Makes the board when the game begins: a row of Board Slots for each slot, holding the starting arrangement, and on the screen an Outline with a Piece in front of it for each slot. The board is made once, for the largest piece count (the last row of Piece Counts); a smaller piece count uses its first slots and hides the rest (Lay Out Slot). The starting arrangement takes every fifth piece; a board where that would not hold each piece once (a piece count that is a multiple of 5, or a game that starts at a smaller count) starts with a Shuffle instead. slotCount is how many slots it makes; outline and piece are the Objects it makes.

Attach toAny Object
DATA STRUCTURES
Make Board Dataself.makeBoardData
SHARED VARIABLES
NameTypeKindStarting Value
outlineObjectConstantNone
pieceObjectConstantNone
When the Game Starts
WhenGame Start
1Declare Variable
Name
largestGridSize
Value
0
2Change Variable
Variable
largestGridSize
Value
data('Piece Counts', dataCount('Piece Counts') - 1, 'gridSize')
3Change Component Value
Component Value
self.makeBoardData.slotCount
Value
largestGridSize * largestGridSize
4Repeatself.makeBoardData.slotCounttimes
Each time
5Control Data Row
Action Name
addedRow
Table
Board Slots
Row
text("Slot ", local.index + 1)
6Set Data Cell
Table
Board Slots
Row
local.index
Column
"piece"
Value
(5 * local.index + 3) % self.makeBoardData.slotCount
7Set Data Cell
Table
Board Slots
Row
local.index
Column
"startPiece"
Value
data('Board Slots', local.index, 'piece')
8Trigger Custom Event on Object
Custom Event
boardMade
9If$gridSize != largestGridSize || (self.makeBoardData.slotCount % 5) == 0
Then
10Trigger Custom Event on Object
Custom Event
shuffleRequested
When the Scene Starts
WhenScene Start
1Repeatself.makeBoardData.slotCounttimes
Each time
2Create Instance
Object to Create
@self.outline
X
0
Y
0
Created As
newOutline
3Change Variable
Variable
newOutline.slot
Value
local.index
4Trigger Custom Event on Object
Applies to
newOutline
Custom Event
placedOnBoard
5Create Instance
Object to Create
@self.piece
X
0
Y
0
Created As
newPiece
6Change Variable
Variable
newPiece.slot
Value
local.index
7Trigger Custom Event on Object
Applies to
newPiece
Custom Event
placedOnBoard

A.7 Pieces Home

Built in Chapter 1, The Picture and the Board.

Logic ComponentPieces HomeAttach to: Puzzle Rules

Keeps $piecesHome, the count the Board Caption shows, equal to the number of pieces in their home slots.

Attach toAny Object
On Board Made
WhenboardMadeCustom Event
1Count Pieces HomeFunction
On Board Arranged
WhenboardArrangedCustom Event
1Count Pieces HomeFunction
On Pieces Exchanged
WhenpiecesExchangedCustom Event
1Count Pieces HomeFunction
On Pair Compared
WhenpairComparedCustom Event
1Count Pieces HomeFunction

A.8 Puzzle Commands

Built in Chapter 1, The Picture and the Board.

Logic ComponentPuzzle CommandsAttach to: Puzzle Rules

The keys ask for the same things as the Buttons: R for Reset, N for a new arrangement. Escape cancels a selection. Space asks the computer for one Step. A starts or pauses the computer's sort, and F opens the How it works panel.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When Reset Is Pressed
WhenCommand PressedCommand: Reset
1Request ResetFunction
puzzleRules
@self.puzzleRules
When New Is Pressed
WhenCommand PressedCommand: New Arrangement
1Request ShuffleFunction
puzzleRules
@self.puzzleRules
When Cancel Is Pressed
WhenCommand PressedCommand: Cancel
1Trigger Custom Event on Object
Custom Event
selectionCanceled
When Step Is Pressed
WhenCommand PressedCommand: Step
1Request StepFunction
puzzleRules
@self.puzzleRules
When Run Is Pressed
WhenCommand PressedCommand: Run or Pause
1Request SortFunction
puzzleRules
@self.puzzleRules
When Lesson Is Pressed
WhenCommand PressedCommand: How It Works
1Request LessonFunction
puzzleRules
@self.puzzleRules

A.9 Request Reset (Function)

Built in Chapter 1, The Picture and the Board.

FunctionRequest Reset

Asks Puzzle Rules to put the starting arrangement back. The Reset Button and the Reset Command both use it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
resetRequested

A.10 Request Shuffle (Function)

Built in Chapter 1, The Picture and the Board.

FunctionRequest Shuffle

Asks Puzzle Rules for a new random arrangement. The Shuffle Button and the New Arrangement Command both use it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
shuffleRequested

A.11 Restore Start Arrangement (Function)

Built in Chapter 1, The Picture and the Board.

FunctionRestore Start Arrangement

Puts every slot's starting piece (startPiece) back in the slot.

ACTIONS
1Repeat$gridSize * $gridSizetimes
Each time
2Set Data Cell
Table
Board Slots
Row
local.index
Column
"piece"
Value
data('Board Slots', local.index, 'startPiece')

A.12 Show Piece

Built in Chapter 1, The Picture and the Board.

Logic ComponentShow PieceAttach to: Piece

Shows the picture frame of the piece that Board Slots puts in this Piece's slot, cut for the chosen piece count. Make Board gives each Piece its slot in its Slot Number (0 is the top-left slot, counting right, then down).

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
On Placed on Board
WhenplacedOnBoardCustom Event
1Choose Piece SpriteFunction
piece
self
2Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')
On Board Arranged
WhenboardArrangedCustom Event
1Choose Piece SpriteFunction
piece
self
2Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')
On Pieces Exchanged
WhenpiecesExchangedCustom Event
1Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')
On Pair Compared
WhenpairComparedCustom Event
1Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')

A.13 Shuffle Board (Function)

Built in Chapter 1, The Picture and the Board.

FunctionShuffle Board

Makes a new random arrangement with the game's random numbers and keeps it as the starting arrangement that Reset puts back. It is the Fisher-Yates shuffle: every arrangement is equally likely, and every piece stays on the board exactly once.

ACTIONS
1Declare Variable
Name
lastSlot
Value
0
2Repeat$gridSize * $gridSizetimes
Each time
3Set Data Cell
Table
Board Slots
Row
local.index
Column
"piece"
Value
local.index
4Repeat$gridSize * $gridSize - 1times
Each time
5Change Variable
Variable
lastSlot
Value
$gridSize * $gridSize - 1 - local.index
6Generate Random Integer
Action Name
partner
Minimum
0
Maximum
lastSlot
7Exchange SlotsFunction
firstSlot
lastSlot
secondSlot
partner.value
8Repeat$gridSize * $gridSizetimes
Each time
9Set Data Cell
Table
Board Slots
Row
local.index
Column
"startPiece"
Value
data('Board Slots', local.index, 'piece')

A.14 Slot Center (Function)

Built in Chapter 1, The Picture and the Board.

FunctionSlot Center

Answers where the center of a slot lies on the screen, in screen pixels. A Screen UI Object is placed from the top-left corner of the screen with +Y up, so x counts right and y is negative below the top edge. The board is a square of boardSide pixels whose top-left corner is boardLeft from the left edge and boardTop from the top edge; gridSize slots fill each row.

PARAMETERS
NameTypeStarts at
slotNumber0
RETURN TYPESlot Center Result (a Data Structure)
ACTIONS
1Declare Variable
Name
slotSide
Value
0
2Declare Variable
Name
column
Value
0
3Declare Variable
Name
row
Value
0
4Declare Variable
Name
centerX
Value
0
5Declare Variable
Name
centerY
Value
0
6Change Variable
Variable
slotSide
Value
$boardSide / $gridSize
7Change Variable
Variable
column
Value
slot % $gridSize
8Change Variable
Variable
row
Value
floor(slot / $gridSize)
9Change Variable
Variable
centerX
Value
$boardLeft + (column + 0.5) * slotSide
10Change Variable
Variable
centerY
Value
-($boardTop + (row + 0.5) * slotSide)
11Return
x
centerX
y
centerY

A.15 Choose Slot (Function)

Built in Chapter 2, Your Hands on the Board.

FunctionChoose Slot

Tells Puzzle Rules that the player chose a slot, as a tap on a piece does. Keys 1 to 9 and Enter use it. A key also lets the player play, even while pieces slide.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
slotNumber0
ACTIONS
1Let Player PlayFunction
puzzleRules
puzzleRules
2Check Cooldown Ready
Action Name
slideDone
Applies to
puzzleRules
Cooldown Key
"pieceSlide"
3IfslideDone.value == true
Then
4Change Variable
Variable
$chosenSlot
Value
slot
5Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
pieceChosen

A.16 Clear Selection (Function)

Built in Chapter 2, Your Hands on the Board.

FunctionClear Selection

Forgets the selected piece: the words "Choose another piece." leave the Message Line, and the Outlines are told.

ACTIONS
1Change Variable
Variable
$selectedSlot
Value
-1
2If$message == data('Messages', 'selected', 'words')
Then
3Change Variable
Variable
$message
Value
""
4Trigger Custom Event
Custom Event
selectionChanged

A.17 Input Interruptions

Built in Chapter 2, Your Hands on the Board.

Logic ComponentInput InterruptionsAttach to: Puzzle Rules

Cancels a selection and a press under way when the player's input is cut off: the game window lost focus, or a touch was cut off. Either way it sends selectionCanceled, as Escape does.

Attach toAny Object
On Focus Lost
WhenFocus Lost
1Trigger Custom Event on Object
Custom Event
selectionCanceled
On Touch Cancelled
WhenTouch Cancelled
1Trigger Custom Event on Object
Custom Event
selectionCanceled

A.18 Keyboard Focus

Built in Chapter 2, Your Hands on the Board.

Logic ComponentKeyboard FocusAttach to: Puzzle Rules

The keyboard plays like the pointer: keys 1 to 9 choose a slot, the arrow keys move a blue focus over the board, and Enter chooses the focused slot.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When Piece1 Is Pressed
WhenCommand PressedCommand: Choose Piece 1
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
0
When Piece2 Is Pressed
WhenCommand PressedCommand: Choose Piece 2
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
1
When Piece3 Is Pressed
WhenCommand PressedCommand: Choose Piece 3
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
2
When Piece4 Is Pressed
WhenCommand PressedCommand: Choose Piece 4
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
3
When Piece5 Is Pressed
WhenCommand PressedCommand: Choose Piece 5
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
4
When Piece6 Is Pressed
WhenCommand PressedCommand: Choose Piece 6
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
5
When Piece7 Is Pressed
WhenCommand PressedCommand: Choose Piece 7
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
6
When Piece8 Is Pressed
WhenCommand PressedCommand: Choose Piece 8
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
7
When Piece9 Is Pressed
WhenCommand PressedCommand: Choose Piece 9
1Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
8
When Left Is Pressed
WhenCommand PressedCommand: Focus Left
1Move FocusFunction
distance
-1
When Right Is Pressed
WhenCommand PressedCommand: Focus Right
1Move FocusFunction
distance
1
When Up Is Pressed
WhenCommand PressedCommand: Focus Up
1Move FocusFunction
distance
-$gridSize
When Down Is Pressed
WhenCommand PressedCommand: Focus Down
1Move FocusFunction
distance
$gridSize
When Select Is Pressed
WhenCommand PressedCommand: Select Focused Piece
1If$focusSlot >= 0
Then
2Choose SlotFunction
puzzleRules
@self.puzzleRules
slot
$focusSlot
On Piece Pressed
WhenpiecePressedCustom Event
1Hide FocusFunction
On Piece Count Chosen
WhenpieceCountChosenCustom Event
1Hide FocusFunction

A.19 Make Player Exchange (Function)

Built in Chapter 2, Your Hands on the Board.

FunctionMake Player Exchange

The player's exchange: the pieces of two slots trade places, Moves counts it, the two pieces slide over slideSeconds, and every Piece is told.

PARAMETERS
NameTypeStarts at
firstSlotNumber0
secondSlotNumber0
puzzleRulesObjectPuzzle Rules
slideSecondsNumber0.22
ACTIONS
1Exchange SlotsFunction
firstSlot
firstSlot
secondSlot
secondSlot
2Change Variable
Variable
$moves
Operator
+=
Value
1
3Slide PiecesFunction
puzzleRules
puzzleRules
firstSlot
firstSlot
secondSlot
secondSlot
seconds
slideSeconds
4Trigger Custom Event
Custom Event
piecesExchanged

A.20 Move Focus (Function)

Built in Chapter 2, Your Hands on the Board.

FunctionMove Focus

Moves the keyboard focus by distance slots in reading order: 1 is one slot right, -1 one slot left, gridSize one row down. The focus stops at the first and the last slot of the board.

PARAMETERS
NameTypeStarts at
distanceNumber1
ACTIONS
1Declare Variable
Name
nextSlot
Value
0
2If$focusSlot == (-1)
Then
3Change Variable
Variable
$focusSlot
Value
0
4Change Variable
Variable
nextSlot
Value
$focusSlot + distance
5IfnextSlot >= 0 && nextSlot < ($gridSize * $gridSize)
Then
6Change Variable
Variable
$focusSlot
Value
nextSlot
7Trigger Custom Event
Custom Event
selectionChanged

A.21 Picture Complete

Built in Chapter 2, Your Hands on the Board.

Logic ComponentPicture CompleteAttach to: Puzzle Rules

Sets the Game State: Solved once every piece is home, Playing while any piece is away from home.

Attach toAny Object
On Variable Changed · Pieces Home
WhenVariable ChangedGlobal Variable: piecesHome
1If$piecesHome == ($gridSize * $gridSize)
Then
2Set Game State
Game State
Solved
3Change Variable
Variable
$message
Value
data('Messages', 'solved', 'words')
4Otherwise
5Set Game State
Game State
Playing

A.22 Piece Pointer

Built in Chapter 2, Your Hands on the Board.

Logic ComponentPiece PointerAttach to: Piece

Tells Puzzle Rules when the pointer is pressed on this Piece and when it is released on it. Puzzle Rules decides what the press and the release mean. While the How it works panel is open, the Piece tells nothing.

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When Left Is Clicked
WhenMouse Pressed on ObjectMouse button: left
1Check Input Context Active
Action Name
controlsOnAtPress
Input Context
Puzzle Controls
2IfcontrolsOnAtPress.value == true
Then
3Change Variable
Variable
$chosenSlot
Value
self.slotNumber.slot
4Trigger Custom Event on Object
Applies to
@self.puzzleRules
Custom Event
piecePressed
When Left Is Released
WhenMouse Released on ObjectMouse button: left
1Check Input Context Active
Action Name
controlsOnAtRelease
Input Context
Puzzle Controls
2IfcontrolsOnAtRelease.value == true
Then
3Change Variable
Variable
$chosenSlot
Value
self.slotNumber.slot
4Trigger Custom Event on Object
Applies to
@self.puzzleRules
Custom Event
pieceReleased

A.23 Piece Press

Built in Chapter 2, Your Hands on the Board.

Logic ComponentPiece PressAttach to: Puzzle Rules

Follows one press of the pointer on a piece: released on the same piece it is a tap, released on another piece it is a drag, and released anywhere else it is forgotten. A press cut off (the game lost focus, or the touch was cut off) is forgotten too, when Input Interruptions sends selectionCanceled.

Attach toAny Object
On Piece Pressed
WhenpiecePressedCustom Event
1Check Cooldown Ready
Action Name
slideDone
Cooldown Key
"pieceSlide"
2IfslideDone.value == true
Then
3Change Variable
Variable
$pressedSlot
Value
$chosenSlot
4Trigger Custom Event
Custom Event
selectionChanged
On Piece Released
WhenpieceReleasedCustom Event
1If$pressedSlot >= 0
Then
2If$pressedSlot == $chosenSlot
Then
3Trigger Custom Event on Object
Custom Event
pieceChosen
4Otherwise
5Trigger Custom Event on Object
Custom Event
piecesDropped
6Change Variable
Variable
$pressedSlot
Value
-1
7Trigger Custom Event
Custom Event
selectionChanged
When the Left Mouse Button Is Released
WhenMouse ReleaseMouse button: left
1Switch Mode
Event
On End Step
Mode
Release Seen
On End Step
WhenEnd Step
ModeNo Release (Starting Mode)
(no Actions)
On End Step
WhenEnd Step
ModeRelease Seen
1Change Variable
Variable
$pressedSlot
Value
-1
2Trigger Custom Event
Custom Event
selectionChanged
3Switch Mode
Event
On End Step
Mode
No Release
On Selection Canceled
WhenselectionCanceledCustom Event
1Change Variable
Variable
$pressedSlot
Value
-1
2Trigger Custom Event
Custom Event
selectionChanged

A.24 Player Exchange

Built in Chapter 2, Your Hands on the Board.

Logic ComponentPlayer ExchangeAttach to: Puzzle Rules

The player exchanges two pieces: the first piece chosen is selected, the second one trades places with it (choosing the selected piece again cancels). A drag from one piece to another exchanges them at once. exchangeSlideSeconds is how long the two pieces of an exchange slide.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
exchangeSlideSecondsNumberConstant0.22
On Piece Chosen
WhenpieceChosenCustom Event
ModeNothing Selected (Starting Mode)
1Change Variable
Variable
$selectedSlot
Value
$chosenSlot
2Change Variable
Variable
$message
Value
data('Messages', 'selected', 'words')
3Switch Mode
Event
On Piece Chosen
Mode
One Selected
4Trigger Custom Event
Custom Event
selectionChanged
On Piece Chosen
WhenpieceChosenCustom Event
ModeOne Selected
1If$chosenSlot != $selectedSlot
Then
2Make Player ExchangeFunction
firstSlot
$selectedSlot
secondSlot
$chosenSlot
puzzleRules
@self.puzzleRules
slideSeconds
@self.exchangeSlideSeconds
3Change Variable
Variable
$message
Value
""
4Switch Mode
Event
On Piece Chosen
Mode
Nothing Selected
5Clear SelectionFunction
On Pieces Dropped
WhenpiecesDroppedCustom Event
1Make Player ExchangeFunction
firstSlot
$pressedSlot
secondSlot
$chosenSlot
puzzleRules
@self.puzzleRules
slideSeconds
@self.exchangeSlideSeconds
2Change Variable
Variable
$message
Value
""
3Switch Mode
Event
On Piece Chosen
Mode
Nothing Selected
4Clear SelectionFunction
On Clear Selection Requested
WhenclearSelectionRequestedCustom Event
1Switch Mode
Event
On Piece Chosen
Mode
Nothing Selected
2Clear SelectionFunction
On Selection Canceled
WhenselectionCanceledCustom Event
1Switch Mode
Event
On Piece Chosen
Mode
Nothing Selected
2Clear SelectionFunction
On Board Arranged
WhenboardArrangedCustom Event
1Change Variable
Variable
$moves
Value
0
2Switch Mode
Event
On Piece Chosen
Mode
Nothing Selected
3Clear SelectionFunction

A.25 Show Outline

Built in Chapter 2, Your Hands on the Board.

Logic ComponentShow OutlineAttach to: Piece Outline

Colors this Outline whenever what it shows may have changed: the player's selection, focus or press, or the computer's compared pair and unsorted range, or who plays.

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
On Selection Changed
WhenselectionChangedCustom Event
1Color OutlineFunction
outline
self
On Pair Compared
WhenpairComparedCustom Event
1Color OutlineFunction
outline
self
On Sort Cleared
WhensortClearedCustom Event
1Color OutlineFunction
outline
self
On Pass Finished
WhenpassFinishedCustom Event
1Color OutlineFunction
outline
self
On Who Plays Changed
WhenwhoPlaysChangedCustom Event
1Color OutlineFunction
outline
self

A.26 Check Board Valid (Function)

Built in Chapter 3, The Computer Compares.

FunctionCheck Board Valid

Answers whether the board holds every piece ID exactly once, so the computer can sort it. isValid is true when it does.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isValid
Value
true
2Repeat$gridSize * $gridSizetimes
Each time
3Count Piece CopiesFunction
Action Name
found
pieceId
local.index
4Iffound.value != 1
Then
5Change Variable
Variable
isValid
Value
false
6Return
Value
isValid

A.27 Clear Sort (Function)

Built in Chapter 3, The Computer Compares.

FunctionClear Sort

Starts the computer's sort fresh: the counters go back to 0, no pair is shown as compared, and the next Step checks the board and begins a new forward pass.

ACTIONS
1Change Variable
Variable
$comparisons
Value
0
2Change Variable
Variable
$swaps
Value
0
3Change Variable
Variable
$comparedSlot
Value
-1
4Trigger Custom Event
Custom Event
sortCleared

A.28 Color Outline (Function)

Built in Chapter 3, The Computer Compares.

FunctionColor Outline

Colors one Outline from what is shown on the board now: a settled slot is green, the keyboard focus and a pressed piece are blue, the selected piece is gold, the pair the computer compared last is amber, and every other Outline keeps the normal color. Green and amber are the computer's colors: they show only while the computer plays ($whoPlays).

PARAMETERS
NameTypeStarts at
outlineObjectStructural
Required Components
Slot NameslotNumber
Component TypeData Structure
Required SchemaSlot Number
ACTIONS
1Declare Variable
Name
outlineSlot
Value
0
2Change Variable
Variable
outlineSlot
Value
outline.slotNumber.slot
3Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'normal', 'color')
4If$whoPlays == "Computer" && $comparedSlot >= 0 && outlineSlot < $rangeStart
Then
5Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'settled', 'color')
6If$whoPlays == "Computer" && $comparedSlot >= 0 && outlineSlot > $rangeEnd
Then
7Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'settled', 'color')
8IfoutlineSlot == $focusSlot || outlineSlot == $pressedSlot
Then
9Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'focus', 'color')
10IfoutlineSlot == $selectedSlot
Then
11Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'selected', 'color')
12If$whoPlays == "Computer" && $comparedSlot >= 0 && outlineSlot >= $comparedSlot && outlineSlot <= ($comparedSlot + 1)
Then
13Change Sprite Tint Property
Applies to
outline
Value
data('Outline Colors', 'compared', 'color')

A.29 Compare Next Pair (Function)

Built in Chapter 3, The Computer Compares.

FunctionCompare Next Pair

One comparison of the computer: it reads the pieces of a slot and the slot to its right, and swaps them when the left piece's ID is larger. It counts the comparison and any swap, and tells the board.

PARAMETERS
NameTypeStarts at
leftSlotNumber0
puzzleRulesObjectPuzzle Rules
ACTIONS
1Change Variable
Variable
$comparisons
Operator
+=
Value
1
2Ifdata('Board Slots', leftSlot, 'piece') > data('Board Slots', leftSlot + 1, 'piece')
Then
3Exchange SlotsFunction
firstSlot
leftSlot
secondSlot
leftSlot + 1
4Change Variable
Variable
$swaps
Operator
+=
Value
1
5Slide PiecesFunction
puzzleRules
puzzleRules
firstSlot
leftSlot
secondSlot
leftSlot + 1
seconds
data('Sort Speeds', $speed, 'slideSeconds')
6Change Variable
Variable
$message
Value
data('Messages', 'swapped', 'words')
7Otherwise
8Change Variable
Variable
$message
Value
data('Messages', 'kept', 'words')
9Change Variable
Variable
$comparedSlot
Value
leftSlot
10Trigger Custom Event
Custom Event
pairCompared

A.30 Computer Sort

Built in Chapter 3, The Computer Compares.

Logic ComponentComputer SortAttach to: Puzzle Rules

The computer's cocktail shaker sort, one comparison per Step. The first Step on a board checks it and begins a forward pass from the first slot. Passes then go back and forth over the unsorted range, which shrinks by one slot at the end of each pass, until every piece is home or a pass makes no swaps. When the sort is finished, or the board cannot be sorted, it sends sortEnded.

Attach toAny Object
DATA STRUCTURES
Computer Sort Dataself.computerSortData
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
On Step Requested
WhenstepRequestedCustom Event
ModeFresh (Starting Mode)
1Check Board ValidFunction
Action Name
boardCheck
2IfboardCheck.value == true
Then
3Change Variable
Variable
$rangeStart
Value
0
4Change Variable
Variable
$rangeEnd
Value
$gridSize * $gridSize - 1
5Change Component Value
Component Value
self.computerSortData.swapsBeforePass
Value
$swaps
6Compare Next PairFunction
leftSlot
$rangeStart
puzzleRules
@self.puzzleRules
7Switch Mode
Event
On Step Requested
Mode
Forward Pass
8Trigger Custom Event on Object
Custom Event
forwardPassStarted
9Otherwise
10Change Variable
Variable
$message
Value
data('Messages', 'invalid', 'words')
11Trigger Custom Event on Object
Custom Event
sortEnded
On Step Requested
WhenstepRequestedCustom Event
ModeForward Pass
1Compare Next PairFunction
leftSlot
$comparedSlot + 1
puzzleRules
@self.puzzleRules
2If($comparedSlot + 1) == $rangeEnd
Then
3Change Variable
Variable
$rangeEnd
Operator
-=
Value
1
4Finish Sort PassFunction
Action Name
forwardPassEnd
swapsBeforePass
self.computerSortData.swapsBeforePass
5IfforwardPassEnd.value == false
Then
6Switch Mode
Event
On Step Requested
Mode
Finished
7Trigger Custom Event on Object
Custom Event
sortEnded
8Trigger Custom Event
Custom Event
passFinished
9IfforwardPassEnd.value == true
Then
10Switch Mode
Event
On Step Requested
Mode
Backward Pass
11Trigger Custom Event on Object
Custom Event
backwardPassStarted
12Change Component Value
Component Value
self.computerSortData.swapsBeforePass
Value
$swaps
On Step Requested
WhenstepRequestedCustom Event
ModeBackward Pass
1Compare Next PairFunction
leftSlot
$comparedSlot - 1
puzzleRules
@self.puzzleRules
2If$comparedSlot == $rangeStart
Then
3Change Variable
Variable
$rangeStart
Operator
+=
Value
1
4Finish Sort PassFunction
Action Name
backwardPassEnd
swapsBeforePass
self.computerSortData.swapsBeforePass
5IfbackwardPassEnd.value == false
Then
6Switch Mode
Event
On Step Requested
Mode
Finished
7Trigger Custom Event on Object
Custom Event
sortEnded
8Trigger Custom Event
Custom Event
passFinished
9IfbackwardPassEnd.value == true
Then
10Switch Mode
Event
On Step Requested
Mode
Forward Pass
11Trigger Custom Event on Object
Custom Event
forwardPassStarted
12Change Component Value
Component Value
self.computerSortData.swapsBeforePass
Value
$swaps
On Step Requested
WhenstepRequestedCustom Event
ModeFinished
(no Actions)
On Board Arranged
WhenboardArrangedCustom Event
1Switch Mode
Event
On Step Requested
Mode
Fresh
2Clear SortFunction
On Pieces Exchanged
WhenpiecesExchangedCustom Event
1Switch Mode
Event
On Step Requested
Mode
Fresh
2Clear SortFunction
On Variable Changed · Pieces Home
WhenVariable ChangedGlobal Variable: piecesHome
1If$piecesHome == ($gridSize * $gridSize)
Then
2Switch Mode
Event
On Step Requested
Mode
Finished
3Trigger Custom Event on Object
Custom Event
sortEnded

A.31 Count Piece Copies (Function)

Built in Chapter 3, The Computer Compares.

FunctionCount Piece Copies

Answers how many slots of the board hold one piece ID. On a sound board the answer is always 1.

PARAMETERS
NameTypeStarts at
pieceIdNumber0
RETURN TYPENumber
ACTIONS
1Declare Variable
Name
copies
Value
0
2Repeat$gridSize * $gridSizetimes
Each time
3Ifdata('Board Slots', local.index, 'piece') == pieceId
Then
4Change Variable
Variable
copies
Operator
+=
Value
1
5Return
Value
copies

A.32 Request Step (Function)

Built in Chapter 3, The Computer Compares.

FunctionRequest Step

Asks Puzzle Rules to pause a running sort, then for one Step of the computer's sort once no piece is sliding. The Step Button and the Step Command (Space) both use it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
pauseRequested
2Check Cooldown Ready
Action Name
slideDone
Applies to
puzzleRules
Cooldown Key
"pieceSlide"
3IfslideDone.value == true
Then
4Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
stepRequested

A.33 Finish Sort Pass (Function)

Built in Chapter 4, The Way Back.

FunctionFinish Sort Pass

Ends one pass of the computer's sort, after the unsorted range has moved in by one slot. When the pass made no swaps, the range has no pair left to compare, or every piece is home, the sort is finished: sortGoesOn answers false. Otherwise it answers true so Computer Sort can begin the next pass.

PARAMETERS
NameTypeStarts at
swapsBeforePassNumber0
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
sortGoesOn
Value
true
2If$swaps == swapsBeforePass || $rangeStart >= $rangeEnd || $piecesHome == ($gridSize * $gridSize)
Then
3Change Variable
Variable
sortGoesOn
Value
false
4Otherwise
5Change Variable
Variable
sortGoesOn
Value
true
6Return
Value
sortGoesOn

A.34 Choose Picture

Built in Chapter 5, The Finished Puzzle.

Logic ComponentChoose PictureAttach to: Picture Button

Clicking or tapping a Picture Button makes its picture the one the board shows: $picture becomes the Button's row of Pictures, and a new arrangement is shuffled. Each placement sets its picture (a row of Pictures) and its Sprite. While the How it works panel is open, the Button does nothing.

Attach toAny Object
PER INSTANCE VARIABLES
NameTypeStarting Value
pictureTextVillage
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
puzzleControlsOn
Input Context
Puzzle Controls
2IfpuzzleControlsOn.value == true
Then
3Use PictureFunction
picture
self.picture

A.35 Choose Piece Count

Built in Chapter 5, The Finished Puzzle.

Logic ComponentChoose Piece CountAttach to: Count Button

Clicking or tapping a Count Button makes its piece count the board's: $gridSize becomes the count's gridSize, and a new arrangement of that size is shuffled. Each placement sets its count (a row of Piece Counts) and its text. While the How it works panel is open, the Button does nothing.

Attach toAny Object
PER INSTANCE VARIABLES
NameTypeStarting Value
pieceCountText64 Pieces
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
puzzleControlsOn
Input Context
Puzzle Controls
2IfpuzzleControlsOn.value == true
Then
3Change Variable
Variable
$gridSize
Value
data('Piece Counts', self.pieceCount, 'gridSize')
4Trigger Custom Event
Custom Event
pieceCountChosen

A.36 Choose Piece Sprite (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionChoose Piece Sprite

Gives a Piece the Sprite of the chosen picture cut for the chosen piece count: Piece Counts names the column of Pictures for the board's gridSize, and $picture names the row.

PARAMETERS
pieceObject
ACTIONS
1Declare Variable
Name
countRow
Value
0
2Declare Variable
Type
Text
Name
piecesColumn
3Change Variable
Variable
countRow
Value
dataFind('Piece Counts', 'gridSize', $gridSize)
4IfcountRow >= 0
Then
5Change Variable
Variable
piecesColumn
Value
data('Piece Counts', countRow, 'piecesColumn')
6Set Sprite
Applies to
piece
Sprite
data('Pictures', $picture, piecesColumn)

A.37 Choose Speed

Built in Chapter 5, The Finished Puzzle.

Logic ComponentChoose SpeedAttach to: Speed Button

Clicking or tapping a Speed Button makes its speed the chosen one. Each placement sets its speed (a row of Sort Speeds) and its text. While the How it works panel is open, the Button does nothing.

Attach toAny Object
PER INSTANCE VARIABLES
NameTypeStarting Value
speedTextFast
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
puzzleControlsOn
Input Context
Puzzle Controls
2IfpuzzleControlsOn.value == true
Then
3Change Variable
Variable
$speed
Value
self.speed
4Trigger Custom Event
Custom Event
speedChosen

A.38 Close Lesson

Built in Chapter 5, The Finished Puzzle.

Logic ComponentClose LessonAttach to: Close Button

Clicking or tapping the Close Button asks Puzzle Rules to close the How it works panel.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
On Hud Activated
WhenUI Activated
1Trigger Custom Event on Object
Applies to
@self.puzzleRules
Custom Event
lessonCloseRequested

A.39 Close Lesson Panel (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionClose Lesson Panel

Closes the How it works panel: the Lesson Panel Controls go off and the Puzzle Controls on again, and the panel's parts are told (lessonToggled).

ACTIONS
1Set Input Context Active
Input Context
Lesson Panel Controls
Active
false
2Set Input Context Active
Input Context
Puzzle Controls
3Trigger Custom Event
Custom Event
lessonToggled

A.40 Hide Focus (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionHide Focus

Hides the keyboard focus ($focusSlot -1), and tells the Outlines.

ACTIONS
1Change Variable
Variable
$focusSlot
Value
-1
2Trigger Custom Event
Custom Event
selectionChanged

A.41 Lay Out One Slot (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionLay Out One Slot

Lays out one Piece or Outline for the board's piece count: a slot on the board is shown at its center and sized to the slot; a slot beyond the piece count is hidden, so it shows nothing and answers no input. drawnSlotSide is the slot side, in screen pixels, that the Object fits at scale 1.

PARAMETERS
NameTypeStarts at
slotObjectObjectStructural
Required Components
Slot NameslotNumber
Component TypeData Structure
Required SchemaSlot Number
drawnSlotSideNumber70
ACTIONS
1Declare Variable
Name
slotSide
Value
0
2IfslotObject.slotNumber.slot < ($gridSize * $gridSize)
Then
3Set Visible
Applies to
slotObject
Visible
true
4Slot CenterFunction
Action Name
center
slot
slotObject.slotNumber.slot
5Set Position
Applies to
slotObject
Position Relative To
Screen
X
center.x
Y
center.y
6Change Variable
Variable
slotSide
Value
$boardSide / $gridSize
7Set Scale
Applies to
slotObject
Horizontal Scale
slotSide / drawnSlotSide
Vertical Scale
slotSide / drawnSlotSide
8Otherwise
9Set Visible
Applies to
slotObject
Visible
false

A.42 Lesson Lines

Built in Chapter 5, The Finished Puzzle.

Logic ComponentLesson LinesAttach to: Puzzle Rules

Keeps the words of the How it works panel's two lines about the computer's sort up to date: the pass it is in ($lessonPass) and what its last comparison did ($lessonOutcome).

Attach toAny Object
On Pair Compared
WhenpairComparedCustom Event
1Change Variable
Variable
$lessonOutcome
Value
$message
On Forward Pass Started
WhenforwardPassStartedCustom Event
1Change Variable
Variable
$lessonPass
Value
data('Messages', 'forwardPass', 'words')
On Backward Pass Started
WhenbackwardPassStartedCustom Event
1Change Variable
Variable
$lessonPass
Value
data('Messages', 'backwardPass', 'words')

A.43 Lesson Panel Switch

Built in Chapter 5, The Finished Puzzle.

Logic ComponentLesson Panel SwitchAttach to: Puzzle Rules

Opens the How it works panel when it is asked, and closes it on Close, F or Escape. While the panel is open the computer is stopped and only the Lesson Panel Controls are on, so the puzzle answers no key, Button or piece.

Attach toAny Object
On Lesson Requested
WhenlessonRequestedCustom Event
1Trigger Custom Event on Object
Custom Event
selectionCanceled
2Set Input Context Active
Input Context
Puzzle Controls
Active
No
3Set Input Context Active
Input Context
Lesson Panel Controls
4Trigger Custom Event
Custom Event
lessonToggled
When Close Is Pressed
WhenCommand PressedCommand: Close Panel
1Close Lesson PanelFunction
On Lesson Close Requested
WhenlessonCloseRequestedCustom Event
1Close Lesson PanelFunction

A.44 Let Computer Play (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionLet Computer Play

The computer takes over from the player: $whoPlays becomes Computer, a half-done selection ends, and the Outlines are told (whoPlaysChanged). When the computer is already playing, nothing changes.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1If$whoPlays == "Player"
Then
2Change Variable
Variable
$whoPlays
Value
'Computer'
3Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
clearSelectionRequested
4Trigger Custom Event
Custom Event
whoPlaysChanged

A.45 Let Player Play (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionLet Player Play

The player takes over from the computer: $whoPlays becomes Player, a running sort pauses where it is, and the Outlines are told (whoPlaysChanged). When the player is already playing, nothing changes.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1If$whoPlays == "Computer"
Then
2Change Variable
Variable
$whoPlays
Value
'Player'
3Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
pauseRequested
4Trigger Custom Event
Custom Event
whoPlaysChanged

A.46 Request Lesson (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionRequest Lesson

Asks Puzzle Rules to open the How it works panel. The How it works Button and the How It Works Command (F) both use it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
lessonRequested

A.47 Request Sort (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionRequest Sort

Asks Puzzle Rules to start the computer's sort, or to pause it while it runs. The Sort Button and the Run or Pause Command (A) both use it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
sortRequested

A.48 Request Upload (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionRequest Upload

Asks Puzzle Rules to let the player choose a picture of their own. The Upload Button uses it.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Trigger Custom Event on Object
Applies to
puzzleRules
Custom Event
uploadRequested

A.49 Show Count Underline

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow Count UnderlineAttach to: Count Underline

Shows this underline under the chosen piece count's Button only. Each placement sets the count it stands for.

Attach toAny Object
PER INSTANCE VARIABLES
NameTypeStarting Value
pieceCountText64 Pieces
When Created
WhenCreate
1Underline Chosen CountFunction
underline
self
pieceCount
self.pieceCount
On Piece Count Chosen
WhenpieceCountChosenCustom Event
1Underline Chosen CountFunction
underline
self
pieceCount
self.pieceCount

A.50 Show If Lesson Open (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionShow If Lesson Open

Shows one part of the How it works panel while the panel is open (the Lesson Panel Controls are on), and hides it otherwise.

PARAMETERS
partObject
ACTIONS
1Check Input Context Active
Action Name
lessonOpen
Input Context
Lesson Panel Controls
2IflessonOpen.value == true
Then
3Set Visible
Applies to
part
Visible
true
4Otherwise
5Set Visible
Applies to
part
Visible
false

A.51 Show If Sort Under Way (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionShow If Sort Under Way

Shows one line about the computer's sort while the How it works panel is open and the sort is under way, and hides it otherwise. Before the first comparison on a board ($comparedSlot is -1) the line has nothing to tell yet.

PARAMETERS
lineObject
ACTIONS
1Check Input Context Active
Action Name
lessonOpen
Input Context
Lesson Panel Controls
2IflessonOpen.value == true && $comparedSlot >= 0
Then
3Set Visible
Applies to
line
Visible
true
4Otherwise
5Set Visible
Applies to
line
Visible
false

A.52 Show Picture

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow PictureAttach to: Picture Preview, Whole Picture

Shows the chosen picture whole ($picture's preview in Pictures). The Picture Preview and the Whole Picture both use it.

Attach toAny Object
When Created
WhenCreate
1Set Sprite
Sprite
data('Pictures', $picture, 'preview')
On Picture Chosen
WhenpictureChosenCustom Event
1Set Sprite
Sprite
data('Pictures', $picture, 'preview')

A.53 Show Sort Lines

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow Sort LinesAttach to: Lesson State, Lesson Result

Shows this line about the computer's sort while the How it works panel is open and the sort is under way, in front of the game. The Lesson State and the Lesson Result use it.

Attach toAny Object
When Created
WhenCreate
1Set Z Order
Depth Amount
200
2Show If Sort Under WayFunction
line
self
On Lesson Toggled
WhenlessonToggledCustom Event
1Show If Sort Under WayFunction
line
self
On Pair Compared
WhenpairComparedCustom Event
1Show If Sort Under WayFunction
line
self
On Sort Cleared
WhensortClearedCustom Event
1Show If Sort Under WayFunction
line
self

A.54 Show Speed Underline

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow Speed UnderlineAttach to: Speed Underline

Shows this underline under the chosen speed's Button only. Each placement sets the speed it stands for.

Attach toAny Object
PER INSTANCE VARIABLES
NameTypeStarting Value
speedTextFast
When Created
WhenCreate
1Underline Chosen SpeedFunction
underline
self
speed
self.speed
On Speed Chosen
WhenspeedChosenCustom Event
1Underline Chosen SpeedFunction
underline
self
speed
self.speed

A.55 Show Whole Picture

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow Whole PictureAttach to: Whole Picture

Shows the whole picture, without the gaps between the pieces, once every piece is home and no piece is sliding.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When Created
WhenCreate
1Update Whole PictureFunction
picture
self
puzzleRules
@self.puzzleRules
On Game State Changed
WhenGame State Changed
1Update Whole PictureFunction
picture
self
puzzleRules
@self.puzzleRules
On Slide Ended
WhenslideEndedCustom Event
1Update Whole PictureFunction
picture
self
puzzleRules
@self.puzzleRules
On Board Arranged
WhenboardArrangedCustom Event
1Update Whole PictureFunction
picture
self
puzzleRules
@self.puzzleRules

A.56 Show With Lesson Panel

Built in Chapter 5, The Finished Puzzle.

Logic ComponentShow With Lesson PanelAttach to: Lesson Panel, Lesson Title, Lesson Line, Close Button

Shows this part of the How it works panel only while the panel is open, in front of the game. The panel, its title, its lines and its Close Button use it.

Attach toAny Object
When Created
WhenCreate
1Set Z Order
Depth Amount
200
2Show If Lesson OpenFunction
part
self
On Lesson Toggled
WhenlessonToggledCustom Event
1Show If Lesson OpenFunction
part
self

A.57 Slide Piece

Built in Chapter 5, The Finished Puzzle.

Logic ComponentSlide PieceAttach to: Piece

Slides this Piece onto its slot when its slot was one of the two in a slide: it starts at the other slot and moves in a straight line to its own over slideSeconds, then stands exactly on its slot. While the Piece slides, only this Logic moves it.

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
Slide Piece Dataself.slidePieceData
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
On Slide Started
WhenslideStartedCustom Event
1Ifself.slotNumber.slot == $slideFrom || self.slotNumber.slot == $slideTo
Then
2Change Component Value
Component Value
self.slidePieceData.otherSlot
Value
$slideFrom
3Ifself.slotNumber.slot == $slideFrom
Then
4Change Component Value
Component Value
self.slidePieceData.otherSlot
Value
$slideTo
5Slot CenterFunction
Action Name
start
slot
self.slidePieceData.otherSlot
6Set Position
Position Relative To
Screen
X
start.x
Y
start.y
7Set Z Order
Depth Amount
1
8Slot CenterFunction
Action Name
home
slot
self.slotNumber.slot
9Tween
Value
self.transform
Property
position.x
Target
home.x
Duration
$slideSeconds
10Tween
Value
self.transform
Property
position.y
Target
home.y
Duration
$slideSeconds
11Switch Mode
Event
Every Step
Mode
Sliding
Every Step
WhenStep
ModeResting (Starting Mode)
(no Actions)
Every Step
WhenStep
ModeSliding
1Check Cooldown Ready
Action Name
slideDone
Applies to
@self.puzzleRules
Cooldown Key
"pieceSlide"
2IfslideDone.value == true
Then
3Set Z Order
Depth Amount
0
4Switch Mode
Event
Every Step
Mode
Resting
5Trigger Custom Event
Custom Event
slideEnded
On Board Arranged
WhenboardArrangedCustom Event
1Control Tween
2Set Z Order
Depth Amount
0
3Switch Mode
Event
Every Step
Mode
Resting

A.58 Slide Pieces (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionSlide Pieces

Shows two slots trading pieces as a slide: each of the two pieces starts at the other slot and moves to its own over seconds. The board has already changed; the slide only shows it. While the pieceSlide cooldown of Puzzle Rules runs, new moves wait.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
firstSlotNumber0
secondSlotNumber0
secondsNumber0.22
ACTIONS
1Change Variable
Variable
$slideFrom
Value
firstSlot
2Change Variable
Variable
$slideTo
Value
secondSlot
3Change Variable
Variable
$slideSeconds
Value
seconds
4Start Cooldown
Applies to
puzzleRules
Cooldown Key
"pieceSlide"
Seconds
seconds
5Trigger Custom Event
Custom Event
slideStarted

A.59 Sort Timer

Built in Chapter 5, The Finished Puzzle.

Logic ComponentSort TimerAttach to: Puzzle Rules

Runs the computer's sort by itself: Sort lets the computer play and starts the pictureSort timer, and every ring of the timer asks Computer Sort for Steps at the chosen speed. Sort again, a Step, the player taking over, a player exchange, Reset, Shuffle, Escape or opening the How it works panel pauses it, and it stops when the sort has ended. The board, the pass and the counters are kept.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When the Game Starts
WhenGame Start
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
On Sort Requested
WhensortRequestedCustom Event
ModeStopped (Starting Mode)
1If$piecesHome < ($gridSize * $gridSize)
Then
2Let Computer PlayFunction
puzzleRules
@self.puzzleRules
3Change Variable
Variable
$message
Value
""
4Switch Mode
Event
On Sort Requested
Mode
Running
5Switch Mode
Event
On Speed Chosen
Mode
Running
6Start Sort TimerFunction
puzzleRules
@self.puzzleRules
On Sort Requested
WhensortRequestedCustom Event
ModeRunning
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
4Change Variable
Variable
$message
Value
data('Messages', 'paused', 'words')
On Speed Chosen
WhenspeedChosenCustom Event
ModeStopped (Starting Mode)
(no Actions)
On Speed Chosen
WhenspeedChosenCustom Event
ModeRunning
1Switch Mode
Event
On Sort Requested
Mode
Running
2Switch Mode
Event
On Speed Chosen
Mode
Running
3Start Sort TimerFunction
puzzleRules
@self.puzzleRules
On the Picture Sort Timer
WhenRecurring TimerTimer name: pictureSort
1Repeatdata('Sort Speeds', $speed, 'comparisonsPerTick')times
Each time
2Check Cooldown Ready
Action Name
slideDone
Cooldown Key
"pieceSlide"
3If$piecesHome < ($gridSize * $gridSize) && slideDone.value == true
Then
4Trigger Custom Event on Object
Custom Event
stepRequested
On Pause Requested
WhenpauseRequestedCustom Event
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
On Sort Ended
WhensortEndedCustom Event
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
On Board Arranged
WhenboardArrangedCustom Event
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
On Pieces Exchanged
WhenpiecesExchangedCustom Event
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules
On Selection Canceled
WhenselectionCanceledCustom Event
1Switch Mode
Event
On Sort Requested
Mode
Stopped
2Switch Mode
Event
On Speed Chosen
Mode
Stopped
3Stop Sort TimerFunction
puzzleRules
@self.puzzleRules

A.60 Start Sort Timer (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionStart Sort Timer

Starts the pictureSort timer at the chosen speed (or starts it again at a new speed) and makes the Sort Button read Pause.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Start Recurring Timer
Applies to
puzzleRules
Timer Name
"pictureSort"
Repeat Every (s)
data('Sort Speeds', $speed, 'intervalSeconds')
2Change Variable
Variable
$sortButtonLabel
Value
data('Messages', 'pauseButton', 'words')

A.61 Stop Sort Timer (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionStop Sort Timer

Stops the pictureSort timer and makes the Sort Button read Sort. The board, the pass and the counters stay as they are.

PARAMETERS
NameTypeStarts at
puzzleRulesObjectPuzzle Rules
ACTIONS
1Stop Recurring Timer
Applies to
puzzleRules
Timer Name
"pictureSort"
2Change Variable
Variable
$sortButtonLabel
Value
data('Messages', 'sortButton', 'words')

A.62 Underline Chosen Count (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionUnderline Chosen Count

Shows one piece-count underline when its count is the board's, and hides it otherwise.

PARAMETERS
NameTypeStarts at
underlineObject
pieceCountText64 Pieces
ACTIONS
1Ifdata('Piece Counts', pieceCount, 'gridSize') == $gridSize
Then
2Set Visible
Applies to
underline
Visible
true
3Otherwise
4Set Visible
Applies to
underline
Visible
false

A.63 Underline Chosen Speed (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionUnderline Chosen Speed

Shows one speed underline when its speed is the chosen one, and hides it otherwise.

PARAMETERS
NameTypeStarts at
underlineObject
speedTextFast
ACTIONS
1Ifspeed == $speed
Then
2Set Visible
Applies to
underline
Visible
true
3Otherwise
4Set Visible
Applies to
underline
Visible
false

A.64 Update Whole Picture (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionUpdate Whole Picture

Shows the whole picture over the board when the picture is complete (Game State Solved) and no piece is sliding, and hides it otherwise.

PARAMETERS
NameTypeStarts at
pictureObject
puzzleRulesObjectPuzzle Rules
ACTIONS
1Check Game State
Action Name
isSolved
Game State
Solved
2Check Cooldown Ready
Action Name
slideDone
Applies to
puzzleRules
Cooldown Key
"pieceSlide"
3IfisSolved.value == true && slideDone.value == true
Then
4Set Visible
Applies to
picture
Visible
true
5Otherwise
6Set Visible
Applies to
picture
Visible
false

A.65 Upload Picture

Built in Chapter 5, The Finished Puzzle.

Logic ComponentUpload PictureAttach to: Puzzle Rules

Lets the player rebuild a picture of their own. Upload opens the file chooser; a PNG, JPEG, WebP or AVIF picture up to 25 MB is cut to a square from its middle and becomes the picture the board shows, for this session only, with a new arrangement. A picture that cannot be opened changes nothing but the message; canceling changes nothing.

Attach toAny Object
On Upload Requested
WhenuploadRequestedCustom Event
1Run Code (JS)
Java Script
const host=window.__mythBabylon,scene=host&&host.controller;
if(!scene)return;
const largestFileBytes=25*1024*1024;
const uploadedRow=scene.dataRowByRef(scene.dataTable('Pictures'),'Uploaded');
if(!uploadedRow)return;
const sprites=Object.values(uploadedRow.cells);
if(window.__picturePuzzleChooser)window.__picturePuzzleChooser.remove();
const chooser=document.createElement('input');
chooser.type='file';chooser.accept='image/png,image/jpeg,image/webp,image/avif';chooser.style.display='none';
document.body.appendChild(chooser);window.__picturePuzzleChooser=chooser;
const finished=()=>{chooser.remove();if(window.__picturePuzzleChooser===chooser)window.__picturePuzzleChooser=null;};
chooser.addEventListener('cancel',finished,{once:true});
chooser.addEventListener('change',async()=>{
const file=chooser.files&&chooser.files[0];let fileUrl='';
try{
if(!file)return;
if(file.size>largestFileBytes)throw new Error('The picture is larger than 25 MB.');
fileUrl=URL.createObjectURL(file);
const chosen=new Image();chosen.src=fileUrl;await chosen.decode();
const side=Math.min(chosen.naturalWidth,chosen.naturalHeight);
if(side<1)throw new Error('The picture is empty.');
const size=Math.max(...sprites.map(name=>(host.RT.textures[name]||{}).natW||1));
const canvas=document.createElement('canvas');canvas.width=canvas.height=size;
canvas.getContext('2d').drawImage(chosen,(chosen.naturalWidth-side)/2,(chosen.naturalHeight-side)/2,side,side,0,0,size,size);
const square=new Image();square.src=canvas.toDataURL('image/png');await square.decode();
if(host.controller!==scene||window.__picturePuzzleChooser!==chooser)return;
sprites.forEach(name=>{
const old=host.RT.textures[name]||{};
host.RT.textures[name]={url:square.src,img:square,natW:size,natH:size,filterMode:old.filterMode||'smooth',filterScale:1};
scene.instances.filter(it=>it.spriteName===name&&!it.destroyed).forEach(it=>scene.swapSprite(it,name));
});
api.fireEvent('pictureUploaded');
}catch(error){if(host.controller===scene)api.fireEvent('uploadFailed');}
finally{if(fileUrl)URL.revokeObjectURL(fileUrl);finished();}
},{once:true});
chooser.click();
On Picture Uploaded
WhenpictureUploadedCustom Event
1Check Input Context Active
Action Name
lessonOpenAtUpload
Input Context
Lesson Panel Controls
2IflessonOpenAtUpload.value == true
Then
3Trigger Custom Event on Object
Custom Event
lessonCloseRequested
4Use PictureFunction
picture
"Uploaded"
5Change Variable
Variable
$message
Value
data('Messages', 'uploaded', 'words')
On Upload Failed
WhenuploadFailedCustom Event
1Change Variable
Variable
$message
Value
data('Messages', 'uploadFailed', 'words')

A.66 Use Picture (Function)

Built in Chapter 5, The Finished Puzzle.

FunctionUse Picture

Makes a row of Pictures the picture the board shows: $picture becomes that row, and everyone who shows the picture is told (pictureChosen). Arrange Board then shuffles a new arrangement of it.

PARAMETERS
NameTypeStarts at
pictureTextVillage
ACTIONS
1Change Variable
Variable
$picture
Value
picture
2Trigger Custom Event
Custom Event
pictureChosen

A.67 Who Plays

Built in Chapter 5, The Finished Puzzle.

Logic ComponentWho PlaysAttach to: Puzzle Rules

Hands the game to the player or to the computer ($whoPlays): H and a press on a piece let the player play, and C and a comparison of the computer let the computer play. Keys that choose a piece let the player play through Choose Slot, and Sort through Sort Timer. The board never changes when who plays changes.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
When Player Is Pressed
WhenCommand PressedCommand: Player Plays
1Let Player PlayFunction
puzzleRules
@self.puzzleRules
When Computer Is Pressed
WhenCommand PressedCommand: Computer Plays
1Let Computer PlayFunction
puzzleRules
@self.puzzleRules
On Piece Pressed
WhenpiecePressedCustom Event
1Let Player PlayFunction
puzzleRules
@self.puzzleRules
On Pair Compared
WhenpairComparedCustom Event
1Let Computer PlayFunction
puzzleRules
@self.puzzleRules