Exemple #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())
Exemple #2
0
class TestStockfish(unittest.TestCase):
    def setUp(self):
        self.stockfish = Stockfish()

    def test_get_best_move(self):
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, (
            'e2e4',
            'g1f3',
        ))

        self.stockfish.set_position(['e2e4', 'e7e6'])
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, (
            'd2d4',
            'g1f3',
        ))

        # mate
        self.stockfish.set_position(['f2f3', 'e7e5', 'g2g4', 'd8h4'])
        self.assertFalse(self.stockfish.get_best_move())

    def test_is_move_correct(self):
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
        self.stockfish.set_position(['e2e4', 'e7e6'])
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
class TestStockfish(unittest.TestCase):
    def setUp(self):
        self.stockfish = Stockfish()

    def test_get_best_move(self):
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, (
            'e2e4',
            'g1f3',
            'b1c3',
        ))

        self.stockfish.set_position(['e2e4', 'e7e6'])
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, (
            'd2d4',
            'g1f3',
        ))

        # mate
        self.stockfish.set_position(['f2f3', 'e7e5', 'g2g4', 'd8h4'])
        self.assertFalse(self.stockfish.get_best_move())

    def test_set_fen_position(self):
        self.stockfish.set_fen_position(
            "7r/1pr1kppb/2n1p2p/2NpP2P/5PP1/1P6/P6K/R1R2B2 w - - 1 27")
        self.assertTrue(self.stockfish.is_move_correct('f4f5'))
        self.assertFalse(self.stockfish.is_move_correct('a1c1'))

    def test_is_move_correct(self):
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
        self.stockfish.set_position(['e2e4', 'e7e6'])
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
Exemple #4
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
Exemple #5
0
def main():
    #Deteremine start
    random.seed(datetime.now())
    white = random.randint(0, 1)

    #initialize board and stockfish
    board = chess.Board()
    fishy = Stockfish(
        '/Users/vishalaiely/Downloads/stockfish-11-mac/Mac/stockfish-11-64')

    if white:
        #playsound.playsound('audio/WhiteStart.mp3')
        speak('Hello, you have the white pieces')
    else:
        #playsound.playsound('audio/BlackStart.mp3')
        speak('Hello, you have the black pieces')

    #Game executes and breaks when over
    while not board.is_game_over():
        if white:
            board.push_uci(playermove(board))

            fishy.set_fen_position(board.fen())
            compMove = fishy.get_best_move()
            board.push_uci(compMove)

            speak(compMove)

        else:
            fishy.set_fen_position(board.fen())
            compMove = fishy.get_best_move()
            board.push_uci(compMove)

            speak(compMove)

            board.push_uci(playermove(board))

    #Determines end state of game
    if board.result() is '1-0':
        #playsound.playsound('audio/WhiteWin.mp3')
        speak('White wins')
    elif board.reset() is '0-1':
        #playsound.playsound('audio/BlackWin.mp3')
        speak('Black wins')
    elif board.is_stalemate():
        speak('Stalemate')
    else:
        speak('Draw')

    speak('Thank you for playing!')
Exemple #6
0
class RandomFish():
    def __init__(self):
        self.stockfish = Stockfish()
        self.board = chess.Board()

    def get_config(self):
        return 'rand0mfish.yml'

    def get_name(self):
        return 'rand0mfish'

    def new_game(self):
        self.board.reset()

    def set_position(self, moves):
        self.board.reset()
        for m in moves:
            self.board.push(chess.Move.from_uci(m))

    def get_move(self):
        # random move
        if bool(getrandbits(1)): return choice(list(self.board.legal_moves))

        # stockfish move
        self.stockfish.set_fen_position(self.board.fen())
        return self.stockfish.get_best_move()
