TutorialsBinary Search

5  Run and Compare

Goal

By the end of this chapter, the computer takes its turns while you watch. You can pause it, compare its search with yours on the same safe, and open a lesson over the game.

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

The finished project is here if you’d like to compare your work. It holds every part of Crack the Safe.

Crack the Safe, Chapter 5 finishedMyth project · 1.8 MB

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

5.1 The Idea

The room is still, and the computer waits for your finger. Every STEP takes another guess. The gold mark moves, a scan card appears, and the teal band shrinks. The rule you’ve built already chooses the middle and reads the clue. Now let it keep going.

Try the game above. Choose Computer cracks it, lock 100, and press RUN. After a short wait, the first card shows 50, followed by another guess from the smaller range. The cards keep arriving. The safe opens on the seventh scan, and PAUSE disappears.

That pause between guesses gives you time to see which marks the clue removed. Watch the teal band. The computer uses exactly the rule you built in Chapter 4. A Recurring Timer calls for another turn after each interval, like a bell that rings at regular times.

RUN starts that bell, and PAUSE stops it. The range stays where it was. Press STEP while it runs, and the bell stops before your one turn happens. Nothing races your finger.

Then try a safe yourself. Once your attempt ends, Watch computer appears below the safe. Press it. The code stays, your result waits beside the safe, and the computer starts a fresh search. You can compare both attempts because neither got a different code.

A panel covers the room at the end. Myth lesson gathers the Functions you’ve built, with their Parameters and answers. While you read, the game holds still. An Input Context is a group of Commands you can turn on or off together. The lesson has its own group, so F can close it even while the game’s keys are off.

Each midpoint miss leaves at most half the previous range, so one hundred codes don’t need one hundred guesses. After six misses, at most one candidate remains. The next scan finds it. Seven scans cover every code here, though a lucky first guess can open one safe sooner.

5.2 The Plan

  • RUN or A -> Run or Pause enables Run Search -> computerTurn calls Take a Step until the trial ends.
  • STEP or Space -> Step Once disables Run Search -> Take a Step makes one turn.
  • Run Search changes -> runChanged -> Show In Situation swaps RUN and PAUSE.
  • Watch computer -> Watch Computer keeps your result and resets the trial on the same code -> Show Human Result displays your attempt.
  • F or Myth lesson -> the Input Contexts trade places -> lessonChanged stops Run Search and shows the lesson’s pieces.

5.3 Set Up

The last Set up card adds keys and places for the finished room. Its pictures are already in your Starter Kit.

INPUT CONTEXTS is new. Rename Default to Game Controls, keeping its Commands, and select its row before pressing Add Command. New Commands join that context. Make Run here with A, and Lesson with F.

Make the Myth Lesson context next, and select its row. Add Close Lesson here, with Escape. Its Command Set starts with that Command alone.

To share Lesson, select Myth Lesson’s row and pick Lesson in Reuse a Command…, below its Command Set. Both groups now share it. F works with the panel open or closed.

Game Controls starts active. Myth Lesson starts inactive. The Making page’s In later chapters passage shows the context’s name and switch.

Keep PLACE THESE beside you, but don’t place anything yet. Each part says when its pieces are ready. The lesson’s repeated lines have different words and sizes, so follow that card’s order when their turn comes.

Set upWhat this chapter adds
COMMANDS (Game Settings > Input Manager)
RunButton
KeybindingsA
LessonButton
KeybindingsF
Close LessonButton
KeybindingsEscape
INPUT CONTEXTS (Game Settings > Input Manager)
Game ControlsActive at Start(rename Default)
CommandsDigit 0, Digit 1, Digit 2, Digit 3, Digit 4, Digit 5, Digit 6, Digit 7, Digit 8, Digit 9, Back, Clear, Scan, New Safe, Human, Computer, Step, Run, Lesson
Myth LessonInactive at Start(new)
CommandsLesson, Close Lesson
SCENE Safe Room: PLACE THESE
ObjectXY
Run Button937-494hidden
Pause Button937-494hidden
Watch Computer Button371-754hidden
Human Result787-535hidden
Myth Lesson Button925-754
Myth Lesson Panel540-393hidden
with Z-Index = 200
Lesson Line540-147hidden
with Z-Index = 200
with Text / UI > Text = ONE SCANNER. TWO PLAYERS. (Edit Object Locally)
with Text / UI > Font Size = 26 (Edit Object Locally)
with Text / UI > Emphasis = Bold (Edit Object Locally)
with Text / UI > Color = #F5CD73 (Edit Object Locally)
Lesson Line540-211hidden
with Z-Index = 200
with Text / UI > Text = MYTH: FUNCTIONS + PARAMETERS + OUTPUTS (Edit Object Locally)
with Text / UI > Font Size = 16 (Edit Object Locally)
with Text / UI > Color = #61C6BE (Edit Object Locally)
Lesson Line540-269hidden
with Z-Index = 200
Lesson Line540-321hidden
with Z-Index = 200
with Text / UI > Text = Check Guess(guess, code) returns Higher, Lower or Unlocked. (Edit Object Locally)
with Text / UI > Font Size = 19 (Edit Object Locally)
Lesson Line540-379hidden
with Z-Index = 200
with Text / UI > Text = Choose Midpoint(low, high) returns the next guess. (Edit Object Locally)
with Text / UI > Font Size = 19 (Edit Object Locally)
Lesson Line540-415hidden
with Z-Index = 200
with Text / UI > Text = floor((low + high) / 2) (Edit Object Locally)
with Text / UI > Font Size = 20 (Edit Object Locally)
with Text / UI > Color = #F5CD73 (Edit Object Locally)
Lesson Line540-465hidden
with Z-Index = 200
with Text / UI > Text = The search reads only low, high and the clues; never your code. (Edit Object Locally)
with Text / UI > Font Size = 16 (Edit Object Locally)
with Text / UI > Color = #AABCC6 (Edit Object Locally)
Lesson Line540-515hidden
with Z-Index = 200
with Text / UI > Text = Step makes one guess. Run repeats it on a named timer. (Edit Object Locally)
with Text / UI > Font Size = 18 (Edit Object Locally)
Lesson Line540-563hidden
with Z-Index = 200
with Text / UI > Text = For codes 1 to 100, binary search needs 7 scans or fewer. (Edit Object Locally)
with Text / UI > Font Size = 17 (Edit Object Locally)
with Text / UI > Color = #F5CD73 (Edit Object Locally)
Lesson Line540-612hidden
with Z-Index = 200
with Text / UI > Text = Type digits / Enter: scan or lock / Backspace: edit (Edit Object Locally)
with Text / UI > Font Size = 15 (Edit Object Locally)
with Text / UI > Color = #AABCC6 (Edit Object Locally)
Lesson Line540-645hidden
with Z-Index = 200
with Text / UI > Text = Space: step / A: run or pause / R: new / F or Esc: close (Edit Object Locally)
with Text / UI > Font Size = 15 (Edit Object Locally)
with Text / UI > Color = #AABCC6 (Edit Object Locally)
Close Lesson Button919-193hidden
with Z-Index = 200

