RosettaCodeData/Task/Tic-tac-toe/Phix/tic-tac-toe.phix
2016-12-05 23:44:36 +01:00

85 lines
2.3 KiB
Text

sequence board = repeat(' ',9) -- {' '/'X'/'O'}
constant wins = {{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{3,5,7}}
function check_winner()
for w=1 to length(wins) do
integer {i,j,k} = wins[w],
boardi = board[i]
if boardi!=' ' and boardi=board[j] and boardi=board[k] then
return boardi
end if
end for
return 0
end function
procedure showboard()
printf(1," %c | %c | %c\n---+---+---\n %c | %c | %c\n---+---+---\n %c | %c | %c\n",board)
end procedure
integer best_i
function test_move(integer val, integer depth)
integer score = check_winner()
integer best = -1, changed = 0
if score!=0 then return iff(score=val?1:-1) end if
for i=1 to 9 do
if board[i]=' ' then
{changed,board[i]} @= val
score = -test_move('O'+'X'-val, depth + 1)
board[i] = ' '
if score>best then
if depth=0 then
best_i = i;
end if
best = score;
end if
end if
end for
return iff(changed!=0?best:0)
end function
integer user = 1
function game()
integer key, k, win
board = repeat(' ',9)
printf(1,"Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n");
printf(1,"You have O, I have X.\n\n");
for n=1 to 9 do
if(user) then
printf(1,"your move: ");
while 1 do
key = wait_key()
if find(key,{#1B,'q','Q'}) then return "Quit" end if
k = key-'0'
if k>=1 and k<=9 and board[k]=' ' then
board[k] = 'O'
printf(1,"%c\n",key)
exit
end if
end while
else
if n=1 then --/* randomize if computer opens, less boring */
best_i = rand(9)
else
{} = test_move('X', 0);
end if
board[best_i] = 'X'
printf(1," my move: %d\n", best_i);
end if
showboard();
user = 1-user
win = check_winner()
if win!=0 then
return iff(win=='O' ? "You win.\n\n" : "I win.\n\n");
end if
end for
return "A draw.\n\n";
end function
while 1 do
string res = game()
puts(1,res)
if res="Quit" then exit end if
end while