TutorialsCocktail Shaker Sort

1  The Picture and the Board

Goal

By the end of this chapter, the Village lies on the board in 64 pieces, and every one is in the wrong slot. The Preview shows the picture whole beside it. The caption over the board reads 0 / 64. Shuffle deals the pieces again, and Reset brings back the deal you started from.

The game as it is at the end of this chapter. Click the game to play.

If your game and this chapter part ways, here is the chapter’s finished project. Open it and compare, or start Chapter 2 from it.

Picture Puzzle, Chapter 1 finishedMyth project · 6.4 MB

To open it, start Myth Engine, choose File › Open Project... and pick the downloaded file.

1.1 The Idea

The Welcome page showed you the Village, cut into 64 pieces and dealt into the wrong slots. Sailboats float along the top row, far from the lake. The cat on the wall has wandered to the board’s right edge.

This chapter builds that board, and then it stops, before anyone can touch it. The pieces lie where they were dealt, and nothing on the board can move them yet. Your hands come in Chapter 2.

Here’s the first real question. How does a game know a picture is wrong? It can’t look at it. Neither can the computer that will sort it, from Chapter 3 on.

So the game turns the picture into numbers. Every piece has an ID, starting from 0 for the top-left corner of the picture and counting the way you read a page. Every slot on the board has a number too, counted the same way. A piece is home when its ID and its slot’s number are the same.

That’s the whole puzzle. Put every piece in the slot with its own number, and the picture is back.

The numbers live in a Data Table, a spreadsheet the game reads while it plays. This one is called Board Slots. Think of it as a seating chart. The slot numbers run down the side, and beside each one is the piece sitting there now. The pieces on the screen only show what the chart says, so trading two numbers in the table trades two pieces.

From Chapter 3 on, the computer reads that chart, two neighboring slots at a time. When the left piece belongs later, it swaps the two. It works forward across the board, then back, then forward again, the way you’d shake a cocktail shaker, and that’s where Cocktail Shaker Sort gets its name. It never needs to see a single flower.

Did you know?

Cocktail Shaker Sort is also called a bidirectional bubble sort. A bubble sort asks the same question about two neighbors, but it only ever goes forward.

Nothing sorts in this chapter. It builds the chart, the pieces that show it, and two ways to deal the board again. One part is long, and it shows nothing until its last piece is in. Then all 64 pieces appear at once.

1.2 The Plan

Here’s how the pieces work together, as the game starts and as you press a key. Read each line from left to right. Nearly every name is new, so read the lines once for their shape. Come back to them at the end. By then they’ll read like a map of everything you built in between.

  • The game starts -> Make Board writes a row of Board Slots for each slot, and sends boardMade.
  • Make Board’s boardMade -> Pieces Home counts the pieces that are home -> the Board Caption shows the count.
  • The Scene starts -> Make Board makes an Outline and a Piece for each slot, gives each one its slot number, and sends it placedOnBoard.
  • Each placedOnBoard -> Lay Out Slot asks Slot Center where the slot is, and moves there. On a Piece, Show Piece shows that slot’s piece of the picture.
  • N or Shuffle -> Request Shuffle sends shuffleRequested -> Arrange Board deals a new arrangement with Shuffle Board, and sends boardArranged.
  • R or Reset -> Request Reset sends resetRequested -> Arrange Board puts the starting arrangement back, and sends boardArranged. The Message Line says Reset.
  • Each boardArranged -> every Piece shows its new piece, and Pieces Home counts again.

1.3 Set Up

Every game starts as an empty project, and an empty project is a strange thing to look at. There’s a Scene, a lot of buttons, and no game anywhere. It fills up faster than you’d think.

If you made a Blank 2D project on the Welcome page and installed the Starter Kit into it, you’re ready. If not, do it now. Choose File > New Project… and pick Blank 2D. Type Picture Puzzle as its name, choose where it goes with Browse…, and press Create Project. Choose File > Install Myth Pack… next, and pick the kit you get from the button below.

Picture Puzzle Starter KitMyth Pack · 4859 KB · every picture

To install it, open Myth Engine, choose File › Install Myth Pack... and pick the downloaded file.

