Tic-tac-toe: Difference between revisions
→J: Clearer code. My prior code was too terse.
(→J: Made the output readable; coded the game to common expectations (e.g., display X’s/O’s) to avoid confusion; removed unnecessary naming of trivial functions.) Tags: Mobile edit Mobile web edit |
(→J: Clearer code. My prior code was too terse.) Tags: Mobile edit Mobile web edit |
||
(5 intermediate revisions by the same user not shown) | |||
Line 6,688:
<syntaxhighlight lang="j">
Until=: {{[F.(u[_2:Z:v)}} NB. apply u until v is true
'`ermsg turn board'=: echo@'no'`{.`}. NB. get turn/board from state vector
'`
'`
move=: get_position (][errmsg)`(-@turn@] , turn@]`[`(board@])})@.open ]
show=: [[:echo@''@echo (,' '&,)/"1@('.XO'{~3 3$board) [echo@'')
▲ get_position=: (cpu_move`you_move@.(1 _1 i.turn))
▲ outcome=: (' wins'echo@,~Marks{~-@t)`(echo@'tie')@.(1:i.~won,full)
prompt=: echo@'you''re X''s. enter a move (1–9) each turn'▼
▲ ttt=: outcome@(show@move Until (won+.full))@State@prompt
NB. use: ttt 0 (arg is ignored)
</syntaxhighlight>
The board is represented by a vector of -1's, 0’s and 1’s, which index into the character vector 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.
ttt 0▼
Note that <nowiki>U=:{{u^:(-.@:v)^:_}}</nowiki> would've quit upon receiving invalid input, as this would leave the argument unchanged.
<pre>
]M=: 0 1 _1{~?3 3$3
0 _1 _1
_1 1 1
_1 1 0
M{'.XO'
.OO
OXX
OX.
</pre>
▲Sample play:
▲<pre> ttt 0
1 2 3
4 5 6
7 8 9
. O .
Line 6,758 ⟶ 6,772:
X O O
X wins</pre>
=={{header|Java}}==
|