#!/usr/bin/python
import pygame
from pygame.locals import *

noir = 1
blanc = 2
BOARDX = 60
BOARDY = 60


def playmove(p, me, adv, play):
    """If play is true, flip the token and returns new board
       else returns the number of token flipped.
       me: who is playing, adv: opponent"""
    global board
    sw = 0
    # test in all directions
    for d in (-1, -11, -10, -9, 1, 11, 10, 9):
        c = p + d
        subsw = 0

        if board[c] != adv:
            continue

        while board[c] == adv:
            subsw = subsw + 1
            c = c + d

        if board[c] != me:
            continue

        sw = sw + subsw

        if play:
            for i in range(0, subsw + 1):
                board[p + i * d] = me

    if play:
        return True
    else:
        return sw


while True:
    start = input("Voulez vous commencer ?")
    if start[0].upper() == "O":
        joueur = noir
        ordi = blanc
        break
    elif start[0].upper() == "N":
        joueur = blanc
        ordi = noir
        break

# Tableau de jeu 8x8. On ajoute une case "illégale" tout autour donnant un
# tableau 10x10. Ce tableau est ensuite transformé en un tableau de 100 cases
# ce qui permet d'accéder aux cases autour d'une case donnée en ajoutant les
# valeurs -1,-10,1,10,-11,-9,11 et 9

board = [0 for i in range(0, 100)]
for i in range(0, 10):
    board[i] = -1
    board[10 * i] = -1
    board[10 * i + 9] = -1
    board[90 + i] = -1

# position de départ
board[44] = blanc
board[55] = blanc
board[45] = noir
board[54] = noir

pionordi = 2
pionjoueur = 2
passe = 0
tour = noir
msg = ""
comptetour = 0

# Valeur de chaque case
valeurcase = [0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
              0, 40,  3, 15, 10, 10, 15,  3, 40,  0,
              0,  3,  0,  9, 12, 12,  9,  0,  3,  0,
              0, 15,  9, 11, 15, 15, 11,  9, 15,  0,
              0, 10, 12, 15, 10, 10, 15, 12, 10,  0,
              0, 10, 12, 15, 10, 10, 15, 12, 10,  0,
              0, 15,  9, 11, 15, 15, 11,  9, 15,  0,
              0,  3,  0,  9, 12, 12,  9,  0,  3,  0,
              0, 40,  3, 15, 10, 10, 15,  3, 40,  0,
              0,  0,  0,  0,  0,  0,  0,  0,  0,  0]

pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
running = True
pos = None
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        if event.type == MOUSEBUTTONDOWN:
            pos = event.pos

    screen.fill("#000000")

    # Next turn. If computer, play immediately, if player wait for click
    # Player interface is refreshed at 10 FPS so first loop, it'll be
    # skipped

    if tour == ordi:
        # Computer plays
        besteval = -100
        move = 0
        bestcap = 0

        for idx in range(11, 89):
            # Case libre ?
            if board[idx] != 0:
                continue
            cap = playmove(idx, ordi, joueur, False)
            # Coup légal ?
            if cap == 0:
                continue
            if comptetour < 19:
                score = valeurcase[idx] - cap
            else:
                score = valeurcase[idx] + cap

            if score > besteval:
                besteval = score
                move = idx
                bestcap = cap

        if besteval == -100:
            msg = "L'ordi passe"
            passe = passe + 1
            tour = joueur
        else:
            msg = "Ordi : {}".format(move)
            passe = 0
            playmove(move, ordi, joueur, True)
            pionordi = pionordi + bestcap + 1
            pionjoueur = pionjoueur - bestcap
            comptetour = comptetour + 1
            tour = joueur

    elif tour == joueur:
        if pos:
            # play player move
            # Pass ?
            if pygame.Rect((600, BOARDY, 150, 40)).collidepoint(pos):
                legalmove = False
                for i in range(11, 89):
                    if board[i] != 0:
                        continue
                    if playmove(i, joueur, ordi, False) > 0:
                        legalmove = True
                        break

                if legalmove:
                    msg = "Vous DEVEZ jouer"
                else:
                    msg = ""
                    passe = passe + 1
                    tour = ordi

            # Board ?
            x = (pos[0] - BOARDX) // 60
            y = (pos[1] - BOARDY) // 60
            if 0 <= x <= 7 and 0 <= y <= 7:
                loc = 11 + x + 10 * y
                if board[loc] != 0:
                    msg = "Coup Illégal"
                else:
                    flip = playmove(loc, joueur, ordi, False)
                    if flip == 0:
                        msg = "Coup Illégal"
                    else:
                        playmove(loc, joueur, ordi, True)
                        pionjoueur = pionjoueur + flip + 1
                        pionordi = pionordi - flip
                        comptetour = comptetour + 1
                        passe = 0
                        tour = ordi
                        msg = ""

            # Click processed, clear it
            pos = None

    if passe == 2 or pionordi == 0 or pionjoueur == 0 or comptetour == 60:
        # End Game
        tour = -1
        if pionjoueur > pionordi:
            msg = "Joueur Gagne"
        else:
            msg = "Ordi Gagne"

    # redraw screen
    # board
    pygame.draw.rect(screen, "#40FF40", (BOARDX, BOARDY, 480, 480), width=5)
    for i in range(60, 480, 60):
        pygame.draw.line(screen, "#40FF40", (BOARDX + i, BOARDY), (BOARDX + i, BOARDY + 480), width=3)
        pygame.draw.line(screen, "#40FF40", (BOARDX, BOARDY + i), (BOARDX + 480, BOARDY + i), width=3)

    # tokens
    for x in range(0, 8):
        for y in range(0, 8):
            idx = 11 + x + 10 * y
            if board[idx] == blanc:
                pygame.draw.circle(screen, "#FFFFFF", (BOARDX + 60 * x + 30, BOARDY + 60 * y + 30), 22, width=0)
            elif board[idx] == noir:
                pygame.draw.circle(screen, "#FFFFFF", (BOARDX + 60 * x + 30, BOARDY + 60 * y + 30), 22, width=2)

    # PASS button
    pygame.draw.rect(screen, "#FFFF00", (600, BOARDY, 150, 40))
    font = pygame.font.Font(None, 24)
    passtext = font.render("PASS", False, "#000000", "#FFFF00")
    x = 675 - passtext.get_width() / 2
    screen.blit(passtext, (x, BOARDY + 12))

    # Scores
    (pionblanc, pionnoir) = (pionordi, pionjoueur)
    if joueur == blanc:
        (pionblanc, pionnoir) = (pionjoueur, pionordi)
    screen.blit(font.render("Blanc : {}".format(pionblanc), False, "#00FFFF"), (600, BOARDY + 60))
    screen.blit(font.render("Noir : {}".format(pionnoir), False, "#00FFFF"), (600, BOARDY + 90))
    screen.blit(font.render(msg, False, "#00FFFF"), (600, BOARDY + 150))

    # End Event Loop

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