Myth Engine asks before it installs. Its window has Add to This Project already chosen, and it says the kit adds 20 resources. Press Install.

Turn on Advanced Mode too, under Settings at the top of the editor. Two Actions in this chapter write into a table while the game runs, and they’re Advanced Mode blocks. The Making page says more about Advanced Mode, in Before your first card.

The Set up card comes after these paragraphs. Read them first, then work down the card from the top. The Set up card on the Making page says where each block lives.

ART lists four pictures: the whole Village, the Village cut into 64 pieces, the face of a button, and a plain square. The Starter Kit brought them, with the Forest and the Harbor for later.

COMMANDS are two keys, R for Reset and N for New Arrangement. Make them now in the Input Manager. They wait there for a piece of Logic to listen for them, in the part called A new deal.

Leave GLOBAL VARIABLES for The board. You’ll make them on your first Logic Component’s Globals card.

The card’s SCENE block makes a Scene called Picture Table. Your project already has one Scene, named Scene, so give it that name instead of making a second one. In the Resources panel, open Scenes and right-click Scene. Choose its Rename line, type Picture Table, and press Enter.

Now the Game Settings, top to bottom, starting with Title, the name on the game’s window. Reference Width and Reference Height make the screen 1000 by 850 pixels. Every X and Y you type for something on the screen counts in those pixels. Puzzle Rules is the one exception, and its part says why.

Texture Filtering is a list that starts at Pixel-Art (Crisp), which keeps every pixel’s hard square edge. A photograph cut into pieces looks better with Smooth Textures. The Page Background is the soft blue-gray around the game, outside its edges.

The Scene’s own Background Color is the table the board lies on, a white with a little blue in it. Start Scene should already read Picture Table · 2D. It moved with the name.

Leave PLACE THESE for later, because each part places its own Objects once they exist.

Set upWhat this chapter adds
ART (sprites, from the starter kit)
Village Picture
Village Pieces 64
Button Face
Outline Square
COMMANDS (Game Settings > Input Manager)
ResetButton
KeybindingsR
New ArrangementButton
KeybindingsN
GLOBAL VARIABLES
$gridSizeNumberstarts at 8
$piecesHomeNumberstarts at 0
$messageTextstarts at
$boardLeftNumberstarts at 60
$boardTopNumberstarts at 220
$boardSideNumberstarts at 560
GAME SETTINGS > Display > Window
TitlePicture Puzzle
GAME SETTINGS > Display > Reference Resolution
Reference Width1000
Reference Height850
GAME SETTINGS > Display > Rendering
Texture FilteringSmooth Textures
GAME SETTINGS > Display > Page Background (Outside the Game)
Color#DCE6EF
SCENEPicture Table (new)
Background Color#F5F7FA
GAME SETTINGS > General > Startup
Start ScenePicture Table · 2D
SCENE Picture Table: PLACE THESE
ObjectXY
Puzzle Rules026.563
Game Title500-43
Board Caption340-199
Preview Caption815-199
Picture Preview815-346
Puzzle Button719-141
with Transform > Bounding Box > Size = X 162, Y 44 (Edit Object Locally)
with Sprite > Transform > Size = X 162, Y 44 (Edit Object Locally)
with Text / UI > Text = Shuffle (Edit Object Locally)
with Per Instance Variables > Command = Shuffle
Puzzle Button900-141
with Text / UI > Text = Reset (Edit Object Locally)
Message Line500-827

Save your project now, with Ctrl+S, and again at the end of each part.

1.4 The Title and the Preview

First come the things that never change.

At the top, in bold dark blue-gray letters, the title reads Picture Puzzle. Off to the right, under the small gray word Preview, the whole Village sits in a square. That’s the picture as it should be. A player glances at it the way you glance at the lid of a jigsaw box.

The title and the caption are words on the screen. Each is a Screen UI Object with a Text / UI. An Object card and its components on the Making page shows how to make one, and this is your first. A new Screen UI Object comes with UI Interaction, and these cards don’t list it, so remove it. Everything else comes from the card.

ObjectGame Title
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
TextPicture Puzzle
Font Size30
EmphasisBold
Color#263D54
RenderingVector

