# util.py
#    Constants and utlility functions for Backgammon board locations and
#    player colors.

#----------------------------------------------------------------------
# Constants for locations and players

LOCATIONS = """B_BAR R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12
               B12 B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 R_BAR
               B_BEAR_OFF R_BEAR_OFF""".split()

# assign constant identifiers for PLAYERS
RED = "RED"
BLACK = "BLACK"

PLAYERS = [RED, BLACK]


#------------------------------------------------------------
# utility functions to compute board locations and movement


def player_sign(player):
    """ return whether player is going "up" or "down" the board. 
    """
    assert player in PLAYERS

    if player == RED:
        return -1

    return 1


def distance(frm, to):
    """ return signed distance between board locations """
    assert frm in LOCATIONS
    assert to in LOCATIONS

    if to == "R_BEAR_OFF":
        return -LOCATIONS.index(frm)
    if to == "B_BEAR_OFF":
        return 25 - LOCATIONS.index(frm)
    return LOCATIONS.index(to) - LOCATIONS.index(frm)


def find_location(player, frm, dist):
    """ return location dist units away for given player """
    assert frm in LOCATIONS
    assert player in PLAYERS

    if frm == "B_BAR":
        to_ind = dist
    elif frm == "R_BAR":
        to_ind = 25-dist
    else:
        to_ind = LOCATIONS.index(frm) + player_sign(player) * dist

    if to_ind <= 0:
        return "R_BEAR_OFF"
    if to_ind >= 25:
        return "B_BEAR_OFF"
    return LOCATIONS[to_ind]