Exemple #7
0
class Bot():
  def __init__(self):
    self.stockfish = Stockfish()

  def acceptable_challenge(self, chall):
    if chall["variant"]["key"] != "standard":
      return False

    if chall["timeControl"]["limit"] > 60:
      return False

    if chall["timeControl"]["increment"] > 0:
      return False

    return True

  def get_move(self, moves):
    b = chess.Board()

    if moves[0] == '': moves = [] 
    for m in moves:
      b.push(chess.Move.from_uci(m))

    if len(list(b.legal_moves)) < 1: return None

    # random move
    if bool(getrandbits(1)): return choice(list(b.legal_moves))

    # stockfish move
    self.stockfish.set_position(moves)

    return self.stockfish.get_best_move()
Exemple #8
0
 def test_get_best_move_wrong_position(self):
     wrong_fen = "3kk3/8/8/8/8/8/8/3KK3 w - - 0 0"
     s = Stockfish()
     s.set_fen_position(wrong_fen)
     assert s.get_best_move() in (
         "d1e2",
         "d1c1",
     )
Exemple #9
0
 def bot_move(self):
     stfish = Stockfish('stockfish')
     stfish.set_fen_position(self.fen())
     if self.board.turn:
         stfish.depth = self.white_bot_power
     else:
         stfish.depth = self.black_bot_power
     move = stfish.get_best_move()
     return self.make_move(move)
Exemple #10
0
def get_best_move(board):
    stockfish = Stockfish()
    move_list = []

    for move in board.moves:
        move_list.append(move.to_long_algebraic())

    stockfish.set_position(move_list)
    return long_algebraic_to_coordinate(stockfish.get_best_move())
Exemple #11
0
 def play(self):
     dirname = os.path.dirname(__file__)
     filename = os.path.join(dirname, 'stockfish-9-win\Windows\stockfish_9_x64')
     stockfish = Stockfish(filename)
     stockfish.set_skill_level(15)
     if not self.chessboard.is_game_over() and not self.chessboard.is_stalemate():
         board = self.chessboard.fen()
         stockfish.set_fen_position(board)
         ai_move = stockfish.get_best_move()
         move = chess.Move.from_uci(ai_move)
         print(move)
         self.chessboard.push(move)
         self.update()
Exemple #12
0
def gen_examples(randomness: float = 0.7,
                 randomness_decline: float = 0.95,
                 max_moves: int = 80,
                 table: str = c.DEFAULT_TABLE) -> None:
    """
    Generates training examples using Stockfish and stores them in a database in algebraic notation. Set up a MySQL 
    database first and set the connection in constants.py. Also make sure that Stockfish is installed correctly.

    :param table: Table the data is stored in.
    :param randomness: Starting Probability for proceeding with are random move instead of the best move. This is
        necessary to not simulate the same game each time.
    :param randomness_decline: Factor applied to the randomness with each move. Should be less than 1 to have less 
        randomness later in the game.
    :param max_moves: Stops the simulated game early to prevent too long end games.
    """
    game = Game()
    stockfish = Stockfish(c.STOCKFISH_PATH)
    examples = []
    moves = []
    for _ in range(max_moves):
        stockfish.set_position(moves)
        best_move = stockfish.get_best_move()

        value = _value(stockfish.get_evaluation())
        if best_move:
            examples.append((_truncate_fen(stockfish.get_fen_position()),
                             (best_move[:4], value)))

        if best_move and random.random() > randomness:
            move_alg = best_move
            move_tuple = _from_algebraic(move_alg)
        else:
            move_tuple = random.sample(game.game_legal_moves(), 1)[0]
            move_alg = _to_algebraic(move_tuple)

        if len(move_alg) == 5:
            print('pawn promotion')

        try:
            game.make_move(move_tuple[0], move_tuple[1])
            moves.append(move_alg)
        except ValueError:
            moves[-1] = moves[-1] + 'q'
            print(examples)

        randomness *= randomness_decline

        if game.game_winner():
            break
    db = Connector()
    db.insert_examples(examples, table)
class TestStockfish(unittest.TestCase):

    def setUp(self):
        self.stockfish = Stockfish()

    def test_get_best_move(self):
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, ('e2e4', 'g1f3',))

        self.stockfish.set_position(['e2e4', 'e7e6'])
        best_move = self.stockfish.get_best_move()
        self.assertIn(best_move, ('d2d4', 'g1f3',))

        # mate
        self.stockfish.set_position(['f2f3', 'e7e5', 'g2g4', 'd8h4'])
        self.assertFalse(self.stockfish.get_best_move())

    def test_is_move_correct(self):
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
        self.stockfish.set_position(['e2e4', 'e7e6'])
        self.assertFalse(self.stockfish.is_move_correct('e2e1'))
        self.assertTrue(self.stockfish.is_move_correct('a2a3'))
