Jump to content

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">
UntilU=: {{[F.(u[_2:Z:v)}} NB. apply u until v is true
'`errmsge turnt boardb a f'=: echo@'no'`{.`}.`(0=[{b@])`(0-.@e.b) NB. get turn/board from state; position available?; board vectorfull?
'Marks State'=:'.OX' ; 10{.1
'`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
'`available full'=: (0=[{board@])`(0-.@e.board)
d=: [[:e@''@e (,' '&,)/"1@('.XO'{~3 3$b)[e@'' NB. display
you_move=: $:@errmsg^:(-.@e.i.@9)@:<:@".@(1!:1@1)
wonw=: ([:+./[: (3=[:|+/)"1@(], |:,(<@i.@2|:]),: <@i.@2|:|.)@(3 3$boardb) NB. 3 in a row (win)?
cpu_move=: (?@#{])@([:I.0=board)
outcomeo=: (' wins'echoe@,~Marks'.XO'{~-@t)`(echoe@'tie')@.(1:i.~wonw,fullf) NB. outcome
get_position=: (cpu_move`you_move@.(1 _1 i.turn))
promptpr=: echo@:>:e@i.@3 3@echoe@'you''re X''s. enter a move (1–9) each turn; asyou''re below:X''s'
move=: get_position (][errmsg)`(-@turn@] , turn@]`[`(board@])})@.available ]
showttt=: [[:echoo@''(d@echom ([,'U ',](w+.f))/"1@(Marks10{~3 3$board._1)[echo@''pr
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:'
ttt=: outcome@(show@move Until (won+.full))@State@prompt
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
you're X's. enter a move (1–9) each turn; asyou're below:X's
1 2 3
4 5 6
13

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.