Save now, and again after each part.

5.4 The Controls Share One Switch

The game’s buttons need to ask about the same group that already controls its keys, Game Controls.

5.4.1 Type Its Digit

Type Its Digit still calls Type Digit with the key’s own digit. Now it checks Check Input Context Active first. Its answer, controlsOn, says whether Game Controls is on. The old call moves inside an If, so a click stays silent while the lesson is open.

The whole card is below, without change marks, so you can see the new nesting. Delete the old Type Digit block by right-clicking it and choosing Delete. Keep the Event and Variables.

Add the check, then the If, joining each with Connect to Sequence. Right-click the If and choose Add Inside Then to add Type Digit again. Fill its Arguments from the card. The call now belongs to the True line.

Logic ComponentType Its DigitAttach to: Digit Key

A keypad button that types its digit when the player clicks it, the same as pressing its digit key on the keyboard. Like the key, it does nothing while the game's controls are off (the Myth Lesson is open).

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
safeRulesObjectConstantNone
PER INSTANCE VARIABLES
NameTypeStarting Value
digitNumber0
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
controlsOn
Input Context
Game Controls
2IfcontrolsOn.value == true
Then
3Type DigitFunction
safeRules
@self.safeRules
digit
self.digit

5.4.2 Safe Button

Safe Button asks the same question before ringing its bell. Most buttons obey Game Controls. The lesson’s two buttons must work while that group is off, or you’d have no way to close the panel.

Its new Shared Variable, worksInLesson, gives those buttons permission. It starts No. The condition uses ||, which means either test can let the click through. Game Controls on, or worksInLesson on: the button sends its word.

This whole card shows the same change. Delete only the old Trigger Custom Event on Object block, keeping the Event and Variables. Join the check and If with Connect to Sequence.

Use the If’s Add Inside Then to add Trigger Custom Event on Object again. Its values are on the card. Now the button checks permission before it sends anything.

Logic ComponentSafe ButtonAttach to: Back Key, Scan Button, New Safe Button, Role Tab, Lock Code Button, Change Code Button, Step Button, Run Button, Pause Button, Watch Computer Button, Close Lesson Button, Myth Lesson Button

A button that sends its Custom Event (clickEvent) to the Safe Rules Object when the player clicks it. Each button sets its own. It works only while the game's controls are on (the Game Controls Input Context), unless worksInLesson says it also works while the Myth Lesson is open.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
safeRulesObjectConstantNone
worksInLessonBooleanConstantNo
PER INSTANCE VARIABLES
NameTypeStarting Value
clickEventText(empty)
On Hud Activated
WhenUI Activated
1Check Input Context Active
Action Name
controlsOn
Input Context
Game Controls
2IfcontrolsOn.value == true || @self.worksInLesson == true
Then
3Trigger Custom Event on Object
Applies to
@self.safeRules
Custom Event
self.clickEvent

Run your game. The keypad and buttons still work as before, because Game Controls starts on. Later, the lesson uses the permission you left off.

5.5 The Computer Keeps Its Own Time

Now the gold mark moves without another press of STEP.

Safe Settings gains two timing fields. Add them to Safe Settings Entry, and fill their cells in Standard Safe. The first wait is runDelay, 0.25 seconds. The runInterval is 0.9 seconds between guesses, long enough to watch each card appear.

Data StructureSafe Settings EntryAddDelete

One row of the Safe Settings Data Table, made by the engine for the table's rows: lowestCode, highestCode, startEntry, scanBudget, runDelay, runInterval (the table's description says what each column means).

lowestCodeNumberdefault 0
highestCodeNumberdefault 0
startEntryNumberdefault 0
scanBudgetNumberdefault 0
runDelayNumberdefault 0
runIntervalNumberdefault 0
Data TableSafe SettingsData Structure: Safe Settings EntryAddDelete
Row 0Standard Safe
lowestCode1
highestCode100
startEntry50
scanBudget7
runDelay0.25
runInterval0.9

Safe Copy gains Paused and Same Code. Add both rows now. The second one waits for the comparison part.

