Related sites: | site map |

# aiju.de Home of aiju

- › about me/
- › b/
- » code/
- - › RatJS
  - › homework/
  - » k/
  - - › cluster
    - › coins
    - › eratothenes
    - › euler phi
    - › feigenbaum
    - › fibonacci
    - › fsm
    - › molecule
    - › pascal
    - › qsort
    - › sierpinski
    - » tictactoe
  - › misc/
  - › pdp11/
- › donate
- › electronics/
- › legal
- › misc/
- › plan 9/

# Tic Tac Toe

    rows:(0 1 2; 3 4 5; 6 7 8; 0 3 6; 1 4 7; 2 5 8; 0 4 8; 2 4 6)
    win:{|/&/+1=/:x@/:rows}
    lose:{|/&/+0=/:x@/:rows}
    end:{:[lose x; -1; :[win x; 1; :[|/-1=x; -2; 0]]]}
    change:{[x;z] {[y] (y # x),z,((y+1) _ x)}}
    next:{change[x;y]'&(x=-1)}
    rnext:{[y]{[x]:[~(-2)=end x; ,x; ,/rnext[1-y]'next[x;y]]}}
    best:{[s] {x@*>{{(+/x)%#x}@ end' rnext[0] x}'x} next[s;1]}
    pp:{`0:3 3#(+((" XO"@/:1+x);(_ci 49+!9)))@'x=-1}
    tonum:{a:_ic x; :[(~1=#a)|(49>*a)|(57<*a);-1;*a-49]}
    board:-1 -1 -1 -1 -1 -1 -1 -1 -1
    while[-2=end board;
        pp board;x:-2;y:-1
        while[(0>x)|(-1)<y;:[-1=x;`0:"?\n";];`0:"- ";x:tonum[0:`];:[0<x;y:board[x]]]
        board:change[board;0]@x
        pp board;`0:,""
        if[-2=end board;board:best board]
    ]
    pp board
    if[1=end board;`0:"You lose\n"]
    if[0=end board;`0:"Tie\n"]
    if[(-1)=end board;`0:"You win\n"]
    \\

This programs plays tic tac toe and is unbeatable (in theory). It tries out all possible moves and is a bit slow. If you want some fun you can replace the line

    best:{[s] {x@*>{{(+/x)%#x}@ end' rnext[0] x}'x} next[s;1]}

by

    best:{[s] {x@*<{{(+/x)%#x}@ end' rnext[0] x}'x} next[s;1]}

This will make it never win.