The Preview Caption is made the same way, smaller and gray.

ObjectPreview Caption
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
TextPreview
Font Size13
EmphasisSemibold
Color#526478
RenderingVector

The Picture Preview shows a picture instead of words: its Sprite is Village Picture, drawn 248 pixels square.

ObjectPicture Preview
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 248, Y 248
Sprite
Z Index Within Object-1
SpriteVillage Picture
Transform > SizeX 248, Y 248

Now place all three. Open Picture Table, find each one under Predefined Objects in the Place Scene Content panel, and drag it onto the Scene. Type its X and Y from PLACE THESE into its Screen Offset (px). The link takes you up to the card, and your browser’s Back button brings you here again.

An X and Y put the middle of the Object there, so the Game Title’s 500 centers it across the 1000-pixel screen.

Run the game: press Play, the triangle at the top of the editor. The game opens in a window of its own. The title stands at the top, and the Village waits whole on the right, beside an empty space where the board will be. Close the game’s window, and the editor is back.

That’s your game, running.

1.5 The Board

Now the board itself.

It’s a square on the left, 560 pixels on a side. Eight rows of eight slots fill it. In every slot, a piece of the Village sits on a plain square a little larger than itself. This is the longest part of the chapter, and the board stays empty until its last piece is in. Keep going, because it’s worth the wait.

Board Slots comes first. It starts with no rows at all, not one. That’s right, because the game writes its 64 rows itself every time it starts. A Data Table card shows how to make it.

Data TableBoard SlotsData Structure: Board Slots Entry
Data StructureBoard Slots Entry

One row of the "Board Slots" Data Table.

pieceNumberdefault 0
startPieceNumberdefault 0

Make Board Slots Entry, the table’s Data Structure, with the fields on its card. Those fields are its two columns. In each row, piece is the ID of the piece in that slot now, and startPiece is the one Reset puts back.

Every Piece on the screen, and every square behind one, needs to know one thing: which slot it stands for. It keeps that in a Data Structure called Slot Number, a small form with one field, slot. A Data Structure card shows how to make it.

Data StructureSlot Number

The slot a Piece or an Outline stands for: its row of Board Slots, 0 for the top-left slot, counting right, then down. Make Board gives each one its slot right after making it.

slotNumberdefault 0

1.5.1 Show Piece

A Piece is one square of the picture. All 64 of them are the same Object, showing the same image, Village Pieces 64. That image holds the whole Village, cut into 64 frames and numbered from 0 the way you read. Frame 0 is the top-left corner of the picture.

So a piece’s ID is two things at once. It’s the slot where the piece belongs, and it’s the frame that shows it. Show Piece has one job. It reads the piece in its own slot from Board Slots, and shows that frame with Set Frame.

It does that at two moments: when the Piece is first placed on the board, and whenever the board is dealt again. Each moment is a message, placedOnBoard and boardArranged. Such a message is a Custom Event, sent by one piece of Logic and heard by others. Nothing sends either one yet. Make Board sends the first, at the end of this part. Arrange Board sends the second, in A new deal.

Its DATA STRUCTURES block needs Slot Number. Add it to this Logic with the + on its Data Structures card. A Logic Component card shows where.

It’s your first Logic Component, so the game’s six Globals go in first. Use Show Piece’s Globals card’s +, then New Global…, for the Set up card’s six rows. Message starts empty. Clear the starting value instead of keeping the 0 Myth may put there.

The two Events come next. Events: the When bars shows how to listen for a message nothing sends yet.

Logic ComponentShow PieceAttach to: Piece

Shows the picture frame of the piece that Board Slots puts in this Piece's slot. 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
1Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')
On Board Arranged
WhenboardArrangedCustom Event
1Set Frame
Frame
data('Board Slots', self.slotNumber.slot, 'piece')

1.5.2 Slot Center

This one has no picture. It answers a question: where on the screen is the middle of a slot? You give it a slot number, slot, and it hands back two numbers, x and y.

