#Copyright (c) 2016 Shaun Ramsey 
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


import sys
import copy

# the board consists of 


class Mancala:

    FirstTurn = True
    FirstBoard = []
    SecondBoard = []
    FirstShole = 0
    SecondShole = 0
    
    def __init__(self):
        self.FirstTurn = True
        #these numbers are displayed in reverse....from right to left
        self.FirstBoard = [ 4, 4, 4, 4, 4, 4 ]
        self.FirstShole = 0
        #displayed in order from left to right
        self.SecondBoard = [ 4, 4, 4, 4, 4, 4 ]
        self.SecondShole = 0


    def setBoard(self, turn, fb, fs, sb, ss):
        self.FirstTurn = turn
        self.FirstBoard = fb
        self.FirstShole = fs
        self.SecondBoard = sb
        self.SecondShole = ss
        
#########################################################
# this will display the board
    def display(self):
        print " ************************************************************** "
        if self.FirstTurn is True:
            print "       5   4   3   2   1   0 ";
        print  " <-----------------------------"
        print "      ",
        for i in reversed(self.FirstBoard):
            print "%-*s" % (3, i),
        print ""
        print "   ",
        print "%-*s" % (3, self.FirstShole),
        print "%-*s" % (21, " "),
        print "%-*s" % (3, self.SecondShole)
        print "      ",
        for i in self.SecondBoard:
            print "%-*s" % (3, i),
        print""
        print  " ------------------------------> "
        if self.FirstTurn is False:
            print "       0   1   2   3   4   5 ";



#this moves stones from in hand and drops them into holes on the first person's side
#if it is the first person's turn, it might reap special benefits
    def firstMove(self, choice, stonesInHand, turn):
        while choice <= 5 and stonesInHand > 0:
            self.FirstBoard[choice] = self.FirstBoard[choice] + 1
            stonesInHand = stonesInHand - 1;
            if turn is True and stonesInHand == 0 and self.FirstBoard[choice] == 1: #placed the last stone in empty hole
                if self.SecondBoard[5-choice] != 0:
                    self.FirstBoard[choice] = 0
                    self.FirstShole = self.FirstShole + 1 + self.SecondBoard[5-choice]                
                    self.SecondBoard[5-choice] = 0
            choice = choice + 1            
            #self.display()
        return 0, stonesInHand

    def secondMove(self, choice, stonesInHand, turn):
        while choice <= 5 and stonesInHand > 0:
            #print "Choice:",choice, " StonesLeftToDrop: ", stonesInHand
            self.SecondBoard[choice] = self.SecondBoard[choice] + 1
            stonesInHand = stonesInHand - 1;
            if turn is False and stonesInHand == 0 and self.SecondBoard[choice] == 1: #placed the last stone in empty hole
                if self.FirstBoard[5-choice] != 0:
                    self.SecondBoard[choice] = 0
                    self.SecondShole = self.SecondShole + 1 + self.FirstBoard[5-choice]
                    self.FirstBoard[5-choice] = 0
            choice = choice + 1
            #self.display()
        return 0, stonesInHand

#if we drop the last stone in the first player's shole, they should go again
#drop a stone in the first person's shole
    def scoreFirstHole(self, stonesInHand):
        if stonesInHand > 0:
            self.FirstShole = self.FirstShole + 1
            stonesInHand = stonesInHand - 1; # drop one in the shole
            if stonesInHand == 0:
                return True #all done
        return False
    
#if we drop the last stone in the first player's shole, they should go again
#drop a stone in the first person's shole
    def scoreSecondHole(self, stonesInHand):
        if stonesInHand > 0:
            self.SecondShole = self.SecondShole + 1
            stonesInHand = stonesInHand - 1; # drop one in the shole
            if stonesInHand == 0:
                return True
        return False

    def doEnd(self):
        v = self.FirstBoard
        w = self.SecondShole
        if self.FirstTurn is True:
            v = self.SecondBoard
            w = self.FirstShole
        sum = 0
        for i,e in enumerate(v):                
            sum = sum + e
            v[i] = 0
        if self.FirstTurn is True:
            self.SecondShole = self.SecondShole + sum
        else:
            self.FirstShole = self.FirstShole + sum


    def endOfGame(self, turn):
        sum = 0
        if turn is True:
            v = self.FirstBoard
        else:
            v = self.SecondBoard
        for i in v:
            sum = sum + i
        if sum == 0:
            self.doEnd()
            return True
        return False

