示例#1
0
def tryMoveAndEval(move):
    tempGame = Game(fen, True)
    tempGame.apply_move(move)
    tempBoard = tempGame.board._position
    score = 0
    for i in range(8):
        for u in range(8):
            if originalBoard[ind(i,u)] != tempBoard[ind(i,u)]:
                score += alignedMap[i][u]
    return score
def play_one_game(fen, last_move, rybka, max_tree_depth=3):
    chess_game = Game(fen=fen)
    chess_game.apply_move(last_move)

    print chess_game

    start_new_game(rybka, chess_game, search_depth=8)
    # print "for " + str(chess_game).split()[1] + ", the cp parameter is " + str(200)
    reasonable_moves = find_all_reasonable_moves(rybka, current_depth=0, search_depth=8, cp_parameter=200)   # CP is 200 the first time

    tree_of_moves = FenTree(root=fen, last_move=last_move, score=0)

    first_player_color = str(chess_game).split()[1]
    # print str(chess_game).split()[1]

    if reasonable_moves:  # If there are any reasonable_moves
        build_the_tree(tree_of_moves, reasonable_moves, chess_game, rybka, first_player_color, max_tree_depth)

    #[x.display_the_tree() for x in tree_of_moves.moves]

    return tree_of_moves
示例#3
0
 def _extract_chessgame(self, pgn_in_file):
     # get game model
     chessgame = Game()
     cmd = ('{0} {1} -Wlalg --nomovenumbers --nocomments --nochecks -V --notags -s'
            .format(self.server.pgn_extract_path, pgn_in_file))
     p = get_command_process(cmd)
     stdout_content = p.stdout.readlines()
     # We need to decode the bytes from stdout when running on python 3
     if not b_legacy.get_python_major_version() <= 2:
         temp = []
         for stdout_line in stdout_content:
             temp.append(stdout_line.decode())
         stdout_content = temp
     stdout_content = ''.join(stdout_content)
     moves = re.sub('[\r\n]+', ' ', stdout_content)
     moves = b_legacy.b_filter(self._filter_move, moves.split(' '))
     result = moves[-1]
     del moves[-1]
     for i in range(0, len(moves)):
         chessgame.apply_move(moves[i])
     # extract existing comments
     comments = {}
     # TODO
     return chessgame, moves, result, comments
示例#4
0
import sys, subprocess

if len(sys.argv) < 2 or 'help' in sys.argv[1]:
    print('Usage:\n    python evaluate_move.py [FEN]')
    print('Reply: [best_move] [NEW_FEN] if valid, otherwise error')
    sys.exit(0);

fen = sys.argv[1].strip()

# Throws error if fen is not valid
try :
    chessgame = Game(fen, True)
except:
    print('Invalid fen: %s' % fen, file=sys.stderr)
    sys.exit(1)

### Interface with Stockfish
searcher = Engine(movetime=100)
searcher.setposition_fen(fen)
bestmove = searcher.bestmove_time()['move']

# Throws error if the move is not valid
try:
    chessgame.apply_move(bestmove)
except:
    print('Invalid move: %s' % bestmove, file=sys.stderr)
    sys.exit(1)

print("%s,%s" % (bestmove, chessgame))
示例#5
0
                        # print index +' : ' + scores
                        cv2.waitKey(10)
                ##=========================================================

                ##==========Detect a Move on the basis of features=========
                ## compute the current and previous features
                prev_board_features = cur_board_features.copy()
                cur_board_features = board_features.copy()
                if len(cur_board_features) == 64 and len(
                        prev_board_features) == 64:
                    move = chess_move.detectMove(cur_board_features,
                                                 prev_board_features,
                                                 chessgame, move_count)
                    print(move)
                    if not (move == None):
                        chessgame.apply_move(move)
                        move_count = move_count + 1
                        print(chess.Board(str(chessgame)))

        ## display the result of corner detection

        cv2.moveWindow('input', 0, 0)
        cv2.moveWindow('output', 0, 270)
        cv2.moveWindow('corners', 0, 400)
        char_input = cv2.waitKey(40)

        if char_input & 0xFF == ord('e'):
            engage_detection = True
        elif char_input & 0xFF == 0x1B:
            break
示例#6
0
from Chessnut import Game

chessgame = Game()
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