Data TableSafe CopyData Structure: Safe Copy EntryAddDelete
Row 0Scan a Guess
textScan a guess to get a clue.
Row 1Higher Than
textHIGHER THAN
Row 2Lower Than
textLOWER THAN
Row 3Unlocked
textUNLOCKED!
Row 4Out of Scans
textOUT OF SCANS
Row 5Outside the Range
textUse the remaining range.
Row 6Start a New Safe
textStart a new safe.
Row 7Code Sealed
textCode sealed.
Row 8Possibilities Remain
textpossibilities remain
Row 9One Possibility Remains
textpossibility remains
Row 10Card Higher
textHIGHER
Row 11Card Lower
textLOWER
Row 12Card Unlocked
textUNLOCKED
Row 13Choose a Code
textCan the computer crack your code?
Row 14Code Outside the Range
textChoose a code from
Row 15No Code Locked
textSet and lock a code first.
Row 16Next Guess
textNEXT GUESS:
Row 17Solved In
textSOLVED IN
Row 18One Scan
textSCAN
Row 19Several Scans
textSCANS
Row 20Paused
textPaused.
Row 21Same Code
textSame code. Computer's turn.

5.5.2 Run or Pause

Run or Pause looks at Run Search itself, with no second flag to keep in step. If the Logic is on, it turns it off and leaves the message Paused. If it’s off, a Locked safe lets it start.

A safe in Setup hasn’t got a locked code yet. An open safe has finished. In either case the Function asks you to set and lock a code first. Neither refusal spends a scan.

The Otherwise at step 5 holds a check before its If. Make it with Add Else, and add both blocks inside that Else. Step 9 is the inner If’s Else. Pick Run Search in each Logic Component list, as you did with the role Logic.

FunctionRun or Pause

Pauses the computer's search if Run is on; otherwise turns Run on, if a locked code is waiting to be cracked.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Check Logic Enabled
Action Name
runIsOn
Applies to
safeRules
Logic Component
Run Search
2IfrunIsOn.value == true
Then
3Set Logic State
Applies to
safeRules
Logic Component
Run Search
State
Disable
4Change Variable
Variable
$message
Value
data('Safe Copy','Paused','text')
5Otherwise
6Check Game State
Action Name
safeIsLocked
Applies to
safeRules
Game State
Locked
7IfsafeIsLocked.value == true
Then
8Set Logic State
Applies to
safeRules
Logic Component
Run Search
9Otherwise
10Change Variable
Variable
$message
Value
data('Safe Copy','No Code Locked','text')

5.5.3 Step Once

STEP needs a quiet moment to itself. Its helper stops the bell before your turn, so a timer can’t add another guess beside yours.

FunctionStep Once

Takes one Step by hand: Run is turned off first if it is on, so the computer makes exactly this one turn.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Set Logic State
Applies to
safeRules
Logic Component
Run Search
State
Disable
2Take a StepFunction
safeRules
safeRules

5.5.4 Take a Step

Take a Step keeps the midpoint and scanner you built. The Function needs no rebuilding.

5.5.5 Human Role and Computer Role

The computer’s keys use the new helpers. Computer Role gives its turns to the bell or your finger, with one helper for each. Human Role hears those Commands too, but answers with No Code Locked. Your human search stays in your hands.

Logic ComponentHuman RoleAttach to: Safe RulesAddDelete

What the controls do while the human cracks the safe: Enter scans the entry and R starts a new safe; Space and A only say that the computer needs a locked code. Choose Human Role turns this Logic on.

Attach toAny Object
DATA STRUCTURES
Safe Stateself.safeState
When Scan Is Pressed
WhenCommand PressedCommand: Scan
1Scan GuessFunction
safeRules
self
When New Safe Is Pressed
WhenCommand PressedCommand: New Safe
1Start New SafeFunction
safeRules
self
When Step Is Pressed
WhenCommand PressedCommand: Step
1Change Variable
Variable
$message
Value
data('Safe Copy','No Code Locked','text')
When Run Is Pressed
WhenCommand PressedCommand: Run
1Change Variable
Variable
$message
Value
data('Safe Copy','No Code Locked','text')
Logic ComponentComputer RoleAttach to: Safe RulesAddDelete

What the controls do while the computer cracks the safe: Enter locks the code, Space takes one Step, A runs or pauses the search, and R goes back to Setup for a new code. Choose Computer Role and Watch Computer turn this Logic on.

Attach toAny Object
DATA STRUCTURES
Safe Stateself.safeState
When Scan Is Pressed
WhenCommand PressedCommand: Scan
1Lock CodeFunction
safeRules
self
When Step Is Pressed
WhenCommand PressedCommand: Step
1Take a StepFunction
safeRules
self
1Step OnceFunction
safeRules
self
When Run Is Pressed
WhenCommand PressedCommand: Run
1Run or PauseFunction
safeRules
self
When New Safe Is Pressed
WhenCommand PressedCommand: New Safe
1Start Code SetupFunction
safeRules
self

Attach Run Search to Safe Rules now, and turn its Attached Logic switch off. It should wait for you to press RUN. Safe Rules’ whole card comes later, once Lesson Keys is ready.

Run the game, press C, and lock 100. Press A. The cards arrive one after another. Press A again before the last one, and the count holds still. Space makes one turn and leaves it paused.

5.6 RUN Gives Way to PAUSE

The timer works, and the room needs to show whether it’s running.

Screen Layout gains humanDone and running. Add their fields to Screen Layout Entry, then fill every changed cell on the table’s card. The humanDone column keeps the human’s pieces visible after the attempt ends. The running column keeps the computer’s readout visible while RUN gives its place to PAUSE.

Data StructureScreen Layout EntryAddDelete

