Build a GameCreating Chess

Appendix A — Logic Reference

Every Logic Component and Function in Chess, 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 Lay Out The Board

Built in Chapter 1, The Board and the Pieces.

Logic ComponentLay Out The BoardAttach to: Board

Makes the Objects that show each Square of the Board when the Scene starts: for every row of the Position table (one Square, a1 to h8), a Piece Object, a Square, a Move Mark, a Threat Mark and a Pin Mark are made on that Square (Square Position), and each is given the Square's name (its Square Info); a Square in the left or right column also gets a Rank Label, and one in the bottom or top row a File Label (turned over, the h-File is on the left and Rank 8 at the bottom). Then it says "boardLaidOut". pieceObject, squareObject, moveMarkObject, threatMarkObject, pinMarkObject: the Objects made on each Square; rankLabelObject, fileLabelObject: the labels. squareMeters: how wide one Square is.

Attach toAny Object
DATA STRUCTURES
Lay Out The Board Dataself.layOutTheBoardData
SHARED VARIABLES
NameTypeKindStarting Value
pieceObjectObjectConstantNone
rankLabelObjectObjectConstantNone
fileLabelObjectObjectConstantNone
squareMetersNumberConstant3.75
squareObjectObjectConstantNone
moveMarkObjectObjectConstantNone
threatMarkObjectObjectConstantNone
pinMarkObjectObjectConstantNone
When the Scene Starts
WhenScene Start
1Declare Variable
Name
boardBottom
Value
0
2Declare Variable
Name
boardLeft
Value
0
3Change Variable
Variable
boardLeft
Value
self.transform.position.x - 4 * @self.squareMeters
4Change Variable
Variable
boardBottom
Value
self.transform.position.y - 4 * @self.squareMeters
5RepeatdataCount('Position')times
Each time
6Change Component Value
Component Value
self.layOutTheBoardData.squareName
Value
dataRow('Position', local.index)
7Square PositionFunction
Action Name
spot
square
self.layOutTheBoardData.squareName
isFlipped
No
squareMeters
@self.squareMeters
boardLeft
boardLeft
boardBottom
boardBottom
8Create Instance
Object to Create
@self.pieceObject
X
spot.x
Y
spot.y
Created As
piece
9Change Variable
Variable
piece.name
Value
self.layOutTheBoardData.squareName
10Create Instance
Object to Create
@self.squareObject
X
spot.x
Y
spot.y
Created As
square
11Change Variable
Variable
square.name
Value
self.layOutTheBoardData.squareName
12Create Instance
Object to Create
@self.moveMarkObject
X
spot.x
Y
spot.y
Created As
moveMark
13Change Variable
Variable
moveMark.name
Value
self.layOutTheBoardData.squareName
14Create Instance
Object to Create
@self.threatMarkObject
X
spot.x
Y
spot.y
Created As
threatMark
15Change Variable
Variable
threatMark.name
Value
self.layOutTheBoardData.squareName
16Create Instance
Object to Create
@self.pinMarkObject
X
spot.x
Y
spot.y
Created As
pinMark
17Change Variable
Variable
pinMark.name
Value
self.layOutTheBoardData.squareName
18Ifdata('Position', self.layOutTheBoardData.squareName, 'file') == 1 || data('Position', self.layOutTheBoardData.squareName, 'file') == 8
Then
19Create Instance
Object to Create
@self.rankLabelObject
X
spot.x
Y
spot.y
Created As
rankLabel
20Change Variable
Variable
rankLabel.name
Value
self.layOutTheBoardData.squareName
21Ifdata('Position', self.layOutTheBoardData.squareName, 'rank') == 1 || data('Position', self.layOutTheBoardData.squareName, 'rank') == 8
Then
22Create Instance
Object to Create
@self.fileLabelObject
X
spot.x
Y
spot.y
Created As
fileLabel
23Change Variable
Variable
fileLabel.name
Value
self.layOutTheBoardData.squareName
24Trigger Custom Event
Custom Event
boardLaidOut

A.2 Show Label

Built in Chapter 1, The Board and the Pieces.

Logic ComponentShow LabelAttach to: Rank Label, File Label

Writes the Rank number or the File letter of the Square this label stands on (its Square Info), read from the Position table: shows names the column (rank, or fileLetter). Its color follows the Board Finish chosen (Settings, on the Game Rules, sends "lookChanged"): the Board Finishes table gives one color for a label on a light Square and one for a label on a dark Square (a Square is dark when its File and Rank add up to an even number, as a1). It shows only while its Square is drawn on the edge of the Board where labels go, the left column or the bottom row, whichever way round the Board is drawn (Flip Board, on the Game Rules, its Other, sends "boardFlipped"). edge: the Position table's column that counts from that edge, file for a Rank Label (the left column) and rank for a File Label (the bottom row).

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
COMPONENTS
self.textText / UI
SHARED VARIABLES
NameTypeKindStarting Value
showsTextConstantrank
edgeTextConstantfile
On Board Laid Out
WhenboardLaidOutCustom Event
1Change Component Value
Component Value
self.text.text
Value
data('Position', self.squareInfo.name, @self.shows)
On Board Flipped
WhenboardFlippedCustom Event
1Declare Variable
Name
edgeLine
Value
0
2Change Variable
Variable
edgeLine
Value
data('Position', self.squareInfo.name, @self.edge)
3Ifother.boardState.isFlipped == true
Then
4Change Variable
Variable
edgeLine
Value
9 - edgeLine
5IfedgeLine == 1
Then
6Set Visible
Visible
Yes
7Otherwise
8Set Visible
Visible
No
On Look Changed
WhenlookChangedCustom Event
1Declare Variable
Type
Text
Name
finish
2Declare Variable
Name
squareShade
Value
0
3Declare Variable
Name
rank
Value
0
4Declare Variable
Name
file
Value
0
5Change Variable
Variable
finish
Value
other.boardState.boardFinish
6Change Variable
Variable
file
Value
data('Position', self.squareInfo.name, 'file')
7Change Variable
Variable
rank
Value
data('Position', self.squareInfo.name, 'rank')
8Change Variable
Variable
squareShade
Value
(file + rank) % 2
9IfsquareShade == 1
Then
10Change Component Value
Component Value
self.text.color
Value
data('Board Finishes', finish, 'labelOnLight')
11Otherwise
12Change Component Value
Component Value
self.text.color
Value
data('Board Finishes', finish, 'labelOnDark')

A.3 Show Piece

Built in Chapter 1, The Board and the Pieces.

Logic ComponentShow PieceAttach to: Piece

Shows the Piece that stands on this Piece Object's Square: once the Board is laid out (Lay Out The Board sends "boardLaidOut"), and again after every Move (the Game Rules send "positionChanged"). While the Computer's Move slides ("slideStarted"), a Piece on a Square a slide starts from (the Slides table) shows nothing, because a Moving Piece carries it. It shows the Piece in the Piece Set chosen, again whenever the choice changes (Settings sends "lookChanged").

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
On Board Laid Out
WhenboardLaidOutCustom Event
1Show Piece On SquareFunction
piece
self
On Position Changed
WhenpositionChangedCustom Event
1Show Piece On SquareFunction
piece
self
On Slide Started
WhenslideStartedCustom Event
1IfdataFind('Slides', 'from', self.squareInfo.name) != (-1)
Then
2Set Alpha
Alpha
0
On Look Changed
WhenlookChangedCustom Event
1Show Piece SetFunction
piece
self
pieceSet
other.boardState.pieceSet
2Show Piece On SquareFunction
piece
self

A.4 Square Position (Function)

Built in Chapter 1, The Board and the Pieces.

FunctionSquare Position

Answers where the center of a Square is in the world, in meters, for the Board as it is drawn. square: the Square's name (a1 to h8). isFlipped: whether the Board is drawn turned over (Black at the bottom). squareMeters: how wide one Square is. boardLeft and boardBottom: where the Board's bottom-left corner is in the world. It returns x and y: the Square's center.

PARAMETERS
NameTypeStarts at
squareText
isFlippedBooleanNo
squareMetersNumber3.75
boardLeftNumber0
boardBottomNumber0
RETURN TYPESquare Position Result (a Data Structure)
ACTIONS
1Declare Variable
Name
file
Value
0
2Declare Variable
Name
rank
Value
0
3Declare Variable
Name
x
Value
0
4Declare Variable
Name
y
Value
0
5Change Variable
Variable
file
Value
data('Position', square, 'file')
6Change Variable
Variable
rank
Value
data('Position', square, 'rank')
7IfisFlipped == true
Then
8Change Variable
Variable
file
Value
9 - file
9Change Variable
Variable
rank
Value
9 - rank
10Change Variable
Variable
x
Value
boardLeft + (file - 0.5) * squareMeters
11Change Variable
Variable
y
Value
boardBottom + (rank - 0.5) * squareMeters
12Return
x
x
y
y

A.5 Clear Targets (Function)

Built in Chapter 2, Select and Move.

FunctionClear Targets

Makes every Square unreachable: the Targets table is emptied, then gets one row for each Square of the Position table, a1 to h8 in the same order, with reachable no (the column's default). The Targets table has no rows of its own; Clear Targets makes them, each time it is used.

ACTIONS
1Declare Variable
Type
Text
Name
square
2Reset Data Table
Table
Targets
3RepeatdataCount('Position')times
Each time
4Change Variable
Variable
square
Value
dataRow('Position', local.index)
5Control Data Row
Action Name
addedRow
Table
Targets
Row
square

A.6 Find Moves (Function)

Built in Chapter 2, Select and Move.

FunctionFind Moves

Finds every Square the Piece on one Square may move to (by how its Kind moves; Check and the special Moves come later) and marks them in the Targets table, clearing the marks of any Piece looked at before. from: the Piece's Square (a1 to h8).

PARAMETERS
fromText
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Clear TargetsFunction
3Change Variable
Variable
kind
Value
data('Position', from, 'kind')
4RepeatdataCount('Directions')times
Each time
5Ifdata('Directions', local.index, 'kind') == kind
Then
6Follow DirectionFunction
from
from
direction
local.index

A.7 Follow Direction (Function)

Built in Chapter 2, Select and Move.

FunctionFollow Direction

Follows one direction a Piece moves in, Square by Square, marking each Square it may go to in the Targets table, until it leaves the Board, meets a Piece, or has taken as many steps as the Directions table allows. from: the Piece's Square (a1 to h8). direction: the row (0 = first) of the Directions table.

PARAMETERS
NameTypeStarts at
fromText
directionNumber0
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Name
forward
Value
1
3Declare Variable
Name
file
Value
0
4Declare Variable
Name
rank
Value
0
5Declare Variable
Name
stepsLeft
Value
0
6Declare Variable
Type
Boolean
Name
keepGoing
Value
true
7Change Variable
Variable
side
Value
data('Position', from, 'side')
8Change Variable
Variable
forward
Value
data('Sides', side, 'forward')
9Change Variable
Variable
file
Value
data('Position', from, 'file')
10Change Variable
Variable
rank
Value
data('Position', from, 'rank')
11Change Variable
Variable
stepsLeft
Value
data('Directions', direction, 'steps')
12Ifrank == data('Sides', side, 'pawnRank')
Then
13Change Variable
Variable
stepsLeft
Value
data('Directions', direction, 'firstMoveSteps')
14WhilekeepGoing == true && stepsLeft > 0
Each time
15Change Variable
Variable
file
Operator
+=
Value
data('Directions', direction, 'fileStep')
16Change Variable
Variable
rank
Operator
+=
Value
data('Directions', direction, 'rankStep') * forward
17Change Variable
Variable
stepsLeft
Operator
-=
Value
1
18Look At SquareFunction
Action Name
squareLook
file
file
rank
rank
side
side
canMove
data('Directions', direction, 'canMove')
canCapture
data('Directions', direction, 'canCapture')
19Change Variable
Variable
keepGoing
Value
squareLook.value

A.8 Look At Square (Function)

Built in Chapter 2, Select and Move.

FunctionLook At Square

Looks at one Square a Piece could step onto. file and rank: the Square (they may be off the Board). side: the Side of the moving Piece. canMove: it may step onto an empty Square. canCapture: it may take an enemy Piece there. It marks the Square in the Targets table when the Piece may go there. keepGoing (returned): yes when the Square is on the Board and empty, so a sliding Piece may go on past it.

PARAMETERS
NameTypeStarts at
fileNumber0
rankNumber0
sideText
canMoveBooleanYes
canCaptureBooleanYes
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isOnBoard
Value
false
2Declare Variable
Name
square
Value
0
3Declare Variable
Type
Boolean
Name
keepGoing
Value
false
4Iffile >= 1 && file <= 8 && rank >= 1 && rank <= 8
Then
5Change Variable
Variable
isOnBoard
Value
true
6Change Variable
Variable
square
Value
(rank - 1) * 8 + (file - 1)
7IfisOnBoard == true && data('Position', square, 'kind') == ""
Then
8Change Variable
Variable
keepGoing
Value
true
9IfkeepGoing == true && canMove == true
Then
10Set Data Cell
Table
Targets
Row
square
Column
"reachable"
Value
"true"
11IfisOnBoard == true && data('Position', square, 'kind') != "" && data('Position', square, 'side') != side && canCapture == true
Then
12Set Data Cell
Table
Targets
Row
square
Column
"reachable"
Value
"true"
13Return
Value
keepGoing

A.9 Report Click

Built in Chapter 2, Select and Move.

Logic ComponentReport ClickAttach to: Square

When the Player clicks this Square while the game is being played (Game State Playing), it tells whoever listens (the Game Rules) with "squareClicked"; the listener reads which Square it was as Other. While the Promotion choice is open, and after the game has ended, the Board does not answer.

Attach toAny Object
When Left Is Clicked
WhenMouse Pressed on ObjectMouse button: left
1Check Game State
Action Name
isPlaying
Game State
Playing
2IfisPlaying.value == true
Then
3Trigger Custom Event
Custom Event
squareClicked

A.10 Select and Move

Built in Chapter 2, Select and Move.

Logic ComponentSelect and MoveAttach to: Game Rules

Decides what a click on a Square means. A click on a Square the selected Piece may move to writes it down (Record Move) and makes it (Make Move: castling and en passant included) and tells the Game Rules "moveMade" (Start Turn then starts the other Side's Turn); when the Move takes a Pawn to its last Rank, it opens the Promotion choice instead (Game State Promotion), and Choose Promotion makes the Move. A click on a Piece of the Side to move selects it and marks its Legal Moves (Find Legal Moves); any other click clears the selection. In Threats mode a click that is not a Move also inspects the Piece clicked, of either Side (Inspect Piece). Then it tells everyone "positionChanged". Its Other is the clicked Square. Every click forgets the Hint (Forget The Hint). Escape (the Command Cancel) clears the selection and the Inspected Piece while the game is being played.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Select and Move Dataself.selectAndMoveData
On Square Clicked
WhensquareClickedCustom Event
1Declare Variable
Type
Text
Name
selectedSquare
2Declare Variable
Type
Text
Name
clickedSquare
3Forget The HintFunction
4Change Variable
Variable
clickedSquare
Value
other.squareInfo.name
5Change Variable
Variable
selectedSquare
Value
self.boardState.selected
6IfselectedSquare != "" && data('Targets', clickedSquare, 'reachable') == true
Then
7Change Component Value
Component Value
self.selectAndMoveData.side
Value
self.boardState.sideToMove
8Ifdata('Position', selectedSquare, 'kind') == "Pawn" && data('Position', clickedSquare, 'rank') == data('Sides', self.selectAndMoveData.side, 'promotionRank')
Then
9Open Promotion ChoiceFunction
gameRules
self
square
clickedSquare
10Otherwise
11Record MoveFunction
gameRules
self
from
selectedSquare
to
clickedSquare
landingKind
data('Position', selectedSquare, 'kind')
12Make MoveFunction
gameRules
self
from
selectedSquare
to
clickedSquare
13Trigger Custom Event on Object
Custom Event
moveMade
14Otherwise
15Ifdata('Position', clickedSquare, 'side') == self.boardState.sideToMove && clickedSquare != selectedSquare
Then
16Change Component Value
Component Value
self.boardState.selected
Value
clickedSquare
17Find Legal MovesFunction
from
clickedSquare
enPassantSquare
self.boardState.enPassantSquare
18Otherwise
19Change Component Value
Component Value
self.boardState.selected
Value
''
20Clear TargetsFunction
21Inspect PieceFunction
gameRules
self
square
clickedSquare
22Trigger Custom Event
Custom Event
positionChanged
When Cancel Is Pressed
WhenCommand PressedCommand: Cancel
1Check Game State
Action Name
isPlaying
Game State
Playing
2IfisPlaying.value == true
Then
3Change Component Value
Component Value
self.boardState.selected
Value
''
4Clear TargetsFunction
5Change Component Value
Component Value
self.boardState.inspected
Value
''
6Trigger Custom Event
Custom Event
positionChanged

A.11 Show Move Mark

Built in Chapter 2, Select and Move.

Logic ComponentShow Move MarkAttach to: Move Mark

Shows whether the selected Piece may move to this Move Mark's Square, after every change (the Game Rules send "positionChanged"): a dot on an empty Square, a ring around a Piece it may take, and nothing on any other Square. It reads the Targets table, which the Game Rules fill when a Piece is selected.

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
On Position Changed
WhenpositionChangedCustom Event
1Ifdata('Targets', self.squareInfo.name, 'reachable') == true
Then
2Set Visible
Visible
Yes
3Ifdata('Position', self.squareInfo.name, 'kind') == ""
Then
4Set Frame
Frame
0
5Otherwise
6Set Frame
Frame
1
7Otherwise
8Set Visible
Visible
No

A.12 Show Piece On Square (Function)

Built in Chapter 2, Select and Move.

FunctionShow Piece On Square

Shows the Piece that stands on one Square of the Board: the frame of the Piece Set art that the Kinds table gives for its Kind and Side, or nothing (fully transparent) when the Square is empty. piece: the Piece Object to show it with; its Square Info names its Square, which is its row in the Position table.

PARAMETERS
NameTypeStarts at
pieceObjectStructural
Required Components
Slot NamesquareInfo
Component TypeData Structure
Required SchemaSquare Info
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Declare Variable
Type
Text
Name
side
3Change Variable
Variable
kind
Value
data('Position', piece.squareInfo.name, 'kind')
4Ifkind == ""
Then
5Set Alpha
Applies to
piece
Alpha
0
6Otherwise
7Set Alpha
Applies to
piece
8Change Variable
Variable
side
Value
data('Position', piece.squareInfo.name, 'side')
9Set Frame
Applies to
piece
Frame
data('Kinds', kind, side)

A.13 Square Marks

Built in Chapter 2, Select and Move.

Logic ComponentSquare MarksAttach to: Square

Shows the highlight on this Square after every change (the Game Rules send "positionChanged" and are its Other): a tint when it was part of the last Move, when its Piece is attacked in Threats mode (the Threats table; a stronger red when it is unprotected), when its Piece is inspected in Threats mode, when its Piece is selected, when it is one of the Hint's two Squares (the Chosen Moves table, row Hint), or when its King is in Check (the most important one shows). The colors, and how strongly each shows, are the Square's Shared Variables (Show Highlight shows them). While the Computer's Move slides ("slideStarted"), no highlight is shown.

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
SHARED VARIABLES
NameTypeKindStarting Value
selectedColorColorConstant#f4d273
selectedAlphaNumberConstant0.44
lastMoveColorColorConstant#e9c44f
lastMoveAlphaNumberConstant0.32
checkColorColorConstant#cd493f
checkAlphaNumberConstant0.66
hintColorColorConstant#61a9b8
hintAlphaNumberConstant0.35
attackedColorColorConstant#d64b46
attackedAlphaNumberConstant0.4
unprotectedAlphaNumberConstant0.5
inspectedColorColorConstant#56a59d
inspectedAlphaNumberConstant0.27
On Position Changed
WhenpositionChangedCustom Event
1Set Alpha
Alpha
0
2Ifself.squareInfo.name == other.boardState.lastFrom || self.squareInfo.name == other.boardState.lastTo
Then
3Show HighlightFunction
square
self
color
@self.lastMoveColor
alpha
@self.lastMoveAlpha
4Ifdata('Threats', self.squareInfo.name, 'isAttacked') == true
Then
5Show HighlightFunction
square
self
color
@self.attackedColor
alpha
@self.attackedAlpha
6Ifdata('Threats', self.squareInfo.name, 'isUnprotected') == true
Then
7Set Alpha
Alpha
@self.unprotectedAlpha
8Ifself.squareInfo.name == other.boardState.inspected
Then
9Show HighlightFunction
square
self
color
@self.inspectedColor
alpha
@self.inspectedAlpha
10Ifself.squareInfo.name == other.boardState.selected
Then
11Show HighlightFunction
square
self
color
@self.selectedColor
alpha
@self.selectedAlpha
12Ifself.squareInfo.name == data('Chosen Moves', 'Hint', 'from') || self.squareInfo.name == data('Chosen Moves', 'Hint', 'to')
Then
13Show HighlightFunction
square
self
color
@self.hintColor
alpha
@self.hintAlpha
14Ifself.squareInfo.name == other.boardState.checkSquare
Then
15Show HighlightFunction
square
self
color
@self.checkColor
alpha
@self.checkAlpha
On Slide Started
WhenslideStartedCustom Event
1Set Alpha
Alpha
0

A.14 Drop Move If Unsafe (Function)

Built in Chapter 3, Turns and Check.

FunctionDrop Move If Unsafe

Tries one marked Move on the Position table, asks whether the mover's own King is then attacked, and takes the Move back, so the Position is as it was; if the King would be attacked, the Move is unmarked in the Targets table. from and to: the Squares of the Move (a1 to h8). taken: the Square of the Piece the Move would take: the same as to, except for en passant. kingSquare: where the mover's King stands now. enemy: the other Side.

PARAMETERS
fromText
toText
takenText
kingSquareText
enemyText
ACTIONS
1Declare Variable
Type
Text
Name
takenKind
2Declare Variable
Type
Text
Name
takenSide
3Declare Variable
Type
Text
Name
checkSquare
4Change Variable
Variable
takenKind
Value
data('Position', taken, 'kind')
5Change Variable
Variable
takenSide
Value
data('Position', taken, 'side')
6Set Data Cell
Table
Position
Row
taken
Column
"kind"
Value
''
7Set Data Cell
Table
Position
Row
taken
Column
"side"
Value
''
8Move PieceFunction
from
from
to
to
9Change Variable
Variable
checkSquare
Value
kingSquare
10Iffrom == kingSquare
Then
11Change Variable
Variable
checkSquare
Value
to
12Is Square AttackedFunction
Action Name
kingLook
square
checkSquare
bySide
enemy
13IfkingLook.attacked == true
Then
14Set Data Cell
Table
Targets
Row
to
Column
"reachable"
Value
"false"
15Move PieceFunction
from
to
to
from
16Set Data Cell
Table
Position
Row
taken
Column
"kind"
Value
takenKind
17Set Data Cell
Table
Position
Row
taken
Column
"side"
Value
takenSide

A.15 Find Attacker Along (Function)

Built in Chapter 3, Turns and Check.

FunctionFind Attacker Along

Looks back from one Square along one direction of the Directions table for the first Piece in the way (Find First Piece Along). attackers (returned): 1 when that Piece belongs to bySide and is of the direction's Kind, so it could capture onto the Square, else 0 (for a Pawn, the direction is turned round by its Side's forward). attacker (returned): the Square of that attacking Piece, or empty when there is none. square: the Square looked from (a1 to h8). direction: the row (0 = first) of the Directions table. bySide: the attacking Side.

PARAMETERS
NameTypeStarts at
squareText
directionNumber0
bySideText
RETURN TYPEFind Attacker Along Result (a Data Structure)
ACTIONS
1Declare Variable
Type
Text
Name
piece
2Declare Variable
Name
attackers
Value
0
3Declare Variable
Type
Text
Name
attacker
4Find First Piece AlongFunction
Action Name
pieceLook
square
square
direction
direction
bySide
bySide
5Change Variable
Variable
piece
Value
pieceLook.value
6Ifpiece != "" && data('Position', piece, 'side') == bySide && data('Position', piece, 'kind') == data('Directions', direction, 'kind')
Then
7Change Variable
Variable
attackers
Value
1
8Change Variable
Variable
attacker
Value
piece
9Return
attackers
attackers
attacker
attacker

A.16 Find King (Function)

Built in Chapter 3, Turns and Check.

FunctionFind King

Finds where one Side's King stands. side: White or Black. kingSquare (returned): its Square (a1 to h8).

PARAMETERS
sideText
RETURN TYPEText
ACTIONS
1Declare Variable
Type
Text
Name
kingSquare
2RepeatdataCount('Position')times
Each time
3Ifdata('Position', local.index, 'kind') == "King" && data('Position', local.index, 'side') == side
Then
4Change Variable
Variable
kingSquare
Value
dataRow('Position', local.index)
5Return
Value
kingSquare

A.17 Is Square Attacked (Function)

Built in Chapter 3, Turns and Check.

FunctionIs Square Attacked

Answers whether any Piece of one Side could capture onto a Square. square: the Square (a1 to h8). bySide: the attacking Side (White or Black). attacked (returned): yes when at least one of its Pieces attacks the Square. attackers (returned): how many do.

PARAMETERS
squareText
bySideText
RETURN TYPEIs Square Attacked Result (a Data Structure)
ACTIONS
1Declare Variable
Name
attackerCount
Value
0
2Declare Variable
Type
Boolean
Name
attacked
Value
false
3RepeatdataCount('Directions')times
Each time
4Ifdata('Directions', local.index, 'canCapture') == true
Then
5Find Attacker AlongFunction
Action Name
attackerLook
square
square
direction
local.index
bySide
bySide
6Change Variable
Variable
attackerCount
Operator
+=
Value
attackerLook.attackers
7IfattackerCount > 0
Then
8Change Variable
Variable
attacked
Value
true
9Return
attacked
attacked
attackers
attackerCount

A.18 Keep Safe Moves (Function)

Built in Chapter 3, Turns and Check.

FunctionKeep Safe Moves

Of the Squares marked in the Targets table for the Piece on one Square, unmarks every one that would leave its own King attacked, so only Legal Moves stay marked. from: the Piece's Square (a1 to h8).

PARAMETERS
fromText
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Text
Name
kingSquare
4Change Variable
Variable
side
Value
data('Position', from, 'side')
5Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
6Find KingFunction
Action Name
kingLook
side
side
7Change Variable
Variable
kingSquare
Value
kingLook.value
8RepeatdataCount('Targets')times
Each time
9Ifdata('Targets', local.index, 'reachable') == true
Then
10Drop Move If UnsafeFunction
from
from
to
dataRow('Targets', local.index)
taken
dataRow('Targets', local.index)
kingSquare
kingSquare
enemy
enemy

A.19 Look For Check (Function)

Built in Chapter 3, Turns and Check.

FunctionLook For Check

Asks whether the Side to move is in Check: whether its King's Square is attacked by the other Side. The Board State remembers the answer (checkSquare: the King's Square, or empty), and the status line's words ($status) say "Check" or "Your move". gameRules: the Game Rules Object, whose Board State says whose Turn it is.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Text
Name
kingSquare
4Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
5Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
6Find KingFunction
Action Name
kingLook
side
side
7Change Variable
Variable
kingSquare
Value
kingLook.value
8Is Square AttackedFunction
Action Name
checkLook
square
kingSquare
bySide
enemy
9IfcheckLook.attacked == true
Then
10Change Component Value
Component Value
gameRules.boardState.checkSquare
Value
kingSquare
11Change Variable
Variable
$status
Value
data('Words', 'Check', 'text')
12Otherwise
13Change Component Value
Component Value
gameRules.boardState.checkSquare
Value
''
14Change Variable
Variable
$status
Value
data('Words', 'Your Move', 'text')