Exemple #14
0
 def insertFEN(self, fen):
     """Is inserting FEN into sqlite
     :param fen: chess position in Forsyth-Edwards-Notation (FEN), e.g. r4rnk/1pp4p/3p4/3P1b2/1PPbpBPq/8/2QNB1KP/1R3R2 w KQkq - 0 25
     """
     self.cursor.execute("select count(*) from FEN where fen = ?;", [fen])
     data = self.cursor.fetchone()[0]
     if data == 0:
         stockfish = Stockfish('/usr/games/stockfish')
         stockfish.set_fen_position(fen)
         bestmove = stockfish.get_best_move()
     try:
         self.cursor.execute("insert into FEN(fen, bestmove) values(?,?);",
                             (str([fen]), bestmove))
     except sqlite3.IntegrityError:
         pass
class ChessGame:
    def __init__(self, fen):
        """ constructor taking initial FEN position"""
        self.d_engine = Stockfish()
        self.setFen(fen)

    def setFen(self, fen):
        """ set board in fen notation """
        self.d_engine.set_fen(fen)

    def move(self, algMove):
        """ move in long algebraic notation, send to stockfish """
        if self.d_engine.is_move_correct(algMove):
            print("correct")

    def bestMove(self):
        return self.d_engine.get_best_move()
Exemple #16
0
class ChessGame:
    def __init__(self, fen):
        """ constructor taking initial FEN position""" 
        self.d_engine = Stockfish()
        self.setFen(fen)

    def setFen(self, fen):
        """ set board in fen notation """
        self.d_engine.set_fen(fen)

    def move(self, algMove):
        """ move in long algebraic notation, send to stockfish """
        if self.d_engine.is_move_correct(algMove):
            print("correct")

    def bestMove(self):
        return self.d_engine.get_best_move()
Exemple #17
0
class Brain:
    def __init__(self):
        self.sf = Stockfish()
        self.ucim = []
        self.tablero = chess.Board()
        print(self.tablero)

    def legal(self, mv):
        mov = self.to_move(mv)
        return (mov in self.tablero.legal_moves)

    def mover_uci(self, mv):
        self.ucim.append(mv)
        self.sf.set_position(self.ucim)
        self.tablero.push_uci(mv)
        print(self.tablero)

    def auto(self):
        mv = self.sf.get_best_move()
        print(mv)
        return (mv)

    def to_move(self, mv):
        return chess.Move.from_uci(mv)

    def is_over(self):
        return self.tablero.is_game_over()

    def capturo(self, mv):
        if self.tablero.is_capture(mv):
            if self.tablero.is_en_passant(mv):
                return (True, True)
            else:
                return (True, False)
        else:
            return (False, False)
        return

    def enroque(self, mv):
        if self.tablero.is_kingside_castling(mv):
            return (True, True)
        elif self.tablero.is_queenside_castling(mv):
            return (True, False)
        else:
            return (False, False)
Exemple #18
0
class Player:
    def __init__(self, controller="random", customFunction=None):
        # "random", "gp", "alphazero", "*anyother we're planning to implement"
        self.controller = controller
        self.customFunction = customFunction
        # add any other variables as needed
        self.stockfish = Stockfish(
            './stockfish-10-win/Windows/stockfish_10_x64.exe')

    def choose_move(self, board, moves):
        if self.controller == "random":
            chosenMoveIndex = random.randint(0, len(moves) - 1)
            chosenMove = moves[chosenMoveIndex]
            return chosenMove
        elif self.controller == "custom":
            return self.customFunction(board, moves)
        elif self.controller == "stockfish":
            self.stockfish.set_fen_position(board.fen())
            uciStr = self.stockfish.get_best_move()
            move = chess.Move.from_uci(uciStr)
            return move
        elif self.controller == "player":
            while True:
                print(board)
                move = input(
                    "Input a move, or input m for a list of possible moves: ")
                if move == 'm':
                    for move in moves:
                        print(move)
                    continue
                try:
                    move = chess.Move.from_uci(move)
                    if move in moves:
                        return move
                    else:
                        print("Invalid move")
                except:
                    print("Invalid move")
                    continue
        else:
            # implement controller's movement choice
            pass
