from board import Board
from display import Display
from vector import Vec2d
from chris import Chris
from heuristicMaker import HeuristicMaker

import time
import graphicsUtils
import math
import numpy
import threading



class Controller(object):
    
    def __init__(self, againstHuman):
        Display.initGraphics()
        #self.heuristicMaker = HeuristicMaker()
        self.chris = Chris()
        self.gameBoard = Board()
        self.gameOver = False
        self.againstHuman = againstHuman

    def run(self):
        while True:
            keys = Display.getKeys()
            userMove = self.getPlayerAMove(keys)
            assert self.gameBoard.isUserTurn()
            legalMoves = self.gameBoard.getLegalActions()
            if userMove != None and userMove in legalMoves:
                self.makeMove(userMove, True)
                Display.graphicsSleep(0.1)
                if self.gameOver: break
                computerMove = self.getChrisMove()
                self.makeMove(computerMove, False)
                Display.graphicsSleep(0.1)
                if self.gameOver: break
            Display.graphicsSleep(0.1)
        self.announceWinner() 
        while True:
            Display.graphicsSleep(0.1)  

    def announceWinner(self):
        if self.winner == 'h':
            print 'YOU WIN!!!!!!'
        else:
            print 'You lose :('
    
    def getChrisMove(self):
        return self.chris.getMove(self.gameBoard)

    def makeMove(self, move, isUser):
        row = self.gameBoard.getHeight(move)
        Display.drawPiece(row, move, isUser)
        self.gameBoard.makeMove(move, isUser)
        
        if self.gameBoard.isTerminal():
            self.gameOver = True
            self.winner = 'c'
            if isUser: self.winner = 'h'

    def printBoard(self):
        for r in range(ROWS - 1, 0 - 1, -1):
            rowString = ''
            for c in range(COLS):
                rowString += self.board[r][c] + ' '
            print rowString

    def getPlayerAMove(self, keys):
        if self.againstHuman:
            return self.getUserMove(keys)
        return yourAlgo.getMove(self.gameBoard)

    def getUserMove(self, keys):
        for i in range(1, 8):
            if str(i) in keys:
                return i - 1
        return None

            
        
