#################################################
# nim.py
#################################################

import random

def getInitialDots(currentPlayer):
    computerShouldAlwaysWin = False # try playing with this set to True!
    if (computerShouldAlwaysWin == True):
        # if the player is the user, we want a multiple of 4,
        # but if it's the computer, we want anything but a multiple of 4!
        result = 4 * random.randint(2,5) # a multiple of 4!
        if (currentPlayer == 'c'):
            result += random.randint(1,3) # no longer a multiple of 4!
        return result
    else:
        return random.randint(10, 20)

def getStartingPlayer():
    while True:
        player = input('Who starts, [u]ser or [c]omputer? ')
        if ((player == 'u') or (player == 'c')):
            return player
        print('That is not a legal response. Please enter a single letter.')

def getComputerMove(dotsLeft):
    move = dotsLeft % 4
    if (move == 0):
        # oh no, we can't win!
        move = 1
    return move

def getUserMove(dotsLeft):
    while True:
        move = int(input('There are ' + str(dotsLeft) + ' dots left.  How many do you pick up? '))
        if (move < 1):
            print('You must pick up at least 1 dot!')
        elif (move > 3):
            print('You can pick up at most 3 dots!')
        elif (move > dotsLeft):
            print('But there are only', dotsLeft, 'dots left!')
        else:
            return move

def getOtherPlayer(player):
    if (player == 'c'):
        return 'u'
    else:
        return 'c'

def playNim():
    print("Nim!!!")
    currentPlayer = getStartingPlayer()
    dotsLeft = getInitialDots(currentPlayer)
    print("Let's start with", dotsLeft, "dots!")
    while (dotsLeft > 0):
        if (currentPlayer == 'c'):
            # computer's turn!
            currentMove = getComputerMove(dotsLeft)
            print('I pick up', currentMove, 'dots!')
        else:
            # user's turn
            currentMove = getUserMove(dotsLeft)
        currentPlayer = getOtherPlayer(currentPlayer)
        dotsLeft -= currentMove
    winner = getOtherPlayer(currentPlayer)
    if (winner == 'c'):
        print('I Win!!!!!')
    else:
        print('You win!!!!')

playNim()
