NCL 309: Winning the Game
In the previous lesson, we built a board, moved a selection around it, and placed Crosses into its cells.
We also built something else: a small piece of shared drawing code.
Each time we wanted to use it, we stored a label in #return, jumped to the drawing code, then jumped back through #return when it was finished.
It worked.
It was also awkward.
NCL has a better way.
Calling a Subroutine
Here is the pattern we used in the previous lesson:
MOVE #return :after_draw
JUMP :draw_cell
:after_draw
The drawing code eventually returned with:
JUMP #return
We needed a memory location to remember where the drawing code should return, and a different return label for every place that used it.
This pattern is common enough that NCL provides an instruction for it:
CALL <target>
CALL jumps to another part of the program while remembering where execution should continue afterward.
Our drawing code can now be used with:
CALL :draw_cell
Code designed to be called this way is called a subroutine.
A subroutine returns with another instruction:
RET
For example, our drawing code can end with:
:draw_glyph
D.CUR #x #y
D.CHR #glyph
RET
When RET executes, the program continues with the instruction immediately following the most recent CALL.
So:
CALL :draw_cell
JUMP :input
means:
- remember the instruction after
CALL; - jump to
:draw_cell; - run the drawing code;
- reach
RET; - return to
JUMP :input.
We no longer need #return, or labels such as :after_left_old and :after_left_new.
Subroutines can call subroutines
A subroutine can use CALL itself.
Each RET returns from the most recent unfinished CALL.
That means one subroutine can call another without losing the return destination of its own caller.
We'll take advantage of that shortly.
Is this how real processors call subroutines?
Yes, although different processor families provide different machinery for remembering the return address.
Some processors have instructions that save a return address on a stack. Others place it in a register, leaving software to preserve it when calls are nested.
The basic problem is the same one we just solved manually:
Jump somewhere, remember where you came from, then get back.
CALL and RET give NCL that operation directly.
We'll look more closely at where those remembered return addresses go later in the course.
Adding the Other Player
So far, each board cell has had two possible values:
| Value | Meaning |
|---|---|
0 |
Empty |
1 |
Cross |
Let's add Nought.
We could choose almost any other value, but we'll use a representation that gives the values some useful arithmetic meaning:
| Value | Meaning |
|---|---|
-1 |
Nought |
0 |
Empty |
1 |
Cross |
Add a glyph for Nought:
#cross "\uE573"
#nought "\uE5CB"
#empty "\u3000"
We'll also keep track of whose turn it is:
#player $00B
Cross goes first:
MOVE #player 1
When a player places a piece, we no longer always store 1:
MOVE #cell4 1
Instead, we store the current player:
MOVE #cell4 #player
Now the board remembers whether each occupied square belongs to Cross or Nought.
After a successful move, we need to alternate between 1 and -1.
For that, we'll introduce another arithmetic instruction.
Negating a Number
NEG changes the sign of a value:
NEG <dst> <value>
For example:
NEG #player #player
If #player contains 1, it becomes -1.
If it contains -1, it becomes 1.
One instruction can therefore alternate between our two players.
The drawing subroutine also needs to recognize both values:
S.MOVE #glyph #empty
BEQ :use_cross #value 1
BEQ :use_nought #value -1
JUMP :paint
:use_cross
S.MOVE #glyph #cross
JUMP :paint
:use_nought
S.MOVE #glyph #nought
The board now remembers which player owns every occupied cell.
Our choice of 1 and -1 is about to become useful for more than drawing.
What Makes a Winning Line?
Consider the top row.
If Cross owns all three cells:
1 + 1 + 1 = 3
If Nought owns all three:
-1 + -1 + -1 = -3
An incomplete line produces something between those two extremes.
For example:
1 + 1 + 0 = 2
or:
-1 + 0 + 1 = 0
Only the two extremes can represent a completed line:
3 = Cross owns all three cells
-3 = Nought owns all three cells
The representation is doing useful work
We could have chosen almost any three different values for Nought, empty, and Cross.
Choosing -1, 0, and 1 gives those values useful arithmetic meaning.
Adding three cells together now tells us something about the balance of a line, and 3 or -3 identifies a completed line immediately.
Our board has eight possible winning lines:
| Line | Cells |
|---|---|
| Top row | 0, 1, 2 |
| Middle row | 3, 4, 5 |
| Bottom row | 6, 7, 8 |
| Left column | 0, 3, 6 |
| Middle column | 1, 4, 7 |
| Right column | 2, 5, 8 |
| Diagonal | 0, 4, 8 |
| Diagonal | 2, 4, 6 |
We could simply check each line for 3 or -3.
Instead, we're going to calculate a little more information: the strongest line belonging to each player.
That will tell us more about the state of the board than only whether somebody has won.
We'll need three more arithmetic instructions.
Finding an Absolute Value
Sometimes we care about the size of a number without caring whether it is positive or negative.
ABS produces the absolute value of a number:
ABS <dst> <value>
For example:
ABS 5 = 5
ABS -5 = 5
We'll use this when we care about the strength of a line without caring which player it favors.
Choosing the Larger Value
MAX chooses the larger of two values:
MAX <dst> <a> <b>
For example:
MAX #result 4 7
stores 7 in #result.
Choosing the Smaller Value
MIN chooses the smaller of two values:
MIN <dst> <a> <b>
For example:
MIN #result 4 7
stores 4 in #result.
Operations we could build ourselves
NEG, ABS, MAX, and MIN are convenient instructions, but none gives the processor a fundamentally new ability.
We can already build each operation from instructions we've learned.
Negation:
SUB #result 0 #value
Absolute value:
MOVE #result #value
BGE :abs_done #result 0
SUB #result 0 #result
:abs_done
Maximum:
MOVE #result #a
BGE :max_done #a #b
MOVE #result #b
:max_done
Minimum:
MOVE #result #a
BLE :min_done #a #b
MOVE #result #b
:min_done
The shorter forms package familiar combinations of arithmetic, branches, and moves into single instructions with useful names.
Checking a Line
We only need one location for the value of the current line:
#line $00C
The top row contains cells 0, 1, and 2.
Its subroutine simply adds them:
:check_top
ADD #line #cell0 #cell1
ADD #line #line #cell2
RET
Every time we call:
CALL :check_top
#line receives the sum of those three cells.
A diagonal works exactly the same way with different cells:
:check_diagonal1
ADD #line #cell0 #cell4
ADD #line #line #cell8
RET
The other six winning lines follow the same pattern.
Each subroutine answers one question:
What is the sum of this line?
It leaves that answer in #line.
We could call all eight and test every result individually.
Instead, we'll summarize them as we go.
Finding the Strongest Lines
A line can have a value from -3 through 3.
We'll keep track of:
#highest $00D
#lowest $00E
#highest will remember the highest line value we've seen.
#lowest will remember the lowest.
Before checking the board, initialize them at opposite extremes:
MOVE #highest -3
MOVE #lowest 3
Now check the first line:
CALL :check_top
MAX #highest #highest #line
MIN #lowest #lowest #line
Suppose the top row has a value of 2.
MAX compares -3 with 2, so:
highest = 2
MIN compares 3 with 2, so:
lowest = 2
Then we can reuse #line for another line:
CALL :check_middle
MAX #highest #highest #line
MIN #lowest #lowest #line
We don't need to remember every individual line value.
Once a line has been compared with #highest and #lowest, #line can be reused for the next one.
Put the whole operation into another subroutine:
:check_win
MOVE #highest -3
MOVE #lowest 3
CALL :check_top
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_middle
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_bottom
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_left
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_center
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_right
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_diagonal1
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_diagonal2
MAX #highest #highest #line
MIN #lowest #lowest #line
RET
This is our first important use of one subroutine calling another.
Suppose the game does this:
CALL :check_win
Execution begins in :check_win.
Then :check_win does this:
CALL :check_top
So the path looks like:
game
CALL :check_win
:check_win
CALL :check_top
:check_top
...
RET
:check_win
...
RET
game
The first RET returns from :check_top to :check_win.
The second returns from :check_win to the game.
Our hand-made #return from the previous lesson couldn't safely do this. Calling :check_top would overwrite the return destination that :check_win still needed.
CALL and RET keep track of those unfinished returns for us.
Who Won?
After:
CALL :check_win
#highest contains the strongest result for Cross, while #lowest contains the strongest result for Nought.
For example:
highest = 2
lowest = -1
Neither player has won.
Or:
highest = 1
lowest = -3
Nought has a complete line.
The sign tells us which player a line favors.
Its absolute value tells us its strength.
Add one more working location:
#strength $00F
First, remove the sign from Nought's strongest line:
ABS #strength #lowest
Then compare its magnitude with Cross's strongest line:
MAX #strength #highest #strength
Now #strength contains the strength of the strongest line belonging to either player.
If it reaches 3, somebody has won:
BNEQ :no_winner #strength 3
BEQ :cross_wins #highest 3
JUMP :nought_wins
:no_winner
We first ask:
Does either player have a line with strength
3?
Only then do we ask:
Which player has it?
The magnitude tells us whether somebody won.
The sign tells us who.
When the Board Is Full
There is one more way the game can end.
Neither player may complete a line before all nine cells are occupied.
We could inspect all nine cells to determine whether the board is full.
But we already know something simpler:
Every successful move fills exactly one previously empty cell.
So we'll count successful moves:
#moves $010
Initialize the counter with the board:
MOVE #moves 0
Whenever a player successfully places a piece:
INC #moves
Don't increment it when the selected cell is already occupied.
After each successful move, the game can now follow this order:
INC #moves
CALL :check_win
ABS #strength #lowest
MAX #strength #highest #strength
BNEQ :no_winner #strength 3
BEQ :cross_wins #highest 3
JUMP :nought_wins
:no_winner
BEQ :draw #moves 9
NEG #player #player
JUMP :input
Check for a win before a draw
The ninth move fills the board, but it may also complete a winning line.
After a successful move, check for a winner first.
Only if nobody won should #moves == 9 mean a draw.
If the game continues, NEG changes the current player and we wait for another move.
Finishing the Game
The three endings can replace the controls at the bottom of the Display:
:cross_wins
D.CUR 9 9
D.TXT "CROSS WINS! "
D.BLT
JUMP 0
:nought_wins
D.CUR 9 9
D.TXT "NOUGHT WINS! "
D.BLT
JUMP 0
:draw
D.CUR 9 9
D.TXT "DRAW! "
D.BLT
JUMP 0
We now have a complete two-player game.
The board itself still contains nothing more complicated than nine integers:
-1 = Nought
0 = Empty
1 = Cross
From those values, the program derives everything it needs to know about the game.
It adds cells together to describe a line.
It uses MIN and MAX to summarize all eight lines.
It uses ABS when the magnitude matters more than the sign.
It uses NEG to move cleanly between the two players.
And it uses CALL and RET to organize those operations into reusable subroutines.
The instructions we added didn't give the computer fundamentally new arithmetic abilities.
What changed is how directly we can express those operations—and how easily we can organize increasingly complicated programs.
The Complete Program
We've changed quite a lot since the previous lesson.
The movement and drawing code should still look familiar. The important additions are the second player, the move counter, the line-checking subroutines, and :check_win.
Complete program
#selection $000
#column $001
#row $002
#x $003
#y $004
#key $005
#draw_cell $006
#value $007
#selected $008
#glyph $009
#player $00B
#line $00C
#highest $00D
#lowest $00E
#strength $00F
#moves $010
#empty "\u3000"
#cross "\uE573"
#nought "\uE5CB"
#cell0 $020
#cell1 $021
#cell2 $022
#cell3 $023
#cell4 $024
#cell5 $025
#cell6 $026
#cell7 $027
#cell8 $028
-- Start the game.
MOVE #selection 0
MOVE #player 1
MOVE #moves 0
-- Draw the board.
D.FIL " "
D.CUR 11 2
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.CUR 11 3
D.TXT "\uE500\uE53C\uE500\uE53C\uE500"
D.CUR 11 4
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.CUR 11 5
D.TXT "\uE500\uE53C\uE500\uE53C\uE500"
D.CUR 11 6
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.TXT "\uE502"
D.TXT #empty
D.CUR 9 8
D.TXT "ARROWS MOVE"
D.CUR 9 9
D.TXT "ENTER PLACE"
D.CUR 9 10
D.TXT "ESC TO EXIT"
D.BLT
-- Draw the initial selection.
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
-- Wait for input.
:input
SYS.AKEY #key
S.BEQ :left #key "LEFT"
S.BEQ :right #key "RIGHT"
S.BEQ :up #key "UP"
S.BEQ :down #key "DOWN"
S.BEQ :place #key "ENTER"
S.BEQ :exit #key "ESC"
JUMP :input
-- Move left.
:left
MOD #column #selection 3
BEQ :input #column 0
MOVE #draw_cell #selection
MOVE #selected 0
CALL :draw_cell
DEC #selection
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
JUMP :input
-- Move right.
:right
MOD #column #selection 3
BEQ :input #column 2
MOVE #draw_cell #selection
MOVE #selected 0
CALL :draw_cell
INC #selection
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
JUMP :input
-- Move up.
:up
BLT :input #selection 3
MOVE #draw_cell #selection
MOVE #selected 0
CALL :draw_cell
SUB #selection #selection 3
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
JUMP :input
-- Move down.
:down
BGE :input #selection 6
MOVE #draw_cell #selection
MOVE #selected 0
CALL :draw_cell
ADD #selection #selection 3
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
JUMP :input
-- Place the current player's piece.
:place
BEQ :place0 #selection 0
BEQ :place1 #selection 1
BEQ :place2 #selection 2
BEQ :place3 #selection 3
BEQ :place4 #selection 4
BEQ :place5 #selection 5
BEQ :place6 #selection 6
BEQ :place7 #selection 7
JUMP :place8
:place0
BNEQ :input #cell0 0
MOVE #cell0 #player
JUMP :placed
:place1
BNEQ :input #cell1 0
MOVE #cell1 #player
JUMP :placed
:place2
BNEQ :input #cell2 0
MOVE #cell2 #player
JUMP :placed
:place3
BNEQ :input #cell3 0
MOVE #cell3 #player
JUMP :placed
:place4
BNEQ :input #cell4 0
MOVE #cell4 #player
JUMP :placed
:place5
BNEQ :input #cell5 0
MOVE #cell5 #player
JUMP :placed
:place6
BNEQ :input #cell6 0
MOVE #cell6 #player
JUMP :placed
:place7
BNEQ :input #cell7 0
MOVE #cell7 #player
JUMP :placed
:place8
BNEQ :input #cell8 0
MOVE #cell8 #player
-- Redraw the placed piece and check the game.
:placed
INC #moves
MOVE #draw_cell #selection
MOVE #selected 1
CALL :draw_cell
CALL :check_win
ABS #strength #lowest
MAX #strength #highest #strength
BNEQ :no_winner #strength 3
BEQ :cross_wins #highest 3
JUMP :nought_wins
:no_winner
BEQ :draw #moves 9
NEG #player #player
JUMP :input
-- Look up the requested board cell.
:draw_cell
BEQ :draw0 #draw_cell 0
BEQ :draw1 #draw_cell 1
BEQ :draw2 #draw_cell 2
BEQ :draw3 #draw_cell 3
BEQ :draw4 #draw_cell 4
BEQ :draw5 #draw_cell 5
BEQ :draw6 #draw_cell 6
BEQ :draw7 #draw_cell 7
JUMP :draw8
:draw0
MOVE #value #cell0
JUMP :choose_glyph
:draw1
MOVE #value #cell1
JUMP :choose_glyph
:draw2
MOVE #value #cell2
JUMP :choose_glyph
:draw3
MOVE #value #cell3
JUMP :choose_glyph
:draw4
MOVE #value #cell4
JUMP :choose_glyph
:draw5
MOVE #value #cell5
JUMP :choose_glyph
:draw6
MOVE #value #cell6
JUMP :choose_glyph
:draw7
MOVE #value #cell7
JUMP :choose_glyph
:draw8
MOVE #value #cell8
-- Choose the visible glyph.
:choose_glyph
S.MOVE #glyph #empty
BEQ :use_cross #value 1
BEQ :use_nought #value -1
JUMP :paint
:use_cross
S.MOVE #glyph #cross
JUMP :paint
:use_nought
S.MOVE #glyph #nought
-- Find the Display position.
:paint
MOD #column #draw_cell 3
DIV #row #draw_cell 3
MUL #x #column 4
ADD #x #x 11
MUL #y #row 2
ADD #y #y 2
-- Choose whether the square is selected.
D.COL #D.COL.WHITE #D.TXT.NORMAL
BEQ :paint_selected #selected 1
JUMP :paint_glyph
:paint_selected
D.COL #D.COL.WHITE #D.TXT.INVERT
:paint_glyph
D.CUR #x #y
D.CHR #glyph
RET
-- Check each winning line.
:check_top
ADD #line #cell0 #cell1
ADD #line #line #cell2
RET
:check_middle
ADD #line #cell3 #cell4
ADD #line #line #cell5
RET
:check_bottom
ADD #line #cell6 #cell7
ADD #line #line #cell8
RET
:check_left
ADD #line #cell0 #cell3
ADD #line #line #cell6
RET
:check_center
ADD #line #cell1 #cell4
ADD #line #line #cell7
RET
:check_right
ADD #line #cell2 #cell5
ADD #line #line #cell8
RET
:check_diagonal1
ADD #line #cell0 #cell4
ADD #line #line #cell8
RET
:check_diagonal2
ADD #line #cell2 #cell4
ADD #line #line #cell6
RET
-- Find the highest and lowest line values.
:check_win
MOVE #highest -3
MOVE #lowest 3
CALL :check_top
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_middle
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_bottom
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_left
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_center
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_right
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_diagonal1
MAX #highest #highest #line
MIN #lowest #lowest #line
CALL :check_diagonal2
MAX #highest #highest #line
MIN #lowest #lowest #line
RET
-- Finish the game.
:cross_wins
D.CUR 9 9
D.TXT "CROSS WINS! "
D.BLT
JUMP 0
:nought_wins
D.CUR 9 9
D.TXT "NOUGHT WINS! "
D.BLT
JUMP 0
:draw
D.CUR 9 9
D.TXT "DRAW! "
D.BLT
JUMP 0
:exit
JUMP 0
Try It
Run the game with another person and take turns placing pieces.
Try winning with:
- a row;
- a column;
- each diagonal.
Then fill the board without either player completing a line and confirm that the game ends in a draw.
While playing, stop before making a move and look at the nine cell values.
Calculate the eight line sums yourself.
What should #highest contain?
What should #lowest contain?
What should #strength contain?
Then make the move and see how those values change.
We started the last lesson manually remembering where shared code should return.
Now CALL and RET let subroutines call one another without managing those return destinations ourselves.
At the same time, our choice of -1, 0, and 1 turned the board into something we can reason about with ordinary arithmetic.
The program can now understand the board after a move.
In the next lesson, NCL 310: The Computer's Turn, we'll see what happens when it starts asking about moves that haven't happened yet.