print(chessgame.get_moves())
"""
['a2a3', 'a2a4', 'b2b3', 'b2b4', 'c2c3', 'c2c4', 'd2d3', 'd2d4', 'e2e3', 
 'e2e4', 'f2f3', 'f2f4', 'g2g3', 'g2g4', 'h2h3', 'h2h4', 'b1c3', 'b1a3', 
 'g1h3', 'g1f3']
"""

chessgame.apply_move('e2e4')  # succeeds!
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

#chessgame.apply_move('e2e4')  # fails! (raises InvalidMove exception)
示例#7
0
if __name__ == "__main__":

    if USE_DUMP:
        #load data directly using pickle
        f = open(sys.argv[1], 'rb')
        data = pickle.load(f)
        f.close()
        detectMove(data[0], data[1], data[2])

    if (len(sys.argv) < 4):
        print "USAGE: python detect_features file1.png file2.png sample_param.yml"
        exit()

    chessgame = Game()
    chessgame.apply_move('e2e4')
    chessgame.apply_move('e7e5')
    chessgame.apply_move('g1f3')
    chessgame.apply_move('d7d5')
    chessgame.apply_move('e4d5')
    print(chessgame)

    img_file1 = sys.argv[1]
    img_file2 = sys.argv[2]
    param_file = sys.argv[3]

    frames = []
    frames.append(cv2.imread(img_file1))
    frames.append(cv2.imread(img_file2))

    detection_status = {}
示例#8
0
文件: chess.py 项目: idandrei94/SWA
import subprocess
import cgitb
import cgi
cgitb.enable()

print("Content-Type: text/html")
print()
board = Game()
moves = ""
arg_moves = []
#try:
# arg = cgi.FieldStorage()['history']
# arg_moves = arg.value.split(' ')
#except:
# pass
#for move in arg_moves:
# try:
#  board.apply_move(move.strip())
#  moves = moves + " " + move
# except:
#  pass
arg = cgi.FieldStorage()['history']
arg_moves = arg.value.split(' ')
for move in arg_moves:
    board.apply_move(move.strip())

available_moves = board.get_moves()
chosen_move = available_moves[randint(0, len(available_moves) - 1)]
moves = moves + " " + chosen_move
print(chosen_move)
def add_the_tree(chess_tree, problem_id, fen, prev_move, blitz_rating, std_rating):
    """
    " Tree size, for each level
    """
    global accumulated_distance
    size = {}

    display_the_size(chess_tree, size)

    print size

    nodes = sorted(size.items(), key=lambda y: y[0])

    fathers = [0] * len(nodes)
    sons = [0] * len(nodes)
    branching_factor = {}

    i = 0
    for x in range(len(nodes) - 1):
        fathers[i] += nodes[x][1]
        i += 1
    i = 0
    for x in range(1, len(nodes)):
        sons[i] += nodes[x][1]
        i += 1
    for x in range(len(nodes)):
        if float(fathers[x]) > 0:
            branching_factor[x] = sons[x] / float(fathers[x])
        else:
            branching_factor[x] = 0

    position = fen.split()[0]
    figures = re.findall('[a-zA-Z]', position)
    types_of_pieces = len(set(figures))
    number_of_pieces = len(figures)

    """
    " 13.10.2014
    " Calculate the piece values
    " example: rnbqkbnr would yield 5 + 3 + 3 + 9 + 0 + 3 + 3 + 5 = 31 points for black
    " RNBQKB1R would yield 5 + 3 + 3 + 9 + 0 + 3 + 5 = 28 points for white
    " If it's white to move, the ratio will then be 28 / 31 = 0.9032258
    " The ratio then helps determine the difficulty of the game
    """
    new_fen = Game(fen=fen)
    new_fen.apply_move(prev_move)
    piece_value_w = calculate_values('w', str(new_fen))
    piece_value_b = calculate_values('b', str(new_fen))
    next_to_move = str(new_fen).split()[1]
    if next_to_move == 'w':
        piece_value_ratio = piece_value_w / float(piece_value_b)
    else:
        piece_value_ratio = piece_value_b / float(piece_value_w)
    # End of piece value calculation code

    with open('C:\Users\Simon\Dropbox\FRI\Diplomsko delo\Program\processed_data.csv', 'a+b') as csv_file:
        fen_writer = csv.writer(csv_file, delimiter=',')

        my_buffer = [problem_id, fen, prev_move, blitz_rating, std_rating]

        for i in range(4):
            my_buffer.append(size.get(i, 0))
        average_branching_factor = 0
        for i in range(4):
            my_buffer.append(branching_factor.get(i, 0))
            average_branching_factor += branching_factor.get(i, 0)
        average_branching_factor /= 4.0
        my_buffer.append(average_branching_factor)
        my_buffer.append(number_of_pieces)
        my_buffer.append(types_of_pieces)
        for i in range(4):
            my_buffer.append(accumulated_distance.get(i, 0))
        my_buffer.append(piece_value_ratio)

        fen_writer.writerow(my_buffer)

        # Reset the distance calculator for the moves
        accumulated_distance = {}
