Example #1
0
    def post(self):
        action = self.get_argument("action")

        if action == 'broadcast':
            fen = self.get_argument("fen")

            move_stack = self.get_argument("moveStack")
            move_stack = json.loads(move_stack)
            game = pgn.Game()

            create_game_header(self, game)

            tmp = game
            for move in move_stack:
                tmp = tmp.add_variation(tmp.board().parse_san(move))
            exporter = pgn.StringExporter()
            game.export(exporter,
                        headers=True,
                        comments=False,
                        variations=False)
            r = {
                'type': 'broadcast',
                'msg': 'Received position from Spectators!',
                'pgn': str(exporter),
                'fen': fen
            }
            EventHandler.write_to_clients(r)
        elif action == 'move':
            WebServer.fire(Event.REMOTE_MOVE,
                           move=(self.get_argument("source") +
                                 self.get_argument("target")),
                           fen=self.get_argument("fen"))
Example #2
0
 def transfer(game):
     pgn_game = pgn.Game().from_board(game)
     create_game_header(pgn_game)
     return pgn_game.accept(
         pgn.StringExporter(headers=True,
                            comments=False,
                            variations=False))
Example #3
0
def update_headers(cls):
    g = pgn.Game()
    create_game_header(cls, g)
    exp = pgn.StringExporter()
    g.export(exp, headers=True, comments=False, variations=False)
    pgn_str = str(exp)
    EventHandler.write_to_clients({'event': 'header', 'header': pgn_str})
Example #4
0
def save_game(channel_or_nick, game):
    """
    Given a `channel_or_nick` and a game state, save in mongodb.
    """

    game_doc = find_game(channel_or_nick)
    exporter = pgn.StringExporter(
        headers=True,
        variations=False,
        comments=False,
    )
    pgn_string = game.accept(exporter)

    if not game_doc:
        db.chess.insert({
            'opponent': channel_or_nick.strip('#'),
            'pgn': pgn_string,
            'round': game.headers['Round'],
            'stockfish_level': game.headers['Event'],
        })

    else:
        db.chess.update_one({
            '_id': game_doc['_id'],
        }, {
            '$set': {
                'pgn': pgn_string,
            },
        })
Example #5
0
 def _transfer(game: chess.Board):
     pgn_game = pgn.Game().from_board(game)
     self._build_game_header(pgn_game)
     self.shared['headers'] = pgn_game.headers
     return pgn_game.accept(
         pgn.StringExporter(headers=True,
                            comments=False,
                            variations=False))
Example #6
0
        def transfer(g):
            msg_game = copy.deepcopy(g)
            pgn_game = pgn.Game()
            moves = []
            # go back, to see if the first fen is not standard fen
            while msg_game.move_stack:
                moves.insert(0, msg_game.pop())
            if msg_game.fen() != chess.STARTING_FEN:
                pgn_game.setup(msg_game.fen())

            create_game_header(self, pgn_game)

            node = pgn_game
            for move in moves:
                node = node.add_variation(move)
            # transfer game to a pgn string
            exporter = pgn.StringExporter(headers=True,
                                          comments=False,
                                          variations=False)
            return pgn_game.accept(exporter)