It works that out in three moves. First, how wide is one slot? That’s the board’s side divided by the slots in a row, and it goes in slotSide. Then, which column and which row? The column is what’s left over when slot is divided by $gridSize. The row is how many whole rows come before it. Last, it counts in from the board’s top-left corner: so many slots across, so many down, and half a slot more to reach the middle.

Its y comes back below zero. On the screen, y is 0 at the top edge, and it goes below zero as you go down. So the lower a slot stands, the smaller its y. That’s why the minus sign sits in front of all of centerY.

Nobody playing Picture Puzzle will ever notice this Function, but the board would fall apart without it. Every piece and every square asks it where to stand.

Its two answers travel together in Slot Center Result, a small form holding x and y. Make it before Slot Center, then pick it as the Function’s Return Type.

Data StructureSlot Center Result

What Slot Center gives back: x and y, the center of the slot on the screen, in screen pixels.

xNumberdefault 0
yNumberdefault 0

It’s your first Function. A Function card on the Making page shows how to make one, with this card.

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

1.5.3 Lay Out Slot

Lay Out Slot waits for placedOnBoard too. When it comes, it asks Slot Center where its slot’s middle is, and calls the answer center. Then Set Position moves it there.

Set Position’s Position Relative To list starts at World. Change it to Screen. Then its numbers count in screen pixels, like a placement’s Screen Offset. Left at World, they’d count in the game world’s meters. The piece would land far off the screen.

Both Objects use Lay Out Slot. Both carry Slot Number, which gives each copy the number of the slot it stands on.

Logic ComponentLay Out SlotAttach to: Piece Outline, Piece

Places this Piece or Outline on the center of its slot, once Make Board has made it.

Attach toAny Object
DATA STRUCTURES
Slot Numberself.slotNumber
On Placed on Board
WhenplacedOnBoardCustom Event
1Slot CenterFunction
Action Name
center
slot
self.slotNumber.slot
2Set Position
Position Relative To
Screen
X
center.x
Y
center.y

Now the two Objects. The Piece Outline is the plain square, 70 pixels, the full width of a slot. Remove its UI Interaction, as on the title. Its Data Structure arrives From Logic when you attach Lay Out Slot.

The Outline’s Tint colors its white picture dark green-gray. Set the Sprite’s Tint from its card. A thin dark edge will show around each piece, and Chapter 2 teaches that edge to change color.

ObjectPiece Outline
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 70, Y 70
Sprite
Z Index Within Object-1
SpriteOutline Square
Tint#46615A
Transform > SizeX 70, Y 70
Data Structure
From LogicLay Out Slot
Data StructureSlot Number
Logic
Lay Out Slot

The Piece is 68 pixels, two less than its slot, which leaves that thin edge of Outline around it. Attach Show Piece first, then Lay Out Slot.

ObjectPiece
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 68, Y 68
Sprite
Z Index Within Object-1
SpriteVillage Pieces 64
Transform > SizeX 68, Y 68
Data Structure
From LogicShow Piece, Lay Out Slot
Data StructureSlot Number
Logic
Show Piece
Lay Out Slot

The Scene never places a Piece or an Outline, because the next piece of Logic makes all of them.

1.5.4 Make Board

Make Board is the longest card in the chapter. It’s the one that brings the whole board to life, every piece of it, out of nothing. Take it one Event at a time.

Make Board keeps its count in a form called Make Board Data. Its slotCount field is how many slots it needs. Make that form with the Data Structures card’s +, and fill it from its card.

Data StructureMake Board Data

What Make Board remembers on Puzzle Rules: slotCount, how many slots of Board Slots it makes and how many Outlines and Pieces.

slotCountNumberdefault 0

Make Board has two Events, and they come in order. Game Start runs once, as the game begins, and Scene Start runs right after it, as the Scene opens. The chart belongs to the game, so its rows are written at Game Start. The pieces belong to the Scene, so they’re made at Scene Start.

At Game Start, a Repeat writes the chart. Inside it, local.index counts the times round, starting at 0, and that’s the slot’s number. Control Data Row has an Operation list too. It starts on adding a row. That’s what Make Board wants, so the card leaves it off.

