Tic-tac-toe: Difference between revisions
→J: Made code shorter, added brief exposition about design
(→J: Attempt to fix syntax highlighting issue) Tags: Mobile edit Mobile web edit |
(→J: Made code shorter, added brief exposition about design) Tags: Mobile edit Mobile web edit |
||
Line 6,687:
=={{header|J}}==
<syntaxhighlight lang="j">
'`
'`c h q'=: (?@#{])@([:I.0=b)`(<:@".@(1!:1@1))`(c`h@.(_1 1 i.t))) NB. cpu move (random); human move; ask for next move
▲ '`errmsg turn board'=: echo@'no'`{.`}. NB. get turn/board from state vector
m=: q (][e@'no')`(-@t@] , t@]`[`(b@])})@.a ] NB. apply move
d=: [[:e@''@e (,' '&,)/"1@('.XO'{~3 3$b)[e@'' NB. display
▲ won=: ([:+./[:(3=[:|+/)"1],|:,(<@i.@2|:]),:<@i.@2|:|.)@(3 3$board)
▲ outcome=: (' wins'echo@,~Marks{~-@t)`(echo@'tie')@.(1:i.~won,full)
▲ prompt=: echo@:>:@i.@3 3@echo@'you''re X''s. enter a move (1–9) each turn as below:'
NB. use: ttt 0 (arg is ignored)
</syntaxhighlight>
The "board" is a vector of -1's, 0’s and 1’s, which shape into a matrix and index into the character vector '.XO' when it’s time to display the board.
Sample play:▼
Encoding data with numbers this way allows the convenience of e.g. being able to simply check whether the absolute value of the sum across a given line is 3, indicating a win.
Note that <code>U=:{{u^:(-.@:v)^:_}}</code> would've quit upon receiving invalid input, as this would leave the argument unchanged.
<pre>
]M=: ?3 3$3
0 2 2
2 1 1
2 1 0
M{'.XO'
.OO
OXX
OX.
</pre>
▲Sample play:
<pre> ttt 0
1 2 3
4 5 6
|