Possible games

In this chapter we will look at how to see if a move has won the game.

As usual, we will prepare the ground by copying in the work we did in the previous chapter and setting ⎕io to zero.

)copy notebook3
Rebuilding user command cache... done
./notebook3.dws saved Wed Dec 30 11:41:14 2020
⎕io  0

Win, lose, draw

How can we find if a position is a winning position?

We need to see if there’s a row, a column or a diagonal where there are three ×s or three s.

We will start by finding a way to pick out the contents of all the positions that could lead to a win.

If we create a 3 by 3 matrix on the numbers from zero to nine we could list the indices that correspond to a winning line.

3 3⍴⍳9
0 1 2 3 4 5 6 7 8

The candidates seem to be the rows: 0 1 2 3 4 5 6 7 8 the columns: 0 3 6 1 4 7 2 5 8 the diagonals: 0 4 8 2 4 6

Actually, we can get APL to check our work. APL has two relevant functions, reverse and transpose .

i  3 3⍴⍳9
wpi  {rows    cols    diagonals  2 3⍴↑(0 0) (0 0⍉⌽)  ⊃⍪/rows cols diagonals} 3 3⍴⍳9
0 1 2 3 4 5 6 7 8 0 3 6 1 4 7 2 5 8 0 4 8 2 4 6

Now we can use wpi to write a function wf which will tell us if a position is a win or not.

We’ll use ild to create the possible locations for three-in-a-row ×s and s, and then use 1 2∘.= to see where each location contains a × or a . Finally, we and () each element in a row of three, or () the results, and or them again to find out if there’s a win.

wf ← {∨⌿∨/^/1 2∘.=wpi ild ⍵} ⍝ is this a win?
wf 1 1 1 0 2 2 0 0 0
1
wf 2 0 1 2 0 1 2 1 0
1
wf 1 2 1 0 1 0 2 2 0
0

Let’s see how many of the unique canonical possible positions are wins.

+/wf ucp
220

Let’s check them. We’ll create a function wp which filters out wins from a matrix of positions, apply it to ucp, and show the first few.

wp  {⌿⍨wf }
list 19wp ucp
┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐ │...│...│...│...│...│...│..×│..×│..×│..×│..×│..×│..×│..×│..×│..×│..×│..×│..×│ │.○○│×××│×××│×××│○.○│○○○│..×│.×.│.××│.×○│.×○│.○×│.○×│×.×│××.│×××│××○│×○×│○.×│ │×××│.○○│○.○│○○○│×××│×××│○○×│×○○│○○○│×○.│×○○│○.×│○○×│○○○│○○○│○○○│×○○│○○×│.○×│ └───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘
)save notebook4 -force
notebook4.dws saved Wed Dec 30 11:41:51 2020