Each new row gets a name, text("Slot ", local.index + 1), which joins the word Slot to a number. So the rows are called Slot 1, Slot 2, and on. The name is for people. The Logic reads a row by its number, so the next two steps write to row local.index.

Which piece goes where? The formula takes every fifth one, counted round the board. Count the first few. Slot 0 gets piece 3, and slot 1 gets piece 8, five pieces further on. Slot 2 gets 13. When the count runs past the last piece, it wraps round to the start, which is what % does. It keeps what’s left over after dividing by slotCount.

Taking every fifth piece of 64 lands on each one exactly once, and never puts a piece in its own home. So the board opens with all 64 pieces, and none of them home.

The last three steps look ahead. The first sends boardMade, to say the rows are ready. It’s a Trigger Custom Event on Object with no Applies To. So it goes to Puzzle Rules alone. Nothing listens yet, but in the next part, Pieces Home will, and it lives on Puzzle Rules.

Then an If guards a board this chapter never makes, a board of 25 pieces. There, counting by fives comes back round too soon. Slot 5 would get piece 3 again, the same as slot 0, and some pieces would never be dealt. So when the count is a multiple of 5, the board starts with a Shuffle instead. At 64 pieces, the If never fires.

At Scene Start, a second Repeat runs once for each slot. Each time round, it makes an Outline, then a Piece in front of it, from the Shared Variables outline and piece. Each new one is handed its slot number, and then placedOnBoard, sent to it alone.

How does a new Piece get its slot number? With a Change Variable that works on the new Piece, not on Puzzle Rules. Its Variable box is a list of the Variables it can reach. Click in it, and under newPiece Variables you’ll find newPiece.slot, the slot field of the new Piece’s own Slot Number. Pick it, or type it. The Outline’s is newOutline.slot, the same way.

It looks different from Show Piece’s self.slotNumber.slot, but it’s the same field. A formula has to name the Data Structure first, by its Slot Name, slotNumber. The Change Variable’s list does that for you.

It’s the seating chart again, now at the door, where each new Piece is handed its seat number. It hears placedOnBoard, finds its seat with Lay Out Slot, and shows its face with Show Piece.

Make Board’s outline and piece are Shared Variables that hold Objects. Each starts at None. After you attach the Logic, Puzzle Rules fills those two names with the Objects it will create. Create Instance reads them as @self.outline and @self.piece.

Type “piece” and “startPiece” into the Column slots, quotes and all. They name columns in Board Slots. The Table slot names the resource itself, so Board Slots goes in bare. Values, quote marks and all explains those two kinds of slot.

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 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) 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
1Change Component Value
Component Value
self.makeBoardData.slotCount
Value
$gridSize * $gridSize
2Repeatself.makeBoardData.slotCounttimes
Each time
3Control Data Row
Action Name
addedRow
Table
Board Slots
Row
text("Slot ", local.index + 1)
4Set Data Cell
Table
Board Slots
Row
local.index
Column
"piece"
Value
(5 * local.index + 3) % self.makeBoardData.slotCount
5Set Data Cell
Table
Board Slots
Row
local.index
Column
"startPiece"
Value
data('Board Slots', local.index, 'piece')
6Trigger Custom Event on Object
Custom Event
boardMade
7If(self.makeBoardData.slotCount % 5) == 0
Then
8Trigger 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

Make Board lives on Puzzle Rules. It’s an Empty Object, with no picture and no words. By the end of the book, the whole puzzle lives on it. Its card lists all four of the Logic Components it carries at the end of this chapter. Attach Make Board now, and the others as you make them. In Puzzle Rules’ Variables, set outline to Piece Outline, piece to Piece, and puzzleRules to Puzzle Rules itself.

ObjectPuzzle Rules
Data Structure
From LogicMake Board
Data StructureMake Board Data
Logic
Make Board
Arrange Board
Pieces Home
Puzzle Commands
Shared Variables
puzzleRulesPuzzle Rules
outlinePiece Outline
piecePiece

Place Puzzle Rules from PLACE THESE. It stands in the world, not on the screen, so its X and Y go into World Position: 0 and 26.563. That’s the screen’s top-left corner, in the world’s meters. The world counts up from the bottom, and 26.563 meters is the full height of the screen’s 850 pixels. With no picture, it never shows, and where it stands changes nothing you’ll see. Type the card’s numbers anyway, to match the Goal’s game.

