示例#1
0
def stockFish_init(request):
    stockfish = Stockfish(parameters={
        "Threads": 2,
        "Minimum Thinking Time": 30
    })
    stockfish.set_position(["e2e4", "e7e6"])
    #posición de Forsyth–Edwards Notation (FEN)
    stockfish.set_fen_position(
        "rnbqkbnr/pppp1ppp/4p3/8/4P3/8/PPPP1PPP/RNBQKBNR w KQkq - 0 2")
    #coge el mejor movimiento
    stockfish.get_best_move(
    )  #stockfish.get_best_move_time(1000) en base al tiempo
    #nivel del motor
    stockfish.set_skill_level(15)
    #parámetros por defecto
    stockfish.get_parameters()
    #coge la posición FEN
    stockfish.get_fen_position()
    #coge el tablero por defecto del usuario
    stockfish.get_board_visual()
    #evalua jugada
    stockfish.get_evaluation()
    p = subprocess.Popen('stockfish-x64.exe',
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    p.stdin.write("position startpos moves e2e4 e7e5\n")
    p.stdin.write("go infinite\n")
    p.stdin.flush()
    time.sleep(1)
    print(p.communicate())
示例#2
0
class Computer:
    def __init__(self, skill_level):
        self.engine = Stockfish("./stockfish12/bin/stockfish")
        self.engine.set_skill_level(skill_level)
        self.move_history = []

    def get_move(self, player_move):
        self.move_history.append(player_move)
        self.engine.set_position(self.move_history)
        auto_move = self.engine.get_best_move()
        self.move_history.append(auto_move)

        return auto_move

    def get_suggestion(self):
        self.engine.set_position(self.move_history)
        auto_move = self.engine.get_best_move()

        return auto_move

    def print_board(self):
        self.engine.set_position(self.move_history)
        print(self.engine.get_board_visual())


# input -- board state (changes based on the user's move)

# output -- stockfish move
示例#3
0
class Engine(object):
    
    def __init__(self):
        super().__init__()
        self.engine = None
        self.max_time = 1000  # Milliseconds

        self.list_moves = []
    
    def set_engine(self, engine_name="stockfish", skill_level=10):
        if engine_name == "stockfish":
            # stockfish_dir = os.path.join(Resource.get_engine_dir(), "stockfish_20090216_x64.exe")
            stockfish_dir = os.path.join("E:\\Jeee\\Documents\\Projects\\Python\\Chess\\engines", "stockfish_20090216_x64.exe")
            self.engine = Stockfish(stockfish_dir)
            self.set_engine_skill_level(skill_level)
            

    def set_engine_skill_level(self, level):
        self.engine.set_skill_level(level)


    
    def get_best_move(self):
        move = self.engine.get_best_move()
        return move

    def move(self, move):
        self.list_moves.append(move)
        self.engine.set_position(self.list_moves)
        # self.print_board_visual()
        Logger.record_move(move)

    def print_board_visual(self):
        print(self.engine.get_board_visual())

    def close_engine(self):
        self.engine.__del__
示例#4
0
#     chester.move_square(move)
if (player == "w"):
    input("Make your first move, then press Enter")
# else:
#     print("I'm making my first move")
#     time.sleep(10)
#     chester.move_piece("d2d4")
#     input("Make your move, then press Enter")

winner = False  #Need to check if there's a winner after each move and if so: break the loop
while (not winner):
    fen, pieces = chester.calculate_fen_position(
    )  #This takes a picture and analyzes it, then generates the fen position of the board and returns it as a string
    print(fen)
    stockfish.set_fen_position(fen)
    print(stockfish.get_board_visual())
    time.sleep(1)
    move = str(stockfish.get_best_move())
    if (move == "None"):
        print("No possible move or something")
        exit()
    for p in pieces:
        if (move[2:4] == p["square"]):
            chester.move_piece(move[2:4] + 't0')
    print("Moving " + move)
    chester.move_piece(move)
    input("Make your move, then press Enter")

# pictures = [cv.imread("Q1.jpg"), cv.imread("Q2.jpg"), cv.imread("Q3.jpg") ,cv.imread("Q4.jpg")]
# print(chester.get_img_pieces(pictures))
示例#5
0
class Player(abc.ABC):
    """
    An abstract class for player.
    """
    QUIT_MOVE = 'a1a1'

    def __init__(self, first: bool, host: str, port: int,
                 skill_level: Optional[int], depth: Optional[int],
                 stockfish: Optional[str]):
        """
        Initialize a player.

        Args:
            first: Is the player going first.
            host: The host of the game.
            port: The port in the host of the game.
            skill_level: Still level for stockfish.
            depth: Depth to search for best move for stockfish.
            stockfish: Path to the stockfish executable to use.
        """
        self.player_turn = first
        self.host = host
        self.port = port
        self.skill_level = skill_level
        self.depth = depth
        self.moves = []
        self.socket = None

        self.stockfish = Stockfish(stockfish or "./stockfish")
        if self.skill_level is not None:
            self.stockfish.set_skill_level(self.skill_level)
        if self.depth is not None:
            self.stockfish.set_depth(self.depth)

    def get_turns(self) -> List[str]:
        """
        Get previous turns to the game from the other player, gets the board to the desired initial state.

        Returns:
            The pre turns set by the other player.
        """
        moves_num = struct.unpack('H', self.socket.recv(2))[0]
        moves = []
        for _ in range(moves_num):
            moves.append(self.socket.recv(5).decode('utf-8').rstrip('\0'))
        return moves

    def forward_turns(self, moves: Optional[List[str]] = None):
        """
        Send previous turns to the game to the other player.

        Args:
            moves: The pre turns set by this player.
        """
        if moves is None:
            moves = []

        self.socket.send(struct.pack('H', len(moves)))
        for move in moves:
            self.socket.send(move.ljust(5, '\0').encode('utf-8'))

    def set_turns(self, moves: List[str]):
        """
        Set the pre turns of the game.

        Args:
            moves: The pre turns of the game.
        """
        self.moves = moves
        self.player_turn ^= len(moves) % 2

    def choose_move(self):
        """
        Choose a move to perform.
        Chooses the move using stockfish and sends it to the other player.
        """
        self.stockfish.set_position(self.moves)
        move = self.stockfish.get_best_move()
        if not move:
            raise RuntimeError('game over')
        print('Move chosen:', move)
        self.socket.send(move.ljust(5, '\0').encode('utf-8'))
        self.moves.append(move)

    def get_move(self):
        """
        Get the move done by the other player.
        """
        move = self.socket.recv(5).decode('utf-8').rstrip('\0')
        if move == self.QUIT_MOVE:
            raise RuntimeError('game over')
        self.moves.append(move)
        print('Move got:', move)

    def turn(self):
        """
        Perform a single turn, either get the move done by the other player, or do a move.
        """
        if self.player_turn:
            self.choose_move()
        else:
            self.get_move()

        self.player_turn = not self.player_turn

    def print_board(self):
        """
        Print the current board's state.
        """
        self.stockfish.set_position(self.moves)
        print(self.stockfish.get_board_visual())

    def __del__(self):
        """
        Destruct a player.
        Disconnects the socket.
        """
        self.socket and self.socket.close()
示例#6
0
            mymove, emove = move_to_san(players_move, engine, board)
            moves.append(mymove)
            emoves.append(emove)

            # Updates move
            engine.set_position(emoves)

            # Makes engine move
            engine_move, emove = move_to_san(engine.get_best_move(), engine,
                                             board)

            # Condition for game over
            # get_best_move() returns false on mate
            if engine_move == False:
                print('Game over')
                print(engine.get_board_visual())
                sys.exit("Goodbye!")

            # Updates move list
            moves.append(engine_move)
            emoves.append(emove)
            engine.set_position(emoves)

            # Print all moves after each round
            index = 0
            move_num = 0
            for m in moves:

                if (index % 2) == 0:
                    move_num = move_num + 1
                    print(str(move_num) + '.' + str(m), end='')
示例#7
0
from stockfish import Stockfish 
import time
import chess
import keyboard
sf = Stockfish("K:\Local Disk\documents\chess\stock\stockfish-11-win\stockfish-11-win\Windows\stockfish_20011801_x64_modern.exe")
print(sf.get_board_visual())
moves=[]
n=0
k=0
white,black,fold,mov50,stalemate=0,0,0,0,0
play=True
threeinrowdraw=False

while threeinrowdraw==False:
    
    time.sleep(2)
    moves=[]
    n=0
    sf.set_position(moves)
    play=True
    board = chess.Board()
    while play==True:
         
        '''
        print('where you movin from')
        froom=input()
        print('where too')
        to=input()
        moves.append(f'{froom}{to}')'''
        bd=sf.get_best_move()
        moves.append(bd)
示例#8
0
from stockfish import Stockfish
stockfish = Stockfish("\Users\Sami\Documents\stockfish_12_win_x64-1")

{
    "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",
}

stockfish.get_best_move()
stockfish.get_board_visual()