class StockfishPlayer:
    def __init__(self, stockfishpath):
        conf = {
            "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",
        }
        self.stockfish = Stockfish(stockfishpath, parameters=conf)

    def get_best_move(self, fen):
        self.stockfish.set_fen_position(fen)
        return self.stockfish.get_best_move()
Exemple #20
0
 def calculate_suggestions(self, gui):
     for _ in range(5):
         stockfish = Stockfish("./src/cpu/stockfish_20090216_x64", 3)
         new_chess_match = copy.deepcopy(self.__chess_match)
         stockfish.set_fen_position(new_chess_match.get_fen_notation())
         new_chess_match.match_moves.limpa_pilha()
         rounds = 0 
         while rounds < 18 and (not new_chess_match.checkmate and not new_chess_match.draw):
             if self.__stop_thread:
                 return
             moviment = stockfish.get_best_move()
             new_chess_match.perform_chess_move(
                 ChessPosition(moviment[0], int(moviment[1])), 
                 ChessPosition(moviment[2], int(moviment[3]))
             )
             stockfish.set_fen_position(new_chess_match.get_fen_notation())
             rounds += 1
         self.__moviment_tree.add(self.get_eval(stockfish, new_chess_match), new_chess_match.match_moves)
     if self.__stop_thread:
             return
     moviments = self.__moviment_tree.max3() if new_chess_match.current_player == 'WHITE' else self.__moviment_tree.min3()
     gui.show_suggestions(moviments)
Exemple #21
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__
Exemple #22
0
class Game:
    def __init__(self):
        self.engine = Stockfish()
        self.board = Board()

    def sync_engine(self):
        self.engine.set_position(self.board.move_list)

    def get_best_move(self) -> str:
        return self.engine.get_best_move()

    def is_move_correct(self, move: str) -> bool:
        return self.engine.is_move_correct(move)

    def make_move(self, move) -> bool:
        if self.is_move_correct(move):
            self.board.make_move(move)
            self.sync_engine()
            return True
        else:
            return False

    def make_best_move(self):
        self.make_move(self.get_best_move())
Exemple #23
0
from bs4 import BeautifulSoup
from types import SimpleNamespace
import requests, json
from stockfish import Stockfish
#Ejemplo de lo que pueden hacer los tramposos XD
stockfish = Stockfish('stockfish',
                      parameters={
                          "Threads": 4,
                          "Minimum Thinking Time": 30
                      })
stockfish.set_depth(15)

while True:
    r = requests.get("https://lichess.org/KuXPWqE0bK55")
    soup = BeautifulSoup(r.content, 'html.parser')
    scripts = soup.select('script')
    game = scripts[-1]
    game = game.contents[0][41:-3]
    x = json.loads(game, object_hook=lambda d: SimpleNamespace(**d))
    stockfish.set_fen_position(x.data.game.fen)
    print("Best move: " + stockfish.get_best_move(), end='')
    next_move = input()
Exemple #24
0
from stockfish import Stockfish


def debug(msg):
    print(msg, file=sys.stderr)


def parser_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('-l',
                        '--level',
                        help='Show board',
                        type=int,
                        action='store',
                        default=1)
    args = parser.parse_args()
    return args


debug("Stockfish bot starting!\n")

args = parser_args()
s = Stockfish('./bin/stockfish')
s.set_skill_level(args.level)

while True:
    fen = input()
    debug(fen)
    s.set_fen_position(fen)
    print(s.get_best_move())
Exemple #25
0
""" Before running do
    pip install stockfish
    to get the stockfish python interface """

from stockfish import Stockfish

