# L-39 MCS 275 Mon 21 Apr 2008 : classboardtree.py

# A tree of boards consists of all moves starting
# at a given board.

from classboard import *

class BoardTree():
   """
   Exports a tic tac toe board.
   """
   def __init__(self,b):
      """
      Returns a tree with as root the
      given board.
      """
      self.b = b
      self.v = 0
      self.c = []
      self.best = 0

   def __str__(self):
      """
      Defines the string representation
      of a tree of boards.
      """
      s = self.b.__str__()
      s = s + '\nvalue = %d' % self.v
      if len(self.c) > 0:
         s = s + '\nchildren :\n'
         for i in range(0,len(self.c)):
            s = s + '\n->child %d :\n' % i
            s = s + self.c[i].__str__()
      return s

   def __repr__(self):
      """
      Takes the string representation as
      the representation of the tree.
      """
      return self.__str__()

   def moves(self,k,n):
      """
      Defines the children via all moves
      originating at self.b for pebble k,
      using n stages.
      """
      for i in range(0,3):
         for j in range(0,3):
            if self.b.m[i,j] == 0:
               nb = Board()
               nb.copyBoard(self.b.m)
               nt = BoardTree(nb)
               nt.b.m[i,j] = k
               if n > 1:
                  nk = k % 2 + 1
                  nt.moves(nk,n-1)
               self.c.append(nt)

   def values(self,k):
      """
      Assigns values to all the nodes
      in the tree of boards.
      """
      if len(self.c) == 0:
         ck = k % 2 + 1
         self.v = self.b.Value(k) - self.b.Value(ck)
      else:
         for i in range(0,len(self.c)):
            self.c[i].values(k)
         max = self.c[0].v
         self.best = 0
         if max < 0:
            self.v = max
         else:
            for i in range(1,len(self.c)):
               if self.c[i].v < 0:
                  max = self.c[i].v
               if max >= 0 and self.c[i].v > max:
                  max = self.c[i].v
                  self.best = i
            self.v = max