#### develop an AI in minimax based on takeMove
#### don't forget that takeMove alters the board
#### Returns a tuple first,second
#### the first return is whether the move was a "good" move or not
#### The second describes whether the turn should change or not False means stay the same persons turn
    
    def takeMove(self, choice, ai):
        if self.endOfGame(self.FirstTurn):
            return True, False
        if choice < 0 or choice > 5: #bad choice
            if ai is False:
                print "Bad choice: ", choice
            return False, False
        #print "Performing the move: ", choice
        if self.FirstTurn:
            stonesInHand = self.FirstBoard[choice]
            if stonesInHand == 0:
                if ai is False:
                    print "Bad choice - no stones in this hole", stonesInHand
                return False, False
            self.FirstBoard[choice] = 0;
            choice = choice + 1 # move to next hole
            while stonesInHand > 0: #walk around the board
                choice, stonesInHand = self.firstMove(choice, stonesInHand, self.FirstTurn)
                if self.scoreFirstHole(stonesInHand) is True:
                    return True, False
                stonesInHand = stonesInHand - 1
                choice, stonesInHand = self.secondMove(choice, stonesInHand, self.FirstTurn)
                self.scoreSecondHole(stonesInHand)
                stonesInHand = stonesInHand - 1
            self.FirstTurn = False
        else: #must be second person's turn
            stonesInHand = self.SecondBoard[choice]
            if stonesInHand == 0:
                if ai is False:
                    print "Bad choice - no stones in this hole", stonesInHand
                return False, False
            self.SecondBoard[choice] = 0;
            choice = choice + 1 # move to next hole
            while stonesInHand > 0: #walk around the board
                choice, stonesInHand = self.secondMove(choice, stonesInHand, self.FirstTurn)
                if self.scoreSecondHole(stonesInHand) is True:
                    return True, False
                stonesInHand = stonesInHand - 1
                choice, stonesInHand = self.firstMove(choice, stonesInHand, self.FirstTurn)
                self.scoreFirstHole(stonesInHand)
                stonesInHand = stonesInHand - 1            
            self.FirstTurn = True
        return True, True
                    

    # what's the score look like from turn's player
    #"True" (first player's) or "False" (second player's)
    def score(self):
        v = self.FirstShole
        w = self.SecondShole
        return v - w


    def minimax(self, depth, maxdepth, originalTurn):
        debug = True ##set this to False if you want to turn off optional output
        if debug is True:  #this will be pretty spammy
            self.display()
        bestScore = -50 # could also be 50 really
        bestIndex = -1
        
        #this makes 6 copies of the current board - you might use this
        myMoves = [ copy.deepcopy(self), copy.deepcopy(self), copy.deepcopy(self),
                    copy.deepcopy(self), copy.deepcopy(self), copy.deepcopy(self) ]
        # you can use myMoves[0].takeMove(0,False) To take move 0 on the first copy in this list
        goodMove, turnChanged = myMoves[0].takeMove(0,False)
        if debug is True:
            print "GoodMove:[", goodMove, " ] Did the Turn Change: ", turnChanged
            myMoves[0].display()
        #I returned a tuple from my minimax
        #consisting of the bestScore found and the bestIndex
        #bestIndex corresponds to what move should be taken!
        return bestScore, bestIndex
                
            




#start a new game
game = Mancala()

# just play forever! why not?!
while not game.endOfGame(game.FirstTurn):
    b, bi = game.minimax(0, 4, game.FirstTurn) #will propose a move
    print "##############"
    game.display()
    print "Ai thinks the best is: ", bi, " with score: ", b

    
    getMove = False
    
    while not getMove: #this is just an error checking loop making sure that move is appropriate
        move = raw_input("Make a move: Please select 0-5 for your hole number: " )
        try:
            move = int(move)
        except ValueError:
            getMove = False
        else:
            getMove = True
    print "Performing move: ", move
    game.takeMove(move, False)
            


game.display()
print game.FirstShole, " vs. ", game.SecondShole

    
