Exemple #1
0
def chessThread(con, addr):
    data = con.recv(1024).decode("utf-8")
    try:
        jsondata = json.loads(data)
    except json.JSONDecodeError as e:
        return
    try:
        print("[*] {} - starts a new game".format(addr[0]))
    except KeyError:
        return
    board = chess.Board()
    board.set_castling_fen("")
    moves = []
    while True:
        data = con.recv(1024).decode("utf-8")
        try:
            jsondata = json.loads(data)
        except json.JSONDecodeError:
            return
        if jsondata["type"] == "move":
            temp = str(jsondata["value"])
            arr = list(temp)
            jsondata["value"] = (arr[0]) + flipx(arr[1]) + (arr[2]) + flipx(
                arr[3])
            print("[*] {} - moved   {}".format(addr[0], jsondata["value"]))
            Nf3 = chess.Move.from_uci(jsondata["value"])
            board.push(Nf3)
        elif jsondata["type"] == "getmove":
            engine = stockfish.Stockfish(stockfish_path)
            engine.set_fen_position(board.fen())
            bestmove = engine.get_best_move()
            print("[*] {} - getmove {}".format(addr[0], bestmove))
            con.sendall(bestmove.encode("utf-8"))
Exemple #2
0
def get_sf_evaluation(fen, sf_location, sf_depth):
    sf = stockfish.Stockfish(sf_location,
                             depth=sf_depth)

    sf.set_fen_position(fen)
    if sf.get_best_move() is not None:
        rating_match = re.search(r'score (cp|mate) (.+?)(?: |$)',
                                 sf.info)

        if rating_match.group(1) == 'mate':
            original_rating = int(rating_match.group(2))

            # adjust ratings for checkmate sequences
            if original_rating:
                rating = 999900 * original_rating / abs(original_rating)
            elif ' w ' in fen:
                rating = 999900
            else:
                rating = -999900
        else:
            rating = int(rating_match.group(2))
        if ' b ' in fen:
            rating *= -1
        rating /= 100
    else:
        rating = None

    return rating
Exemple #3
0
    def __init__(self, drawScreen, exitGame):
        self.drawScreen = drawScreen
        self.exitGame = exitGame

        self.stockfish = stockfish.Stockfish(settings.stockfishPath)

        self.boardDrawer = BoardDrawer.BoardDrawer()
        self.boardDrawer.setPieces(self.stockfish.get_fen_position())

        self.inputWidget = urwid.Edit(caption=">",
                                      edit_text="",
                                      multiline=True)
        # self.inputWidget.keypress = self.inputKeypress
        inputContainer = self.inputWidget
        inputContainer = urwid.LineBox(inputContainer)
        inputContainer = urwid.Filler(inputContainer, valign="top")
        # inputContainer = urwid.Padding(inputContainer, align="center", width=30)

        urwid.connect_signal(self.inputWidget, "postchange",
                             self.userInputKeystroke)

        self.logWidget = urwid.Text("")
        logContainer = self.logWidget
        logContainer = urwid.LineBox(logContainer)
        logContainer = urwid.Filler(logContainer, valign="bottom")
        # logContainer = urwid.

        logInputPile = urwid.Pile([logContainer, inputContainer])
        logInputPile = urwid.Padding(logInputPile, align="center", width=30)

        columns = urwid.Columns([(10 * 16, self.boardDrawer.topWidget),
                                 logInputPile])
        self.topWidget = urwid.Filler(columns, height=("relative", 100))
Exemple #4
0
def test_stockfish_evaluation():
    stockfish_defaults = {
        "Write Debug Log": "false",
        "Contempt": 0,
        "Min Split Depth": 0,
        "Threads": 1,
        "Ponder": "false",
        "Hash": 16,
        "MultiPV": 1,
        "Skill Level": 20,
        "Move Overhead": 30,
        "Minimum Thinking Time": 20,
        "Slow Mover": 80,
        "UCI_Chess960": "false",
    }

    engine = stockfish.Stockfish(
        path="C:\Program Files (x86)\Tarrasch\Engines\stockfish_11_x64.exe",
        parameters={
            "Threads": 6,
            "Hash": 1024,
            "Minimum Thinking Time": 30
        })
    engine.set_fen_position(
        "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")
    engine.set_depth(30)

    print(engine.get_best_move())

    print(engine.get_evaluation())