Example #7
0
    def task(self, message):
        if message == Message.BOOK_MOVE:
            EventHandler.write_to_clients({
                'event': 'Message',
                'msg': 'Book move'
            })

        elif message == Message.START_NEW_GAME:
            EventHandler.write_to_clients({'event': 'NewGame'})
            EventHandler.write_to_clients({
                'event': 'Message',
                'msg': 'New game'
            })
            update_headers(self)

        elif message == Message.SEARCH_STARTED:
            EventHandler.write_to_clients({
                'event': 'Message',
                'msg': 'Thinking..'
            })

        elif message == Message.UCI_OPTION_LIST:
            self.shared['uci_options'] = message.options

        elif message == Message.SYSTEM_INFO:
            self.shared['system_info'] = message.info
            self.shared['system_info']['old_engine'] = self.shared[
                'system_info']['engine_name']
            update_headers(self)

        elif message == Message.ENGINE_NAME:
            self.shared['system_info']['engine_name'] = message.ename
            update_headers(self)

        elif message == Message.STARTUP_INFO:
            self.shared['game_info'] = message.info

        elif message == Message.OPENING_BOOK:  # Process opening book
            self.create_game_info()
            self.shared['game_info']['book'] = message.book

        elif message == Message.INTERACTION_MODE:  # Process interaction mode
            self.create_game_info()
            self.shared['game_info']['mode'] = message.mode
            if self.shared['game_info']['mode'] == Mode.REMOTE:
                self.shared['system_info']['engine_name'] = "Remote Player"
            else:
                self.shared['system_info']['engine_name'] = self.shared[
                    'system_info']['old_engine']
            update_headers(self)

        elif message == Message.PLAY_MODE:  # Process play mode
            self.create_game_info()
            self.shared['game_info']['play_mode'] = message.play_mode

        elif message == Message.TIME_CONTROL:
            self.create_game_info()
            self.shared['game_info'][
                'time_control_string'] = message.time_control_string

        elif message == Message.LEVEL:
            self.shared['game_info']['level'] = message.level
            update_headers(self)

        elif message == Message.COMPUTER_MOVE or message == Message.USER_MOVE or message == Message.REVIEW_MODE_MOVE:
            game = pgn.Game()
            custom_fen = getattr(message.game, 'custom_fen', None)
            if custom_fen:
                game.setup(custom_fen)
            create_game_header(self, game)

            tmp = game
            move_stack = message.game.move_stack
            for move in move_stack:
                tmp = tmp.add_variation(move)
            exporter = pgn.StringExporter()

            game.export(exporter,
                        headers=True,
                        comments=False,
                        variations=False)
            fen = message.game.fen()
            pgn_str = str(exporter)
            r = {'pgn': pgn_str, 'fen': fen, 'event': "newFEN"}

            if message == Message.COMPUTER_MOVE:
                r['move'] = message.result.bestmove.uci()
                r['msg'] = 'Computer move: ' + str(message.result.bestmove)
            elif message == Message.USER_MOVE:
                r['move'] = message.move.uci()
                r['msg'] = 'User move: ' + str(message.move)

            if message == Message.REMOTE_MODE_MOVE:
                r['move'] = 'User move: ' + str(message.move)
                r['remote_play'] = True

            self.shared['last_dgt_move_msg'] = r
            EventHandler.write_to_clients(r)
async def move_bd(msg):
    parts = msg.content.split(' ')
    if (len(parts) != 3):
        await msg.channel.send(
            "Erreur dans la lecture des données : mauvais nombre d'arguments")
        return
    game_id = 0

    try:
        game_id = int(parts[1])
    except ValueError:
        await msg.channel.send(
            "Erreur : Le second argument n'est pas un identifiant valide")
        return

    move = parts[2]
    cdesc = psycopg2.connect(**params_db)
    curs = cdesc.cursor()

    requete_modele = "SELECT pgn, id_blanc, id_noir, joueur_jouant, nom_blanc, nom_noir FROM games WHERE id_partie = {0};"

    req = requete_modele.format(str(game_id))

    curs.execute(req)
    l = curs.fetchone()

    if (l == None):
        await msg.channel.send("Identifiant de la partie non trouvé")
        curs.close()
        cdesc.close()
        return

    (game_pgn, id_blanc, id_noir, joueur_jouant, nom_blanc, nom_noir) = l

    board = chess.Board()
    pgn_ = io.StringIO(game_pgn)
    game = pgn.read_game(pgn_)

    for m in game.mainline_moves():
        board.push(m)

    id_messager = str(msg.author.id)
    id_player_to_move = id_blanc if board.turn == chess.WHITE else id_noir

    if (id_messager != id_player_to_move):
        await msg.channel.send("Le mauvais joueur tente de jouer")
        curs.close()
        cdesc.close()
        return
    try:

        move_played = board.push_san(move)
        new_pgn_g = game.from_board(board)
        new_pgn = new_pgn_g.accept(pgn.StringExporter(headers=True))

        if board.is_game_over(claim_draw=True):
            result = board.result(claim_draw=True)
            await fin_de_partie_bd(msg, result, new_pgn, game_id, id_blanc,
                                   id_noir, nom_blanc, nom_noir, curs)
            cdesc.commit()
            curs.close()
            cdesc.close()
            return

        requete_update = "UPDATE games SET pgn = '{0}', joueur_jouant = '{1}' WHERE id_partie = {2};"
        req2 = requete_update.format(new_pgn, str(not joueur_jouant), game_id)

        curs.execute(req2)
        cdesc.commit()
        curs.close()
        cdesc.close()

        await msg.channel.send("Le coup a été joué")

    except ValueError:
        await msg.channel.send("Le coup est mauvais.")
        curs.close()
        cdesc.close()
        return