Tic-tac-toe: Difference between revisions
Content deleted Content added
→{{header|J}}: shorten code; prefer separate explanation over comments |
|||
(18 intermediate revisions by one other user not shown) | |||
Line 4,741:
It uses minimax with alpha-beta pruning. Therefore, the computer never loses.
[https://easylang.
<syntaxhighlight>
Line 4,828:
else
rval = alpha
start =
mov = start
repeat
Line 6,687:
=={{header|J}}==
<syntaxhighlight lang="j">
(Until=: {{[ F.(u[_2:Z:v)}}) prompt=: [ echo@'enter a move (1–9):'
'`turn board open
'`cpu_move pos'=: (?@#{])@([:I.0=board)`(cpu_move`you_move@.(_1 1 i.turn))
won=: [:+./ (3=[:|+/)"1@(], |:, (<@i.@2|:]),: <@i.@2|:|.)@(3 3$board) ▼
show=: [
▲ outcome=: (' wins'echo@,~'.XO'{~-@turn)`(echo@'tie')@.(1:i.~won,full)
</syntaxhighlight>
{{out}}
The verb <code>open</code> tests whether the selected position is available on the board. Fold (<code>F.</code>) is used because <code>Until=:<tt>{{</tt>u^:(-.@:v)^:_<tt>}}</tt></code> would've quit upon receiving invalid input, as the argument would be unchanged between that iteration and the next. ▼
<pre> ttt 0
enter a move (1–9) each turn; you're X's▼
. O .
. . .
. . .
1
Line 6,736 ⟶ 6,715:
. . .
. . O
enter a move (1–9):
5
Line 6,747 ⟶ 6,726:
. X .
. O O
enter a move (1–9):
_1
invalid!
enter a move (1–9):
7
Line 6,758 ⟶ 6,740:
O X .
X O O
enter a move (1–9):
9
already taken!
enter a move (1–9):
3
Line 6,772 ⟶ 6,750:
X O O
X wins</pre>
CPU selects a random open position.
▲This implementation is stateless (no mutation or variables) and written entirely in tacit style. The <code>turn</code> and <code>board</code> verbs extract the turn/board from the vector which represents the game state. The verb <code>open</code> tests whether the selected position is available on the board. Fold (<code>F.</code>) is used because the familiar <code>Until=:<tt>{{</tt>u^:(-.@:v)^:_<tt>}}</tt></code> idiom would've quit upon receiving invalid input, as the argument would
=={{header|Java}}==
|