Exemple #5
0
    def __init__(self):
        """
            la scacchiera si suddivide in 3 parti:
                - left / blu / bianchi
                - right / rossi / neri
                - grid / griglia
            contenute nel dizionario chessboard
        """
        self.vatange = 0.5
        self.player = "w"
        self.castling = "KQkq"
        self.en_passant = "-"
        self.half_move_counter = 0
        self.move_counter = 1

        self.fen_position = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"

        self.stockfish = stockfish.Stockfish("./Chessboard/stockfish")
        self.stockfish.set_skill_level(1)
        self.board = chess.Board(self.fen_position)

        self.chessboard = {
            # TODO aggiungere un inizializzazione di wpn e bpn da due file .txt
            "grid": [
                ["r", "n", "b", "q", "k", "b", "n", "r"],
                ["p", "p", "p", "p", "p", "p", "p", "p"],
                [" ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " "],
                ["P", "P", "P", "P", "P", "P", "P", "P"],
                ["R", "N", "B", "Q", "K", "B", "N", "R"],
            ],
            "left": [
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
            ],
            "right": [
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
                [" ", " "],
            ]
        }
Exemple #6
0
def get_sf_evaluation(fen, sf_location, sf_depth):

    # get cloud eval if available
    try:
        cloud_eval = lichess.api.cloud_eval(fen=fen, multiPv=1)
        rating = cloud_eval['pvs'][0]
        if 'cp' in rating:
            rating = rating['cp'] / 100
        elif 'mate' in rating:
            rating = -9999 if rating['mate'] < 0 else 9999
        else:
            raise KeyError(f'{fen}, {rating}')
        return rating
    except lichess.api.ApiHttpError:
        # continue execution
        pass

    # implicit else
    sf = stockfish.Stockfish(sf_location, depth=sf_depth)

    sf.set_fen_position(fen)
    if sf.get_best_move() is not None:
        rating_match = re.search(r'score (cp|mate) (.+?)(?: |$)', sf.info)

        if rating_match.group(1) == 'mate':
            original_rating = int(rating_match.group(2))

            # adjust ratings for checkmate sequences
            if original_rating:
                rating = 999900 * original_rating / abs(original_rating)
            elif ' w ' in fen:
                rating = 999900
            else:
                rating = -999900
        else:
            rating = int(rating_match.group(2))
        if ' b ' in fen:
            rating *= -1
        rating /= 100
    else:
        rating = None

    return rating
Exemple #7
0
    def __init__(self, client: berserk.Client, user_id: str, game_id: str):
        self.client = client
        self.user_id = user_id
        self.game_id = game_id

        self.stream = client.bots.stream_game_state(game_id)

        event = next(self.stream)
        if user_id == event['white']['id']:
            self.color = 'white'
        elif user_id == event['black']['id']:
            self.color = 'black'
        else:
            raise RuntimeError("This bot is not playing in the game.")

        self.board = chess.Board()
        self.engine = stockfish.Stockfish(
            r'C:\Users\danie\PythonProjects\lichess-bot'
            r'\stockfish-11-win\Windows\stockfish_20011801_32bit.exe')
        self.engine.set_skill_level(3)
Exemple #8
0
def run_stockfish(fens_queue, evals_queue, stockfish_location, depth):
    sf = stockfish.Stockfish(stockfish_location, depth=depth)

    while True:
        try:
            fen = fens_queue.get(timeout=5)
        except queue.Empty:
            return

        sf.set_fen_position(fen)

        # this is copy-pasted from chess_pipeline.py; the current version of
        # the stockfish library supports a better method but i do not want
        # to upgrade yet because i am pretty sure something will break

        if sf.get_best_move() is not None:
            rating_match = re.search(r'score (cp|mate) (.+?)(?: |$)', sf.info)

            if rating_match.group(1) == 'mate':
                original_rating = int(rating_match.group(2))

                # adjust ratings for checkmate sequences
                if original_rating:
                    rating = 999900 * original_rating / abs(original_rating)
                elif ' w ' in fen:
                    rating = 999900
                else:
                    rating = -999900
            else:
                rating = int(rating_match.group(2))
            if ' b ' in fen:
                rating *= -1
            rating /= 100
        else:
            rating = None

        evals_queue.put((fen, str(rating)))
Exemple #9
0
def run_benchmark(stockfish_location):
    times = []

    fen = 'rnb1k1nr/pp1p1ppp/1q2p3/2b5/4P3/5N2/PPP1QPPP/RNB1KB1R b KQkq - 2 5'

    for n in range(10, 26):
        sf = stockfish.Stockfish(stockfish_location, depth=n)  # noqa

        statement = f'sf.set_fen_position("{fen}"); sf.get_best_move()'
        time_taken = min(
            timeit.repeat(
                statement,
                repeat=5,
                number=10,
                globals=locals(),
            ))

        print(f'Minimum time taken for depth {n}: {time_taken:.2e}')

        times.append(time_taken)

    print(f'All times: {times}')

    return times
Exemple #10
0
import stockfish
import os
import platform

dir_stockfishWin = os.path.abspath('stockfish64.exe')
dir_stockfishLin = os.path.abspath('stockfish')

stockfish = stockfish.Stockfish(dir_stockfishWin)

if platform.system() == "Linux":
    stockfish = stockfish.Stockfish(dir_stockfishLin)


def get_next_move(fen1, fen2: str) -> str:
    stockfish.set_position([fen1, fen2])
    return stockfish.get_best_move()


def is_best_move(move: str) -> bool:
    return stockfish.is_move_correct(move)
Exemple #11
0
 def __init__(self, sf_path: str, level: int = 20, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.engine = stockfish.Stockfish(sf_path)
     self.engine.set_skill_level(level)
Exemple #12
0
        res = wait_for_turn(d)
        if res != 'turn':
            print(f'game end: {res}')
            break

        b = get_board(d)
        print(b)

        play_move(d, b, sf)


def main(d, sf):
    find_human_game(d)
    while True:
        try:
            play_game(d, sf)
        except Exception as e:
            print(e)
            continue

        break



d = webdriver.Chrome()
sf = stockfish.Stockfish(parameters=SF_PARAMS)

# main(d, sf)
# print('[main] exited')

Exemple #13
0
 def __init__(self, name, cname):
     super(CStrategyWrapper, self).__init__(name)
     self.strategy = CFactory.makeStrategy(cname)
     self.stockfish = stockfish.Stockfish()
Exemple #14
0
import time
import pyautogui
import string
from PIL import Image
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
import chess
import stockfish
import random
import sys
import time

stockfish = stockfish.Stockfish("stockfish_20090216_x64_bmi2.exe",
                                parameters={
                                    "Threads": 4,
                                    "Minimum Thinking Time": 5,
                                    "Hash": 16
                                })
stockfish.set_skill_level(9)
stockfish.set_depth(10)

CurrentFEN = ""
IsWhite = True
DoMove = False

CurrentFlippedPieces = {}

Icons = {}
Castles = {}

Exemple #15
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
Exemple #16
0
 def __init__(self, name, listeners=None):
     model.FairPriceModel.__init__(self, name, listeners)
     self.stockfish = stockfish.Stockfish()
     self.head = ['total', 's', 'pctM']
     self.clear()
Exemple #17
0
 def __init__(self):
     self.engine = stockfish.Stockfish()