One row of the Screen Layout Data Table, made by the engine for the table's rows: human, codeSetup, searching, solved, outOfScans, humanDone, running (the table's description says what each column means).

humanBooleandefault false
codeSetupBooleandefault false
searchingBooleandefault false
solvedBooleandefault false
outOfScansBooleandefault false
humanDoneBooleandefault false
runningBooleandefault false
Data TableScreen LayoutData Structure: Screen Layout EntryAddDelete
Row 0Keypad
humanYes
codeSetupYes
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo
Row 1Entry Caption
humanYes
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo
Row 2Scan Button
humanYes
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo
Row 3New Safe Button
humanYes
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo
Row 4Human Goal
humanYes
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo
Row 5Computer Goal
humanNo
codeSetupYes
searchingYes
solvedYes
outOfScansYes
humanDoneNo
runningYes
Row 6Code Caption
humanNo
codeSetupYes
searchingNo
solvedNo
outOfScansNo
humanDoneNo
runningNo
Row 7Lock Code Button
humanNo
codeSetupYes
searchingNo
solvedNo
outOfScansNo
humanDoneNo
runningNo
Row 8Change Code Button
humanNo
codeSetupNo
searchingYes
solvedYes
outOfScansYes
humanDoneNo
runningYes
Row 9Step Button
humanNo
codeSetupNo
searchingYes
solvedNo
outOfScansNo
humanDoneNo
runningYes
Row 10Search Title
humanNo
codeSetupNo
searchingYes
solvedYes
outOfScansYes
humanDoneNo
runningYes
Row 11Search Readout
humanNo
codeSetupNo
searchingYes
solvedYes
outOfScansNo
humanDoneNo
runningYes
Row 12Last Guess Caption
humanNo
codeSetupNo
searchingYes
solvedNo
outOfScansYes
humanDoneNo
runningYes
Row 13Midpoint Formula
humanNo
codeSetupNo
searchingYes
solvedNo
outOfScansNo
humanDoneNo
runningYes
Row 14Found Code Caption
humanNo
codeSetupNo
searchingNo
solvedYes
outOfScansNo
humanDoneNo
runningNo
Row 15Run Button
humanNo
codeSetupNo
searchingYes
solvedNo
outOfScansNo
humanDoneNo
runningNo
Row 16Pause Button
humanNo
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneNo
runningYes
Row 17Watch Computer Button
humanNo
codeSetupNo
searchingNo
solvedNo
outOfScansNo
humanDoneYes
runningNo

5.6.1 Current Situation

Current Situation learns both new names. Inside its computer branch, the last check asks whether Run Search is enabled. If so, running replaces searching. Outside the computer branch, an Unlocked or Exhausted trial answers humanDone.

Check the new nesting against this whole card. Add steps 17 and 18 through step 4’s Add Inside Then, at the end of that True line. Step 19 goes inside the new If’s True line. Now give step 4 an Else. Use Add Else, then Add Inside Else for steps 21, 22 and 23. Step 24 belongs inside step 23’s True line. Return still sits last, at the very left, outside both branches.

FunctionCurrent Situation

Answers which situation the game is in, as the name of a Screen Layout column: human or humanDone in the Human role; in the Computer role codeSetup, searching, running, solved or outOfScans for the phase of the trial and whether Run is on.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
RETURN TYPEText
ACTIONS
1Declare Variable
Type
Text
Name
situation
2Change Variable
Variable
situation
Value
'human'
3Check Logic Enabled
Action Name
computerCracks
Applies to
safeRules
Logic Component
Computer Role
4IfcomputerCracks.value == true
Then
5Check Game State
Action Name
inSetup
Applies to
safeRules
Game State
Setup
6IfinSetup.value == true
Then
7Change Variable
Variable
situation
Value
'codeSetup'
8Check Game State
Action Name
inLocked
Applies to
safeRules
Game State
Locked
9IfinLocked.value == true
Then
10Change Variable
Variable
situation
Value
'searching'
11Check Game State
Action Name
inUnlocked
Applies to
safeRules
Game State
Unlocked
12IfinUnlocked.value == true
Then
13Change Variable
Variable
situation
Value
'solved'
14Check Game State
Action Name
inExhausted
Applies to
safeRules
Game State
Exhausted
15IfinExhausted.value == true
Then
16Change Variable
Variable
situation
Value
'outOfScans'
17Check Logic Enabled
Action Name
runIsOn
Applies to
safeRules
Logic Component
Run Search
18IfrunIsOn.value == true
Then
19Change Variable
Variable
situation
Value
'running'
20Otherwise
21Check Game State
Action Name
safeIsOpen
Applies to
safeRules
Game State
Unlocked
22Check Game State
Action Name
scansUsedUp
Applies to
safeRules
Game State
Exhausted
23IfsafeIsOpen.value == true || scansUsedUp.value == true
Then
24Change Variable
Variable
situation
Value
'humanDone'
25Return
Value
situation

5.6.2 Show In Situation

Show In Situation hears runChanged now. Its new Event calls Show For Situation with the same Arguments as its other two Events. That word Run Search sends finally has a listener.

Logic ComponentShow In SituationAttach to: Entry Caption, Digit Key, Back Key, Scan Button, New Safe Button, Human Goal, Computer Goal, Search Readout, Code Caption, Last Guess Caption, Found Code Caption, Search Title, Midpoint Formula, Lock Code Button, Change Code Button, Step Button, Run Button, Pause Button, Watch Computer ButtonAddDelete