stockfish = Stockfish()
stockfish.set_position(['e2e4', 'e7e6'])
stockfish.depth = 20
print(stockfish.get_best_move())
print(stockfish.is_move_correct('a2a3'))
Exemple #26
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()
Exemple #27
0
def results():

    stockfish = Stockfish(
        '/Users/faizaanmadhani/Desktop/PCHACKS/chessapp/stockfish-10-mac/Mac/stockfish-10-64'
    )

    board = chess.Board()
    legalMove = board.legal_moves

    # build a request object
    req = request.get_json(force=True)

    oldPosition = req.get('queryResult').get('parameters').get('oldPosition')
    newPosition = req.get('queryResult').get('parameters').get('newPosition')
    checkmate = req.get('queryResult').get('queryText')
    piece = req.get('queryResult').get('parameters').get('piece')

    pieceStr = str(piece)
    newPositionStr = str(newPosition)

    if (pieceStr == 'knight' or 'night'):
        pieceStr = 'N' + newPositionStr
    elif (pieceStr == 'pawn' or 'Pawn'):
        pieceStr = newPositionStr
    else:
        pieceStr = pieceStr.charAt(0).upper() + newPositionStr

    # fetch action from json
    action = req.get('queryResult').get('action')

    if (os.stat("fenState.txt").st_size == 0):
        #If file fenState is empty, Write initial state of board to fenState
        writeFile = open("fenState.txt", "w")
        strBoardFen = board.fen()
        writeFile.write(str(strBoardFen))
        writeFile.close()

        #Then, read the state of the file
        readFile = open("fenState.txt", "r")
        boardState = readFile.read()
        board = chess.Board(boardState)

    else:
        #Otherwise, Read initial state of board
        readFile = open("fenState.txt", "r")
        boardState = readFile.read()
        board = chess.Board(boardState)

    if (chess.Move.from_uci(str(oldPosition) + str(newPosition))
            in board.legal_moves):
        board.push_san(pieceStr)

        #Get Fen position
        fenPosition = board.fen()

        #Engine makes their move
        stockfish.set_fen_position(fenPosition)
        bestmove = stockfish.get_best_move()
        board.push_san(bestmove)
        finalReturn = "I have moved " + bestmove

        #Write State to file (Debugging)
        writeFile = open("state.txt", "w")
        strBoard = str(board)
        writeFile.write(strBoard)
        writeFile.close()

        #Write FenState to file (State saving between moves)
        writeFile = open("fenState.txt", "w")
        boardFen = board.fen()
        strBoardFen = boardFen
        writeFile.write(strBoardFen)
        writeFile.close()

        if (str(checkmate) == 'checkmate' and board.is_checkmate() == True):
            finalReturn = "Checkmate!, and game over"
        elif (board.is_checkmate() == False and str(checkmate) == 'checkmate'):
            finalReturn = "You Can't Checkmate bro"

    else:
        finalReturn = "This move is wrong"

        writeFile = open("move.txt", "w+")
        Position = str(oldPosition + newPosition)
        writeFile.write(Position)
        writeFile.close()

    # return a fulfillment response
    return {'fulfillmentText': finalReturn}
