
#include "functions.bas"
#include "lines.bas"

const one     =  1
const four    =  4
const six     =  6
const seven   =  7
const nothing =  0
const piece   =  1
const border  =  2
const cBlack  = -1
const cWhite  =  1

enum boolean
  true = -1
  false = not true
end enum

type tGrid
  as integer array(one - 1 to seven + 1, one - 1 to six + 1)
  declare sub Empty
  declare sub Copy(g() as integer)
  declare function IsFull as boolean
  declare function Insert(p as integer, x as integer) as boolean
  declare function LinePoints(l as tLine, p as integer) as integer
  declare function GridPoints(p as integer) as integer
  declare function AsString as string
end type

sub tGrid.Empty
  dim as integer x, y
  for x = one - 1 to seven + 1
    for y = one - 1 to six + 1
      array(x, y) = border
    next y
  next x
  for x = one to seven
    for y = one to six
      array(x, y) = nothing
    next y
  next x
end sub

sub tGrid.Copy(g() as integer)
  for x as integer = one to seven
    for y as integer = one to six
      array(x, y) = g(x, y)
    next y
  next x
end sub

function tGrid.IsFull as boolean
  dim result as boolean = true
  dim x as integer = one
  do while (x <= seven) and result
    if array(x, six) = nothing then result = false
    x += 1
  loop
  return result
end function

function tGrid.Insert(p as integer, x as integer) as boolean
  dim y as integer = six
  dim result as boolean = (array(x, y) = nothing)
  if result then
    do while (array(x, y - 1) = nothing)
      y -= 1
    loop
    array(x, y) = p
  end if
  return result
end function

function tGrid.LinePoints(l as tLine, p as integer) as integer
  dim as integer x, y, n=0, o=0, nmx=0, omx=0, result
  x = l.x1
  y = l.y1
  do while array(x, y) <> border
    if array(x, y) = p then n += 1 else n = 0
    if array(x, y) <> cBlack * p then o += 1 else o = 0
    if n > nmx then nmx = n
    if o > omx then omx = o
    x += l.dx
    y += l.dy 
  loop
  if omx < 4 then result = 0 else result = nmx
  return result
end function

function tGrid.GridPoints(p as integer) as integer
  dim aux(24) as integer
  for i as integer = 0 to 24
    aux(i) = LinePoints(lines(i), p)
  next i
  return Maximum(aux())
end function

function tGrid.AsString as string
  dim result as string = ""
  for y as integer = six + 1 to one - 1 step -1
    for x as integer = one - 1 to seven + 1
      select case array(x, y)
        case nothing
          result = result & " "
        case piece * cWhite
          result = result & "W"
        case piece * cBlack
          result = result & "B"
        case border
          result = result & "#"
      end select
    next x
    result = result & chr(13,10)
  next y
  return result
end function