示例#10
0
import sys, subprocess

if len(sys.argv) < 2 or 'help' in sys.argv[1]:
    print('Usage:\n    python evaluate_move.py [FEN]')
    print('Reply: [best_move] [NEW_FEN] if valid, otherwise error')
    sys.exit(0)

fen = sys.argv[1].strip()

# Throws error if fen is not valid
try:
    chessgame = Game(fen, True)
except:
    print('Invalid fen: %s' % fen, file=sys.stderr)
    sys.exit(1)

### Interface with Stockfish
searcher = Engine(movetime=100)
searcher.setposition_fen(fen)
bestmove = searcher.bestmove_time()['move']

# Throws error if the move is not valid
try:
    chessgame.apply_move(bestmove)
except:
    print('Invalid move: %s' % bestmove, file=sys.stderr)
    sys.exit(1)

print("%s,%s" % (bestmove, chessgame))
示例#11
0
from __future__ import print_function
from Chessnut import Game

import sys

if len(sys.argv) < 3 or "help" in sys.argv[1]:
    print("Usage:\n    python make_move.py [FEN] [move]")
    print("Reply: [NEW_FEN] if valid, otherwise error")
    sys.exit(0)

fen = sys.argv[1].strip()
move = sys.argv[2].strip().replace("_", "")

# Throws error if fen is not valid
try:
    chessgame = Game(fen, True)
except:
    print("Invalid fen: %s" % fen, file=sys.stderr)
    sys.exit(1)


# Throws error if the move is not valid
try:
    chessgame.apply_move(move)
except:
    print("Invalid move: %s" % move, file=sys.stderr)
    sys.exit(1)

print("%s" % chessgame)
示例#12
0
from Chessnut import Game

chessgame = Game()
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

print(chessgame.get_moves())
"""
['a2a3', 'a2a4', 'b2b3', 'b2b4', 'c2c3', 'c2c4', 'd2d3', 'd2d4', 'e2e3', 
 'e2e4', 'f2f3', 'f2f4', 'g2g3', 'g2g4', 'h2h3', 'h2h4', 'b1c3', 'b1a3', 
 'g1h3', 'g1f3']
"""

chessgame.apply_move('e2e4')  # succeeds!
print(
    chessgame)  # 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

#chessgame.apply_move('e2e4')  # fails! (raises InvalidMove exception)
示例#13
0
uci_frontend.init_engine(options)
print (Position(chessgame.get_fen()).fen_to_string_board())

while True:
    if not args.b: # if user plays black, skip first user move
        # get move from user
        while True:
            print ('-- Your move: ')
            try:
                raw = b_legacy.b_raw_input().strip()
            except KeyboardInterrupt:
                print ('Goodbye!')
                exit(0)
            if raw is None or raw == '':
                print ('Invalid input! Please try again.')
            try:
                chessgame.apply_move(raw)
                print (Position(chessgame.get_fen()).fen_to_string_board())
                break
            except InvalidMove as e:
                print ('{0}'.format(e.message))

    args.b = False

    # get move from engine
    print ('-- Waiting for engine move')
    engine_move = uci_frontend.bestmove(chessgame.get_fen(), 2500).pop()
    print ('-- Engine played {0}'.format(engine_move))
    chessgame.apply_move(engine_move)
    print (Position(str(chessgame)).fen_to_string_board())