Run the game, and the board is there. All 64 pieces appear at once, eight by eight: flowers, water, rooftops and the cat, in no order at all. You never placed a single piece.

1.6 The Count

Next, the board learns to keep count.

Above the board, small and gray, a caption reads 0 / 64: how many pieces are home, out of how many. That first number is the one the whole game is about.

The Board Caption is words, like the title, but its braces show two live values. The first is $piecesHome. The second, $gridSize * $gridSize, is worked out as it’s shown, so it reads 64. Type the Text as the card spells it.

ObjectBoard Caption
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
Text{$piecesHome} / {$gridSize * $gridSize}
Font Size13
EmphasisSemibold
Color#526478
RenderingVector

1.6.1 Count Pieces Home

Count Pieces Home starts the count at 0, then walks the board. A Repeat visits every slot, and an If asks the same question each time: is the piece in this slot the one whose home it is? When it is, the count goes up by 1.

That If is the test for home from the start of the chapter, written as a formula.

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

1.6.2 Pieces Home

Pieces Home calls Count Pieces Home when the board changes, and at no other time. Remember boardMade, which Make Board sends once its rows are written? This is who it was for. Its second Event hears boardArranged, from Arrange Board in the next part.

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

Attach Pieces Home to Puzzle Rules. Place the Board Caption at 340 and -199, centered over the board, and run the game. Above the board, it says 0 / 64.

1.7 A New Deal

The board learns to start over.

Press N, and every piece jumps to a new slot at once. Press R, and the deal you started from comes back, while a green line at the foot of the screen says Reset.

Both are the same job, done two ways. Write a whole new arrangement into Board Slots, then tell every Piece to look again.

1.7.1 Exchange Slots

First comes a small Function the rest of the book leans on. It trades the pieces of two slots, firstSlot and secondSlot, and it’s the one place in the game where two slots trade. The shuffle uses it today, your hands in Chapter 2, and the computer in Chapter 3.

Why keep a piece aside before trading? Copy the second slot’s piece into the first, and the first slot’s piece is gone. So Exchange Slots keeps it first, in firstPiece, the way you’d hold one cup aside while you pour the other.

A Function’s Column boxes read what you type as a formula. So the word piece goes in with its quote marks there, as the card shows.

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

1.7.2 Shuffle Board

Shuffle Board deals a fresh arrangement, and every arrangement is as likely as any other. It’s called the Fisher-Yates shuffle.

First it puts every piece home, so the board holds each piece exactly once. Then it walks the board backward, from the last slot to the second. At each slot, it picks a random partner, anywhere from the first slot up to this one, and the two trade pieces. The partner may be the slot itself. Once the walk has passed a slot, nothing picks it again.

Count the first trades. At the last slot, the partner can be any slot on the board. One step back, it can be any slot but the last. Each step, the choice is one slot smaller.

Last, it copies the new arrangement into startPiece, so Reset puts back this deal now, not the first one.

The partner comes from Generate Random Integer. It’s named partner, so the number it picked is partner.value.

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')

1.7.3 Restore Start Arrangement

Restore Start Arrangement is the shortest of the three. It picks nothing and counts nothing. It only remembers: every slot’s startPiece goes back into its piece.

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')

1.7.4 Arrange Board

Now the piece that decides. Arrange Board waits for two requests, resetRequested and shuffleRequested.

For a Reset, it restores the starting arrangement, and sets $message to the reset row of Messages. For a Shuffle, it shuffles, and clears $message with "", a word with no letters. Either way, it then sends boardArranged to every Object that listens: every Piece’s Show Piece, and Pieces Home.

The words come from a table, Messages, so the Logic never spells them itself. Today it has one row. Its columns come from Messages Entry. Before you add the row, make the words field on that form’s own card.

Data StructureMessages Entry

One row of the "Messages" Data Table.