Exemple #28
0
class Ai(Player):
    def __init__(self, color: str, game):
        """
        une classe pour l'ordinateur

        Parameters
        ----------
            color : str
                la couleur des pièces
            game: Game
                le jeu
        """
        super().__init__()
        self.name = f"ai{color}"
        self.color = color
        self.check = False
        self.game = game

        # variables propres
        self.engine = Stockfish(
            path="stockfish/stockfish_13_win_x64_bmi2.exe",
            parameters=self.game.settings["parameters"],
        )
        self.steps = self.game.settings["number_of_steps"]
        self.depth = self.game.settings["depth"]

    def en_avant_pawn(self, board) -> np.array:
        """
        clone de la méthode de la classe Board\\
        ne modifie pas les valeurs étant donné qu'on ne déplace pas de pièces dans le tableau courant\\
        mais dans des tableaux provisoires
        """
        for i in range(8):  # ligne
            for j in range(8):  # colonne
                piece = board[i, j]
                if piece is not None:
                    if piece.pawn_forward >= 2:
                        piece.pawn_forward = 0
                    piece.pawn_forward += piece.pawn_forward
        return board

    def get_move(self) -> str:
        move = self.game.board.last_move
        indexes = ["a", "b", "c", "d", "e", "f", "g", "h"]
        y1 = str(8 - move[0][0])
        y2 = str(8 - move[1][0])
        x1 = indexes[move[0][1]]
        x2 = indexes[move[1][1]]
        return x1 + y1 + x2 + y2

    def get_pos(self, move: str) -> list({tuple({int})}):
        indexes = ["a", "b", "c", "d", "e", "f", "g", "h"]
        x1, y1, x2, y2 = move[:4]
        x1 = indexes.index(x1)
        x2 = indexes.index(x2)
        y1 = 8 - int(y1)
        y2 = 8 - int(y2)
        return [(y1, x1), (y2, x2)]

    def empty(self, board, color: str) -> set({tuple({int})}):
        """
        clone de la méthode de la classe Board\\
        ne modifie pas les valeurs étant donné qu'on ne déplace pas de pièces dans le tableau courant\\
        mais dans des tableaux provisoires
        """
        res = set()
        for i in range(8):  # ligne
            for j in range(8):  # colonne
                piece = board[i, j]
                if piece is None or piece.color != color:
                    res.add((i, j))
        return res

    def play(self):
        """
        joue le coup de l'ia        
        """
        # affichage
        textsurface = font.render(
            "modélisation...", True,
            self.game.data["ai_thinking_indicator_color"])
        self.game.screen.blit(textsurface, (720, 25))
        pygame.display.flip()

        # si l'ia ne joue pas le premier coup de la partie
        if self.game.board.last_move[0][0] >= 0:
            moves = self.game.all_moves  # on récupère les coups précédents
            # !print("last moves :", moves)
            self.engine.set_position(moves)

        # meilleur coup
        self.engine.set_depth(self.depth)
        move = self.engine.get_best_move()
        self.engine.set_depth(2)
        # !print("best move :", move)

        # nouvelle position pour le moteur
        self.engine.set_position([move])
        # !print()
        getpos = self.get_pos(move)
        from_index = getpos[0]
        to_index = getpos[1]

        # affichage
        pygame.draw.rect(self.game.screen, self.game.data["background_color"],
                         (720, 25, 100, 20))
        textsurface = font.render(
            "réflexion...", True,
            self.game.data["ai_thinking_indicator_color"])
        self.game.screen.blit(textsurface, (720, 25))
        pygame.display.flip()

        # préparer les coups
        board = self.game.board.board
        for i in range(8):
            for j in range(8):
                piece = board[i, j]
                if piece is not None:
                    piece.viable = piece.accessible(
                        board,
                        (i, j)).intersection(self.empty(board, piece.color))
                    piece.viable = piece.accessible_with_checked(
                        (i, j), piece.viable, board)

        # jouer le coup
        piece = self.game.board.board[from_index]
        if len(move) == 5:
            piece.promoted = move[4]
        if to_index in piece.viable:
            piece.move_to(self.game, self.game.board.board, from_index,
                          to_index)
        else:
            print("error : illegal move played by ai\nsearching new move...\n")
            self.play_alt()

        self.game.next_player()  # joueur suivant

    def play_alt(self):
        """
        permet à l'ordinateur de jouer son tour 
        """
        self.tree = Node(
            self.color,
            None,
            self.game.board.deep_copy(self.game.board.board),
            ((0, 0), (0, 0)),
        )
        steps = self.steps
        start = time.time()  # durée de la réflexion totale

        # on construit l'arbre des coups
        pygame.draw.rect(self.game.screen, self.game.data["background_color"],
                         (720, 25, 100, 20))
        textsurface = font.render(
            "modélisation...", True,
            self.game.data["ai_thinking_indicator_color"])
        self.game.screen.blit(textsurface, (720, 25))
        pygame.display.flip()
        self.build(self.tree, steps, self.color)

        # on cherche le meilleur coup
        pygame.draw.rect(self.game.screen, self.game.data["background_color"],
                         (720, 25, 100, 20))
        textsurface = font.render(
            "réflexion...", True,
            self.game.data["ai_thinking_indicator_color"])
        self.game.screen.blit(textsurface, (720, 25))
        pygame.display.flip()
        self.tree.get_values(self.game.board.get_score)

        # on modifie le nombre d'étape au besoin
        end = time.time()
        if end - start <= 0.5 and not self.check:
            if self.steps + 1 <= self.settings["max_number_of_steps"]:
                self.steps += self.settings["number_of_steps_increase_allowed"]

        move = ()
        # on joue ce coup
        for child in self.tree.list_of_leaves:
            if child.value == self.tree.value:
                move = child.move
                break
        from_index = move[0]
        to_index = move[1]
        self.game.board.board[from_index].move_to(self.game,
                                                  self.game.board.board,
                                                  from_index, to_index)

        # on passe au joueur suivant
        self.game.next_player()

    def build(self, current_node: Node, remaining_steps: int, color: str):
        if remaining_steps == 0:
            current_node.value = self.game.board.get_score(current_node.board)
            return

        board = current_node.board.copy()
        list_of_pieces = []
        # création de la liste des pièces de la bonne couleur
        for i in range(8):
            for j in range(8):
                piece = board[i, j]
                if piece is not None and piece.color == color:
                    list_of_pieces.append((piece, (i, j)))

        # pour chaque pièce
        for piece, from_index in list_of_pieces:
            piece.viable = piece.accessible(board, from_index).intersection(
                self.empty(board, piece.color))
            piece.viable = piece.accessible_with_checked(
                from_index, piece.viable, board)
            # pour chaque déplacement viable
            for to_index in piece.viable:
                new_board = board.copy()

                new_board = self.en_avant_pawn(new_board)
                piece.move_to(None, new_board, from_index, to_index)
                if piece.name == "pion":
                    if to_index[0] == 0 or to_index[0] == 7:
                        new_board[to_index] = Dame(piece.color)

                new_node = Node(
                    color,
                    current_node,
                    new_board,
                    (from_index, to_index),
                )
                color = ("b", "n")[color == "b"]
                current_node.__append__(new_node)
                self.build(new_node, remaining_steps - 1, color)
