예제 #1
0
class ChessEngine:
    def __init__(self):
        self.Engine = Engine(depth=19)

    def get_best_move(self, fen):
        self.Engine.setfenposition(fen)
        return self.Engine.bestmove()["move"]
예제 #2
0
파일: minimax.py 프로젝트: js837/chess
    def breadth_search(cls, position, depth):

        with open('dump1.txt','rb') as old_file:
            old_data = old_file.readlines()

        old_data_dict = dict((ln.strip().split(';')[0],ln.strip().split(';')[2]) for ln in old_data)



        with open('dump2.txt','a') as f:

            # Temp
            from pystockfish import Engine
            eng = Engine(depth=15)

            from ai.basic import ShannonAI
            unexplored = [(position, 0)]
            explored = []
            while unexplored:
                new_position, new_depth = unexplored.pop(0)



                fen = PositionSerializer.to_fen(new_position)

                if fen not in old_data_dict:
                    eng.setfenposition(fen)

                    best_move = eng.bestmove()['move']

                    line = '{0};{1};{2}\n'.format(fen,str(new_depth), best_move)

                    f.write(line)
                    f.flush()

                evaluation = ShannonAI.evaluate(new_position)
                explored.append((new_position, new_depth, evaluation))
                if new_depth < depth:
                    moves = new_position.get_moves()
                    for move in moves:
                        unexplored.append((move, new_depth+1))

            return explored
예제 #3
0
    def testParseMate(self):
        def mockread():
            yield "info depth 0 score mate 0"
            yield "info nodes 0 time 2"
            yield "bestmove (none) ponder (none)"

        gen = mockread()
        self.mock_eng.stdout.readline = lambda: next(gen)

        out = Engine._parse_output(self.mock_eng)
        self.assertEqual(out['analysis']['score'], 0)
        self.assertEqual(out['analysis']['unit'], 'mate')
예제 #4
0
    def testParseOutput(self):
        def mockread():
            yield "info depth 120 seldepth 2 score mate 1 nodes 4697 nps 391416 time 12 multipv 1 pv f7d7"
            yield "info nodes 0 time 2"
            yield "bestmove (none) ponder (none)"

        gen = mockread()
        self.mock_eng.stdout.readline = lambda: next(gen)

        out = Engine._parse_output(self.mock_eng)
        self.assertEqual(out['analysis']['score'], 1)
        self.assertEqual(out['analysis']['unit'], 'mate')
예제 #5
0
    def testParseUpperbound(self):
        def mockread():
            yield "info depth 10 seldepth 12 score cp -31 upperbound nodes 66588 nps 812048 time 82 multipv 1 pv a8e8 e2e3 f5c2 d4f4 c2e4"
            yield "info nodes 66588 time 82"
            yield "bestmove a8e8 ponder e2e3"

        gen = mockread()
        self.mock_eng.stdout.readline = lambda: next(gen)

        out = Engine._parse_output(self.mock_eng)
        self.assertEqual(out['analysis']['score'], -0.31)
        self.assertEqual(out['analysis']['unit'], 'p')
        self.assertEqual(out['analysis']['modifier'], 'upperbound')
예제 #6
0
def analyze_game(game, game_pgn, thinktime, stockfish_path):
    game_analysis = {}
    game_analysis['white'] = game_pgn.white
    game_analysis['black'] = game_pgn.black
    game_analysis['event'] = game.event
    game_analysis['date'] = game.date
    game_analysis['analysis_date'] = str(datetime.now())
    game_analysis['positions'] = []

    engine = Engine(stockfish_path)
    moves = []
    for i in range(len(game.moves)):
        move_pgn = game_pgn.moves[i]
        white_to_move = i % 2 == 0

        move_str = str((i + 2) // 2)
        if white_to_move:
            move_str = move_str + "."
        else:
            move_str = move_str + "..."

        print("Analyzing move " + move_str)

        position = {
            'move_number': move_str,
            'side': 'white' if white_to_move else 'black',
            'move': move_pgn,
            'details': engine.go_time(thinktime),
        }

        move = game.moves[i]
        moves.append(move)
        engine.setposition(moves)

        position['fen'] = engine.fen()
        game_analysis['positions'].append(position)

    engine.terminate()
    return game_analysis
예제 #7
0
 def train_vs_stockfish(self, debug=False, think_time=20, depth=8):
     fish = Engine(depth=20, param={"Threads": 12, "Hash": 1024})
     wins = 0
     draws = 0
     games = 0
     while True:
         board, win = self.play_vs_stockfish(fish,
                                             think_time=think_time,
                                             depth=depth,
                                             debug=debug)
         if win == 1:
             wins += 1
             if think_time > 1:
                 think_time -= 1
         elif win == 0.5:
             draws += 1
         else:
             if think_time < 20:
                 think_time += 1
             pass
         games += 1
         self.train_from_board(board)
         print('Wins:', wins, 'Draws:', draws, 'Games:', games,
               'Think Time:', think_time)
예제 #8
0
 def __init__(self):
     self.Engine = Engine(depth=19)
예제 #9
0
파일: untitled2.py 프로젝트: freesloth/fsd
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 03:05:42 2020

@author: user
"""

from pystockfish import Engine

deepthinker = Engine(depth=15)
deepthinker.setposition(['e2e4', 'e7e5'])
deepthinker.bestmove()