RosettaCodeData/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy
2026-04-30 12:34:36 -04:00

129 lines
2.2 KiB
Text

len f[] 9
state = 0
gtextsize 13
#
proc init .
glinewidth 2
gclear
gcolor 666
gline 34 96 34 20
gline 62 96 62 20
gline 10 72 86 72
gline 10 44 86 44
glinewidth 2.5
for i = 1 to 9 : f[i] = 0
if state = 1 : timer 0.2
.
proc draw ind .
c = (ind - 1) mod 3
r = (ind - 1) div 3
x = c * 28 + 20
y = r * 28 + 30
if f[ind] = 4
gcolor 900
gline x - 7 y - 7 x + 7 y + 7
gline x + 7 y - 7 x - 7 y + 7
elif f[ind] = 1
gcolor 009
gcircle x y 10
gcolor -2
gcircle x y 7.5
.
.
proc sum3 a d &st .
for i = 1 to 3
s += f[a]
a += d
.
if s = 3
st = -1
elif s = 12
st = 1
.
.
proc rate &res &done .
res = 0
for i = 1 step 3 to 7 : sum3 i 1 res
for i = 1 to 3 : sum3 i 3 res
sum3 1 4 res
sum3 3 2 res
cnt = 1
for i = 1 to 9
if f[i] = 0 : cnt += 1
.
res *= cnt
done = 0
if res <> 0 or cnt = 1 : done = 1
.
proc minmax player alpha beta &rval &rmov .
rate rval done
if done = 1
if player = 1 : rval = -rval
return
.
rval = alpha
start = random 1 9
mov = start
repeat
if f[mov] = 0
f[mov] = player
minmax (5 - player) (-beta) (-rval) val h
val = -val
f[mov] = 0
if val > rval
rval = val
rmov = mov
.
.
mov = mov mod 9 + 1
until mov = start or rval >= beta
.
.
proc show_result val .
gcolor 555
if val < 0
# this never happens
gtext 16 4 "You won"
elif val > 0
gtext 16 4 "You lost"
else
gtext 16 4 "Tie"
.
state += 2
.
proc computer_turn .
minmax 4 -11 11 val mov
f[mov] = 4
draw mov
rate val done
if done = 1
timer 0.5
else
state = 0
.
.
proc human_turn .
mov = floor ((mouse_x - 6) / 28) + 3 * floor ((mouse_y - 16) / 28) + 1
if f[mov] <> 0 : return
f[mov] = 1
draw mov
state = 1
timer 0.5
.
on timer
rate val done
if done = 1
show_result val
else
computer_turn
.
.
on mouse_down
if state = 0 and mouse_x - 6 < 84 and mouse_y > 16
human_turn
elif state >= 2
state -= 2
init
.
.
init