Tic-tac-toe: Difference between revisions

→‎J: Clearer code. My prior code was too terse.
(→‎J: Attempt to correct bad templating)
Tags: Mobile edit Mobile web edit
(→‎J: Clearer code. My prior code was too terse.)
Tags: Mobile edit Mobile web edit
Line 6,686:
 
=={{header|J}}==
<syntaxhighlight lang="j">
UUntil=: {{[F.(u[_2:Z:v)}} NB. apply u until v is true
'`eermsg tturn b a fboard'=: echo@'no'`{.`}.`(0=[{b@])`(0-.@e.b) NB. get turn/board from state; position available?; board full?vector
'`open full'=: (0=[{board@])`(0-.@e.board)
'`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
'`cpu_move you_move'=: (?@#{])@([:I.0=board)`(<:@".@(1!:1@1))
m=: q (][e@'no')`(-@t@] , t@]`[`(b@])})@.a ] NB. apply move
get_position=: cpu_move`you_move@.(_1 1 i.turn)
d=: [[:e@''@e (,' '&,)/"1@('.XO'{~3 3$b)[e@'' NB. display
move=: get_position (][errmsg)`(-@turn@] , turn@]`[`(board@])})@.open ]
w=: [:+./ (3=[:|+/)"1@(], |:,(<@i.@2|:]),: <@i.@2|:|.)@(3 3$b) NB. 3 in a row (win)?
oshow=: [[:echo@''@echo (,' wins'e&,)/"1@,~('.XO'{~-@t3 3$board)`(e [echo@'tie')@.(1:i.~w,f) NB. outcome
wwon=: [:+./ (3=[:|+/)"1@(], |:, (<@i.@2|:]),: <@i.@2|:|.)@(3 3$b) NB. 3 in a row (winboard)?
prprompt=: eecho@:>:@i.@3 3@eecho@'enter a move (1–9) each turn; you''re X''s'
ttt=: o@(d@m U (w+.f))@(10{._1)@pr
outcome=: (' wins'echo@,~'.XO'{~-@turn)`(echo@'tie')@.(1:i.~won,full)
ttt=: ooutcome@(dshow@mmove UUntil (wwon+.ffull))@(10{._1)@prprompt
NB. use: ttt 0 (arg is ignored)
</syntaxhighlight>
The "board" is represented by 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.
 
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.
Line 6,704 ⟶ 6,706:
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 2_1 2_1
2_1 1 1
2_1 1 0
M{'.XO'
.OO
13

edits