
#include "grid.bas"

type tEngine
  as integer flag
  as tGrid g1, g2, g3
  as integer a(one to seven)
  as integer b(one to seven, one to seven)
  as integer c(one to seven, one to seven, one to seven)
  declare function BestMove(g as tGrid, p as integer) as integer
end type

function tEngine.BestMove(g as tGrid, p as integer) as integer
  const impossible = -100
  dim as integer i, j, k, result
  dim aux(one to seven) as integer
  g1.Empty
  g2.Empty
  g3.Empty
  
  for i = one to seven
    g1.Copy(g.array())
    if g1.Insert(p, i) then
      for j = one to seven
        g2.Copy(g1.array())
        if g2.Insert(cBlack * p, j) then
          for k = one to seven
            g3.Copy(g2.array())
            if g3.Insert(p, k) then
              c(i, j, k) = g3.GridPoints(p)
            else
              c(i, j, k) = impossible
            end if
          next k
          b(i, j) = g2.GridPoints(cBlack * p)
        else
          b(i, j) = impossible
        end if
      next j
      a(i) = g1.GridPoints(p)
    else
      a(i) = impossible
    end if
  next i
  
  i = Maximum(a())
  if i >= four then
    result = IndexOf(a(), i)
    flag = 1
  else
    for i = one to seven
      for j = one to seven
        aux(j) = b(i, j)
      next j
      a(i) -= Maximum(aux())
    next i
    i = Maximum(a())
    if NumberOf(a(), i) <= 3 then
      result = IndexOf(a(), i)
      flag = 2
    else
      for i = one to seven
        for j = one to seven
          for k = one to seven
            aux(k) = c(i, j, k)
          next k
          b(i, j) = Maximum(aux())
        next j
        for j = one to seven
          aux(j) = b(i, j)
        next j
        a(i) += Minimum(aux())
      next i
      i = Maximum(a())
      if NumberOf(a(), i) <= 3 then
        result = IndexOf(a(), i)
        flag = 3
      else
        for i = one to seven
          a(i) -= Abs(i - 4)
        next i
        i = Maximum(a())
        result = IndexOf(a(), i)
        flag = 4
      end if
    end if
  end if
  
  return result
end function