Exemple #29
0
    x = np.where(np.array(color) != np.array(color2))

    print(np.array(color))
    print(x)

    if color2.iloc[x[0][0], x[1][0]] != 'e':
        x = np.array([[x[0][1], x[0][0]], [x[1][1], x[1][0]]])

    position, color = update1(position, color, x)

    print(board)
    print(color)
    print(position)

    move1 = chess.Move.from_uci(pos(x, index, columns))
    board.push(move1)

    sf.set_fen_position(board.fen())
    zz = sf.get_best_move()
    move2 = chess.Move.from_uci(zz)
    board.push(move2)

    initial = list(zz[1::-1])
    final = list(zz[3::-1])
    position, color = update2(position, color, initial, final)

    print(board)
    print(color)
    print(position)
    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))

chester.move_to_z(chester.grab_height)
ser.close()
Exemple #31
0
import time

board = chess.Board()

shallowfish = Stockfish(depth=17)
deepfish = Stockfish(depth=17)



moves = []

while True:
	if board.is_game_over():
		break
	#raw_input("Press enter to continue...")
	moves.append(shallowfish.get_best_move())
	shallowfish.set_position(moves)
	deepfish.set_position(moves)
	board.push(chess.Move.from_uci(moves[len(moves)-1]))

	print "ai 1 made move:",moves[len(moves)-1]
	print board 

	if board.is_game_over():
		break

	moves.append(deepfish.get_best_move())
	shallowfish.set_position(moves)
	deepfish.set_position(moves)
	board.push(chess.Move.from_uci(moves[len(moves)-1]))
Exemple #32
0
def play_back(fen):
    sf = Stockfish()
    sf.set_fen_position(fen)
    next_move = sf.get_best_move()
    del sf
    return next_move