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
'Marks State'=:'.OX' ; 10{.1
'`errmsgopen turn boardfull'=: echo(0=[{board@'no'])`{(0-.`}@e. NB. get turn/board from state vector)
'`availablecpu_move fullyou_move'=: (?@#{])@([:I.0=[{board@])`(0-.<:@e".board@(1!:1@1))
get_position=: (cpu_move`you_move@.(_1 1 _1 i.turn))
you_move=: $:@errmsg^:(-.@e.i.@9)@:<:@".@(1!:1@1)
move=: get_position (][errmsg)`(-@turn@] , turn@]`[`(board@])})@.open ]
cpu_move=: (?@#{])@([:I.0=board)
show=: [[:echo@''@echo (,' '&,)/"1@('.XO'{~3 3$board) [echo@'')
get_position=: (cpu_move`you_move@.(1 _1 i.turn))
movewon=: get_position[:+./ (]3=[errmsg:|+/)`(-@turn"1@(], |:, turn@]`[`(board<@i.@2|:])}),: <@i.available@2|:|.)@(3 ]3$board)
showprompt=: [[:echo@'':>:@echo ([,' ',])/"1i.@(Marks{~3 3$board)[@echo@'enter a move (1–9) each turn; you''re X''s'
outcome=: (' wins'echo@,~Marks'.XO'{~-@tturn)`(echo@'tie')@.(1:i.~won,full)
won=: ([:+./[:(3=[:|+/)"1],|:,(<@i.@2|:]),:<@i.@2|:|.)@(3 3$board)
ttt=: outcome@(show@move Until (won+.full))@State(10{._1)@prompt
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
 
you're X's. enter a move (1–9) each turn'
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
prompt=: echo@'you''re X''s. enter a move (1–9) each turn; you're X's
1 2 3
4 5 6
7 8 9
 
. O .
Line 6,758 ⟶ 6,772:
X O O
 
X wins</pre>
 
=={{header|Java}}==
16

edits