Shows this piece only in the situations its row of the Screen Layout table picks (the keypad, the SCAN and LOCK CODE buttons, the RUN and PAUSE buttons, the Watch computer button, the computer's readout, and the rest), and hides it otherwise.

Attach toAny Object
SHARED VARIABLES
NameTypeKindStarting Value
safeRulesObjectConstantNone
layoutRowTextConstant(empty)
On Game State Changed
WhenGame State Changed
1Show For SituationFunction
piece
self
safeRules
@self.safeRules
layoutRow
@self.layoutRow
On Role Chosen
WhenroleChosenCustom Event
1Show For SituationFunction
piece
self
safeRules
@self.safeRules
layoutRow
@self.layoutRow
On Run Changed
WhenrunChangedCustom Event
1Show For SituationFunction
piece
self
safeRules
@self.safeRules
layoutRow
@self.layoutRow

Make Run Button and Pause Button like Step Button, with Safe Button and Show In Situation attached to each. Each sends its own word and reads its own Screen Layout row.

ObjectRun Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 146, Y 51
Text / UI
TextRUN
Font Size18
EmphasisBold
Color#F5E9CA
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteSafe Gold
Transform > SizeX 146, Y 51
UI Interaction(as it is added)
Logic
Show In Situation
Safe Button
Shared Variables
safeRulesSafe Rules
layoutRowRun Button
Per Instance Variables
clickEventrunClicked
ObjectPause Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 146, Y 51
Text / UI
TextPAUSE
Font Size18
EmphasisBold
Color#F5E9CA
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteSafe Gold
Transform > SizeX 146, Y 51
UI Interaction(as it is added)
Logic
Show In Situation
Safe Button
Shared Variables
safeRulesSafe Rules
layoutRowPause Button
Per Instance Variables
clickEventpauseClicked

5.6.3 Button Clicks

Button Clicks grows for the last time. Its Step Event calls Step Once now, and Run and Pause both call Run or Pause. Watch Computer and the lesson’s Functions are new, so leave those Events until their Functions are built below. This card shows all the changes in one place.

Logic ComponentButton ClicksAttach to: Safe RulesAddDelete

Does what each button on the screen asks. A button sends its Custom Event to Safe Rules when clicked, and each one here calls the Function its key calls.

Attach toAny Object
DATA STRUCTURES
Safe Stateself.safeState
On Back Clicked
WhenbackClickedCustom Event
1Erase DigitFunction
safeRules
self
On Scan Clicked
WhenscanClickedCustom Event
1Scan GuessFunction
safeRules
self
On New Safe Clicked
WhennewSafeClickedCustom Event
1Start New SafeFunction
safeRules
self
On Human Tab Clicked
WhenhumanTabClickedCustom Event
1Choose Human RoleFunction
safeRules
self
On Computer Tab Clicked
WhencomputerTabClickedCustom Event
1Choose Computer RoleFunction
safeRules
self
On Lock Code Clicked
WhenlockCodeClickedCustom Event
1Lock CodeFunction
safeRules
self
On Step Clicked
WhenstepClickedCustom Event
1Take a StepFunction
safeRules
self
1Step OnceFunction
safeRules
self
On Change Code Clicked
WhenchangeCodeClickedCustom Event
1Start Code SetupFunction
safeRules
self
On Run Clicked
WhenrunClickedCustom Event
1Run or PauseFunction
safeRules
self
On Pause Clicked
WhenpauseClickedCustom Event
1Run or PauseFunction
safeRules
self
On Watch Computer Clicked
WhenwatchComputerClickedCustom Event
1Watch ComputerFunction
safeRules
self
On Myth Lesson Clicked
WhenmythLessonClickedCustom Event
1Open or Close Myth LessonFunction
safeRules
self
On Close Lesson Clicked
WhencloseLessonClickedCustom Event
1Close Myth LessonFunction
safeRules
self

Place Run Button and Pause Button from PLACE THESE, both hidden. They share a place, but Screen Layout shows only one at a time.

Run it, choose the computer, and lock a code. Click RUN. PAUSE takes its place. Click PAUSE, and RUN returns while the range stays where it was.

5.7 The Same Safe, Two Searches

Your attempt ends, and the computer gets the code you had.

Safe State needs somewhere to keep your result. Add humanScans and humanUnlocked. They remember the count and whether the safe opened. Reset Trial leaves them alone, as it leaves the code alone.

Data StructureSafe StateAddDelete

What the Safe Rules Object carries for its Logic to share. code: the secret code that opens the safe. startsNewEntry: true when the next digit typed starts a new entry instead of adding to the one shown. clue: what the last scan told: 1 the code is higher than the guess, -1 lower, 0 the guess is the code. humanScans and humanUnlocked: the result of the human's last finished attempt, kept by Watch Computer: how many scans it took, and whether it opened the safe.

codeNumberdefault 0
startsNewEntryBooleandefault true
clueNumberdefault 0
humanScansNumberdefault 0
humanUnlockedBooleandefault false

5.7.1 Start Code Setup

A different code needs a clean comparison. Start Code Setup now clears humanScans before entering Setup. That zero tells the result line there is no human attempt to display. Add the block between Reset Trial and Set Game State, using their round handles.

FunctionStart Code SetupAddDelete

Starts a fresh trial in the Computer role: the player types the code the computer will crack, then locks it.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Reset TrialFunction
safeRules
safeRules
2Change Component Value
Component Value
safeRules.safeState.humanScans
Value
0
3Set Game State
Applies to
safeRules
Game State
Setup
4Change Variable
Variable
$message
Value
data('Safe Copy','Choose a Code','text')

5.7.2 Watch Computer

Watch Computer is the handover. Before it resets the trial, it keeps your count and outcome in Safe State. Then Computer Role takes over, and Reset Trial clears the range, scans and record. The secret code stays where it was.

The check’s answer is humanUnlocked.value. The field at safeRules.safeState.humanUnlocked keeps that answer after this Function ends. Their shared name describes the same fact in two places.

The trial goes straight to Locked. There is no setup keypad, because the computer is searching your old safe. The entry becomes dashes, leaving the readout to show the computer’s guesses. The message says Same code. Computer’s turn. Last, roleChosen tells the room to follow the new role.

FunctionWatch Computer

Hands the human's safe to the computer after the human's attempt has ended: keeps the human's result, turns the Computer role on, and starts a fresh trial on the same code, already locked, so the computer searches it at once.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Change Component Value
Component Value
safeRules.safeState.humanScans
Value
$scans
2Check Game State
Action Name
humanUnlocked
Applies to
safeRules
Game State
Unlocked
3Change Component Value
Component Value
safeRules.safeState.humanUnlocked
Value
humanUnlocked.value
4Set Logic State
Applies to
safeRules
Logic Component
Human Role
State
Disable
5Set Logic State
Applies to
safeRules
Logic Component
Computer Role
6Reset TrialFunction
safeRules
safeRules
7Change Variable
Variable
$entry
Value
0
8Set Game State
Applies to
safeRules
Game State
Locked
9Change Variable
Variable
$message
Value
data('Safe Copy','Same Code','text')
10Trigger Custom Event
Custom Event
roleChosen

5.7.3 Write Human Result

Write Human Result reads those kept facts. It shows them only while the computer plays and a human count remains. The new trial’s scans can change without changing your old result.

The line has its own Data Structure, Result Line. scansUsed holds your count, scanWord supplies SCAN or SCANS, and outcome supplies the ending. The Text puts them together, as Search Readout put its own fields together.

Data StructureResult Line

What the human's result line shows, written by Show Human Result. scansUsed: how many scans the human's attempt took. scanWord: SCAN or SCANS. outcome: UNLOCKED, or OUT OF SCANS.

scansUsedNumberdefault 0
scanWordTextdefault (empty)
outcomeTextdefault (empty)

The two Ifs inside the main True line pick the grammar and the outcome separately. Step 8 follows step 4’s If. Add it from step 2’s Add Inside Then, and do the same for Set Visible at step 12. The outer Else hides the line when there is no result to show.

FunctionWrite Human Result

Shows the human's kept result on the result line while the computer searches the human's code (after Watch computer), and hides the line otherwise. line: the text that shows the result. safeRules: the Object whose Safe State keeps the human's result (humanScans, humanUnlocked).

PARAMETERS
NameTypeStarts at
lineObjectStructural
Required Components
Slot NameresultLine
Component TypeData Structure
Required SchemaResult Line
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Check Logic Enabled
Action Name
computerCracks
Applies to
safeRules
Logic Component
Computer Role
2IfcomputerCracks.value == true && safeRules.safeState.humanScans > 0
Then
3Change Component Value
Component Value
line.resultLine.scansUsed
Value
safeRules.safeState.humanScans
4IfsafeRules.safeState.humanScans == 1
Then
5Change Component Value
Component Value
line.resultLine.scanWord
Value
data('Safe Copy','One Scan','text')
6Otherwise
7Change Component Value
Component Value
line.resultLine.scanWord
Value
data('Safe Copy','Several Scans','text')
8IfsafeRules.safeState.humanUnlocked == true
Then
9Change Component Value
Component Value
line.resultLine.outcome
Value
data('Safe Copy','Card Unlocked','text')
10Otherwise
11Change Component Value
Component Value
line.resultLine.outcome
Value
data('Safe Copy','Out of Scans','text')
12Set Visible
Applies to
line
Visible
true
13Otherwise
14Set Visible
Applies to
line
Visible
false

5.7.4 Show Human Result

Show Human Result listens for roleChosen and Game State Changed. Either change can make the kept result relevant, or end its time on screen. Write Human Result reads the stored facts for either Event.

Logic ComponentShow Human ResultAttach to: Human Result

Shows the human's result beside the computer's search after Watch computer, and hides it again when a role is chosen or a new code is set up.

Attach toAny Object
DATA STRUCTURES
Result Lineself.resultLine
SHARED VARIABLES
NameTypeKindStarting Value
safeRulesObjectConstantNone
On Role Chosen
WhenroleChosenCustom Event
1Write Human ResultFunction
line
self
safeRules
@self.safeRules
On Game State Changed
WhenGame State Changed
1Write Human ResultFunction
line
self
safeRules
@self.safeRules

Attach Result Line before the Logic on Human Result, and use the field names alone inside its Text’s braces. They need no dollar sign. The new button sends watchComputerClicked.

ObjectHuman Result
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
TextYOU: {scansUsed} {scanWord} / {outcome}
Font Size14
EmphasisBold
Color#F5CD73
RenderingVector
Data Structure
Data StructureResult Line
Logic
Show Human Result
Shared Variables
safeRulesSafe Rules
ObjectWatch Computer Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 219, Y 40
Text / UI
TextWatch computer
Font Size18
EmphasisBold
Color#F5E9CA
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteSafe Gold
Transform > SizeX 219, Y 40
UI Interaction(as it is added)
Logic
Show In Situation
Safe Button
Shared Variables
safeRulesSafe Rules
layoutRowWatch Computer Button
Per Instance Variables
clickEventwatchComputerClicked

Add On Watch Computer Clicked to Button Clicks from its earlier Changes card. Place both new Objects hidden, leaving Screen Layout to reveal the button when your attempt ends.

Finish an attempt in the Human role, then click Watch computer to hand the same safe over. Your result appears beside the safe, and the computer’s counter starts fresh. Press RUN and watch it search the same code.

5.8 A Lesson Over the Room

Last, give the room a place for someone to read what made that search work.

5.8.1 Open Myth Lesson

The game needs to stop listening to your keys. Open Myth Lesson trades Game Controls for Myth Lesson, then sends lessonChanged so the panel sees the finished switch. Run Search hears the same word and stops its timer.

Set Input Context Active has an Input Context list and an Active switch. Pick each group there. Active false means off. With no Active line, keep the switch on, as it starts. That’s step 2 here.

The card still prints Applies to safeRules, but the block has no Object box. Leave that line out. Check Input Context Active has no Object box either. Both ask about a group that belongs to the whole game.

FunctionOpen Myth Lesson

Opens the Myth Lesson: the game's controls turn off (the Game Controls Input Context), the lesson's keys turn on (the Myth Lesson Input Context), and lessonChanged tells the lesson's pieces and Run Search.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Set Input Context Active
Applies to
safeRules
Input Context
Game Controls
Active
false
2Set Input Context Active
Applies to
safeRules
Input Context
Myth Lesson
3Trigger Custom Event
Custom Event
lessonChanged

5.8.2 Close Myth Lesson

Close Myth Lesson trades the groups back while keeping every fact of your old trial where it was. Run Search hears lessonChanged again and stays off, so closing the panel never starts another guess by surprise.

FunctionClose Myth Lesson

Closes the Myth Lesson: the lesson's keys turn off, the game's controls turn back on, and lessonChanged tells the lesson's pieces and Run Search.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Set Input Context Active
Applies to
safeRules
Input Context
Myth Lesson
Active
false
2Set Input Context Active
Applies to
safeRules
Input Context
Game Controls
3Trigger Custom Event
Custom Event
lessonChanged

5.8.3 Open or Close Myth Lesson

One button can do either job. Open or Close Myth Lesson asks whether the Myth Lesson context is active, and calls the Function for the other state. There is no separate lesson flag to forget.

FunctionOpen or Close Myth Lesson

Closes the Myth Lesson if it is open, and opens it otherwise. F and the Myth lesson button call it.

PARAMETERS
NameTypeStarts at
safeRulesObjectStructural
Required Components
Slot NamesafeState
Component TypeData Structure
Required SchemaSafe State
ACTIONS
1Check Input Context Active
Action Name
lessonIsOpen
Applies to
safeRules
Input Context
Myth Lesson
2IflessonIsOpen.value == true
Then
3Close Myth LessonFunction
safeRules
safeRules
4Otherwise
5Open Myth LessonFunction
safeRules
safeRules

5.8.4 Lesson Keys

F brings you back too. Lesson Keys listens to that shared Command, whichever group is active. Escape belongs only to Myth Lesson, so it closes the panel without changing the room’s other keys.

Logic ComponentLesson KeysAttach to: Safe Rules

Lets the keyboard open and close the Myth Lesson: F opens it or closes it, and Escape closes it. The Myth lesson and Close buttons call the same Functions.

Attach toAny Object
DATA STRUCTURES
Safe Stateself.safeState
When Lesson Is Pressed
WhenCommand PressedCommand: Lesson
1Open or Close Myth LessonFunction
safeRules
self
When Close Lesson Is Pressed
WhenCommand PressedCommand: Close Lesson
1Close Myth LessonFunction
safeRules
self

Attach Lesson Keys to Safe Rules. The Object’s whole card below shows its final Logic list. Run Search and Computer Role still start turned off. Button Clicks can now get On Myth Lesson Clicked and On Close Lesson Clicked from its Changes card.

ObjectSafe Rules
Transform
Bounding Box > SizeX 0.8, Y 0.8
Data Structure
Data StructureSafe State
Data Structure
From LogicLay Out Scan Record
Data StructureLay Out Scan Record Data
Logic
New Safe
Keypad Keys
Button Clicks
Lay Out Scan Record
Choose Role
Human Role
Computer Role(turned off)
Run Search(turned off)
Lesson Keys
Shared Variables
codeMarkCode Mark
scanCardScan Card
cardGuessCard Guess
cardClueCard Clue

5.8.5 Show With Lesson

The panel follows lessonChanged. Show With Lesson asks the Myth Lesson Input Context whether each piece of the panel should show. There is no list of eleven lines to keep in the Function that opens them.

Logic ComponentShow With LessonAttach to: Myth Lesson Panel, Lesson Line, Close Lesson Button

Shows this piece of the Myth Lesson while the lesson is open, and hides it while it is closed.

Attach toAny Object
On Lesson Changed
WhenlessonChangedCustom Event
1Check Input Context Active
Action Name
lessonIsOpen
Input Context
Myth Lesson
2IflessonIsOpen.value == true
Then
3Set Visible
Visible
Yes
4Otherwise
5Set Visible
Visible
No

Myth Lesson Panel is the dark background. Lesson Line is one Text Object, placed repeatedly with its own words. Both carry Show With Lesson. The panel’s card has no UI Interaction, so remove that component if it’s attached.

ObjectMyth Lesson Panel
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 910, Y 606
Sprite
Z Index Within Object-1
SpriteSafe Panel
Transform > SizeX 910, Y 606
Logic
Show With Lesson
ObjectLesson Line
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Text / UI
TextBoth players call the same Scan Guess Function.
Font Size21
EmphasisMedium
Color#E8EEF0
RenderingVector
Logic
Show With Lesson

The two buttons keep worksInLesson on in their Shared Variables. Myth Lesson Button can open or close the panel, and Close Lesson Button closes it. That is the permission Safe Button was waiting for.

ObjectMyth Lesson Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 211, Y 40
Text / UI
TextMyth lesson
Font Size18
EmphasisBold
Color#F5E9CA
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteSafe Button
Transform > SizeX 211, Y 40
UI Interaction(as it is added)
Logic
Safe Button
Shared Variables
safeRulesSafe Rules
worksInLessonYes
Per Instance Variables
clickEventmythLessonClicked
ObjectClose Lesson Button
Transform
Presentation > SpaceWindow / UI
Presentation > Render LayerUI
Bounding Box > SizeX 110, Y 42
Text / UI
TextClose
Font Size18
EmphasisBold
Color#F5E9CA
AlignmentCenter
RenderingVector
Sprite
Z Index Within Object-1
SpriteSafe Button
Transform > SizeX 110, Y 42
UI Interaction(as it is added)
Logic
Show With Lesson
Safe Button
Shared Variables
safeRulesSafe Rules
worksInLessonYes
Per Instance Variables
clickEventcloseLessonClicked

Find PLACE THESE in the Set up card above, and place the lesson’s pieces in that order. Each Lesson Line’s Text, Font Size and Color belongs to that placement. Use Edit Object Locally for its Text / UI changes, then Back to Scene before placing the next. A line without an override keeps those words.

For each lesson placement, select it in the Scene and open Rendering in its Properties. Type its Z-Index there, keeping the panel and words above the room. Myth Lesson Button starts visible. It opens the rest.

Run your game and press F, and the lesson you built covers the room. Try a digit and Space: nothing underneath changes. Escape closes it, and the safe is still waiting where you left it.

Play it!

Run it and watch these moments, in order.

  • Press C, lock 100, and click RUN. The first scan arrives after about 0.25 seconds, then another every 0.9 seconds. PAUSE replaces RUN.
  • Click PAUSE before the search ends, and look for Paused in the message under the safe. Wait a few seconds: the range, count and cards stay still.
  • Press Space. One new card appears, and RUN stays visible. Press A to continue. The safe opens within seven scans, and no eighth card appears.
  • Press R, type 50, lock it, and press A to open the safe on the first scan. The readout uses SOLVED IN 1 SCAN.
  • Press H. Watch computer is hidden while your attempt is in progress. Scan until the safe opens, or spend your seven scans.
  • Click Watch computer and look for the message that says the computer is taking its turn on the same code. Your old result appears as YOU: with its count and outcome. The computer’s counter starts at 0 / 7.
  • Let the computer run. Its final FOUND CODE is the code your safe held. Your result stays beside it throughout the search.
  • Press R. Setup returns, and the kept human result disappears.
  • Lock 100 and start RUN again, then press F before the search reaches the last card. The lesson opens, and the search stops.
  • While the panel is open, press digits, Enter, Space, A, R, H and C. Click a game control outside the panel, such as a role tab. Nothing changes underneath.
  • Close with Escape. The old range and count remain, and RUN waits for you. Open again and close with F, then try the two lesson buttons.
How it works

The timer calls the turn you already built. The turn uses the scanner both players share. Watch Computer keeps the code and gives that scanner a fresh trial. Your result waits beside it.

Binary search needs truthful clues and an ordered range. Each midpoint miss discards at least half the candidates, while the secret remains inside. From one hundred codes, six misses leave at most one. One more scan opens it.

The timer decides when to ask, while Choose Midpoint supplies the guess without ever reading the secret code. Slowing the timer changes what you can watch, and leaves the search rule alone.

5.9 If It Didn’t Work

The last pieces connect to several things you built earlier. A missed connection is normal. Watch one moment, and make one correction before trying again.

Does RUN start when the game opens? Run Search’s Attached Logic switch on Safe Rules should start off, waiting for your press. Turn it off, save, and begin a new run.

RUN does nothing? First lock a code in the Computer role. Then check Run Search’s On Enable and Recurring Timer Events. Their timer names must match computerTurn. A block standing apart from the line needs Connect to Sequence.

The scans continue after PAUSE? Look at On Disable’s Stop Recurring Timer, and compare its name with the timer On Enable started. Correct that name, run again, and pause between two cards.

Does PAUSE remain after the search stops? Look for runChanged in Show In Situation, the Event that listens when Run Search turns on or off. Check the running column too: Pause Button is Yes there, Run Button is No. Try the switch again.

Does Watch computer give a different code? Look at its reset call, before the new trial starts. Reset Trial leaves the code alone, while Start New Safe would draw a different code for the computer. Restore Reset Trial, then finish another human attempt and compare again.

Your result vanishes after the computer’s first scan? Write Human Result reads humanScans from Safe State, not the new $scans. Check that field path and try the handover again.

F opens the panel but can’t close it? Check both context lists for Lesson, the Command that belongs in each group. Put it in Myth Lesson’s Command Set too, and F can get you back.

A button still works under the lesson? Safe Button’s new If must hold its old trigger, with worksInLesson on only for the lesson’s two buttons. Check that nesting first. Digit Key uses the separate check in Type Its Digit. Fix the one you clicked, then open the panel again.

The lesson’s lines all change together? You edited Lesson Line itself instead of a placement. Restore the Object from its card, then change each placement with Edit Object Locally. Its words become its own again.

The catch-up download in the Goal holds the finished game. Compare one piece at a time with yours, and keep what you learn from the difference.

Challenge

Give the computer a pace of your own. Change runDelay or runInterval in Safe Settings, then watch the same code again. What pace lets you see every clue?

Or make a different lesson panel for someone who will play your game. What do you want them to notice? Use your own words and examples, with the Functions you’ve made beside them.

In Chapter 1, nothing could ask the safe about its code. Now the room you built asks, remembers, compares, and waits while someone learns from its clues. It’s yours to change.