A.20 Move Piece (Function)

Built in Chapter 3, Turns and Check.

FunctionMove Piece

Moves the Piece on one Square to another in the Position table: the Piece takes the new Square (and any Piece that stood there is gone), and its old Square becomes empty. from and to: the two Squares (a1 to h8).

PARAMETERS
fromText
toText
ACTIONS
1Set Data Cell
Table
Position
Row
to
Column
"kind"
Value
data('Position', from, 'kind')
2Set Data Cell
Table
Position
Row
to
Column
"side"
Value
data('Position', from, 'side')
3Set Data Cell
Table
Position
Row
from
Column
"kind"
Value
''
4Set Data Cell
Table
Position
Row
from
Column
"side"
Value
''

A.21 Start Turn

Built in Chapter 3, Turns and Check.

Logic ComponentStart TurnAttach to: Game Rules

Starts each Turn: the first one (White's) when the game begins, and the next one after every Move, giving the Turn to the other Side (Pass The Turn). Each Turn starts with Start The Turn: it asks whether the Side to move is in Check, then tells the Game Rules that the Turn has started ("turnStarted").

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
When Created
WhenCreate
1Start The TurnFunction
gameRules
self
2Trigger Custom Event
Custom Event
positionChanged
On Move Made
WhenmoveMadeCustom Event
1Pass The TurnFunction
gameRules
self
2Change Component Value
Component Value
self.boardState.selected
Value
''
3Change Component Value
Component Value
self.boardState.inspected
Value
''
4Clear TargetsFunction
5Start The TurnFunction
gameRules
self

A.22 Choose Promotion

Built in Chapter 4, Special Moves.

Logic ComponentChoose PromotionAttach to: Game Rules

Closes the Promotion choice when the Player presses one of its buttons ("promotionChosen"; the button is its Other): the panel is hidden and the game is played again (Game State Playing). A Kind then writes down the waiting Pawn Move (Record Move) and makes it (Make Move), puts the chosen Kind on the Square, and tells the Game Rules "moveMade"; Cancel makes no Move, and the Pawn stays selected. Then everyone hears "positionChanged".

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Choose Promotion Dataself.choosePromotionData
On Promotion Chosen
WhenpromotionChosenCustom Event
1Check Game State
Action Name
isChoosing
Game State
Promotion
2IfisChoosing.value == true
Then
3Change Component Value
Component Value
self.choosePromotionData.chosenKind
Value
other.promotionChoice.kind
4Change Component Value
Component Value
self.choosePromotionData.landingSquare
Value
self.boardState.promotionSquare
5Change Component Value
Component Value
self.boardState.promotionSquare
Value
''
6Set UI Group Visibility
UI Group
"Promotion"
Visible
No
7Set Game State
Game State
Playing
8Ifself.choosePromotionData.chosenKind != ""
Then
9Record MoveFunction
gameRules
self
from
self.boardState.selected
to
self.choosePromotionData.landingSquare
landingKind
self.choosePromotionData.chosenKind
10Make MoveFunction
gameRules
self
from
self.boardState.selected
to
self.choosePromotionData.landingSquare
11Set Data Cell
Table
Position
Row
self.choosePromotionData.landingSquare
Column
"kind"
Value
self.choosePromotionData.chosenKind
12Trigger Custom Event on Object
Custom Event
moveMade
13Otherwise
14Look For CheckFunction
gameRules
self
15Trigger Custom Event
Custom Event
positionChanged

A.23 Find En Passant Move (Function)

Built in Chapter 4, Special Moves.

FunctionFind En Passant Move

Marks the en passant Square in the Targets table when the Pawn on one Square may take en passant there, and the Move does not leave its own King attacked. from: the Pawn's Square (a1 to h8). enPassantSquare: the Square an enemy Pawn has just passed over (empty when none).

PARAMETERS
fromText
enPassantSquareText
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Name
fromFile
Value
0
4Declare Variable
Name
fromRank
Value
0
5Declare Variable
Name
targetFile
Value
0
6Declare Variable
Name
targetRank
Value
0
7Declare Variable
Name
forward
Value
0
8Declare Variable
Type
Text
Name
passedPawn
9Declare Variable
Type
Text
Name
kingSquare
10Change Variable
Variable
side
Value
data('Position', from, 'side')
11Change Variable
Variable
forward
Value
data('Sides', side, 'forward')
12Change Variable
Variable
fromFile
Value
data('Position', from, 'file')
13Change Variable
Variable
fromRank
Value
data('Position', from, 'rank')
14Change Variable
Variable
targetFile
Value
data('Position', enPassantSquare, 'file')
15Change Variable
Variable
targetRank
Value
data('Position', enPassantSquare, 'rank')
16IfenPassantSquare != "" && data('Position', from, 'kind') == "Pawn" && (targetRank - fromRank) == forward && abs(targetFile - fromFile) == 1
Then
17Change Variable
Variable
passedPawn
Value
dataRow('Position', (fromRank - 1) * 8 + (targetFile - 1))
18Set Data Cell
Table
Targets
Row
enPassantSquare
Column
"reachable"
Value
"true"
19Find KingFunction
Action Name
kingLook
side
side
20Change Variable
Variable
kingSquare
Value
kingLook.value
21Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
22Drop Move If UnsafeFunction
from
from
to
enPassantSquare
taken
passedPawn
kingSquare
kingSquare
enemy
enemy

A.25 Make Move (Function)

Built in Chapter 4, Special Moves.

FunctionMake Move

Makes one Legal Move on the Position table, with everything it brings: the fifty-move rule's count, the Rook's part of castling (Update Castling), en passant (Update En Passant), and the last Move's Squares. gameRules: the Game Rules Object, whose Board State it updates. from and to: the Squares of the Move (a1 to h8).

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
fromText
toText
ACTIONS
1Ifdata('Position', from, 'kind') == "Pawn" || data('Position', to, 'kind') != ""
Then
2Change Component Value
Component Value
gameRules.boardState.fiftyMoveCount
Value
0
3Otherwise
4Change Component Value
Component Value
gameRules.boardState.fiftyMoveCount
Operator
+=
Value
1
5Update CastlingFunction
from
from
to
to
6Update En PassantFunction
gameRules
gameRules
from
from
to
to
7Move PieceFunction
from
from
to
to
8Change Component Value
Component Value
gameRules.boardState.lastFrom
Value
from
9Change Component Value
Component Value
gameRules.boardState.lastTo
Value
to

A.26 Report Choice

Built in Chapter 4, Special Moves.

Logic ComponentReport ChoiceAttach to: Promotion Button, Cancel Promotion

When the Player presses this button of the Promotion panel, it tells whoever listens (the Game Rules) with "promotionChosen"; the listener reads the button's Promotion Choice (a Kind, or empty to cancel) as Other.

Attach toAny Object
DATA STRUCTURES
Promotion Choiceself.promotionChoice
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
promotionChosen

A.27 Show Promotion Choice

Built in Chapter 4, Special Moves.

Logic ComponentShow Promotion ChoiceAttach to: Promotion Button

Shows this Promotion Button's Kind (its Promotion Choice) in the Piece Set art of the Side to move, after every change (the Game Rules send "positionChanged" and are its Other), so the panel always offers the Pieces of the Side that promotes. It shows the Piece Set chosen, whenever the choice changes (Settings sends "lookChanged").

Attach toAny Object
DATA STRUCTURES
Promotion Choiceself.promotionChoice
On Position Changed
WhenpositionChangedCustom Event
1Declare Variable
Type
Text
Name
choiceKind
2Declare Variable
Type
Text
Name
side
3Change Variable
Variable
side
Value
other.boardState.sideToMove
4Change Variable
Variable
choiceKind
Value
self.promotionChoice.kind
5Set Frame
Frame
data('Kinds', choiceKind, side)
On Look Changed
WhenlookChangedCustom Event
1Show Piece SetFunction
piece
self
pieceSet
other.boardState.pieceSet

A.28 Try Castling (Function)

Built in Chapter 4, Special Moves.

FunctionTry Castling

Marks one castling's King Square in the Targets table when the castling is legal now: the Squares between the King and the Rook are empty, and the King is not in Check, does not cross an attacked Square, and does not land on one. castling: the row (0 = first) of the Castling table, still allowed. enemy: the other Side.

PARAMETERS
NameTypeStarts at
castlingNumber0
enemyText
ACTIONS
1Declare Variable
Name
row
Value
0
2Declare Variable
Type
Text
Name
kingFrom
3Declare Variable
Type
Text
Name
kingTo
4Declare Variable
Type
Text
Name
rookTo
5Declare Variable
Type
Text
Name
rookPasses
6Declare Variable
Name
attacks
Value
0
7Change Variable
Variable
row
Value
castling
8Change Variable
Variable
kingFrom
Value
data('Castling', row, 'kingFrom')
9Change Variable
Variable
kingTo
Value
data('Castling', row, 'kingTo')
10Change Variable
Variable
rookTo
Value
data('Castling', row, 'rookTo')
11Change Variable
Variable
rookPasses
Value
data('Castling', row, 'rookPasses')
12Ifdata('Position', kingTo, 'kind') == "" && data('Position', rookTo, 'kind') == "" && data('Position', rookPasses, 'kind') == ""
Then
13Is Square AttackedFunction
Action Name
startLook
square
kingFrom
bySide
enemy
14Change Variable
Variable
attacks
Value
startLook.attackers
15Is Square AttackedFunction
Action Name
crossLook
square
rookTo
bySide
enemy
16Change Variable
Variable
attacks
Operator
+=
Value
crossLook.attackers
17Is Square AttackedFunction
Action Name
landLook
square
kingTo
bySide
enemy
18Change Variable
Variable
attacks
Operator
+=
Value
landLook.attackers
19Ifattacks == 0
Then
20Set Data Cell
Table
Targets
Row
kingTo
Column
"reachable"
Value
"true"

A.29 Update Castling (Function)

Built in Chapter 4, Special Moves.

FunctionUpdate Castling

Keeps the Castling table up to date for one Move, before the Move is made. When the Move is a King castling (from its starting Square to a castling's King Square), the Rook moves too. Any Move from the King's or a Rook's starting Square, or onto a Rook's starting Square (taking it), ends that castling for the rest of the game. from and to: the Squares of the Move (a1 to h8).

PARAMETERS
fromText
toText
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Declare Variable
Type
Text
Name
castling
3Change Variable
Variable
kind
Value
data('Position', from, 'kind')
4RepeatdataCount('Castling')times
Each time
5Change Variable
Variable
castling
Value
dataRow('Castling', local.index)
6Ifkind == "King" && data('Castling', castling, 'kingFrom') == from && data('Castling', castling, 'kingTo') == to
Then
7Move PieceFunction
from
data('Castling', castling, 'rookFrom')
to
data('Castling', castling, 'rookTo')
8Ifdata('Castling', castling, 'kingFrom') == from || data('Castling', castling, 'rookFrom') == from || data('Castling', castling, 'rookFrom') == to
Then
9Set Data Cell
Table
Castling
Row
castling
Column
"isAllowed"
Value
"false"

A.30 Can Take En Passant (Function)

Built in Chapter 5, The End of the Game.

FunctionCan Take En Passant

Asks whether the Side to move may take en passant right now: an enemy Pawn has just passed over the en passant Square, and a Pawn of the Side to move may take it there without leaving its own King attacked. gameRules: the Game Rules Object, whose Board State says whose Turn it is and where en passant is possible. canTake (returned): true when such a Move is a Legal Move. It leaves the Targets table empty.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enPassant
3Declare Variable
Type
Text
Name
square
4Declare Variable
Type
Boolean
Name
canTake
Value
false
5Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
6Change Variable
Variable
enPassant
Value
gameRules.boardState.enPassantSquare
7Clear TargetsFunction
8RepeatdataCount('Position')times
Each time
9Change Variable
Variable
square
Value
dataRow('Position', local.index)
10IfenPassant != "" && data('Position', square, 'kind') == "Pawn" && data('Position', square, 'side') == side
Then
11Find En Passant MoveFunction
from
square
enPassantSquare
enPassant
12IfdataFind('Targets', 'reachable', true) != (-1)
Then
13Change Variable
Variable
canTake
Value
true
14Clear TargetsFunction
15Return
Value
canTake

A.31 Is Material Insufficient (Function)

Built in Chapter 5, The End of the Game.

FunctionIs Material Insufficient

Asks whether neither Side has enough Pieces left to give Checkmate, which ends the game as a Draw: only the two Kings; a King and one Knight or one Bishop against a King; or Kings and Bishops whose Bishops all stand on Squares of one shade. isInsufficient (returned): true when that is so.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Declare Variable
Name
file
Value
0
3Declare Variable
Name
rank
Value
0
4Declare Variable
Name
squareShade
Value
0
5Declare Variable
Name
otherPieces
Value
0
6Declare Variable
Name
knights
Value
0
7Declare Variable
Name
darkBishops
Value
0
8Declare Variable
Name
lightBishops
Value
0
9Declare Variable
Type
Boolean
Name
isInsufficient
Value
false
10RepeatdataCount('Position')times
Each time
11Change Variable
Variable
kind
Value
data('Position', local.index, 'kind')
12Change Variable
Variable
file
Value
data('Position', local.index, 'file')
13Change Variable
Variable
rank
Value
data('Position', local.index, 'rank')
14Change Variable
Variable
squareShade
Value
(file + rank) % 2
15Ifkind != "" && kind != "King"
Then
16Change Variable
Variable
otherPieces
Operator
+=
Value
1
17Ifkind == "Knight"
Then
18Change Variable
Variable
knights
Operator
+=
Value
1
19Ifkind == "Bishop" && squareShade == 0
Then
20Change Variable
Variable
darkBishops
Operator
+=
Value
1
21Ifkind == "Bishop" && squareShade == 1
Then
22Change Variable
Variable
lightBishops
Operator
+=
Value
1
23IfotherPieces == 1 && knights == 1
Then
24Change Variable
Variable
isInsufficient
Value
true
25IfotherPieces == darkBishops || otherPieces == lightBishops
Then
26Change Variable
Variable
isInsufficient
Value
true
27Return
Value
isInsufficient

A.32 Is Out Of Moves (Function)

Built in Chapter 5, The End of the Game.

FunctionIs Out Of Moves

Asks whether the Side to move has no Legal Move at all, which ends the game. gameRules: the Game Rules Object, whose Board State says whose Turn it is and where en passant is possible. isOutOfMoves (returned): true when no Piece of the Side to move has a Legal Move. It leaves the Targets table empty.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enPassant
3Declare Variable
Type
Text
Name
square
4Declare Variable
Type
Boolean
Name
isOutOfMoves
Value
true
5Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
6Change Variable
Variable
enPassant
Value
gameRules.boardState.enPassantSquare
7Clear TargetsFunction
8RepeatdataCount('Position')times
Each time
9Change Variable
Variable
square
Value
dataRow('Position', local.index)
10IfisOutOfMoves == true && data('Position', square, 'side') == side
Then
11Find Legal MovesFunction
from
square
enPassantSquare
enPassant
12IfdataFind('Targets', 'reachable', true) != (-1)
Then
13Change Variable
Variable
isOutOfMoves
Value
false
14Clear TargetsFunction
15Return
Value
isOutOfMoves

A.33 Is Position Repeated (Function)

Built in Chapter 5, The End of the Game.

FunctionIs Position Repeated

Asks whether the position recorded last in the Position History table has now been seen timesForDraw times, which ends the game as a Draw. Only every other position before it can be the same, because the Sides take turns: those had the same Side to move. timesForDraw: how many times the same position must be seen (3, threefold repetition). isRepeated (returned): true when it has been seen that often.

PARAMETERS
NameTypeStarts at
timesForDrawNumber3
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Name
lastPosition
Value
0
2Declare Variable
Name
earlier
Value
0
3Declare Variable
Name
timesSeen
Value
1
4Declare Variable
Type
Boolean
Name
isRepeated
Value
false
5Change Variable
Variable
lastPosition
Value
dataCount('Position History') / dataCount('Position') - 1
6Repeatfloor(lastPosition / 2)times
Each time
7Change Variable
Variable
earlier
Value
lastPosition - 2 * (local.index + 1)
8Is Same PositionFunction
Action Name
positionLook
earlier
earlier
later
lastPosition
9IfpositionLook.value == true
Then
10Change Variable
Variable
timesSeen
Operator
+=
Value
1
11IftimesSeen >= timesForDraw
Then
12Change Variable
Variable
isRepeated
Value
true
13Return
Value
isRepeated

A.34 Is Same Position (Function)

Built in Chapter 5, The End of the Game.

FunctionIs Same Position

Asks whether two positions recorded in the Position History table are the same: the same Piece on every Square and the same number of castlings allowed. earlier and later: the two positions' numbers in the table (0 is the first one recorded). isSame (returned): true when they are the same.

PARAMETERS
NameTypeStarts at
earlierNumber0
laterNumber0
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Name
squares
Value
0
2Declare Variable
Name
earlierRow
Value
0
3Declare Variable
Name
laterRow
Value
0
4Declare Variable
Name
sameSquares
Value
0
5Declare Variable
Type
Boolean
Name
isSame
Value
false
6Change Variable
Variable
squares
Value
dataCount('Position')
7Repeatsquarestimes
Each time
8Change Variable
Variable
earlierRow
Value
earlier * squares + local.index
9Change Variable
Variable
laterRow
Value
later * squares + local.index
10Ifdata('Position History', earlierRow, 'kind') == data('Position History', laterRow, 'kind') && data('Position History', earlierRow, 'side') == data('Position History', laterRow, 'side') && data('Position History', earlierRow, 'castlingsAllowed') == data('Position History', laterRow, 'castlingsAllowed')
Then
11Change Variable
Variable
sameSquares
Operator
+=
Value
1
12IfsameSquares == squares
Then
13Change Variable
Variable
isSame
Value
true
14Return
Value
isSame

A.35 Look For Game End

Built in Chapter 5, The End of the Game.

Logic ComponentLook For Game EndAttach to: Game Rules

Ends the game at the start of every Turn (Start Turn sends "turnStarted") when the Side to move has no Legal Move (Is Out Of Moves), when neither Side can give Checkmate (Is Material Insufficient), when the same position has come timesSeenForDraw times (Record Position, Is Position Repeated), or when fiftyMoveCountForDraw Moves in a row have had no Capture and no Pawn Move (the fifty-move rule; Make Move counts them). The status line shows the result (Show Result), a Checkmate is marked # in the Move History, and the game is over (Game State Game Over), so the Board no longer answers and the final position stays. Otherwise it tells the Game Rules "gameContinues", and the Turn goes on. timesSeenForDraw: 3, threefold repetition. fiftyMoveCountForDraw: 100, fifty Moves by each Side.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
SHARED VARIABLES
NameTypeKindStarting Value
timesSeenForDrawNumberConstant3
fiftyMoveCountForDrawNumberConstant100
On Turn Started
WhenturnStartedCustom Event
1Is Out Of MovesFunction
Action Name
outOfMoves
gameRules
self
2Is Material InsufficientFunction
Action Name
material
3Record PositionFunction
gameRules
self
4Is Position RepeatedFunction
Action Name
repetition
timesForDraw
@self.timesSeenForDraw
5IfoutOfMoves.value == true || material.value == true || repetition.value == true || self.boardState.fiftyMoveCount >= @self.fiftyMoveCountForDraw
Then
6Show ResultFunction
gameRules
self
isOutOfMoves
outOfMoves.value
isMaterialInsufficient
material.value
isRepeated
repetition.value
7IfoutOfMoves.value == true && self.boardState.checkSquare != "" && dataCount('Move History') > 0
Then
8Set Data Cell
Table
Move History
Row
dataCount('Move History') - 1
Column
"checkMark"
Value
data('Words', 'Checkmate Mark', 'text')
9Set Game State
Game State
Game Over
10Otherwise
11Trigger Custom Event on Object
Custom Event
gameContinues

A.36 Record Position (Function)

Built in Chapter 5, The End of the Game.

FunctionRecord Position

Adds the position on the Board to the Position History table at the start of a Turn: for every Square, the Piece on it and how many castlings are still allowed. After a Capture or a Pawn Move (and at the start of a game) the table starts over, because no earlier position can come again. A position in which en passant can be taken is not recorded: en passant is possible only on the very next Move, so that position can never come again either. gameRules: the Game Rules Object, whose Board State holds the fifty-move rule's count, whose Turn it is, and the en passant Square.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Declare Variable
Name
castlingsStillAllowed
Value
0
2Declare Variable
Type
Text
Name
square
3Declare Variable
Name
lastRow
Value
0
4IfgameRules.boardState.fiftyMoveCount == 0
Then
5Reset Data Table
Table
Position History
6Can Take En PassantFunction
Action Name
enPassantLook
gameRules
gameRules
7RepeatdataCount('Castling')times
Each time
8Ifdata('Castling', local.index, 'isAllowed') == true
Then
9Change Variable
Variable
castlingsStillAllowed
Operator
+=
Value
1
10IfenPassantLook.value != true
Then
11RepeatdataCount('Position')times
Each time
12Change Variable
Variable
square
Value
dataRow('Position', local.index)
13Control Data Row
Action Name
addedRow
Table
Position History
Row
dataCount('Position History')
14Change Variable
Variable
lastRow
Value
dataCount('Position History') - 1
15Set Data Cell
Table
Position History
Row
lastRow
Column
"kind"
Value
data('Position', square, 'kind')
16Set Data Cell
Table
Position History
Row
lastRow
Column
"side"
Value
data('Position', square, 'side')
17Set Data Cell
Table
Position History
Row
lastRow
Column
"castlingsAllowed"
Value
castlingsStillAllowed

A.37 Show Result (Function)

Built in Chapter 5, The End of the Game.

FunctionShow Result

Shows how the game ended in the status line ($status), once the game has ended. When the Side to move has no Legal Move: Checkmate if its King is in Check (the Player wins or loses), else Stalemate (a Draw). Otherwise the game ended as a Draw by rule: insufficient material, else threefold repetition, else the fifty-move rule. gameRules: the Game Rules Object, whose Board State says whose Turn it is, where Check is, and which Side the Player plays. isOutOfMoves: the Side to move has no Legal Move. isMaterialInsufficient: neither Side can give Checkmate. isRepeated: the same position has come for the third time.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
isOutOfMovesBooleanNo
isMaterialInsufficientBooleanNo
isRepeatedBooleanNo
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
checkSquare
3Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
4Change Variable
Variable
checkSquare
Value
gameRules.boardState.checkSquare
5IfisOutOfMoves == true && checkSquare != "" && side == gameRules.boardState.playerSide
Then
6Change Variable
Variable
$status
Value
data('Words', 'Loss By Checkmate', 'text')
7Otherwise
8IfisOutOfMoves == true && checkSquare != ""
Then
9Change Variable
Variable
$status
Value
data('Words', 'Win By Checkmate', 'text')
10Otherwise
11IfisOutOfMoves == true
Then
12Change Variable
Variable
$status
Value
data('Words', 'Draw By Stalemate', 'text')
13Otherwise
14IfisMaterialInsufficient == true
Then
15Change Variable
Variable
$status
Value
data('Words', 'Draw By Insufficient Material', 'text')
16Otherwise
17IfisRepeated == true
Then
18Change Variable
Variable
$status
Value
data('Words', 'Draw By Threefold Repetition', 'text')
19Otherwise
20Change Variable
Variable
$status
Value
data('Words', 'Draw By Fifty Move Rule', 'text')

A.38 Update En Passant (Function)

Built in Chapter 5, The End of the Game.

FunctionUpdate En Passant

Keeps en passant up to date for one Move, before the Move is made. A Pawn moving onto the en passant Square takes the enemy Pawn that passed over it. Then the en passant Square is set for the next Move: the Square a Pawn passes over with a two-Square Move, else empty. gameRules: the Game Rules Object, whose Board State holds the en passant Square. from and to: the Squares of the Move (a1 to h8).

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
fromText
toText
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Declare Variable
Name
fromFile
Value
0
3Declare Variable
Name
fromRank
Value
0
4Declare Variable
Name
toFile
Value
0
5Declare Variable
Name
toRank
Value
0
6Declare Variable
Name
passedPawn
Value
0
7Declare Variable
Name
passedRank
Value
0
8Declare Variable
Type
Text
Name
passedSquare
9Change Variable
Variable
kind
Value
data('Position', from, 'kind')
10Change Variable
Variable
fromFile
Value
data('Position', from, 'file')
11Change Variable
Variable
fromRank
Value
data('Position', from, 'rank')
12Change Variable
Variable
toFile
Value
data('Position', to, 'file')
13Change Variable
Variable
toRank
Value
data('Position', to, 'rank')
14Ifkind == "Pawn" && to == gameRules.boardState.enPassantSquare
Then
15Change Variable
Variable
passedPawn
Value
(fromRank - 1) * 8 + (toFile - 1)
16Set Data Cell
Table
Position
Row
passedPawn
Column
'kind'
Value
''
17Set Data Cell
Table
Position
Row
passedPawn
Column
"side"
Value
''
18Change Component Value
Component Value
gameRules.boardState.enPassantSquare
Value
''
19Ifkind == "Pawn" && abs(toRank - fromRank) == 2
Then
20Change Variable
Variable
passedRank
Value
(fromRank + toRank) / 2
21Change Variable
Variable
passedSquare
Value
dataRow('Position', (passedRank - 1) * 8 + (fromFile - 1))
22Change Component Value
Component Value
gameRules.boardState.enPassantSquare
Value
passedSquare

A.39 Close New Game

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentClose New Game

What the Cancel button of the New Game panel does: it closes the panel and the game goes on as it was.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
New Game Panel

A.40 Flip Board

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentFlip BoardAttach to: Game Rules

Turns the Board over for viewing when the Player presses Flip ("flipPressed"), or back again; once everyone has heard "boardFlipped", it tells its own Object "flipFinished", so Save The Game saves the game the new way round. Only the way the Board is drawn changes (Board State's isFlipped): the position, the Turn, and the Player's Side stay as they are. Then it tells everyone "boardFlipped", so every Piece, Square, Move Mark, and label shows itself the new way round. When the Board has been laid out ("boardLaidOut"), it tells everyone "boardFlipped" too, so everything is shown the way round the Board is drawn.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
On Flip Pressed
WhenflipPressedCustom Event
1Ifself.boardState.isFlipped == true
Then
2Change Component Value
Component Value
self.boardState.isFlipped
Value
false
3Otherwise
4Change Component Value
Component Value
self.boardState.isFlipped
Value
true
5Trigger Custom Event
Custom Event
boardFlipped
6Trigger Custom Event on Object
Custom Event
flipFinished
On Board Laid Out
WhenboardLaidOutCustom Event
1Trigger Custom Event
Custom Event
boardFlipped

A.41 New Game

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentNew GameAttach to: Game Rules

Starts every game with the Side and the Strength the Player chose last, and lets the Player start a new game. When the game begins (Game Start, before the first Turn), it takes the choices saved on this device (the Strength through Use The Last Strength, which it uses again when a saved game has been brought back, "savedGameLoaded") (Persistent Values), when the game has them (the Sides and Strengths tables; otherwise, and the first time, Board State's own playerSide and strength), turns the Board over for a Player who plays Black, and tells everyone "gameStarted". When the Player presses New Game ("newGamePressed"), it opens the New Game panel, a menu that holds the game while it is open, showing the current choices as chosen and asking "Replace the current game?" when a game is in progress and has Moves. Each Side or Strength pressed ("sideChosen", "strengthChosen"; the button is its Other) becomes the chosen one. Play ("playPressed") saves the choices, forgets the saved game (the slot "auto"), and restarts the game, which starts again from the beginning with them.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
When the Game Starts
WhenGame Start
1Load Persistent Value
Action Name
savedSide
Key
"playerSide"
Default
self.boardState.playerSide
2Check Data Row Exists
Action Name
isKnownSide
Table
Sides
Row
savedSide.value
3IfisKnownSide.value == true
Then
4Change Component Value
Component Value
self.boardState.playerSide
Value
savedSide.value
5Use The Last StrengthFunction
gameRules
self
6Ifself.boardState.playerSide == "Black"
Then
7Change Component Value
Component Value
self.boardState.isFlipped
Value
true
8Trigger Custom Event
Custom Event
gameStarted
On New Game Pressed
WhennewGamePressedCustom Event
1Change Component Value
Component Value
self.boardState.chosenSide
Value
self.boardState.playerSide
2Change Component Value
Component Value
self.boardState.chosenStrength
Value
self.boardState.strength
3Control Menu
Menu Element
New Game Panel
4Set Menu Pause State
Menu Element
New Game Panel
5Check Game State
Action Name
isOver
Game State
Game Over
6Ifself.boardState.lastFrom != "" && isOver.value == false
Then
7Set UI Element Visibility
Element
Replace Question
8Otherwise
9Set UI Element Visibility
Element
Replace Question
Visible
No
10Trigger Custom Event
Custom Event
choiceChanged
On Side Chosen
WhensideChosenCustom Event
1Change Component Value
Component Value
self.boardState.chosenSide
Value
other.panelOption.option
2Trigger Custom Event
Custom Event
choiceChanged
On Strength Chosen
WhenstrengthChosenCustom Event
1Change Component Value
Component Value
self.boardState.chosenStrength
Value
other.panelOption.option
2Trigger Custom Event
Custom Event
choiceChanged
On Play Pressed
WhenplayPressedCustom Event
1Save Persistent Value
Action Name
persistentWriteResult
Key
"playerSide"
Value
self.boardState.chosenSide
2Save Persistent Value
Action Name
persistentWriteResult2
Key
"strength"
Value
self.boardState.chosenStrength
3Delete Save
Slot
"auto"
4Restart Game
On Saved Game Loaded
WhensavedGameLoadedCustom Event
1Use The Last StrengthFunction
gameRules
self

A.42 Place On Board

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentPlace On BoardAttach to: Piece, Rank Label, File Label, Square, Move Mark, Threat Mark, Pin Mark

Keeps this Object on its Square (Square Info) when the Board is turned over: when the Game Rules say "boardFlipped" (they are its Other), it moves to where its Square is now drawn (Square Position). The Piece, the Square, the Move Mark, the Threat Mark, and the Pin Mark of each Square all use it. squareMeters: how wide one Square is (3.75 m: the Board art is 30 m across). boardLeft and boardBottom: where the Board's bottom-left corner is in the world (0 and 4.375 m: the game window is 140 px taller than the Board, for the status line and the buttons under it).

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
SHARED VARIABLES
NameTypeKindStarting Value
squareMetersNumberConstant3.75
boardLeftNumberConstant0
boardBottomNumberConstant4.375
On Board Flipped
WhenboardFlippedCustom Event
1Declare Variable
Type
Boolean
Name
isFlipped
Value
false
2Change Variable
Variable
isFlipped
Value
other.boardState.isFlipped
3Square PositionFunction
Action Name
mySquare
square
self.squareInfo.name
isFlipped
isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
4Set Position
X
mySquare.x
Y
mySquare.y

A.43 Report Flip

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentReport Flip

What the Flip button does: it tells whoever listens (the Game Rules) with "flipPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
flipPressed

A.44 Report New Game

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentReport New Game

What the New Game button does: it tells whoever listens (the Game Rules) with "newGamePressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
newGamePressed

A.45 Report Play

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentReport Play

What the Play button of the New Game panel does: it tells whoever listens (the Game Rules) with "playPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
playPressed

A.46 Report Side

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentReport Side

What a Side button of the New Game panel does (White or Black): it tells whoever listens (the Game Rules) with "sideChosen"; the listener reads the button's Panel Option as Other.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
sideChosen

A.47 Report Strength

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentReport Strength

What a Strength button of the New Game panel does (Gentle to Expert): it tells whoever listens (the Game Rules) with "strengthChosen"; the listener reads the button's Panel Option as Other.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
strengthChosen

A.48 Show Option

Built in Chapter 6, New Game, Side and Flip.

Logic ComponentShow OptionAttach to: Option Button

Marks this option of a panel (New Game or Settings) when it is chosen, whenever the choice changes (the Game Rules send "choiceChanged" and are its Other): the Side or the Strength the panel shows as chosen, the Board Finish, or the Piece Set. chosenColor: the color of a chosen option. plainColor: the color of the others.

Attach toAny Object
DATA STRUCTURES
Panel Optionself.panelOption
SHARED VARIABLES
NameTypeKindStarting Value
chosenColorColorConstant#a9c79b
plainColorColorConstant#e2d5b4
On Choice Changed
WhenchoiceChangedCustom Event
1Declare Variable
Type
Text
Name
myOption
2Change Variable
Variable
myOption
Value
self.panelOption.option
3IfmyOption == other.boardState.chosenSide || myOption == other.boardState.chosenStrength || myOption == other.boardState.boardFinish || myOption == other.boardState.pieceSet
Then
4Change Sprite Tint Property
Value
@self.chosenColor
5Otherwise
6Change Sprite Tint Property
Value
@self.plainColor

A.49 Ask The Computer (Function)

Built in Chapter 7, The Computer.

FunctionAsk The Computer

Asks the Computer for its Move: the Board waits (Game State Computer's Turn), the status line says the Computer is thinking, and the Stockfish Bridge (a Library of code) asks Stockfish for a Move at the Strength in Board State; it answers with "computerMoveChosen". The named timer answerWait rings once if no answer has come in time: the Strength's thinking time plus spareSeconds. gameRules: the Game Rules Object. spareSeconds: how much longer than its thinking time the Computer may take to answer, starting Stockfish included.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
spareSecondsNumber20
ACTIONS
1Declare Variable
Name
waitSeconds
Value
0
2Set Game State
Game State
Computer's Turn
3Change Variable
Variable
$status
Value
data('Words', 'Thinking', 'text')
4Run Code (JS)
Applies to
gameRules
Java Script
lib.ext.stockfishBridge.chooseComputerMove(api, ctx.self);
5Change Variable
Variable
waitSeconds
Value
data('Strengths', gameRules.boardState.strength, 'thinkingSeconds')
6Change Variable
Variable
waitSeconds
Operator
+=
Value
spareSeconds
7Start Recurring Timer
Applies to
gameRules
Timer Name
"answerWait"
Repeat Every (s)
waitSeconds
Ring Once
true

A.50 Can Undo (Function)

Built in Chapter 7, The Computer.

FunctionCan Undo

Asks whether the Undo button can be used: once a Move has been made (the Move History has a row). isOn (returned): true when it can.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isOn
Value
false
2IfdataCount('Move History') > 0
Then
3Change Variable
Variable
isOn
Value
true
4Return
Value
isOn

A.51 Go Back To The Start (Function)

Built in Chapter 7, The Computer.

FunctionGo Back To The Start

Puts the game back as it is when a game starts: the starting position, every castling allowed again, no position seen yet, and nothing marked (the tables as they were made), and Board State as a game starts: White to move, no en passant Square, no Moves counted for the fifty-move rule, no last Move, and nothing selected or inspected. gameRules: the Game Rules Object.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Reset Data Table
Table
Position
2Reset Data Table
Table
Castling
3Reset Data Table
Table
Position History
4Clear TargetsFunction
5Change Component Value
Component Value
gameRules.boardState.sideToMove
Value
'White'
6Change Component Value
Component Value
gameRules.boardState.enPassantSquare
Value
''
7Change Component Value
Component Value
gameRules.boardState.fiftyMoveCount
Value
0
8Change Component Value
Component Value
gameRules.boardState.lastFrom
Value
''
9Change Component Value
Component Value
gameRules.boardState.lastTo
Value
''
10Change Component Value
Component Value
gameRules.boardState.selected
Value
''
11Change Component Value
Component Value
gameRules.boardState.inspected
Value
''

A.52 Make Computer Move

Built in Chapter 7, The Computer.

Logic ComponentMake Computer MoveAttach to: Game Rules

Plays the Computer's Turns. When a Turn goes on ("gameContinues", from Look For Game End) and the Side to move is the Player's opponent (the Sides table), it asks the Computer for a Move (Ask The Computer: the Board waits in Computer's Turn while the Stockfish Bridge asks Stockfish at the Strength in Board State). When Stockfish answers ("computerMoveChosen"; the Move is in the Chosen Moves table) and it is still the Computer's Turn and the Move is a Legal Move, the Move slides first (Plan The Slide fills the Slides table; everyone hears "slideStarted"). When it has landed ("pieceLanded", from the Moving Piece), it is made if it is still the Computer's Turn, the way the Player's Moves are made: Record Move, Make Move, the Kind it lands as (a promoted Pawn becomes the Kind Stockfish named), then "moveMade" (Start Turn starts the Player's Turn) and "positionChanged". When Stockfish gives no Move, or one that is not legal, or does not answer within its thinking time and spareSeconds more (the answerWait timer), the position stays and the Computer is marked unavailable (Mark Computer Unavailable) until the Player presses Retry ("retryPressed"), which asks again. spareSeconds: how much longer than its thinking time the Computer may take to answer, starting Stockfish included. A Player whose device asks for less motion (the system setting "reduce motion", the Myth Global prefersReducedMotion) sees the Move made at once, with no slide.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Make Computer Move Dataself.makeComputerMoveData
SHARED VARIABLES
NameTypeKindStarting Value
spareSecondsNumberConstant20
On Game Continues
WhengameContinuesCustom Event
1Ifself.boardState.sideToMove == data('Sides', self.boardState.playerSide, 'opponent')
Then
2Ask The ComputerFunction
gameRules
self
spareSeconds
@self.spareSeconds
On Computer Move Chosen
WhencomputerMoveChosenCustom Event
1Check Game State
Action Name
isThinking
Game State
Computer's Turn
2IfisThinking.value == true
Then
3Stop Recurring Timer
Timer Name
"answerWait"
4Change Component Value
Component Value
self.makeComputerMoveData.fromSquare
Value
data('Chosen Moves', 'Computer', 'from')
5Change Component Value
Component Value
self.makeComputerMoveData.toSquare
Value
data('Chosen Moves', 'Computer', 'to')
6Find Legal MovesFunction
from
self.makeComputerMoveData.fromSquare
enPassantSquare
self.boardState.enPassantSquare
7Ifdata('Targets', self.makeComputerMoveData.toSquare, 'reachable') == true
Then
8If$prefersReducedMotion == 1
Then
9Trigger Custom Event on Object
Custom Event
pieceLanded
10Otherwise
11Plan The SlideFunction
from
self.makeComputerMoveData.fromSquare
to
self.makeComputerMoveData.toSquare
12Trigger Custom Event
Custom Event
slideStarted
13Otherwise
14Clear TargetsFunction
15Mark Computer UnavailableFunction
gameRules
self
On Piece Landed
WhenpieceLandedCustom Event
1Check Game State
Action Name
isLanding
Game State
Computer's Turn
2IfisLanding.value == true
Then
3Change Component Value
Component Value
self.makeComputerMoveData.fromSquare
Value
data('Chosen Moves', 'Computer', 'from')
4Change Component Value
Component Value
self.makeComputerMoveData.toSquare
Value
data('Chosen Moves', 'Computer', 'to')
5Change Component Value
Component Value
self.makeComputerMoveData.landingKind
Value
data('Chosen Moves', 'Computer', 'landingKind')
6Set Game State
Game State
Playing
7Record MoveFunction
gameRules
self
from
self.makeComputerMoveData.fromSquare
to
self.makeComputerMoveData.toSquare
landingKind
self.makeComputerMoveData.landingKind
8Make MoveFunction
gameRules
self
from
self.makeComputerMoveData.fromSquare
to
self.makeComputerMoveData.toSquare
9Set Data Cell
Table
Position
Row
self.makeComputerMoveData.toSquare
Column
"kind"
Value
self.makeComputerMoveData.landingKind
10Trigger Custom Event on Object
Custom Event
moveMade
11Trigger Custom Event
Custom Event
positionChanged
On the Answer Wait Timer
WhenRecurring TimerTimer name: answerWait
1Check Game State
Action Name
isStillThinking
Game State
Computer's Turn
2IfisStillThinking.value == true
Then
3Mark Computer UnavailableFunction
gameRules
self
On Retry Pressed
WhenretryPressedCustom Event
1Check Game State
Action Name
isUnavailable
Game State
Computer Unavailable
2IfisUnavailable.value == true
Then
3Ask The ComputerFunction
gameRules
self
spareSeconds
@self.spareSeconds

A.53 Mark Computer Unavailable (Function)

Built in Chapter 7, The Computer.

FunctionMark Computer Unavailable

Gives up waiting for the Computer: the game keeps its position and waits for the Player to press Retry (Game State Computer Unavailable, which shows the message and its Retry button), and the status line says the opponent is disconnected. gameRules: the Game Rules Object.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Stop Recurring Timer
Applies to
gameRules
Timer Name
"answerWait"
2Set Game State
Game State
Computer Unavailable
3Change Variable
Variable
$status
Value
data('Words', 'Disconnected', 'text')

A.54 Pass The Turn (Function)

Built in Chapter 7, The Computer.

FunctionPass The Turn

Gives the Turn to the other Side (the Sides table's opponent column). gameRules: the Game Rules Object, whose Board State holds whose Turn it is (sideToMove).

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Declare Variable
Type
Text
Name
side
2Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
3Change Component Value
Component Value
gameRules.boardState.sideToMove
Value
data('Sides', side, 'opponent')

A.55 Plan The Slide (Function)

Built in Chapter 7, The Computer.

FunctionPlan The Slide

Writes where the Pieces of one Move slide, before the Move is made (the Slides table): the Piece from its Square to the new one, and, when the Move is a castling, the Rook too, as the Castling table says. from and to: the Squares the Piece moves from and to.

PARAMETERS
fromText
toText
ACTIONS
1Declare Variable
Type
Text
Name
kind
2Declare Variable
Type
Text
Name
rookFrom
3Declare Variable
Type
Text
Name
rookTo
4Change Variable
Variable
kind
Value
data('Position', from, 'kind')
5Reset Data Table
Table
Slides
6Set Data Cell
Table
Slides
Row
"Piece"
Column
'from'
Value
from
7Set Data Cell
Table
Slides
Row
"Piece"
Column
'to'
Value
to
8RepeatdataCount('Castling')times
Each time
9Ifkind == "King" && data('Castling', local.index, 'kingFrom') == from && data('Castling', local.index, 'kingTo') == to
Then
10Change Variable
Variable
rookFrom
Value
data('Castling', local.index, 'rookFrom')
11Change Variable
Variable
rookTo
Value
data('Castling', local.index, 'rookTo')
12Set Data Cell
Table
Slides
Row
"Rook"
Column
'from'
Value
rookFrom
13Set Data Cell
Table
Slides
Row
"Rook"
Column
'to'
Value
rookTo

A.56 Record Move (Function)

Built in Chapter 7, The Computer.

FunctionRecord Move

Writes a Move at the end of the Move History table just before it is made: the Squares it goes from and to, the Kind the Piece lands as (its own Kind, or the Kind a promoted Pawn becomes), and its name as chess players write it (Name The Move), which depends on the position before the Move. Each Logic that makes a Move calls it just before Make Move (Select and Move, Choose Promotion, Make Computer Move). gameRules: the Game Rules Object, whose Board State holds the en passant Square. from, to: the Move's Squares. landingKind: the Kind the Piece lands as.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
fromText
toText
landingKindText
ACTIONS
1Declare Variable
Name
lastRow
Value
0
2Control Data Row
Action Name
addedRow
Table
Move History
Row
dataCount('Move History')
3Change Variable
Variable
lastRow
Value
dataCount('Move History') - 1
4Set Data Cell
Table
Move History
Row
lastRow
Column
'from'
Value
from
5Set Data Cell
Table
Move History
Row
lastRow
Column
'to'
Value
to
6Set Data Cell
Table
Move History
Row
lastRow
Column
'landingKind'
Value
landingKind
7Name The MoveFunction
from
from
to
to
landingKind
landingKind
enPassantSquare
gameRules.boardState.enPassantSquare
row
lastRow

A.57 Report Retry

Built in Chapter 7, The Computer.

Logic ComponentReport Retry

What the Retry button does: it tells whoever listens (the Game Rules) with "retryPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
retryPressed

A.58 Report Undo

Built in Chapter 7, The Computer.

Logic ComponentReport Undo

What the Undo button does: it tells whoever listens (the Game Rules) with "undoPressed". After every change on the Board ("positionChanged"), which the Game Rules also send when the game begins, it asks Can Undo whether the button can be used now, and turns it on or off (Show Button On Or Off).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
undoPressed
On Position Changed
WhenpositionChangedCustom Event
1Can UndoFunction
Action Name
canUse
2Show Button On Or OffFunction
button
self
isOn
canUse.value

A.59 Show Button On Or Off (Function)

Built in Chapter 7, The Computer.

FunctionShow Button On Or Off

Turns a button on or off: while it can be used (isOn) it answers presses and is drawn as usual; otherwise it takes no presses and is drawn faded. Each button that is sometimes off calls it after every change on the Board, with the answer of its own Can ... Function (the Undo button: Can Undo). button: the button. isOn: whether it can be used now. offAlpha: how see-through the button is drawn while it is off, from 0 (invisible) to 1 (solid).

PARAMETERS
NameTypeStarts at
buttonObjectStructural
Required Components
Slot Nameui
Component TypeUI Interaction
isOnBooleanNo
offAlphaNumber0.3
ACTIONS
1IfisOn == true
Then
2Change Component Value
Component Value
button.ui.enabled
Value
true
3Set Alpha
Applies to
button
Alpha
1
4Otherwise
5Change Component Value
Component Value
button.ui.enabled
Value
false
6Set Alpha
Applies to
button
Alpha
offAlpha

A.60 Show Unavailable Message

Built in Chapter 7, The Computer.

Logic ComponentShow Unavailable MessageAttach to: Unavailable Message

Shows the message "Opponent unavailable." and its Retry button (the UI Group "Computer Unavailable") exactly while the Game State is Computer Unavailable, and hides them otherwise.

Attach toAny Object
On Game State Changed
WhenGame State Changed
1Check Game State
Action Name
isUnavailable
Game State
Computer Unavailable
2IfisUnavailable.value == true
Then
3Set UI Group Visibility
UI Group
"Computer Unavailable"
4Otherwise
5Set UI Group Visibility
UI Group
"Computer Unavailable"
Visible
No

A.61 Slide Piece

Built in Chapter 7, The Computer.

Logic ComponentSlide PieceAttach to: Moving Piece

Slides one Piece of the Computer's Move across the Board before the Move is made. When the Game Rules say "slideStarted" (they are its Other), it reads its row of the Slides table: if the row names a Square, it shows the Piece standing there, in the Piece Set chosen, and glides from that Square to the row's other Square in slideSeconds, starting and ending slowly. The Moving Piece that says so (saysWhenLanded) then tells the Game Rules "pieceLanded", and they make the Move; the next "positionChanged" hides it again. While it slides, a Board turned over or back ("boardFlipped") ends the slide at once (Event Logic Land At Once): the Move is made, drawn the new way round; and another Piece Set chosen meanwhile ("lookChanged") shows on it at once (Show The New Piece Set); between slides a turned Board changes nothing here (Stay Hidden). slide: which row of the Slides table it follows (Piece, or Rook for a castling). slideSeconds: how long the slide takes. saysWhenLanded: true for the one Moving Piece that says when the slide is over (a King and its Rook land together). squareMeters, boardLeft, and boardBottom: where the Squares are (as for Place On Board).

Attach toAny Object
DATA STRUCTURES
Slide Piece Dataself.slidePieceData
SHARED VARIABLES
NameTypeKindStarting Value
slideSecondsNumberConstant0.36
squareMetersNumberConstant3.75
boardLeftNumberConstant0
boardBottomNumberConstant4.375
PER INSTANCE VARIABLES
NameTypeStarting Value
slideTextPiece
saysWhenLandedBooleanYes
On Slide Started
WhenslideStartedCustom Event
1Declare Variable
Type
Text
Name
toSquare
2Declare Variable
Type
Text
Name
fromSquare
3Change Variable
Variable
fromSquare
Value
data('Slides', self.slide, 'from')
4Change Variable
Variable
toSquare
Value
data('Slides', self.slide, 'to')
5IffromSquare != ""
Then
6Change Component Value
Component Value
self.slidePieceData.isFlipped
Value
other.boardState.isFlipped
7Square PositionFunction
Action Name
startSquare
square
fromSquare
isFlipped
self.slidePieceData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
8Square PositionFunction
Action Name
endSquare
square
toSquare
isFlipped
self.slidePieceData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
9Change Component Value
Component Value
self.slidePieceData.kind
Value
data('Position', fromSquare, 'kind')
10Change Component Value
Component Value
self.slidePieceData.side
Value
data('Position', fromSquare, 'side')
11Show Piece SetFunction
piece
self
pieceSet
other.boardState.pieceSet
12Set Frame
Frame
data('Kinds', self.slidePieceData.kind, self.slidePieceData.side)
13Set Position
X
startSquare.x
Y
startSquare.y
14Set Visible
Visible
Yes
15Switch Mode
Event
On Board Flipped
Mode
Land At Once
16Switch Mode
Event
On Look Changed
Mode
Show The New Piece Set
17Tween
Value
self.transform.position.x
Target
endSquare.x
Duration
@self.slideSeconds
Ease
Sine in Out
18Tween
Value
self.transform.position.y
Target
endSquare.y
Duration
@self.slideSeconds
Ease
Sine in Out
19Otherwise
20Return
21Ifself.saysWhenLanded == true
Then
22Start Recurring Timer
Timer Name
"landing"
Repeat Every (s)
@self.slideSeconds
Ring Once
Yes
On the Landing Timer
WhenRecurring TimerTimer name: landing
1Trigger Custom Event
Custom Event
pieceLanded
On Position Changed
WhenpositionChangedCustom Event
1Set Visible
Visible
No
2Stop Recurring Timer
Timer Name
"landing"
3Switch Mode
Event
On Board Flipped
Mode
Stay Hidden
4Switch Mode
Event
On Look Changed
Mode
Stay Hidden
On Board Flipped
WhenboardFlippedCustom Event
ModeStay Hidden (Starting Mode)
(no Actions)
On Board Flipped
WhenboardFlippedCustom Event
ModeLand At Once
1Ifself.saysWhenLanded == true
Then
2Trigger Custom Event
Custom Event
pieceLanded
On Look Changed
WhenlookChangedCustom Event
ModeStay Hidden (Starting Mode)
(no Actions)
On Look Changed
WhenlookChangedCustom Event
ModeShow The New Piece Set
1Show Piece SetFunction
piece
self
pieceSet
other.boardState.pieceSet
2Set Frame
Frame
data('Kinds', self.slidePieceData.kind, self.slidePieceData.side)

A.62 Start The Turn (Function)

Built in Chapter 7, The Computer.

FunctionStart The Turn

Starts the Turn of the Side to move, in the position on the Board: marks a King in Check and sets the status line (Look For Check), marks the Move that gave Check with + in the Move History, then tells the Game Rules "turnStarted" (Look For Game End asks whether the game is over; if it goes on, Make Computer Move asks whether it is the Computer's Turn). gameRules: the Game Rules Object.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Look For CheckFunction
gameRules
gameRules
2IfgameRules.boardState.checkSquare != "" && dataCount('Move History') > 0
Then
3Set Data Cell
Table
Move History
Row
dataCount('Move History') - 1
Column
"checkMark"
Value
data('Words', 'Check Mark', 'text')
4Trigger Custom Event on Object
Applies to
gameRules
Custom Event
turnStarted

A.63 Take Back Moves (Function)

Built in Chapter 7, The Computer.

FunctionTake Back Moves

Takes back every Move after the first movesKept Moves: they leave the Move History, the game goes back to its start (Go Back To The Start), and the Moves kept are made again in order, as the game made them, with the position of each Turn recorded first (as at the start of every Turn) so threefold repetition still counts them. Castling, en passant, Promotion, and the fifty-move count come back as they were, because every Move is made with Make Move. gameRules: the Game Rules Object. movesKept: how many Moves, from the first, stay made.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
movesKeptNumber0
ACTIONS
1Declare Variable
Type
Text
Name
movedFrom
2Declare Variable
Type
Text
Name
movedTo
3Declare Variable
Type
Text
Name
landingKind
4RepeatdataCount('Move History') - movesKepttimes
Each time
5Control Data Row
Action Name
addedRow
Operation
Remove
Table
Move History
Row
dataCount('Move History') - 1
6Go Back To The StartFunction
gameRules
gameRules
7RepeatmovesKepttimes
Each time
8Change Variable
Variable
movedFrom
Value
data('Move History', local.index, 'from')
9Change Variable
Variable
movedTo
Value
data('Move History', local.index, 'to')
10Change Variable
Variable
landingKind
Value
data('Move History', local.index, 'landingKind')
11Record PositionFunction
gameRules
gameRules
12Make MoveFunction
gameRules
gameRules
from
movedFrom
to
movedTo
13Set Data Cell
Table
Position
Row
movedTo
Column
"kind"
Value
landingKind
14Pass The TurnFunction
gameRules
gameRules

A.64 Undo

Built in Chapter 7, The Computer.

Logic ComponentUndoAttach to: Game Rules

Takes back the Player's last Turn when the Player presses Undo ("undoPressed"): the Computer's reply and the Player's Move before it, or only the Player's Move when the Computer has not replied (it is still thinking, or the game ended on that Move). Then that Turn starts again, as play went: a finished game is played again, and if the Turn is the Computer's (a Player who plays Black, back at the start), the Computer moves again. A Stockfish answer still on its way counts for nothing, because the Game State is no longer Computer's Turn. Undo answers only when a Move has been made, and not while the Promotion choice or a menu (the New Game panel) is open. Undo forgets the Hint (Forget The Hint).

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Undo Dataself.undoData
On Undo Pressed
WhenundoPressedCustom Event
1IfdataCount('Move History') > 0
Then
2Forget The HintFunction
3Change Component Value
Component Value
self.undoData.movesKept
Value
dataCount('Move History') - 1
4Ifself.boardState.sideToMove == self.boardState.playerSide && self.undoData.movesKept > 0
Then
5Change Component Value
Component Value
self.undoData.movesKept
Operator
-=
Value
1
6Take Back MovesFunction
gameRules
self
movesKept
self.undoData.movesKept
7Set Game State
Game State
Playing
8Start The TurnFunction
gameRules
self
9Trigger Custom Event
Custom Event
positionChanged

A.65 Can Ask For A Hint (Function)

Built in Chapter 8, The Hint.

FunctionCan Ask For A Hint

Asks whether the Hint button can be used: on the Player's Turn in a game that goes on (Game State Playing). isOn (returned): true when it can.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isOn
Value
false
2Check Game State
Action Name
isPlaying
Game State
Playing
3IfisPlaying.value == true
Then
4Change Variable
Variable
isOn
Value
true
5Return
Value
isOn

A.66 Forget The Hint (Function)

Built in Chapter 8, The Hint.

FunctionForget The Hint

Forgets the Hint: the Chosen Moves table's row Hint is emptied, so no Square shows it any more (the Squares redraw on the next "positionChanged").

ACTIONS
1Set Data Cell
Table
Chosen Moves
Row
"Hint"
Column
"from"
Value
''
2Set Data Cell
Table
Chosen Moves
Row
"Hint"
Column
"to"
Value
''
3Set Data Cell
Table
Chosen Moves
Row
"Hint"
Column
"landingKind"
Value
''

A.67 Give A Hint

Built in Chapter 8, The Hint.

Logic ComponentGive A HintAttach to: Game Rules

Gives the Player a Hint. When the Hint button is pressed ("hintPressed") on the Player's Turn (Game State Playing), the selection is cleared, the Board waits (Game State Finding A Hint), the status line says a Hint is being found, and the Stockfish Bridge asks Stockfish for a Move at the Hint Strength (the Hint Strength table). When Stockfish answers ("hintChosen"; the Move is in the Chosen Moves table, row Hint) and the Move is a Legal Move, the game is played again, the status line shows the Turn again (Look For Check), everyone hears "hintFound" (the Hint message shows it), and the Squares redraw ("positionChanged") with the Hint marked. When the Move is not legal, is empty, or has not come within the Hint's thinking time and spareSeconds more (the hintWait timer), no Hint is shown (Mark Hint Not Found). spareSeconds: how much longer than its thinking time Stockfish may take to answer, starting Stockfish included. When a saved game is brought back while a Hint was being found ("savedGameLoaded"), the Player's Turn goes on without it.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Give A Hint Dataself.giveAHintData
SHARED VARIABLES
NameTypeKindStarting Value
spareSecondsNumberConstant20
On Hint Pressed
WhenhintPressedCustom Event
1Check Game State
Action Name
isPlaying
Game State
Playing
2IfisPlaying.value == true
Then
3Change Component Value
Component Value
self.boardState.selected
Value
''
4Clear TargetsFunction
5Forget The HintFunction
6Set Game State
Game State
Finding A Hint
7Change Variable
Variable
$status
Value
data('Words', 'Finding Hint', 'text')
8Run Code (JS)
Java Script
lib.ext.stockfishBridge.chooseHint(api, ctx.self);
9Change Component Value
Component Value
self.giveAHintData.waitSeconds
Value
data('Hint Strength', 'Hint', 'thinkingSeconds')
10Change Component Value
Component Value
self.giveAHintData.waitSeconds
Operator
+=
Value
@self.spareSeconds
11Start Recurring Timer
Timer Name
"hintWait"
Repeat Every (s)
self.giveAHintData.waitSeconds
Ring Once
Yes
12Trigger Custom Event
Custom Event
positionChanged
On Hint Chosen
WhenhintChosenCustom Event
1Check Game State
Action Name
isFinding
Game State
Finding A Hint
2IfisFinding.value == true
Then
3Stop Recurring Timer
Timer Name
"hintWait"
4Change Component Value
Component Value
self.giveAHintData.fromSquare
Value
data('Chosen Moves', 'Hint', 'from')
5Change Component Value
Component Value
self.giveAHintData.toSquare
Value
data('Chosen Moves', 'Hint', 'to')
6Find Legal MovesFunction
from
self.giveAHintData.fromSquare
enPassantSquare
self.boardState.enPassantSquare
7Ifdata('Targets', self.giveAHintData.toSquare, 'reachable') == true
Then
8Clear TargetsFunction
9Set Game State
Game State
Playing
10Look For CheckFunction
gameRules
self
11Trigger Custom Event
Custom Event
hintFound
12Trigger Custom Event
Custom Event
positionChanged
13Otherwise
14Clear TargetsFunction
15Mark Hint Not FoundFunction
gameRules
self
16Otherwise
17Forget The HintFunction
On the Hint Wait Timer
WhenRecurring TimerTimer name: hintWait
1Check Game State
Action Name
isStillFinding
Game State
Finding A Hint
2IfisStillFinding.value == true
Then
3Mark Hint Not FoundFunction
gameRules
self
On Saved Game Loaded
WhensavedGameLoadedCustom Event
1Check Game State
Action Name
wasFindingHint
Game State
Finding A Hint
2IfwasFindingHint.value == true
Then
3Set Game State
Game State
Playing
4Look For CheckFunction
gameRules
self

A.68 Mark Hint Not Found (Function)

Built in Chapter 8, The Hint.

FunctionMark Hint Not Found

Gives up on the Hint: nothing is marked, the game is played again (Game State Playing), and the status line says that no Hint could be found. gameRules: the Game Rules Object.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Stop Recurring Timer
Applies to
gameRules
Timer Name
"hintWait"
2Forget The HintFunction
3Set Game State
Game State
Playing
4Change Variable
Variable
$status
Value
data('Words', 'Hint Not Found', 'text')
5Trigger Custom Event
Custom Event
positionChanged

A.69 Open Promotion Choice (Function)

Built in Chapter 8, The Hint.

FunctionOpen Promotion Choice

Opens the Promotion choice for a Pawn that is about to reach its last Rank: the Board waits (Game State Promotion), the status line asks for the Piece, and the Promotion panel is shown; Choose Promotion then makes the Move. gameRules: the Game Rules Object. square: the Square the Pawn will be promoted on.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
squareText
ACTIONS
1Change Component Value
Component Value
gameRules.boardState.promotionSquare
Value
square
2Change Variable
Variable
$status
Value
data('Words', 'Promotion', 'text')
3Set UI Group Visibility
UI Group
"Promotion"
4Set Game State
Game State
Promotion

A.70 Report Hint

Built in Chapter 8, The Hint.

Logic ComponentReport Hint

What the Hint button does: it tells whoever listens (the Game Rules) with "hintPressed". After every change on the Board ("positionChanged"), which the Game Rules also send when the game begins, it asks Can Ask For A Hint whether the button can be used now, and turns it on or off (Show Button On Or Off).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
hintPressed
On Position Changed
WhenpositionChangedCustom Event
1Can Ask For A HintFunction
Action Name
canUse
2Show Button On Or OffFunction
button
self
isOn
canUse.value

A.71 Show Hint Message

Built in Chapter 8, The Hint.

Logic ComponentShow Hint MessageAttach to: Hint Message

Shows the Hint message ("Try e2 to e4.", with ", promote to queen" when the Move promotes a Pawn) for showSeconds when a Hint has been found ("hintFound"), then hides it. The Move is read from the Chosen Moves table (row Hint) into the message's own Hint Words, which its words show. showSeconds: how long the message stays, in seconds.

Attach toAny Object
DATA STRUCTURES
Hint Wordsself.hintWords
COMPONENTS
self.uiUI Interaction
SHARED VARIABLES
NameTypeKindStarting Value
showSecondsNumberConstant4
On Hint Found
WhenhintFoundCustom Event
1Declare Variable
Type
Text
Name
landingKind
2Declare Variable
Type
Text
Name
fromSquare
3Change Variable
Variable
fromSquare
Value
data('Chosen Moves', 'Hint', 'from')
4Change Variable
Variable
landingKind
Value
data('Chosen Moves', 'Hint', 'landingKind')
5Change Component Value
Component Value
self.hintWords.from
Value
fromSquare
6Change Component Value
Component Value
self.hintWords.to
Value
data('Chosen Moves', 'Hint', 'to')
7Change Component Value
Component Value
self.hintWords.promotion
Value
''
8IflandingKind != data('Position', fromSquare, 'kind')
Then
9Change Component Value
Component Value
self.hintWords.promotion
Value
data('Kinds', landingKind, 'promotionWords')
10Set UI Element Visibility
11Start Recurring Timer
Timer Name
"messageTime"
Repeat Every (s)
@self.showSeconds
Ring Once
Yes
On the Message Time Timer
WhenRecurring TimerTimer name: messageTime
1Set UI Element Visibility
Visible
No

A.72 Can Capture (Function)

Built in Chapter 9, Threats.

FunctionCan Capture

Answers whether the Piece on one Square can legally capture an enemy Piece: the Capture must be one of its Moves, and must not leave its own King attacked. from: the capturing Piece's Square. to: the Square it moves to. taken: the Square of the Piece it takes (the same as to, except en passant). enPassantSquare: the en passant Square when the Capture may be en passant, else empty. canCapture (returned): yes when it can.

PARAMETERS
fromText
toText
takenText
enPassantSquareText
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Boolean
Name
canCapture
Value
false
4Change Variable
Variable
side
Value
data('Position', from, 'side')
5Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
6Find MovesFunction
from
from
7Find En Passant MoveFunction
from
from
enPassantSquare
enPassantSquare
8Ifdata('Targets', to, 'reachable') == true && data('Position', taken, 'side') == enemy
Then
9Find KingFunction
Action Name
kingLook
side
side
10Drop Move If UnsafeFunction
from
from
to
to
taken
taken
kingSquare
kingLook.value
enemy
enemy
11Ifdata('Targets', to, 'reachable') == true && data('Position', taken, 'side') == enemy
Then
12Change Variable
Variable
canCapture
Value
true
13Return
Value
canCapture

A.73 Can Recapture (Function)

Built in Chapter 9, Threats.

FunctionCan Recapture

Answers whether a Capture can be answered: the Piece on from legally captures, and then a Piece of the captured Side can legally capture back on the Square it moved to. Pinned Pieces cannot, since every Capture is a Legal Move. from: the capturing Piece's Square. to: the Square it moves to. taken: the Square of the Piece it takes (the same as to, except en passant). enPassantSquare: the en passant Square for an en passant Capture, else empty. canRecapture (returned): yes when the Capture can be made and answered.

PARAMETERS
fromText
toText
takenText
enPassantSquareText
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
takenKind
2Declare Variable
Type
Text
Name
defender
3Declare Variable
Type
Boolean
Name
canRecapture
Value
false
4Change Variable
Variable
takenKind
Value
data('Position', taken, 'kind')
5Change Variable
Variable
defender
Value
data('Position', taken, 'side')
6Can CaptureFunction
Action Name
captureLook
from
from
to
to
taken
taken
enPassantSquare
enPassantSquare
7IfcaptureLook.value == true
Then
8Set Data Cell
Table
Position
Row
taken
Column
"kind"
Value
''
9Set Data Cell
Table
Position
Row
taken
Column
"side"
Value
''
10Move PieceFunction
from
from
to
to
11Can Side CaptureFunction
Action Name
recaptureLook
square
to
bySide
defender
12Change Variable
Variable
canRecapture
Value
recaptureLook.value
13Move PieceFunction
from
to
to
from
14Set Data Cell
Table
Position
Row
taken
Column
"kind"
Value
takenKind
15Set Data Cell
Table
Position
Row
taken
Column
"side"
Value
defender
16Return
Value
canRecapture

A.74 Can Show Threats (Function)

Built in Chapter 9, Threats.

FunctionCan Show Threats

Asks whether the Threats button can be used: on the Player's Turn (Game State Playing) or once the game has ended (Game Over), when no Move is being made. isOn (returned): true when it can.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isOn
Value
false
2Check Game State
Action Name
isPlaying
Game State
Playing
3Check Game State
Action Name
isOver
Game State
Game Over
4IfisPlaying.value == true || isOver.value == true
Then
5Change Variable
Variable
isOn
Value
true
6Return
Value
isOn

A.75 Can Side Capture (Function)

Built in Chapter 9, Threats.

FunctionCan Side Capture

Answers whether any Piece of one Side can legally capture the enemy Piece on a Square (Can Capture, for each of its Pieces in turn until one can). square: the Square (a1 to h8). bySide: the capturing Side. canCapture (returned): yes when one can.

PARAMETERS
squareText
bySideText
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
piece
2Declare Variable
Type
Boolean
Name
canCapture
Value
false
3RepeatdataCount('Position')times
Each time
4Change Variable
Variable
piece
Value
dataRow('Position', local.index)
5Ifdata('Position', piece, 'side') == bySide && canCapture == false
Then
6Can CaptureFunction
Action Name
captureLook
from
piece
to
square
taken
square
enPassantSquare
''
7Change Variable
Variable
canCapture
Value
captureLook.value
8Return
Value
canCapture

A.76 Clear Threats (Function)

Built in Chapter 9, Threats.

FunctionClear Threats

Marks nothing on any Square: the Threats table is emptied, then gets one row for each Square of the Position table, a1 to h8 in the same order, every cell its column's default (no, or empty). The Threats table has no rows of its own; Clear Threats makes them, each time it is used.

ACTIONS
1Declare Variable
Type
Text
Name
square
2Reset Data Table
Table
Threats
3RepeatdataCount('Position')times
Each time
4Change Variable
Variable
square
Value
dataRow('Position', local.index)
5Control Data Row
Action Name
addedRow
Table
Threats
Row
square

A.77 Find First Piece Along (Function)

Built in Chapter 9, Threats.

FunctionFind First Piece Along

Looks back from one Square along one direction of the Directions table, Square by Square, and finds the first Piece in the way. square: the Square looked from (a1 to h8). direction: the row (0 = first) of the Directions table. bySide: the Side whose Pieces move this way (a Pawn's direction is turned round by its Side's forward). firstPiece (returned): the Square of the first Piece, or empty when the edge of the Board, or the end of the direction's steps, comes first.

PARAMETERS
NameTypeStarts at
squareText
directionNumber0
bySideText
RETURN TYPEText
ACTIONS
1Declare Variable
Name
forward
Value
1
2Declare Variable
Name
file
Value
0
3Declare Variable
Name
rank
Value
0
4Declare Variable
Name
stepsLeft
Value
0
5Declare Variable
Type
Boolean
Name
isOnBoard
Value
false
6Declare Variable
Name
index
Value
0
7Declare Variable
Type
Boolean
Name
keepLooking
Value
true
8Declare Variable
Type
Text
Name
firstPiece
9Change Variable
Variable
forward
Value
data('Sides', bySide, 'forward')
10Change Variable
Variable
file
Value
data('Position', square, 'file')
11Change Variable
Variable
rank
Value
data('Position', square, 'rank')
12Change Variable
Variable
stepsLeft
Value
data('Directions', direction, 'steps')
13WhilekeepLooking == true && stepsLeft > 0
Each time
14Change Variable
Variable
file
Operator
-=
Value
data('Directions', direction, 'fileStep')
15Change Variable
Variable
rank
Operator
-=
Value
data('Directions', direction, 'rankStep') * forward
16Change Variable
Variable
stepsLeft
Operator
-=
Value
1
17Change Variable
Variable
isOnBoard
Value
false
18Iffile >= 1 && file <= 8 && rank >= 1 && rank <= 8
Then
19Change Variable
Variable
isOnBoard
Value
true
20Change Variable
Variable
index
Value
(rank - 1) * 8 + (file - 1)
21Change Variable
Variable
keepLooking
Value
false
22IfisOnBoard == true && data('Position', index, 'kind') == ""
Then
23Change Variable
Variable
keepLooking
Value
true
24IfisOnBoard == true && data('Position', index, 'kind') != ""
Then
25Change Variable
Variable
firstPiece
Value
dataRow('Position', index)
26Return
Value
firstPiece

A.78 Find Passed Pawn (Function)

Built in Chapter 9, Threats.

FunctionFind Passed Pawn

Finds the Pawn that the Side to move can take en passant right now: the enemy Pawn that has just passed one of its Pawns by moving two Squares. It stands one Rank behind the en passant Square, as seen by the Side to move. gameRules: the Game Rules Object. passedPawn (returned): its Square, or empty when no Pawn can be taken en passant (Can Take En Passant).

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
RETURN TYPEText
ACTIONS
1Declare Variable
Type
Text
Name
enPassant
2Declare Variable
Type
Text
Name
side
3Declare Variable
Name
passedRank
Value
0
4Declare Variable
Name
passedFile
Value
0
5Declare Variable
Type
Text
Name
passedPawn
6Can Take En PassantFunction
Action Name
enPassantLook
gameRules
gameRules
7IfenPassantLook.value == true
Then
8Change Variable
Variable
enPassant
Value
gameRules.boardState.enPassantSquare
9Change Variable
Variable
side
Value
gameRules.boardState.sideToMove
10Change Variable
Variable
passedRank
Value
data('Position', enPassant, 'rank')
11Change Variable
Variable
passedRank
Operator
-=
Value
data('Sides', side, 'forward')
12Change Variable
Variable
passedFile
Value
data('Position', enPassant, 'file')
13Change Variable
Variable
passedPawn
Value
dataRow('Position', (passedRank - 1) * 8 + passedFile - 1)
14Return
Value
passedPawn

A.79 Find Pin Along (Function)

Built in Chapter 9, Threats.

FunctionFind Pin Along

Looks from a King along one line (a direction of the Directions table) for a pin: the first Piece on the line is one of the King's own, and the next Piece beyond it is an enemy that moves along this line (the direction's Kind). That own Piece is pinned: the Threats table's pinnedBy gets the enemy Piece's Square. king: the King's Square. direction: the row (0 = first) of the Directions table.

PARAMETERS
NameTypeStarts at
kingText
directionNumber0
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Text
Name
candidate
4Declare Variable
Type
Text
Name
pinner
5Change Variable
Variable
side
Value
data('Position', king, 'side')
6Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
7Find First Piece AlongFunction
Action Name
firstLook
square
king
direction
direction
bySide
enemy
8Change Variable
Variable
candidate
Value
firstLook.value
9Ifcandidate != "" && data('Position', candidate, 'side') == side
Then
10Find First Piece AlongFunction
Action Name
beyondLook
square
candidate
direction
direction
bySide
enemy
11Change Variable
Variable
pinner
Value
beyondLook.value
12Ifpinner != "" && data('Position', pinner, 'side') == enemy && data('Position', pinner, 'kind') == data('Directions', direction, 'kind')
Then
13Set Data Cell
Table
Threats
Row
candidate
Column
"pinnedBy"
Value
pinner

A.80 Find Threats (Function)

Built in Chapter 9, Threats.

FunctionFind Threats

Fills the Threats table for the position on the Board: every Piece that an enemy Piece can legally capture is attacked (Mark Captures, for each Piece of both Sides), the King in Check is attacked (Board State's checkSquare), and so is a Pawn that the Side to move can take en passant (Find Passed Pawn); every Piece pinned to its King is marked (Mark Pins, for each King); then every attacked Piece with no legal recapture is unprotected (Mark Unprotected Pieces). gameRules: the Game Rules Object.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Declare Variable
Type
Text
Name
kingSquare
2Declare Variable
Type
Text
Name
square
3Declare Variable
Type
Text
Name
passedPawn
4Clear ThreatsFunction
5Change Variable
Variable
kingSquare
Value
gameRules.boardState.checkSquare
6IfkingSquare != ""
Then
7Set Data Cell
Table
Threats
Row
kingSquare
Column
"isAttacked"
Value
"true"
8Find Passed PawnFunction
Action Name
passedLook
gameRules
gameRules
9Change Variable
Variable
passedPawn
Value
passedLook.value
10IfpassedPawn != ""
Then
11Set Data Cell
Table
Threats
Row
passedPawn
Column
"isAttacked"
Value
"true"
12RepeatdataCount('Position')times
Each time
13Change Variable
Variable
square
Value
dataRow('Position', local.index)
14Ifdata('Position', square, 'side') != ""
Then
15Mark CapturesFunction
from
square
16Ifdata('Position', square, 'kind') == "King"
Then
17Mark PinsFunction
king
square
18Mark Unprotected PiecesFunction
gameRules
gameRules
passedPawn
passedPawn
19Clear TargetsFunction

A.81 Is Unprotected (Function)

Built in Chapter 9, Threats.

FunctionIs Unprotected

Answers whether an attacked Piece is unprotected: no enemy Capture of it can be answered by a legal recapture (Can Recapture, for each enemy Piece in turn until one Capture can be answered). square: the Piece's Square. passedPawn: the Pawn the Side to move can take en passant, else empty (Find Passed Pawn). enPassantSquare: the en passant Square. isUnprotected (returned): yes when it is unprotected.

PARAMETERS
squareText
passedPawnText
enPassantSquareText
RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Text
Name
attacker
4Declare Variable
Type
Boolean
Name
isProtected
Value
false
5Declare Variable
Type
Boolean
Name
isUnprotected
Value
false
6Change Variable
Variable
side
Value
data('Position', square, 'side')
7Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
8RepeatdataCount('Position')times
Each time
9Change Variable
Variable
attacker
Value
dataRow('Position', local.index)
10Ifdata('Position', attacker, 'side') == enemy && isProtected == false
Then
11Can RecaptureFunction
Action Name
recaptureLook
from
attacker
to
square
taken
square
enPassantSquare
''
12Change Variable
Variable
isProtected
Value
recaptureLook.value
13Ifsquare == passedPawn && data('Position', attacker, 'kind') == "Pawn" && data('Position', attacker, 'side') == enemy && isProtected == false
Then
14Can RecaptureFunction
Action Name
enPassantLook
from
attacker
to
enPassantSquare
taken
square
enPassantSquare
enPassantSquare
15Change Variable
Variable
isProtected
Value
enPassantLook.value
16IfisProtected == false
Then
17Change Variable
Variable
isUnprotected
Value
true
18Return
Value
isUnprotected

A.82 Mark Captures (Function)

Built in Chapter 9, Threats.

FunctionMark Captures

Marks, in the Threats table, every enemy Piece that the Piece on one Square can legally capture. It asks Find Legal Moves, so a Capture that would leave the capturing Side's own King attacked does not count. En passant is left to Find Threats, because the Pawn it takes does not stand on the Square moved to. from: the Square of the capturing Piece.

PARAMETERS
fromText
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Type
Text
Name
enemy
3Declare Variable
Type
Text
Name
target
4Change Variable
Variable
side
Value
data('Position', from, 'side')
5Change Variable
Variable
enemy
Value
data('Sides', side, 'opponent')
6Find Legal MovesFunction
from
from
enPassantSquare
''
7RepeatdataCount('Targets')times
Each time
8Change Variable
Variable
target
Value
dataRow('Targets', local.index)
9Ifdata('Targets', target, 'reachable') == true && data('Position', target, 'side') == enemy
Then
10Set Data Cell
Table
Threats
Row
target
Column
"isAttacked"
Value
"true"

A.83 Mark Pins (Function)

Built in Chapter 9, Threats.

FunctionMark Pins

Marks, in the Threats table, every Piece pinned to one King (Find Pin Along, for every line a Queen, Rook, or Bishop slides along). king: the King's Square.

PARAMETERS
kingText
ACTIONS
1RepeatdataCount('Directions')times
Each time
2Ifdata('Directions', local.index, 'steps') > 1
Then
3Find Pin AlongFunction
king
king
direction
local.index

A.84 Mark Unprotected Pieces (Function)

Built in Chapter 9, Threats.

FunctionMark Unprotected Pieces

Marks, in the Threats table, every attacked Piece other than a King that is unprotected (Is Unprotected). It runs once every attacked Piece is marked. gameRules: the Game Rules Object. passedPawn: the Pawn the Side to move can take en passant, else empty (Find Passed Pawn).

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
passedPawnText
ACTIONS
1Declare Variable
Type
Text
Name
enPassant
2Declare Variable
Type
Text
Name
square
3Change Variable
Variable
enPassant
Value
gameRules.boardState.enPassantSquare
4RepeatdataCount('Position')times
Each time
5Change Variable
Variable
square
Value
dataRow('Position', local.index)
6Ifdata('Threats', square, 'isAttacked') == true && data('Position', square, 'kind') != "King"
Then
7Is UnprotectedFunction
Action Name
unprotectedLook
square
square
passedPawn
passedPawn
enPassantSquare
enPassant
8Set Data Cell
Table
Threats
Row
square
Column
"isUnprotected"
Value
unprotectedLook.value

A.85 Report Threats

Built in Chapter 9, Threats.

Logic ComponentReport Threats

What the Threats button does: it tells whoever listens (the Game Rules) with "threatsPressed". After every change on the Board ("positionChanged"), which the Game Rules also send when the game begins, it asks Can Show Threats whether the button can be used now, and turns it on or off (Show Button On Or Off).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
threatsPressed
On Position Changed
WhenpositionChangedCustom Event
1Can Show ThreatsFunction
Action Name
canUse
2Show Button On Or OffFunction
button
self
isOn
canUse.value

A.86 Show Pin Mark

Built in Chapter 9, Threats.

Logic ComponentShow Pin MarkAttach to: Pin Mark

Shows the amber bar under this Pin Mark's Piece in Threats mode when the Piece is pinned to its own King (the Threats table's pinnedBy), after every change (the Game Rules send "positionChanged"), and hides it while the Computer's Move slides ("slideStarted").

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
On Position Changed
WhenpositionChangedCustom Event
1Ifdata('Threats', self.squareInfo.name, 'pinnedBy') != ""
Then
2Set Visible
Visible
Yes
3Otherwise
4Set Visible
Visible
No
On Slide Started
WhenslideStartedCustom Event
1Set Visible
Visible
No

A.87 Show Threat Mark

Built in Chapter 9, Threats.

Logic ComponentShow Threat MarkAttach to: Threat Mark

Outlines this Threat Mark's Square in Threats mode when the Piece standing there is attacked, with a double ring around it when it is unprotected (the Threats table), after every change (the Game Rules send "positionChanged"), and hides the mark while the Computer's Move slides ("slideStarted").

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
On Position Changed
WhenpositionChangedCustom Event
1Ifdata('Threats', self.squareInfo.name, 'isAttacked') == true
Then
2Set Visible
Visible
Yes
3Otherwise
4Set Visible
Visible
No
5Ifdata('Threats', self.squareInfo.name, 'isUnprotected') == true
Then
6Set Frame
Frame
1
7Otherwise
8Set Frame
Frame
0
On Slide Started
WhenslideStartedCustom Event
1Set Visible
Visible
No

A.88 Show Threats

Built in Chapter 9, Threats.

Logic ComponentShow ThreatsAttach to: Game Rules

Turns Threats mode on and off, and keeps its marks up to date. When the game begins (Game Start), and when a saved game has been brought back ("savedGameLoaded"), it takes the choice kept on this device (the Persistent Value "threats", through Use The Last Threats Choice); after a saved game it also fills the Threats table and shows the legend, or empties it, ends any inspecting, and hides the legend, and shows the legend (the UI Group "Threats Legend") when Threats mode is on. At the start of every Turn ("turnStarted") it fills the Threats table again (Find Threats) while Threats mode is on. When the Threats button is pressed ("threatsPressed") on the Player's Turn or after the game has ended, it turns Threats mode over (Board State's isShowingThreats) and ends any inspecting, fills or empties the Threats table, shows or hides the legend, keeps the choice on this device, and every Square redraws ("positionChanged").

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
When the Game Starts
WhenGame Start
1Clear ThreatsFunction
2Use The Last Threats ChoiceFunction
gameRules
self
When Created
WhenCreate
1Ifself.boardState.isShowingThreats == true
Then
2Set UI Group Visibility
UI Group
"Threats Legend"
On Turn Started
WhenturnStartedCustom Event
1Ifself.boardState.isShowingThreats == true
Then
2Find ThreatsFunction
gameRules
self
On Threats Pressed
WhenthreatsPressedCustom Event
1Can Show ThreatsFunction
Action Name
threatsLook
2IfthreatsLook.value == true
Then
3Change Component Value
Component Value
self.boardState.inspected
Value
''
4Ifself.boardState.isShowingThreats == true
Then
5Change Component Value
Component Value
self.boardState.isShowingThreats
Value
false
6Clear ThreatsFunction
7Set UI Group Visibility
UI Group
"Threats Legend"
Visible
No
8Otherwise
9Change Component Value
Component Value
self.boardState.isShowingThreats
Value
true
10Find ThreatsFunction
gameRules
self
11Set UI Group Visibility
UI Group
"Threats Legend"
12Ifself.boardState.selected != ""
Then
13Find Legal MovesFunction
from
self.boardState.selected
enPassantSquare
self.boardState.enPassantSquare
14Save Persistent Value
Action Name
persistentWriteResult
Key
"threats"
Value
self.boardState.isShowingThreats
15Trigger Custom Event
Custom Event
positionChanged
On Saved Game Loaded
WhensavedGameLoadedCustom Event
1Use The Last Threats ChoiceFunction
gameRules
self
2Ifself.boardState.isShowingThreats == true
Then
3Find ThreatsFunction
gameRules
self
4Set UI Group Visibility
UI Group
"Threats Legend"
5Otherwise
6Clear ThreatsFunction
7Change Component Value
Component Value
self.boardState.inspected
Value
''
8Set UI Group Visibility
UI Group
"Threats Legend"
Visible
No

A.89 Add Arrow (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionAdd Arrow

Adds one arrow at the end of the Arrows table. from and to: the Squares it runs from and to (a1 to h8). color: its color, with how strongly it shows.

PARAMETERS
NameTypeStarts at
fromText
toText
colorColor#ffffff
ACTIONS
1Declare Variable
Name
lastRow
Value
0
2Control Data Row
Action Name
addedRow
Table
Arrows
Row
dataCount('Arrows')
3Change Variable
Variable
lastRow
Value
dataCount('Arrows') - 1
4Set Data Cell
Table
Arrows
Row
lastRow
Column
'from'
Value
from
5Set Data Cell
Table
Arrows
Row
lastRow
Column
'to'
Value
to
6Set Data Cell
Table
Arrows
Row
lastRow
Column
'color'
Value
color

A.90 Add Arrow Along (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionAdd Arrow Along

Adds the arrow a Piece shows along one of its directions, to the farthest Square it reaches that way (Find Farthest Square Along): in toEnemyColor when an enemy Piece stands there, else in otherColor (an empty Square, or a Piece of its own Side that it protects). No arrow when the direction leaves the Board at once. from: the Square of the Piece. direction: the row (0 = first) of the Directions table.

PARAMETERS
NameTypeStarts at
fromText
directionNumber0
toEnemyColorColor#ffffff
otherColorColor#ffffff
ACTIONS
1Declare Variable
Type
Text
Name
enemy
2Declare Variable
Type
Text
Name
farthest
3Declare Variable
Type
Color
Name
color
Value
'#ffffff'
4Change Variable
Variable
enemy
Value
data('Sides', data('Position', from, 'side'), 'opponent')
5Find Farthest Square AlongFunction
Action Name
reachLook
from
from
direction
direction
6Change Variable
Variable
farthest
Value
reachLook.value
7Change Variable
Variable
color
Value
otherColor
8Ifdata('Position', farthest, 'side') == enemy
Then
9Change Variable
Variable
color
Value
toEnemyColor
10Iffarthest != ""
Then
11Add ArrowFunction
from
from
to
farthest
color
color

A.91 Add Threat Arrow (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionAdd Threat Arrow

Adds an arrow from an enemy Piece that attacks a Piece, when it could really capture it: the Capture is a Legal Move (Can Capture), or the Piece attacked is a King. from: the Square of the attacking Piece (empty: no arrow). to: the Square it would move to. taken: the Square of the Piece it would take (not to for en passant). enPassantSquare: the en passant Square, for an en passant Capture, else empty. color: the arrow's color.

PARAMETERS
NameTypeStarts at
fromText
toText
takenText
enPassantSquareText
colorColor#ffffff
ACTIONS
1Declare Variable
Type
Boolean
Name
isThreat
Value
false
2Iffrom != ""
Then
3Can CaptureFunction
Action Name
captureLook
from
from
to
to
taken
taken
enPassantSquare
enPassantSquare
4Change Variable
Variable
isThreat
Value
captureLook.value
5Ifdata('Position', taken, 'kind') == "King"
Then
6Change Variable
Variable
isThreat
Value
true
7IfisThreat == true
Then
8Add ArrowFunction
from
from
to
to
color
colorInput

A.92 Draw Arrow (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionDraw Arrow

Draws one arrow, in the current Draw Color, from one point on the game screen toward another: a straight shaft and a head of two short lines at its end. Use it in a Draw Event. fromX, fromY: where the arrow starts; toX, toY: where it points to (screen pixels, from the bottom-left corner). startGap: how far after the start the shaft begins; endGap: how far before the end the head's tip is. headLength: how far back the head reaches along the shaft. headSpread: how far each side of the head reaches out, as a share of headLength. width: how thick the lines are. All but headSpread in screen pixels.

PARAMETERS
NameTypeStarts at
fromXNumber0
fromYNumber0
toXNumber0
toYNumber0
startGapNumber0
endGapNumber0
headLengthNumber0
headSpreadNumber0.6
widthNumber2
ACTIONS
1Declare Variable
Name
distance
Value
0
2Declare Variable
Name
stepX
Value
0
3Declare Variable
Name
stepY
Value
0
4Declare Variable
Name
tipX
Value
0
5Declare Variable
Name
tipY
Value
0
6Declare Variable
Name
backX
Value
0
7Declare Variable
Name
backY
Value
0
8Declare Variable
Name
sideX
Value
0
9Declare Variable
Name
sideY
Value
0
10Change Variable
Variable
distance
Value
hypot(toX - fromX, toY - fromY)
11Ifdistance > 0
Then
12Change Variable
Variable
stepX
Value
(toX - fromX) / distance
13Change Variable
Variable
stepY
Value
(toY - fromY) / distance
14Change Variable
Variable
tipX
Value
toX - stepX * endGap
15Change Variable
Variable
tipY
Value
toY - stepY * endGap
16Change Variable
Variable
backX
Value
tipX - stepX * headLength
17Change Variable
Variable
backY
Value
tipY - stepY * headLength
18Change Variable
Variable
sideX
Value
stepY * headLength * headSpread
19Change Variable
Variable
sideY
Value
stepX * headLength * headSpread
20Draw Line
X 1
fromX + stepX * startGap
Y 1
fromY + stepY * startGap
X 2
tipX
Y 2
tipY
Line Width
width
21Draw Line
X 1
tipX
Y 1
tipY
X 2
backX - sideX
Y 2
backY + sideY
Line Width
width
22Draw Line
X 1
tipX
Y 1
tipY
X 2
backX + sideX
Y 2
backY - sideY
Line Width
width

A.93 Draw Dashed Line (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionDraw Dashed Line

Draws one dashed line, in the current Draw Color, from one point on the game screen toward another. Use it in a Draw Event. fromX, fromY: where the line starts; toX, toY: where it points to (screen pixels, from the bottom-left corner). startGap: how far after the start the first dash begins; endGap: how far before the end the last dash stops. dashLength: how long each dash is; dashSpacing: how far one dash starts after the one before (more than dashLength leaves a gap). width: how thick the line is. All in screen pixels.

PARAMETERS
NameTypeStarts at
fromXNumber0
fromYNumber0
toXNumber0
toYNumber0
startGapNumber0
endGapNumber0
dashLengthNumber0
dashSpacingNumber0
widthNumber2
ACTIONS
1Declare Variable
Name
distance
Value
0
2Declare Variable
Name
stepX
Value
0
3Declare Variable
Name
stepY
Value
0
4Declare Variable
Name
along
Value
0
5Declare Variable
Name
lastPoint
Value
0
6Declare Variable
Name
dashEnd
Value
0
7Change Variable
Variable
distance
Value
hypot(toX - fromX, toY - fromY)
8Change Variable
Variable
along
Value
startGap
9Change Variable
Variable
lastPoint
Value
distance - endGap
10Ifdistance > 0
Then
11Change Variable
Variable
stepX
Value
(toX - fromX) / distance
12Change Variable
Variable
stepY
Value
(toY - fromY) / distance
13Whilealong < lastPoint
Each time
14Change Variable
Variable
dashEnd
Value
along + dashLength
15IfdashEnd > lastPoint
Then
16Change Variable
Variable
dashEnd
Value
lastPoint
17Draw Line
X 1
fromX + stepX * along
Y 1
fromY + stepY * along
X 2
fromX + stepX * dashEnd
Y 2
fromY + stepY * dashEnd
Line Width
width
18Change Variable
Variable
along
Operator
+=
Value
dashSpacing

A.94 Draw Threat Lines

Built in Chapter 10, Pin Lines and Arrows.

Logic ComponentDraw Threat LinesAttach to: Game Rules

Draws the lines of Threats mode over the Board: the arrows of the selected or inspected Piece (the Arrows table, which Find Arrows fills on every "positionChanged": red to an enemy Piece it attacks and teal to any other Square it reaches, and red from each enemy Piece that can capture it), and a dashed amber line from every Piece that pins an enemy Piece to its King, to that King (the Threats table's pinnedBy, which Find Threats fills only while Threats mode is on). The Draw Event runs every frame; nothing is drawn while the Computer's Move slides ("slideStarted") or the Promotion choice is open (Game State Promotion), until the next "positionChanged". arrowToEnemyColor, arrowToOtherColor, arrowFromAttackerColor: the arrows' colors. arrowWidth, arrowGapAtStart, arrowGapAtEnd, arrowHeadLength: the arrows' sizes, in Squares (0.035, 0.22, 0.27, 0.11); arrowHeadSpread: how far each side of a head reaches out, as a share of its length (0.6). pinColor: the pin lines' color. pinLineWidth, pinDashLength, pinDashSpacing: the dashes, in Squares (0.03, 0.12, 0.22). pinGapAtStart, pinGapAtKing: how far from the pinning Piece's and the King's centers the line starts and stops, in Squares. squareMeters, boardLeft, boardBottom: where the Squares are (as for Place On Board). pixelsPerMeter: the project's Pixels Per Unit.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Draw Threat Lines Dataself.drawThreatLinesData
SHARED VARIABLES
NameTypeKindStarting Value
pinColorColorConstant#c68a20cc
pinLineWidthNumberConstant0.03
pinDashLengthNumberConstant0.12
pinDashSpacingNumberConstant0.22
pinGapAtStartNumberConstant0.3
pinGapAtKingNumberConstant0.25
arrowToEnemyColorColorConstant#b6403ab0
arrowToOtherColorColorConstant#257f7690
arrowFromAttackerColorColorConstant#b6403acc
arrowWidthNumberConstant0.035
arrowGapAtStartNumberConstant0.22
arrowGapAtEndNumberConstant0.27
arrowHeadLengthNumberConstant0.11
arrowHeadSpreadNumberConstant0.6
squareMetersNumberConstant3.75
boardLeftNumberConstant0
boardBottomNumberConstant4.375
pixelsPerMeterNumberConstant32
When Drawn
WhenDraw
ModeDraw The Lines (Starting Mode)
1Declare Variable
Name
squarePixels
Value
0
2Change Variable
Variable
squarePixels
Value
@self.squareMeters * @self.pixelsPerMeter
3RepeatdataCount('Arrows')times
Each time
4Change Component Value
Component Value
self.drawThreatLinesData.arrowFrom
Value
data('Arrows', local.index, 'from')
5Change Component Value
Component Value
self.drawThreatLinesData.arrowTo
Value
data('Arrows', local.index, 'to')
6Set Draw Color
Color
data('Arrows', local.index, 'color')
7Square Screen PointFunction
Action Name
arrowStart
square
self.drawThreatLinesData.arrowFrom
isFlipped
self.boardState.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
pixelsPerMeter
@self.pixelsPerMeter
8Square Screen PointFunction
Action Name
arrowEnd
square
self.drawThreatLinesData.arrowTo
isFlipped
self.boardState.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
pixelsPerMeter
@self.pixelsPerMeter
9Draw ArrowFunction
fromX
arrowStart.x
fromY
arrowStart.y
toX
arrowEnd.x
toY
arrowEnd.y
startGap
@self.arrowGapAtStart * squarePixels
endGap
@self.arrowGapAtEnd * squarePixels
headLength
@self.arrowHeadLength * squarePixels
headSpread
@self.arrowHeadSpread
width
@self.arrowWidth * squarePixels
10Set Draw Color
Color
@self.pinColor
11RepeatdataCount('Threats')times
Each time
12Change Component Value
Component Value
self.drawThreatLinesData.pinned
Value
dataRow('Threats', local.index)
13Ifdata('Threats', self.drawThreatLinesData.pinned, 'pinnedBy') != ""
Then
14Change Component Value
Component Value
self.drawThreatLinesData.pinner
Value
data('Threats', self.drawThreatLinesData.pinned, 'pinnedBy')
15Find KingFunction
Action Name
kingLook
side
data('Position', self.drawThreatLinesData.pinned, 'side')
16Square Screen PointFunction
Action Name
pinnerPoint
square
self.drawThreatLinesData.pinner
isFlipped
self.boardState.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
pixelsPerMeter
@self.pixelsPerMeter
17Square Screen PointFunction
Action Name
kingPoint
square
kingLook.value
isFlipped
self.boardState.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
pixelsPerMeter
@self.pixelsPerMeter
18Draw Dashed LineFunction
fromX
pinnerPoint.x
fromY
pinnerPoint.y
toX
kingPoint.x
toY
kingPoint.y
startGap
@self.pinGapAtStart * squarePixels
endGap
@self.pinGapAtKing * squarePixels
dashLength
@self.pinDashLength * squarePixels
dashSpacing
@self.pinDashSpacing * squarePixels
width
@self.pinLineWidth * squarePixels
When Drawn
WhenDraw
ModeDraw Nothing
(no Actions)
On Slide Started
WhenslideStartedCustom Event
1Switch Mode
Event
When Drawn
Mode
Draw Nothing
On Position Changed
WhenpositionChangedCustom Event
1Find ArrowsFunction
gameRules
self
toEnemyColor
@self.arrowToEnemyColor
otherColor
@self.arrowToOtherColor
attackerColor
@self.arrowFromAttackerColor
2Check Game State
Action Name
isChoosing
Game State
Promotion
3IfisChoosing.value == true
Then
4Switch Mode
Event
When Drawn
Mode
Draw Nothing
5Otherwise
6Switch Mode
Event
When Drawn
Mode
Draw The Lines

A.95 Find Arrows (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionFind Arrows

Fills the Arrows table for the position on the Board. In Threats mode the selected Piece, or, when none is selected, the inspected Piece, shows an arrow along each direction it captures along, to the farthest Square it reaches (Add Arrow Along), and an arrow from every enemy Piece that can capture it (Find Arrows Toward). Outside Threats mode, or with no such Piece, the table stays empty. gameRules: the Game Rules Object. toEnemyColor, otherColor: the colors of its own arrows to an enemy Piece and to anything else. attackerColor: the color of the arrows from enemy Pieces.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
toEnemyColorColor#ffffff
otherColorColor#ffffff
attackerColorColor#ffffff
ACTIONS
1Declare Variable
Type
Text
Name
focus
2Reset Data Table
Table
Arrows
3Change Variable
Variable
focus
Value
gameRules.boardState.selected
4Iffocus == ""
Then
5Change Variable
Variable
focus
Value
gameRules.boardState.inspected
6IfgameRules.boardState.isShowingThreats != true
Then
7Change Variable
Variable
focus
Value
''
8RepeatdataCount('Directions')times
Each time
9Iffocus != "" && data('Directions', local.index, 'kind') == data('Position', focus, 'kind') && data('Directions', local.index, 'canCapture') == true
Then
10Add Arrow AlongFunction
from
focus
direction
local.index
toEnemyColor
toEnemyColor
otherColor
otherColor
11Iffocus != ""
Then
12Find Arrows TowardFunction
gameRules
gameRules
target
focus
color
attackerColor
13IfgameRules.boardState.selected != ""
Then
14Find Legal MovesFunction
from
gameRules.boardState.selected
enPassantSquare
gameRules.boardState.enPassantSquare
15Otherwise
16Clear TargetsFunction

A.96 Find Arrows Toward (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionFind Arrows Toward

Adds an arrow from every enemy Piece that can capture a Piece (Add Threat Arrow): each direction a Piece captures along is looked along backwards from it for an enemy attacker (Find Attacker Along). A Pawn that can be taken en passant also gets an arrow from each enemy Pawn that can take it, to the en passant Square. gameRules: the Game Rules Object. target: the Square of the Piece. color: the arrows' color.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
targetText
colorColor#ffffff
ACTIONS
1Declare Variable
Type
Text
Name
enemy
2Declare Variable
Type
Text
Name
enPassant
3Change Variable
Variable
enemy
Value
data('Sides', data('Position', target, 'side'), 'opponent')
4Find Passed PawnFunction
Action Name
passedLook
gameRules
gameRules
5IfpassedLook.value == target
Then
6Change Variable
Variable
enPassant
Value
gameRules.boardState.enPassantSquare
7RepeatdataCount('Directions')times
Each time
8Ifdata('Directions', local.index, 'canCapture') == true
Then
9Find Attacker AlongFunction
Action Name
attackerLook
square
target
direction
local.index
bySide
enemy
10Add Threat ArrowFunction
from
attackerLook.attacker
to
target
taken
target
enPassantSquare
''
color
colorInput
11Ifdata('Directions', local.index, 'canCapture') == true && data('Directions', local.index, 'kind') == "Pawn" && enPassant != ""
Then
12Find Attacker AlongFunction
Action Name
enPassantLook
square
enPassant
direction
local.index
bySide
enemy
13Add Threat ArrowFunction
from
enPassantLook.attacker
to
enPassant
taken
target
enPassantSquare
enPassant
color
colorInput

A.97 Find Farthest Square Along (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionFind Farthest Square Along

Follows one direction of the Directions table from a Piece, Square by Square, as far as the Piece reaches that way: up to the first Piece in the way (of either Side), the edge of the Board, or the end of the direction's steps. from: the Square of the Piece (a1 to h8). direction: the row (0 = first) of the Directions table (a Pawn's direction is turned round by its Side's forward). farthest (returned): the last Square reached, or empty when the first step leaves the Board.

PARAMETERS
NameTypeStarts at
fromText
directionNumber0
RETURN TYPEText
ACTIONS
1Declare Variable
Type
Text
Name
side
2Declare Variable
Name
forward
Value
1
3Declare Variable
Name
file
Value
0
4Declare Variable
Name
rank
Value
0
5Declare Variable
Name
stepsLeft
Value
0
6Declare Variable
Type
Boolean
Name
isOnBoard
Value
false
7Declare Variable
Name
index
Value
0
8Declare Variable
Type
Boolean
Name
keepGoing
Value
true
9Declare Variable
Type
Text
Name
farthest
10Change Variable
Variable
side
Value
data('Position', from, 'side')
11Change Variable
Variable
forward
Value
data('Sides', side, 'forward')
12Change Variable
Variable
file
Value
data('Position', from, 'file')
13Change Variable
Variable
rank
Value
data('Position', from, 'rank')
14Change Variable
Variable
stepsLeft
Value
data('Directions', direction, 'steps')
15WhilekeepGoing == true && stepsLeft > 0
Each time
16Change Variable
Variable
file
Operator
+=
Value
data('Directions', direction, 'fileStep')
17Change Variable
Variable
rank
Operator
+=
Value
data('Directions', direction, 'rankStep') * forward
18Change Variable
Variable
stepsLeft
Operator
-=
Value
1
19Change Variable
Variable
isOnBoard
Value
false
20Iffile >= 1 && file <= 8 && rank >= 1 && rank <= 8
Then
21Change Variable
Variable
isOnBoard
Value
true
22Change Variable
Variable
index
Value
(rank - 1) * 8 + (file - 1)
23Change Variable
Variable
keepGoing
Value
false
24IfisOnBoard == true
Then
25Change Variable
Variable
farthest
Value
dataRow('Position', index)
26IfisOnBoard == true && data('Position', index, 'kind') == ""
Then
27Change Variable
Variable
keepGoing
Value
true
28Return
Value
farthest

A.98 Inspect Piece (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionInspect Piece

In Threats mode, inspects the Piece standing on a Square the Player clicked (Board State's inspected), whichever Side it belongs to, so its arrows can be shown without selecting it for a Move. A click on an empty Square, or any click outside Threats mode, inspects nothing. gameRules: the Game Rules Object. square: the Square that was clicked.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
squareText
ACTIONS
1IfgameRules.boardState.isShowingThreats == true && data('Position', square, 'kind') != ""
Then
2Change Component Value
Component Value
gameRules.boardState.inspected
Value
square
3Otherwise
4Change Component Value
Component Value
gameRules.boardState.inspected
Value
''

A.99 Show Highlight (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionShow Highlight

Shows a Square's highlight in one color: tints the Square and sets how strongly the tint shows. square: the Square Object to highlight. color: the color. alpha: how strongly it shows, from 0 (not at all) to 1 (solid).

PARAMETERS
NameTypeStarts at
squareObject
colorColor#ffffff
alphaNumber1
ACTIONS
1Change Sprite Tint Property
Applies to
square
Value
color
2Set Alpha
Applies to
square
Alpha
alpha

A.100 Show Threats Button Pressed

Built in Chapter 10, Pin Lines and Arrows.

Logic ComponentShow Threats Button Pressed

Draws the Threats button pressed while Threats mode is on (Board State's isShowingThreats), and plain while it is off: its Sprite is tinted, and its word colored, with the pressed colors or the plain ones. It looks after every change on the Board ("positionChanged"), which the Game Rules also send when the game begins (and again after New Game) and when Threats mode is turned on or off. The Game Rules send positionChanged, so they are its Other, whose Board State says whether Threats mode is on. pressedColor, pressedWordColor: the button's color and its word's color while pressed. plainColor, plainWordColor: the same while not pressed (the Tool Button's own colors).

Attach toAny Object
COMPONENTS
self.spriteSprite
self.textText / UI
SHARED VARIABLES
NameTypeKindStarting Value
pressedColorColorConstant#e3eadc
pressedWordColorColorConstant#244739
plainColorColorConstant#e2d5b4
plainWordColorColorConstant#503a2b
On Position Changed
WhenpositionChangedCustom Event
1Ifother.boardState.isShowingThreats == true
Then
2Change Sprite Tint Property
Value
@self.pressedColor
3Change Component Value
Component Value
self.text.color
Value
@self.pressedWordColor
4Otherwise
5Change Sprite Tint Property
Value
@self.plainColor
6Change Component Value
Component Value
self.text.color
Value
@self.plainWordColor

A.101 Square Screen Point (Function)

Built in Chapter 10, Pin Lines and Arrows.

FunctionSquare Screen Point

Answers where the center of a Square is on the game screen, in screen pixels counted from the bottom-left corner of the screen, as the Draw Actions count them. It asks Square Position where the Square is in the world, in meters, and turns meters into pixels: the camera never moves, so the world's (0, 0) is the screen's bottom-left corner. square: the Square (a1 to h8). isFlipped, squareMeters, boardLeft, boardBottom: as for Square Position. pixelsPerMeter: the project's Pixels Per Unit (32). It returns x and y: the Square's center on the screen.

PARAMETERS
NameTypeStarts at
squareText
isFlippedBooleanNo
squareMetersNumber3.75
boardLeftNumber0
boardBottomNumber4.375
pixelsPerMeterNumber32
RETURN TYPESquare Screen Point Result (a Data Structure)
ACTIONS
1Declare Variable
Name
x
Value
0
2Declare Variable
Name
y
Value
0
3Square PositionFunction
Action Name
worldPoint
square
square
isFlipped
isFlipped
squareMeters
squareMeters
boardLeft
boardLeft
boardBottom
boardBottom
4Change Variable
Variable
x
Value
worldPoint.x * pixelsPerMeter
5Change Variable
Variable
y
Value
worldPoint.y * pixelsPerMeter
6Return
x
x
y
y

A.102 Close Settings

Built in Chapter 11, Settings and Saving.

Logic ComponentClose Settings

What the Done button of the Settings panel does: it closes the panel, and the game goes on with the choices made.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
Settings Panel

A.103 Continue The Game

Built in Chapter 11, Settings and Saving.

Logic ComponentContinue The GameAttach to: Game Rules

Brings back the saved game (the save slot "auto") when the game is opened. On Game Start, when the slot holds a game, it turns Save The Game off and loads it: the Scene's own new game still begins first, and must not be saved over the game on its way. When the engine has brought the saved game back ("load:succeeded"), it tells its own Object "savedGameLoaded" (Settings, New Game, and Show Threats use the choices kept on this device again), every Square redraws ("positionChanged"), and, when the game is not over, it says "gameContinues", so the Computer moves when it is its Move and the game is saved again. Save The Game comes back on with the saved game; when a load fails ("load:failed") it is turned on again here.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
When the Game Starts
WhenGame Start
1Check Save Exists
Action Name
hasSavedGame
Slot
"auto"
2IfhasSavedGame.value == true
Then
3Set Logic State
Logic Component
Save The Game
State
Disable
4Load Game
Action Name
gameLoad
Slot
"auto"
On Load:succeeded
Whenload:succeededCustom Event
1Trigger Custom Event on Object
Custom Event
savedGameLoaded
2Trigger Custom Event
Custom Event
positionChanged
3Check Game State
Action Name
isGameOver
Game State
Game Over
4IfisGameOver.value != true
Then
5Trigger Custom Event on Object
Custom Event
gameContinues
On Load:failed
Whenload:failedCustom Event
1Set Logic State
Logic Component
Save The Game

A.104 Report Board Finish

Built in Chapter 11, Settings and Saving.

Logic ComponentReport Board Finish

What a Board Finish button of the Settings panel does (Walnut, Tournament, Slate, Marble): it tells whoever listens (the Game Rules) with "boardFinishChosen"; the listener reads the button's Panel Option as Other.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
boardFinishChosen

A.105 Report Piece Set

Built in Chapter 11, Settings and Saving.

Logic ComponentReport Piece Set

What a Piece Set button of the Settings panel does (Carved walnut, Ivory & gold, Sculpted marble): it tells whoever listens (the Game Rules) with "pieceSetChosen"; the listener reads the button's Panel Option as Other.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
pieceSetChosen

A.106 Report Settings

Built in Chapter 11, Settings and Saving.

Logic ComponentReport Settings

What the Settings button does: it tells whoever listens (the Game Rules) with "settingsPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
settingsPressed

A.107 Report Strength Setting

Built in Chapter 11, Settings and Saving.

Logic ComponentReport Strength Setting

What a Strength button of the Settings panel does (Gentle to Expert): it tells whoever listens (the Game Rules) with "strengthSettingChosen"; the listener reads the button's Panel Option as Other.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
strengthSettingChosen

A.108 Save The Game

Built in Chapter 11, Settings and Saving.

Logic ComponentSave The GameAttach to: Game Rules

Saves the game in the save slot "auto" whenever it changes: at the start of every Turn of a game that goes on ("gameContinues", which Look For Game End sends after deciding the game is not over, and Continue The Game after a saved game has been brought back), when the game ends (the Game State becomes Game Over), and when the Player has turned the Board over or back ("flipFinished", from Flip Board). The save holds the Board, the Move History, Board State, the Game State, and every Object as it is; Continue The Game brings it back when the game is opened again.

Attach toAny Object
On Game Continues
WhengameContinuesCustom Event
1Save Game
Action Name
gameSave
Slot
"auto"
On Game State Changed
WhenGame State Changed
1Check Game State
Action Name
isGameOver
Game State
Game Over
2IfisGameOver.value == true
Then
3Save Game
Action Name
finishedGameSave
Slot
"auto"
On Flip Finished
WhenflipFinishedCustom Event
1Save Game
Action Name
flippedGameSave
Slot
"auto"

A.109 Settings

Built in Chapter 11, Settings and Saving.

Logic ComponentSettingsAttach to: Game Rules

Keeps the Player's settings: the Strength, the Board Finish, and the Piece Set. When the game begins (Game Start, and again after Restart Game), and when a saved game has been brought back ("savedGameLoaded"), it takes (Use The Last Look) the Board Finish and the Piece Set saved on this device (Persistent Values), when the game has them (the Board Finishes and Piece Sets tables; otherwise, and the first time, Board State's own boardFinish and pieceSet), and tells everyone "lookChanged", so the Board, its labels, and every Piece show them. (New Game takes the Strength saved, with the Side.) When the Player presses Settings ("settingsPressed"), it opens the Settings panel, a menu that holds the game while it is open. Each option pressed is used at once and kept on this device: a Strength ("strengthSettingChosen") is the Computer's from its next Move; a Board Finish ("boardFinishChosen") or a Piece Set ("pieceSetChosen") is shown at once ("lookChanged"). The pressed button is its Other, and every option then shows whether it is chosen ("choiceChanged").

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
When the Game Starts
WhenGame Start
1Use The Last LookFunction
gameRules
self
On Board Laid Out
WhenboardLaidOutCustom Event
1Trigger Custom Event
Custom Event
lookChanged
On Settings Pressed
WhensettingsPressedCustom Event
1Change Component Value
Component Value
self.boardState.chosenStrength
Value
self.boardState.strength
2Control Menu
Menu Element
Settings Panel
3Set Menu Pause State
Menu Element
Settings Panel
4Trigger Custom Event
Custom Event
choiceChanged
On Strength Setting Chosen
WhenstrengthSettingChosenCustom Event
1Change Component Value
Component Value
self.boardState.strength
Value
other.panelOption.option
2Change Component Value
Component Value
self.boardState.chosenStrength
Value
other.panelOption.option
3Save Persistent Value
Action Name
persistentWriteResult
Key
"strength"
Value
self.boardState.strength
4Trigger Custom Event
Custom Event
choiceChanged
On Board Finish Chosen
WhenboardFinishChosenCustom Event
1Change Component Value
Component Value
self.boardState.boardFinish
Value
other.panelOption.option
2Save Persistent Value
Action Name
persistentWriteResult2
Key
"boardFinish"
Value
self.boardState.boardFinish
3Trigger Custom Event
Custom Event
lookChanged
4Trigger Custom Event
Custom Event
choiceChanged
On Piece Set Chosen
WhenpieceSetChosenCustom Event
1Change Component Value
Component Value
self.boardState.pieceSet
Value
other.panelOption.option
2Save Persistent Value
Action Name
persistentWriteResult3
Key
"pieceSet"
Value
self.boardState.pieceSet
3Trigger Custom Event
Custom Event
lookChanged
4Trigger Custom Event
Custom Event
choiceChanged
On Saved Game Loaded
WhensavedGameLoadedCustom Event
1Use The Last LookFunction
gameRules
self
2Trigger Custom Event
Custom Event
lookChanged

A.110 Show Board Finish

Built in Chapter 11, Settings and Saving.

Logic ComponentShow Board FinishAttach to: Board

Shows the Board in the Board Finish chosen (Board State's boardFinish, a row of the Board Finishes table) when the game begins and whenever the choice changes (Settings, on the Game Rules, sends "lookChanged" and is its Other).

Attach toAny Object
On Look Changed
WhenlookChangedCustom Event
1Set Sprite
Sprite
data('Board Finishes', other.boardState.boardFinish, 'board')

A.111 Show Piece Set (Function)

Built in Chapter 11, Settings and Saving.

FunctionShow Piece Set

Shows a Piece Set's art on one Object that shows a Piece (a Piece, a Moving Piece, or a Promotion button), at the set's size. Changing the art shows its first frame, so the caller shows the right Piece afterwards. piece: the Object. pieceSet: the Piece Set, a row of the Piece Sets table.

PARAMETERS
pieceObject
pieceSetText
ACTIONS
1Set Sprite
Applies to
piece
Sprite
data('Piece Sets', pieceSet, 'pieces')
2Set Scale
Applies to
piece
Horizontal Scale
data('Piece Sets', pieceSet, 'size')
Vertical Scale
data('Piece Sets', pieceSet, 'size')

A.112 Use The Last Look (Function)

Built in Chapter 11, Settings and Saving.

FunctionUse The Last Look

Takes the Board Finish and the Piece Set kept on this device (the Persistent Values "boardFinish" and "pieceSet") into Board State, when the game has them (a row of the Board Finishes table, a row of the Piece Sets table; otherwise Board State's own value stays), and tells everyone "lookChanged", so the Board, its labels, and every Piece show them. gameRules: the Object that carries Board State.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Load Persistent Value
Action Name
savedFinish
Key
"boardFinish"
Default
gameRules.boardState.boardFinish
2Load Persistent Value
Action Name
savedPieceSet
Key
"pieceSet"
Default
gameRules.boardState.pieceSet
3Check Data Row Exists
Action Name
isKnownFinish
Table
Board Finishes
Row
savedFinish.value
4IfisKnownFinish.value == true
Then
5Change Component Value
Component Value
gameRules.boardState.boardFinish
Value
savedFinish.value
6Check Data Row Exists
Action Name
isKnownPieceSet
Table
Piece Sets
Row
savedPieceSet.value
7IfisKnownPieceSet.value == true
Then
8Change Component Value
Component Value
gameRules.boardState.pieceSet
Value
savedPieceSet.value

A.113 Use The Last Strength (Function)

Built in Chapter 11, Settings and Saving.

FunctionUse The Last Strength

Takes the Strength kept on this device (the Persistent Value "strength") into Board State, when the game has it (a row of the Strengths table; otherwise Board State's own strength stays). gameRules: the Object that carries Board State.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Load Persistent Value
Action Name
savedStrength
Key
"strength"
Default
gameRules.boardState.strength
2Check Data Row Exists
Action Name
isKnownStrength
Table
Strengths
Row
savedStrength.value
3IfisKnownStrength.value == true
Then
4Change Component Value
Component Value
gameRules.boardState.strength
Value
savedStrength.value

A.114 Use The Last Threats Choice (Function)

Built in Chapter 11, Settings and Saving.

FunctionUse The Last Threats Choice

Takes Threats mode as it is kept on this device (the Persistent Value "threats") into Board State's isShowingThreats: on when the kept value is true, off otherwise (the first time there is none, and Board State's own value stays). gameRules: the Object that carries Board State.

PARAMETERS
NameTypeStarts at
gameRulesObjectStructural
Required Components
Slot NameboardState
Component TypeData Structure
Required SchemaBoard State
ACTIONS
1Load Persistent Value
Action Name
savedThreats
Key
"threats"
Default
gameRules.boardState.isShowingThreats
2IfsavedThreats.value == true
Then
3Change Component Value
Component Value
gameRules.boardState.isShowingThreats
Value
true
4Otherwise
5Change Component Value
Component Value
gameRules.boardState.isShowingThreats
Value
false

A.115 Ask To Resign

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentAsk To Resign

What the Resign button of the Game menu does: the Game menu closes and the question "Resign?" opens in its place, a menu that holds the game while it is open. After every change on the Board ("positionChanged"), which the Game Rules also send when the game begins, it asks Can Resign whether the button can be used now, and turns it on or off (Show Button On Or Off).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
Game Menu Panel
2Control Menu
Menu Element
Resign Question
3Set Menu Pause State
Menu Element
Resign Question
On Position Changed
WhenpositionChangedCustom Event
1Can ResignFunction
Action Name
canUse
2Show Button On Or OffFunction
button
self
isOn
canUse.value

A.116 Can Resign (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionCan Resign

Asks whether the Resign button can be used: while the game is not over (any Game State but Game Over). isOn (returned): true when it can.

RETURN TYPEBoolean
ACTIONS
1Declare Variable
Type
Boolean
Name
isOn
Value
false
2Check Game State
Action Name
isGameOver
Game State
Game Over
3IfisGameOver.value != true
Then
4Change Variable
Variable
isOn
Value
true
5Return
Value
isOn

A.117 Cancel With Escape

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentCancel With EscapeAttach to: Cancel Promotion

Lets Escape (the Command Cancel Choice) cancel the Promotion choice, as a click on its Cancel button does: the button tells whoever listens (the Game Rules) "promotionChosen", and the listener reads its Promotion Choice, empty for Cancel, as Other. Cancel Choice is one of the Promotion choice's own keys, live only while the choice is open (Choose With Keys turns them on).

Attach toAny Object
When Cancel Choice Is Pressed
WhenCommand PressedCommand: Cancel Choice
1Trigger Custom Event
Custom Event
promotionChosen

A.118 Choose With Keys

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentChoose With KeysAttach to: Promotion Focus

Lets the Player choose the Promotion with the keyboard. While the Promotion choice is open the keys choose among its Pieces instead of playing on the Board: the Input Context Promotion Choice is on and Default (the Board's keys) is off, turned when the choice opens or closes and when a saved game comes back ("positionChanged", from the Game Rules). Left and Right (the Command Choose Piece) move this outline from Piece to Piece, from the Queen to the Knight; Enter or Space (Promote) promotes the Pawn to the Piece it is on: this Object carries that Kind in its Promotion Choice, so the Game Rules (Choose Promotion) hear "promotionChosen" from it as from a button. The outline starts on the Queen each time the choice opens. firstPieceX and pieceY: where the Queen's button stands, in screen pixels right of and above the middle of the screen; pieceSpacing: how far apart the buttons stand.

Attach toAny Object
DATA STRUCTURES
Promotion Choiceself.promotionChoice
Choose With Keys Dataself.chooseWithKeysData
SHARED VARIABLES
NameTypeKindStarting Value
firstPieceXNumberConstant-195
pieceYNumberConstant66
pieceSpacingNumberConstant130
On Position Changed
WhenpositionChangedCustom Event
1Check Game State
Action Name
isChoosing
Game State
Promotion
2IfisChoosing.value == true
Then
3Set Input Context Active
Input Context
Default
Active
No
4Set Input Context Active
Input Context
Promotion Choice
5Change Component Value
Component Value
self.chooseWithKeysData.place
Value
1
6Move The Promotion FocusFunction
promotionFocus
self
place
self.chooseWithKeysData.place
firstPieceX
@self.firstPieceX
pieceY
@self.pieceY
pieceSpacing
@self.pieceSpacing
7Otherwise
8Set Input Context Active
Input Context
Promotion Choice
Active
No
9Set Input Context Active
Input Context
Default
When Choose Piece Left Is Pressed
When2D Direction PressedCommand: Choose PieceDirection: Left
1Change Component Value
Component Value
self.chooseWithKeysData.place
Value
clamp(self.chooseWithKeysData.place - 1, 1, 4)
2Move The Promotion FocusFunction
promotionFocus
self
place
self.chooseWithKeysData.place
firstPieceX
@self.firstPieceX
pieceY
@self.pieceY
pieceSpacing
@self.pieceSpacing
When Choose Piece Right Is Pressed
When2D Direction PressedCommand: Choose PieceDirection: Right
1Change Component Value
Component Value
self.chooseWithKeysData.place
Value
clamp(self.chooseWithKeysData.place + 1, 1, 4)
2Move The Promotion FocusFunction
promotionFocus
self
place
self.chooseWithKeysData.place
firstPieceX
@self.firstPieceX
pieceY
@self.pieceY
pieceSpacing
@self.pieceSpacing
When Promote Is Pressed
WhenCommand PressedCommand: Promote
1Trigger Custom Event
Custom Event
promotionChosen

A.119 Close Game Menu

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentClose Game Menu

What the Done button of the Game menu does: it closes the menu, and the game goes on.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
Game Menu Panel

A.120 Close How To Play

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentClose How To Play

What the Done button of the How to play panel does: it closes the panel, and the game goes on.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
How To Play Panel

A.121 Close Resign Question

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentClose Resign Question

What the Cancel button of the question "Resign?" does: it closes the question, and the game goes on.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
Resign Question

A.122 Find Other Pieces Reaching (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionFind Other Pieces Reaching

Asks, before a Move is made, whether another Piece of the same Kind and Side as the one on from could also make a Legal Move to the Square to, as standard notation needs to know (a Pawn is never asked: its Capture is named by its File). from, to: the Move's Squares. enPassantSquare: the Square a Pawn may take en passant now (Board State). isFileNeeded (returned): true when the name must say the File the Piece came from (another such Piece reaches to from another File, or from the same File and the same Rank). isRankNeeded (returned): true when the name must say the Rank it came from (another such Piece reaches to from the same File). The Targets table is left empty.

PARAMETERS
fromText
toText
enPassantSquareText
RETURN TYPEFind Other Pieces Reaching Result (a Data Structure)
ACTIONS
1Declare Variable
Type
Text
Name
square
2Declare Variable
Type
Boolean
Name
isReached
Value
false
3Declare Variable
Type
Boolean
Name
isSameFile
Value
false
4Declare Variable
Type
Boolean
Name
isSameRank
Value
false
5Declare Variable
Type
Boolean
Name
isFileNeeded
Value
false
6Declare Variable
Type
Boolean
Name
isRankNeeded
Value
false
7RepeatdataCount('Position')times
Each time
8Change Variable
Variable
square
Value
dataRow('Position', local.index)
9Ifdata('Position', square, 'kind') == data('Position', from, 'kind') && data('Position', square, 'side') == data('Position', from, 'side') && square != from && data('Position', from, 'kind') != "Pawn"
Then
10Find Legal MovesFunction
from
square
enPassantSquare
enPassantSquare
11Ifdata('Targets', to, 'reachable') == true
Then
12Change Variable
Variable
isReached
Value
true
13Ifdata('Targets', to, 'reachable') == true && data('Position', square, 'file') == data('Position', from, 'file')
Then
14Change Variable
Variable
isSameFile
Value
true
15Ifdata('Targets', to, 'reachable') == true && data('Position', square, 'rank') == data('Position', from, 'rank')
Then
16Change Variable
Variable
isSameRank
Value
true
17Clear TargetsFunction
18IfisReached == true
Then
19IfisSameFile == true && isSameRank == true
Then
20Change Variable
Variable
isFileNeeded
Value
true
21Change Variable
Variable
isRankNeeded
Value
true
22Otherwise
23IfisSameFile == true
Then
24Change Variable
Variable
isRankNeeded
Value
true
25Otherwise
26Change Variable
Variable
isFileNeeded
Value
true
27Return
isFileNeeded
isFileNeeded
isRankNeeded
isRankNeeded

A.123 Game Menu

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentGame MenuAttach to: Game Rules

Opens the Game menu when the Player presses the Game button ("gameMenuPressed"): a menu that holds the game while it is open, so the Board takes no clicks. The menu's buttons close it again (Done) or ask to resign (Resign). Once it is open, it tells its own Object "gameMenuOpened", so the Move List shows the newest page (Move Pages).

Attach toAny Object
On Game Menu Pressed
WhengameMenuPressedCustom Event
1Control Menu
Menu Element
Game Menu Panel
2Set Menu Pause State
Menu Element
Game Menu Panel
3Trigger Custom Event on Object
Custom Event
gameMenuOpened

A.124 Keyboard Focus

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentKeyboard FocusAttach to: Focus Mark

Lets the Player play with the keyboard: keeps the focused Square (this Object's Square Info) and draws the Focus Mark on it. The arrow keys (Move Focus) move the focus one Square on the screen, Home and End (Focus Row Start, Focus Row End) to the ends of its row, always stopping at the Board's edges, and the way the Board is drawn turns them round ("boardFlipped", from the Game Rules). Enter or Space (Press Square) presses the focused Square as a click does ("squareClicked"), while the game is being played. The focus starts on the Square in front of the Player's King when each game begins ("gameStarted", from the Game Rules), and shows itself from the first key. These keys are the Input Context Default: while the Promotion choice is open they rest, and the focus stays where it is (Choose With Keys turns them off and the choice's own keys on). startFile: the File the focus starts on (5: File e). squareMeters, boardLeft, boardBottom: the Board as Place On Board draws it.

Attach toAny Object
DATA STRUCTURES
Square Infoself.squareInfo
Keyboard Focus Dataself.keyboardFocusData
SHARED VARIABLES
NameTypeKindStarting Value
squareMetersNumberConstant3.75
boardLeftNumberConstant0
boardBottomNumberConstant4.375
startFileNumberConstant5
On Game Started
WhengameStartedCustom Event
1Declare Variable
Name
row
Value
0
2Declare Variable
Name
rank
Value
0
3Change Component Value
Component Value
self.keyboardFocusData.isFlipped
Value
other.boardState.isFlipped
4Change Variable
Variable
rank
Value
data('Sides', other.boardState.playerSide, 'pawnRank')
5Change Variable
Variable
row
Value
(rank - 1) * 8 + (@self.startFile - 1)
6Change Component Value
Component Value
self.squareInfo.name
Value
dataRow('Position', row)
7Move The Focus MarkFunction
focusMark
self
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
On Board Flipped
WhenboardFlippedCustom Event
1Change Component Value
Component Value
self.keyboardFocusData.isFlipped
Value
other.boardState.isFlipped
2Move The Focus MarkFunction
focusMark
self
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Move Focus Left Is Pressed
When2D Direction PressedCommand: Move FocusDirection: Left
1Step The FocusFunction
focusMark
self
fileStep
-1
rankStep
0
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Move Focus Right Is Pressed
When2D Direction PressedCommand: Move FocusDirection: Right
1Step The FocusFunction
focusMark
self
fileStep
1
rankStep
0
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Move Focus Up Is Pressed
When2D Direction PressedCommand: Move FocusDirection: Up
1Step The FocusFunction
focusMark
self
fileStep
0
rankStep
1
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Move Focus Down Is Pressed
When2D Direction PressedCommand: Move FocusDirection: Down
1Step The FocusFunction
focusMark
self
fileStep
0
rankStep
-1
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Focus Row Start Is Pressed
WhenCommand PressedCommand: Focus Row Start
1Step The FocusFunction
focusMark
self
fileStep
-7
rankStep
0
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Focus Row End Is Pressed
WhenCommand PressedCommand: Focus Row End
1Step The FocusFunction
focusMark
self
fileStep
7
rankStep
0
isFlipped
self.keyboardFocusData.isFlipped
squareMeters
@self.squareMeters
boardLeft
@self.boardLeft
boardBottom
@self.boardBottom
When Press Square Is Pressed
WhenCommand PressedCommand: Press Square
1Check Game State
Action Name
isPlaying
Game State
Playing
2IfisPlaying.value == true
Then
3Set Visible
Visible
Yes
4Trigger Custom Event
Custom Event
squareClicked

A.125 Move Pages

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentMove PagesAttach to: Game Rules

Chooses which full Moves the Game menu's Move List shows, movesPerPage at a time (Board State's firstShownMove): the page that holds the newest Move when the menu opens ("gameMenuOpened"), the page before when Earlier is pressed ("earlierMovesPressed"), and the page after when Later is pressed ("laterMovesPressed"). Each time it tells everyone "movePageChanged", so the list shows the page.

Attach toAny Object
DATA STRUCTURES
Board Stateself.boardState
Move Pages Dataself.movePagesData
On Game Menu Opened
WhengameMenuOpenedCustom Event
1Change Component Value
Component Value
self.boardState.firstShownMove
Value
0
2IfdataCount('Move History') > 0
Then
3Change Component Value
Component Value
self.movePagesData.newestMove
Value
floor((dataCount('Move History') - 1) / 2)
4Change Component Value
Component Value
self.movePagesData.newestPage
Value
floor(self.movePagesData.newestMove / self.boardState.movesPerPage)
5Change Component Value
Component Value
self.boardState.firstShownMove
Value
self.movePagesData.newestPage * self.boardState.movesPerPage
6Trigger Custom Event
Custom Event
movePageChanged
On Earlier Moves Pressed
WhenearlierMovesPressedCustom Event
1Change Component Value
Component Value
self.boardState.firstShownMove
Operator
-=
Value
self.boardState.movesPerPage
2Trigger Custom Event
Custom Event
movePageChanged
On Later Moves Pressed
WhenlaterMovesPressedCustom Event
1Change Component Value
Component Value
self.boardState.firstShownMove
Operator
+=
Value
self.boardState.movesPerPage
2Trigger Custom Event
Custom Event
movePageChanged

A.126 Move The Focus Mark (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionMove The Focus Mark

Moves the Focus Mark to where its Square (its Square Info) is drawn now, as Place On Board moves a Piece (Square Position). focusMark: the Focus Mark. isFlipped: whether the Board is drawn turned over. squareMeters, boardLeft and boardBottom: the Board's size and corner, as Place On Board has them.

PARAMETERS
NameTypeStarts at
focusMarkObjectStructural
Required Components
Slot NamesquareInfo
Component TypeData Structure
Required SchemaSquare Info
isFlippedBooleanNo
squareMetersNumber3.75
boardLeftNumber0
boardBottomNumber4.375
ACTIONS
1Square PositionFunction
Action Name
focusedSquare
square
focusMark.squareInfo.name
isFlipped
isFlipped
squareMeters
squareMeters
boardLeft
boardLeft
boardBottom
boardBottom
2Set Position
Applies to
focusMark
X
focusedSquare.x
Y
focusedSquare.y

A.127 Move The Promotion Focus (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionMove The Promotion Focus

Puts the Promotion Focus on the Piece at one place of the Promotion choice: its Promotion Choice becomes that Kind, and its outline is drawn over that Piece's button. promotionFocus: the Promotion Focus. place: 1 to 4, the Queen, Rook, Bishop and Knight, as their buttons stand from left to right. firstPieceX and pieceY: where the Queen's button stands, in screen pixels right of and above the middle of the screen; pieceSpacing: how far apart the buttons stand.

PARAMETERS
NameTypeStarts at
promotionFocusObjectStructural
Required Components
Slot NamepromotionChoice
Component TypeData Structure
Required SchemaPromotion Choice
placeNumber1
firstPieceXNumber-195
pieceYNumber66
pieceSpacingNumber130
ACTIONS
1Change Component Value
Component Value
promotionFocus.promotionChoice.kind
Value
dataRow('Kinds', place)
2Set Position
Applies to
promotionFocus
Position Relative To
Screen
X
firstPieceX + (place - 1) * pieceSpacing
Y
pieceY

A.128 Name The Move (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionName The Move

Writes a Move's name, as chess players write it (standard algebraic notation: e4, Nf3, exd5, O-O, e8=Q, Rad1), into its row of the Move History, before the Move is made: the name depends on the position the Move is made in. The check mark (+ or #) is written when the next Turn starts (Start The Turn, Look For Game End). from, to: the Move's Squares. landingKind: the Kind the Piece lands as. enPassantSquare: the Square a Pawn may take en passant now. row: the Move's row in the Move History.

PARAMETERS
NameTypeStarts at
fromText
toText
landingKindText
enPassantSquareText
rowNumber0
ACTIONS
1Declare Variable
Type
Text
Name
movedKind
2Declare Variable
Type
Text
Name
castling
3Change Variable
Variable
movedKind
Value
data('Position', from, 'kind')
4Set Data Cell
Table
Move History
Row
row
Column
"letter"
Value
data('Kinds', movedKind, 'letter')
5Set Data Cell
Table
Move History
Row
row
Column
"square"
Value
to
6Ifdata('Position', to, 'kind') != ""
Then
7Set Data Cell
Table
Move History
Row
row
Column
"capture"
Value
data('Words', 'Capture Mark', 'text')
8IfmovedKind == "Pawn" && data('Position', from, 'file') != data('Position', to, 'file')
Then
9Set Data Cell
Table
Move History
Row
row
Column
"capture"
Value
data('Words', 'Capture Mark', 'text')
10Set Data Cell
Table
Move History
Row
row
Column
"fromFile"
Value
data('Position', from, 'fileLetter')
11IflandingKind != movedKind
Then
12Set Data Cell
Table
Move History
Row
row
Column
"promotion"
Value
data('Kinds', landingKind, 'promotionMark')
13RepeatdataCount('Castling')times
Each time
14Change Variable
Variable
castling
Value
dataRow('Castling', local.index)
15IfmovedKind == "King" && data('Castling', castling, 'kingFrom') == from && data('Castling', castling, 'kingTo') == to
Then
16Set Data Cell
Table
Move History
Row
row
Column
"letter"
Value
data('Castling', castling, 'notation')
17Set Data Cell
Table
Move History
Row
row
Column
"square"
Value
''
18Find Other Pieces ReachingFunction
Action Name
others
from
from
to
to
enPassantSquare
enPassantSquare
19Ifothers.isFileNeeded == true
Then
20Set Data Cell
Table
Move History
Row
row
Column
"fromFile"
Value
data('Position', from, 'fileLetter')
21Ifothers.isRankNeeded == true
Then
22Set Data Cell
Table
Move History
Row
row
Column
"fromRank"
Value
data('Position', from, 'rank')

A.129 Report Earlier Moves

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentReport Earlier Moves

What the Earlier button of the Move List does: it tells whoever listens (the Game Rules) with "earlierMovesPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
earlierMovesPressed

A.130 Report Game Menu

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentReport Game Menu

What the Game button does: it tells whoever listens (the Game Rules) with "gameMenuPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
gameMenuPressed

A.131 Report Later Moves

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentReport Later Moves

What the Later button of the Move List does: it tells whoever listens (the Game Rules) with "laterMovesPressed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
laterMovesPressed

A.132 Report Resign

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentReport Resign

What the Resign button of the question "Resign?" does: it tells whoever listens (the Game Rules) with "resignConfirmed".

Attach toAny Object
On Hud Activated
WhenUI Activated
1Trigger Custom Event
Custom Event
resignConfirmed

A.133 Resign

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentResignAttach to: Game Rules

Ends the game when the Player resigns: when the Player answers "Resign?" with Resign ("resignConfirmed"), the question closes and, if the game is not over yet, the status line shows "You lose · Resignation" (the Words row Loss By Resignation) and the game is over (Game State Game Over), so the Board no longer answers and the final position stays, as at every other end of a game. Then everyone hears "positionChanged", so the buttons show what can be used now. An answer from the Computer still on its way is not used: the Computer's Logic asks whether it is still the Computer's Turn.

Attach toAny Object
On Resign Confirmed
WhenresignConfirmedCustom Event
1Control Menu
Operation
Hide
Menu Element
Resign Question
2Check Game State
Action Name
isGameOver
Game State
Game Over
3IfisGameOver.value != true
Then
4Change Variable
Variable
$status
Value
data('Words', 'Loss By Resignation', 'text')
5Set Game State
Game State
Game Over
6Trigger Custom Event
Custom Event
positionChanged

A.134 Show How To Play

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentShow How To Play

What the How to play button of the Game menu does: the Game menu closes and the How to play panel opens in its place, a menu that holds the game while it is open.

Attach toAny Object
On Hud Activated
WhenUI Activated
1Control Menu
Operation
Hide
Menu Element
Game Menu Panel
2Control Menu
Menu Element
How To Play Panel
3Set Menu Pause State
Menu Element
How To Play Panel

A.135 Show No Moves Note

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentShow No Moves NoteAttach to: No Moves Note

Shows "No moves yet." in the Game menu's Move List while no Move has been made, and hides it once there is one, each time the page is drawn ("movePageChanged", from the Game Rules).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
On Move Page Changed
WhenmovePageChangedCustom Event
1IfdataCount('Move History') == 0
Then
2Set UI Element Visibility
3Otherwise
4Set UI Element Visibility
Visible
No

A.136 Show Page Button

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentShow Page Button

Shows a page button of the Game menu's Move List (Earlier or Later) only when there is a page to turn to, each time the page is drawn ("movePageChanged", from the Game Rules, whose Board State holds the page shown and movesPerPage). direction: -1 on the Earlier Moves Button (the page before), 1 on the Later Moves Button (the page after).

Attach toAny Object
COMPONENTS
self.uiUI Interaction
SHARED VARIABLES
NameTypeKindStarting Value
directionNumberConstant1
On Move Page Changed
WhenmovePageChangedCustom Event
1Declare Variable
Name
pageFirstMove
Value
0
2Change Variable
Variable
pageFirstMove
Value
other.boardState.movesPerPage * @self.direction
3Change Variable
Variable
pageFirstMove
Operator
+=
Value
other.boardState.firstShownMove
4IfpageFirstMove >= 0 && (pageFirstMove * 2) < dataCount('Move History')
Then
5Set UI Element Visibility
6Otherwise
7Set UI Element Visibility
Visible
No

A.137 Show Recorded Move

Built in Chapter 12, Game Menu and Keyboard.

Logic ComponentShow Recorded MoveAttach to: Move Words

Shows one Move of the game in the Game menu's Move List, as chess players write it, read from its row of the Move History into this Object's own Move Notation, which its words show. Each line of the list is two placements, White's Move and Black's. When the page changes ("movePageChanged", from the Game Rules), the Move shown is the line's full Move on that page; a line past the newest Move shows nothing. line: the line of the list, 0 (top) to 11. isBlackMove: true for the placement that shows Black's Move of the line (false: White's, with the move number).

Attach toAny Object
DATA STRUCTURES
Move Notationself.moveNotation
COMPONENTS
self.uiUI Interaction
PER INSTANCE VARIABLES
NameTypeStarting Value
lineNumber0
isBlackMoveBooleanNo
On Move Page Changed
WhenmovePageChangedCustom Event
1Declare Variable
Name
row
Value
0
2Change Variable
Variable
row
Value
(other.boardState.firstShownMove + self.line) * 2
3Ifself.isBlackMove == true
Then
4Change Variable
Variable
row
Operator
+=
Value
1
5Ifrow < dataCount('Move History')
Then
6Change Component Value
Component Value
self.moveNotation.number
Value
objectComponentProperty("otherObject","boardState","firstShownMove") + instanceVar("self","line") + 1
7Change Component Value
Component Value
self.moveNotation.letter
Value
data('Move History', row, 'letter')
8Change Component Value
Component Value
self.moveNotation.fromFile
Value
data('Move History', row, 'fromFile')
9Change Component Value
Component Value
self.moveNotation.fromRank
Value
data('Move History', row, 'fromRank')
10Change Component Value
Component Value
self.moveNotation.capture
Value
data('Move History', row, 'capture')
11Change Component Value
Component Value
self.moveNotation.square
Value
data('Move History', row, 'square')
12Change Component Value
Component Value
self.moveNotation.promotion
Value
data('Move History', row, 'promotion')
13Change Component Value
Component Value
self.moveNotation.checkMark
Value
data('Move History', row, 'checkMark')
14Set UI Element Visibility
15Otherwise
16Set UI Element Visibility
Visible
No

A.138 Step The Focus (Function)

Built in Chapter 12, Game Menu and Keyboard.

FunctionStep The Focus

Moves the focus by a number of Squares on the screen, and stops at the Board's edges: the Focus Mark's Square becomes the one reached, the mark is shown, and it moves there (Move The Focus Mark). focusMark: the Focus Mark. fileStep: Squares to the right; rankStep: Squares up (negative: left, down). isFlipped: whether the Board is drawn turned over. squareMeters, boardLeft and boardBottom: the Board's size and corner.

PARAMETERS
NameTypeStarts at
focusMarkObjectStructural
Required Components
Slot NamesquareInfo
Component TypeData Structure
Required SchemaSquare Info
fileStepNumber0
rankStepNumber0
isFlippedBooleanNo
squareMetersNumber3.75
boardLeftNumber0
boardBottomNumber4.375
ACTIONS
1Declare Variable
Name
across
Value
0
2Declare Variable
Name
up
Value
0
3Declare Variable
Name
file
Value
0
4Declare Variable
Name
rank
Value
0
5Declare Variable
Name
row
Value
0
6Change Variable
Variable
across
Value
fileStep
7Change Variable
Variable
up
Value
rankStep
8IfisFlipped == true
Then
9Change Variable
Variable
across
Operator
*=
Value
-1
10Change Variable
Variable
up
Operator
*=
Value
-1
11Change Variable
Variable
file
Value
data('Position', focusMark.squareInfo.name, 'file')
12Change Variable
Variable
file
Operator
+=
Value
across
13Change Variable
Variable
file
Value
clamp(file, 1, 8)
14Change Variable
Variable
rank
Value
data('Position', focusMark.squareInfo.name, 'rank')
15Change Variable
Variable
rank
Operator
+=
Value
up
16Change Variable
Variable
rank
Value
clamp(rank, 1, 8)
17Change Variable
Variable
row
Value
(rank - 1) * 8 + (file - 1)
18Change Component Value
Component Value
focusMark.squareInfo.name
Value
dataRow('Position', row)
19Set Visible
Applies to
focusMark
Visible
true
20Move The Focus MarkFunction
focusMark
focusMark
isFlipped
isFlipped
squareMeters
squareMeters
boardLeft
boardLeft
boardBottom
boardBottom