示例#14
0
def view():
    keyboard.on_press(key_press)

    arduino_python.connection()
    chessgame = Game()

    coordinate, listxy = chess3.points()

    # _,  = chess3.poinxts()
    cap = cv2.VideoCapture(2)
    diff = []
    diff1 = []
    old_place = np.zeros((64, ), dtype=np.int)
    place = np.zeros((64, ), dtype=np.int)
    place1 = np.zeros((64, ), dtype=np.int)
    aligment = 0
    legal_move = 0
    white_check = 0
    black_check = 0
    emotion_time = time.time()
    timer_a = time.time()
    change = 0
    # count = 0
    black_start = 0
    white_start = 0
    started = 0
    robot_time = time.time()
    robot = 0
    rook = 0
    white_find_rook = 0
    black_find_rook = 0
    rook_control = 0
    stock_fish = stockfish.Stockfish()
    contempt_value = 0
    check2 = 0
    check1 = 0
    contempt_factor = {'Contempt': contempt_value}
    while True:

        # Yuz tanima ve contempt factor degeri ayarlama
        face_emotions = emotions()

        if time.time() - emotion_time > 10:
            emotion_time = time.time()
            if face_emotions == "sad":
                contempt_value = random.randrange(0, 20)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "fear":
                contempt_value = random.randrange(20, 40)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "neutral":
                contempt_value = random.randrange(40, 60)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "angry":
                contempt_value = random.randrange(60, 80)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "happy":
                contempt_value = random.randrange(80, 100)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            else:
                contempt_value = random.randrange(0, 100)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            # print(face_emotions)
        _, img = cap.read()
        img = cv2.resize(img, (640, 400))

        masked = chess3.masked(img, coordinate[0], coordinate[1],
                               coordinate[2], coordinate[3])
        red_pieces, blue_pieces, img1 = pieces_detect(masked)
        cv2.imshow("Pieces Place", img1)

        # Beyaz tas sayaci
        if white_start == 0:
            control(listxy, place, blue_pieces)

            check = 0
            for i in range(0, len(place)):
                if place[i] == 1:

                    check = check + 1
                    old_place[i] = place[i]
                    place[i] = 0
            if check1 != check:
                print("Beyaz Tas Sayisi : " + str(check))
                check1 = check

            if check == 16:
                black_start = 2
                white_start = 1
                print("Beyazlarsiniz")

        # Siyah tas sayaci
        if black_start == 0:
            control(listxy, place, red_pieces)
            check = 0

            for i in range(0, len(place)):
                if place[i] == 1:

                    check = check + 1
                    old_place[i] = place[i]
                    place[i] = 0
            if check2 != check:
                print("Siyah Tas Sayisi : " + str(check))
                check2 = check

            # print(check)
            if check == 16:
                black_start = 1
                white_start = 2
                print("Siyahlarsiniz")

        # Siyah Tas Islemleri
        if black_start == 1:

            if white_check == 0:
                control(listxy, place, blue_pieces)

                check = 0

                for i in range(0, len(place)):
                    if place[i] == 1:
                        check = check + 1
                        old_place[i] = place[i]
                        place[i] = 0
                if check == 16:
                    white_check = 1

            if (started == 0) and white_check == 1:
                robot = 2
                robot_time = time.time()
                best_move, poslist = sfish.black_start_game()
                chessgame.apply_move(best_move)

                if old_place[character.index(best_move[2:], 0)] == 1:
                    arduino_python.push('-' + best_move[:2] + '-fully-' +
                                        best_move[2:] + '_down-' + "empty-")
                    arduino_python.push('-redL-')
                    robot_time = robot_time + 30
                else:
                    arduino_python.push('-' + best_move[:2] + '-fully-' +
                                        best_move[2:] + '_down-' + "empty-")
                    robot_time = robot_time + 30
                    arduino_python.push('-redL-')

                started = 1
            if robot == 2 and time.time() - robot_time > 0:
                robot_time = time.time()
                print("lutfen oynayin 1")

                arduino_python.push('-greenL-')

                robot = 0

            if (change == 0) and white_check == 1 and robot == 0:

                for i in range(0, 64):
                    place[i] = 0

                if aligment == 0:

                    control(listxy, place, red_pieces)
                    for i in range(0, 64):
                        old_place[i] = place[i]
                    aligment = 1

                control(listxy, place, red_pieces)

                for i in range(0, len(place)):

                    if place[i] != old_place[i]:
                        robot = 1
                        print("10 saniye icinde oyna")
                        arduino_python.push('-tenSec-')
                        timer_a = time.time()
                        change = 1
                        break
                    elif old_place.any() == place.any():
                        change = 0
                        robot = 0

            if time.time(
            ) - timer_a > 10 and change == 1 and started == 1 and robot == 1:
                robot = 0
                arduino_python.push('-greenL-')

                for i in range(0, 64):
                    place1[i] = 0

                control(listxy, place1, red_pieces)

                timer_a = time.time()
                # if (count == 0):
                #     for i in range(0, len(place1)):
                #         old_place[i] = place1[i]
                #         count = 1
                # count = 1
                # if count == 1:
                for i in range(0, len(place1)):
                    if place1[i] != old_place[i]:
                        diff.append(i)

                        if len(diff) == 2:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])
                        elif len(diff) == 4 and rook == 0:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        old_place[i] = place1[i]

                if len(diff1) == 2:
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)

                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:

                                arduino_python.push('-redL-' + '-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')

                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-redL-' + '-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-redL-' + '-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-redL-' + '-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        print("Yanlis Hamle Oynadiniz" + character[diff1[0]] +
                              character[diff1[1]])
                        arduino_python.push('-illegal_move-')

                    diff1.clear()
                    rook_control = 0

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'e8f8' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e8'
                    character[diff1[1]] = 'g8'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)

                        character[diff1[0]] = 'e8'
                        character[diff1[1]] = 'f8'
                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                            robot_time = robot_time + 30
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])

                    diff1.clear()
                    rook_control = 0
                    rook = 1

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'a8c8' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e8'
                    character[diff1[1]] = 'c8'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'a8'
                        character[diff1[1]] = 'c8'
                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    diff1.clear()
                    rook_control = 0
                    rook = 1

                # elif len(diff1) == 1:
                #     robot = 3
                change = 0
                diff.clear()
                diff1.clear()

            if robot == 3 and time.time() - robot_time > 0:

                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, red_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 2")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0
        # Beyaz Tas islemleri
        elif white_start == 1:

            if black_check == 0:
                control(listxy, place, red_pieces)

                check = 0

                for i in range(0, len(place)):
                    if place[i] == 1:
                        check = check + 1
                        old_place[i] = place[i]
                        place[i] = 0
                if check == 16:
                    black_check = 1

            if change == 0 and robot == 0 and black_check == 1:

                for i in range(0, 64):
                    place[i] = 0

                if aligment == 0:

                    control(listxy, place, blue_pieces)
                    for i in range(0, 64):
                        old_place[i] = place[i]
                    aligment = 1
                control(listxy, place, blue_pieces)

                for i in range(0, len(place)):

                    if place[i] != old_place[i]:
                        robot = 1
                        print("10 saniye icinde oyna")
                        arduino_python.push('-tenSec-')
                        timer_a = time.time()
                        change = 1

                        break
                    elif old_place.any() == place.any():
                        change = 0
                        robot = 0

            if time.time() - timer_a > 10 and change == 1 and robot == 1:
                arduino_python.push('-greenL-')
                robot = 0
                for i in range(0, 64):
                    place1[i] = 0

                control(listxy, place1, blue_pieces)

                timer_a = time.time()
                # if count == 2:
                #     for i in range(0, len(place1)):
                #         old_place[i] = place1[i]
                #         count = 1
                # count = 1
                # if count == 1:

                for i in range(0, len(place1)):

                    if place1[i] != old_place[i]:
                        diff.append(i)

                        if len(diff) == 2:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        elif len(diff) == 4 and rook == 0:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        old_place[i] = place1[i]

                if len(diff1) == 2:
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')

                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    rook_control = 0
                    diff1.clear()

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'e1f1' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e1'
                    character[diff1[1]] = 'g1'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'e1'
                        character[diff1[1]] = 'f1'
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    rook_control = 0
                    diff1.clear()

                    rook = 1

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'a1c1' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e1'
                    character[diff1[1]] = 'c1'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'a1'
                        character[diff1[1]] = 'c1'
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, black_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])

                    rook_control = 0
                    diff1.clear()
                    rook = 1

                change = 0
                diff.clear()
                diff1.clear()
            if robot == 3 and time.time() - robot_time > 0 and black_start == 1:
                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, red_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 3")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0
            elif robot == 3 and time.time(
            ) - robot_time > 0 and white_start == 1:
                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, blue_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 4")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0

        # print(blue_pieces)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break