#!/usr/bin/mawk -f
BEGIN {
print "\nmu-TicTacToe (8 apr 1999) by Andrea Manzini <linux@netbusiness.it>"
print "You have naughts, I have crosses. To move, type a number 1-9"
  split("000000000",A,"")
  split("147258369123456789159357",C,"")
  split("X O",B,"")
  SEP="\n+---+---+---+\n"
  ORS=""
  turn=(2*int(rand()+0.5))-1
  while(1) {
    refresh_check()
    if (turn==1) {
      do { k=prompt() } while(k==0)
    } else {
      if (moves==0) k=5; else k=cpumove()
      print "My move: " k "\n"
    }
    moves++
    A[k]=turn
    turn=-turn
  }
}

function tris(dir)
{
 sum=0
 for(j=0;j<3;j++) sum+=A[C[j+dir]]
 return sum
}

function refresh_check()
{
  print SEP
  for(j=1;j<=9;j+=3) {
    for(i=0; i<3; i++) {
     k=B[A[i+j]+2];
     if (k==" ") print "| " (i+j) " " ; else print "| " k " "
    }
    print "|"SEP
  }
  for(i=1;i<=24;i+=3) {
    k=tris(i)
    if (k==-3) { print "\nYOU LOSE !\n" ; exit }
    if (k==3) { print "\nYOU WIN !\n" ; exit }
  }
  j=0
  for(i=1;i<=9;i++) if ( A[i]=="0" ) j=1
  if (j==0) {print "\nIT'S A DRAW !!\n"; exit}
}

function prompt() {
  i=0
  print "Enter your move: "
  getline i
  if (i<1) i=0
  if (i>9) i=0
  if (A[i]!="0") i=0
  return i
}

function cpumove() {
  for(i=1;i<=24;i+=3) if (tris(i)==-2) return (gap(i))
  for(i=1;i<=24;i+=3) if (tris(i)==2) return (gap(i))
  do { move=2*int(rand()*4)+1 } while (A[move]!=0);
  return move
}

function gap(dir) {
  for(j=0;j<3;j++) if ( A[C[j+dir]]==0 ) return (C[j+dir])
}