wordsTextdefault (empty)
Data TableMessagesData Structure: Messages Entry
Row 0reset
wordsReset.
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. 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')
3Trigger Custom Event
Custom Event
boardArranged
On Shuffle Requested
WhenshuffleRequestedCustom Event
1Shuffle BoardFunction
2Change Variable
Variable
$message
Value
""
3Trigger Custom Event
Custom Event
boardArranged

Attach Arrange Board to Puzzle Rules. The Message Line shows $message in green, across the foot of the screen. Its card has two lines more than the title’s, so a long message can wrap. An Object card and its components explains both.

ObjectMessage Line
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
Text{$message}
Font Size15
EmphasisSemibold
Color#2B694E
Text BoundsWrap to Width
RenderingVector
Transform > Size X900

Place it at 500 and -827.

1.7.5 Request Reset

Nothing calls Arrange Board directly. The keys and the buttons ask, through two small Functions.

Request Reset sends resetRequested to Puzzle Rules, and that’s all it does. Its one Parameter, puzzleRules, says which Object to ask: an Object Parameter, Nominal, set to Puzzle Rules, as A Function card shows.

Why a whole Function for one Action? Because two things ask for a Reset, the R key and the Reset button. Both call Request Reset, so they can never ask for different things.

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

1.7.6 Request Shuffle

This works like Request Reset, but it sends shuffleRequested instead.

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

1.7.7 Puzzle Commands

Puzzle Commands is the keys. When Reset is pressed, it calls Request Reset. When New Arrangement is pressed, it calls Request Shuffle. It asks for the Command. It never asks for the key. So you could give Reset another key in the Input Manager and change nothing here.

It passes @self.puzzleRules to both Functions.

Logic ComponentPuzzle CommandsAttach to: Puzzle Rules

The keys ask for the same things as the Buttons: R for Reset, N for a new arrangement.

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

Attach Puzzle Commands to Puzzle Rules, whose puzzleRules Shared Variable already names itself. Both Commands use that same value to reach the Object that holds the whole puzzle.

Run the game, and press N. Every piece jumps. Press it again, and again, and watch the caption, because a shuffle can land a piece or two at home by chance. Now press R. The last deal comes back, and the bottom line says Reset.

1.8 The Two Buttons

Last come two buttons, Shuffle and Reset, side by side above the Preview.

They’re one Object, the Puzzle Button, placed twice. The Object doesn’t know which button it is. Each placement says so, with its own words and its own job.

1.8.1 Button Action

Button Action reads the pressed button’s command. Reset calls Request Reset, while Shuffle calls Request Shuffle for a new deal. Both use @self.puzzleRules to reach the puzzle. The two placements share this Logic, but each keeps its own command and its own words.

The Event is UI Activated, which Myth names On Hud Activated. The command is a Per Instance Variable, so every placed button has its own copy.

Logic ComponentButton ActionAttach to: Puzzle Button

Clicking or tapping a Puzzle Button runs the Request Function of its command: Reset or Shuffle. Each placement sets its own command and its own text.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
puzzleRulesObjectConstantNone
PER INSTANCE VARIABLES
NameTypeStarting Value
commandTextReset
On Hud Activated
WhenUI Activated
1Ifself.command == "Reset"
Then
2Request ResetFunction
puzzleRules
@self.puzzleRules
3Ifself.command == "Shuffle"
Then
4Request ShuffleFunction
puzzleRules
@self.puzzleRules

The Puzzle Button is words on a picture, the Button Face, and a Z Index Within Object of -1 keeps the picture under the words. This time, keep its UI Interaction. That’s what lets a player press it.

ObjectPuzzle Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 150, Y 44
Text / UI
TextButton
Font Size16
EmphasisSemibold
Color#263D54
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteButton Face
Transform > SizeX 150, Y 44
UI Interaction(as it is added)
Logic
Button Action
Shared Variables
puzzleRulesPuzzle Rules

Now the two placements, from PLACE THESE, each with its own “with” lines. A placement’s own values shows each kind.

The Shuffle button goes at 719 and -141. It’s 162 pixels wide for this placement alone, in both its Bounding Box and its Sprite. Its Text is Shuffle, and its Command is Shuffle, under Per Instance Variables. The Reset button goes at 900 and -141. Its Text is Reset, and its Command keeps Reset, the starting value.

Run the game. Click Shuffle, then Reset. They do what N and R do, because they call the same Functions.

Play it!

Watch for each of these.

  • Picture Puzzle stands at the top, in bold dark blue-gray.
  • The board is eight pieces across and eight down, on the left, with thin dark green-gray lines between the pieces.
  • No piece is home. Compare the top-left piece with the Preview: it comes from further along the picture’s top row.
  • Above the board, the caption reads 0 / 64. On the right, the word Preview stands over the whole Village.
  • Shuffle and Reset sit side by side at the top right, and Shuffle is a little wider.
  • Press N, or click Shuffle. Every piece jumps at once, and the caption may read 1 / 64 or 2 / 64.
  • Press R, or click Reset. The deal from your last Shuffle comes back, and the bottom line says Reset.
  • Close the game, and run it again. The very first deal is back, every piece in the same wrong slot.
  • Click a piece. Nothing happens yet.
How it works

Board Slots holds the board as numbers. Make Board writes its rows and makes a Piece for each slot. Each Piece finds its place with Slot Center and shows its frame with Show Piece. Pieces Home counts the pieces that are home. Arrange Board deals again when it’s asked.

Underneath all of it is one idea: the table is the puzzle. The pieces only show it. A piece is home when its number matches its slot’s, and the picture is whole when every number does. From Chapter 3, the computer reads only those numbers, and never looks at the picture at all.

1.9 If It Didn’t Work

Something may be a little off the first time. That’s normal, and it’s how everyone learns where things live in the editor. Run the game, watch what it does, and think it through one piece at a time.

No pieces at all, but the title and the Preview are there? Perhaps Make Board never ran. Look for Puzzle Rules in Picture Table, and for Make Board on it, with Piece Outline and Piece in its two boxes. Open Make Board too, and look for a block standing apart from its line. Join it with Connect to Sequence.

All the pieces piled in one corner? They were made, but they never moved to their slots. Perhaps they never heard placedOnBoard. Look at the name in two places, Make Board’s Trigger Custom Event on Object and Lay Out Slot’s When bar. They must match, capital B and all. Or Slot Center may hand back its starting 0s. In Slot Center’s Return, x should say centerX, and y should say centerY.

Only one piece, or only one Outline? The Actions belong inside the Repeat, on its line, where the card puts them under Each time. One left outside runs once, not once for each slot.

The pieces are nowhere to be seen, though Make Board looks right? They may have gone into the game world, far off the screen, where no player would ever find them. Look at Lay Out Slot’s Set Position. Its Position Relative To should say Screen. Or perhaps the board sits above the screen, with every y the wrong way up. Look for the minus sign at the front of centerY, in Slot Center.

Every piece shows the same corner of the picture? Then every Piece is reading 0. Perhaps the rows never got their pieces. Look at Make Board’s first Repeat, and the two Set Data Cells inside it. Or look at Show Piece’s Set Frame, and its formula.

The caption says 0 / 0? Look at $gridSize in your Global Variables. Its Default is 8.

N and R do nothing? Look in the Input Manager first, for both Commands and their keys. After that, look for Puzzle Commands on Puzzle Rules, and at Arrange Board’s two When bars. Their names must match what Request Reset and Request Shuffle send.

The caption changes, but the pieces don’t? Show Piece may hear only one of its messages. Its second Event is boardArranged.

A button does nothing when you click it? Its UI Interaction may have gone with the others, so look in Attached Components. Then look at its Command Variable and the Object’s puzzleRules Shared Variable.

Each of these is one small fix. Make it, run the game again, and you’re back with the chapter. And if you’d like to compare, the catch-up download in the Goal is this chapter’s game, finished.

Challenge

The first deal is yours to change. In Make Board’s first Repeat, the 5 in step 4’s formula is the step it counts by. Try 7, or any odd number, and run the game. A new deal appears, and still no piece is home. Count the first few slots by hand, the way you did with 5, and see whether the board agrees. Put the 5 back before Chapter 2, because the later chapters count from this exact deal.

The Village lies on the board, every piece in the wrong slot. In Chapter 2, it meets your hands.