Ejemplo n.º 1
0
    def offerError(self, offer, error):
        log.debug("Human.offerError: self=%s error=%s %s" %
                  (self, error, offer))
        assert offer.type in ACTION_NAMES
        actionName = ACTION_NAMES[offer.type]
        if error == ACTION_ERROR_NONE_TO_ACCEPT:
            heading = _("Unable to accept %s") % actionName.lower()
            text = _("Probably because it has been withdrawn.")
        elif error == ACTION_ERROR_NONE_TO_DECLINE or \
                error == ACTION_ERROR_NONE_TO_WITHDRAW:
            # If the offer was not there, it has probably already been either
            # declined or withdrawn.
            return
        else:
            heading = _("%s returns an error") % actionName
            text = ERROR_MESSAGES[error]

        content = InfoBar.get_message_content(heading, text,
                                              Gtk.STOCK_DIALOG_WARNING)

        def response_cb(infobar, response, message):
            message.dismiss()

        message = InfoBarMessage(Gtk.MessageType.WARNING, content, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.gmwidg.showMessage(message)
Ejemplo n.º 2
0
    def offer_callback(self, player, offer, gamemodel, gmwidg):
        if gamemodel.status != RUNNING:
            # If the offer has already been handled by Gamemodel and the game was
            # drawn, we need to do nothing
            return

        message = ""
        if offer.type == ABORT_OFFER:
            message = _("You sent an abort offer")
        elif offer.type == ADJOURN_OFFER:
            message = _("You sent an adjournment offer")
        elif offer.type == DRAW_OFFER:
            message = _("You sent a draw offer")
        elif offer.type == PAUSE_OFFER:
            message = _("You sent a pause offer")
        elif offer.type == RESUME_OFFER:
            message = _("You sent a resume offer")
        elif offer.type == TAKEBACK_OFFER:
            message = _("You sent an undo offer")
        elif offer.type == HURRY_ACTION:
            message = _("You asked your opponent to move")
        elif offer.type == FLAG_CALL:
            message = _("You sent flag call")
        else:
            return

        def response_cb(infobar, response, message):
            message.dismiss()
            return False
        content = InfoBar.get_message_content("", message, Gtk.STOCK_DIALOG_INFO)
        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        gmwidg.replaceMessages(message)

        return False
Ejemplo n.º 3
0
    def offer(self, offer):
        log.debug("Human.offer: self=%s %s" % (self, offer))
        assert offer.type in OFFER_MESSAGES

        if self.gamemodel.players[1 - self.color].__type__ is LOCAL:
            self.emit("accept", offer)
            return

        heading, text, takes_param = OFFER_MESSAGES[offer.type]
        if takes_param:
            param = offer.param
            if offer.type == TAKEBACK_OFFER and \
                    self.gamemodel.players[1 - self.color].__type__ != REMOTE:
                param = self.gamemodel.ply - offer.param
            heading = heading % param
            text = text % param

        def response_cb(infobar, response, message):
            if response == Gtk.ResponseType.ACCEPT:
                self.emit("accept", offer)
            elif response == Gtk.ResponseType.NO:
                self.emit("decline", offer)
            message.dismiss()

        content = InfoBar.get_message_content(heading, text,
                                              Gtk.STOCK_DIALOG_QUESTION)
        message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                 response_cb)
        message.add_button(InfoBarMessageButton(
            _("Accept"), Gtk.ResponseType.ACCEPT))
        message.add_button(InfoBarMessageButton(
            _("Decline"), Gtk.ResponseType.NO))
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.gmwidg.showMessage(message)
Ejemplo n.º 4
0
    def offerError(self, offer, error):
        log.debug("Human.offerError: self=%s error=%s %s" %
                  (self, error, offer))
        assert offer.type in ACTION_NAMES
        actionName = ACTION_NAMES[offer.type]
        if error == ACTION_ERROR_NONE_TO_ACCEPT:
            heading = _("Unable to accept %s") % actionName.lower()
            text = _("Probably because it has been withdrawn.")
        elif error == ACTION_ERROR_NONE_TO_DECLINE or \
                error == ACTION_ERROR_NONE_TO_WITHDRAW:
            # If the offer was not there, it has probably already been either
            # declined or withdrawn.
            return
        else:
            heading = _("%s returns an error") % actionName
            text = ERROR_MESSAGES[error]

        content = InfoBar.get_message_content(heading, text,
                                              Gtk.STOCK_DIALOG_WARNING)

        def response_cb(infobar, response, message):
            message.dismiss()

        message = InfoBarMessage(Gtk.MessageType.WARNING, content, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.gmwidg.showMessage(message)
Ejemplo n.º 5
0
 def offer (self, offer):
     log.debug("Human.offer: self=%s %s" % (self, offer))
     assert offer.type in OFFER_MESSAGES
     
     if self.gamemodel.players[1-self.color].__type__ is LOCAL:
         self.emit("accept", offer)
         return
     
     heading, text, takes_param = OFFER_MESSAGES[offer.type]
     if takes_param:
         param = offer.param
         if offer.type == TAKEBACK_OFFER and \
                 self.gamemodel.players[1-self.color].__type__ is not REMOTE:
             param = self.gamemodel.ply - offer.param
         heading = heading % param
         text = text % param
     
     def response_cb (infobar, response, message):
         if response == Gtk.ResponseType.ACCEPT:
             self.emit("accept", offer)
         elif response == Gtk.ResponseType.NO:
             self.emit("decline", offer)
         message.dismiss()
     content = InfoBar.get_message_content(heading, text, Gtk.STOCK_DIALOG_QUESTION)
     message = InfoBarMessage(Gtk.MessageType.QUESTION, content, response_cb)
     message.add_button(InfoBarMessageButton(_("Accept"), Gtk.ResponseType.ACCEPT))
     message.add_button(InfoBarMessageButton(_("Decline"), Gtk.ResponseType.NO))
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self._show_message(message)
Ejemplo n.º 6
0
 def hurry (self):
     title = _("Your opponent asks you to hurry!")
     text = _("Generally this means nothing, as the game is time-based, but if you want to please your opponent, perhaps you should get going.")
     content = InfoBar.get_message_content(title, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self._show_message(message)
Ejemplo n.º 7
0
 def hurry (self):
     title = _("Your opponent asks you to hurry!")
     text = _("Generally this means nothing, as the game is time-based, but if you want to please your opponent, perhaps you should get going.")
     content = InfoBar.get_message_content(title, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self.gmwidg.showMessage(message)
Ejemplo n.º 8
0
 def offerWithdrawn (self, offer):
     log.debug("Human.offerWithdrawn: self=%s %s" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was withdrawn by your opponent") % ACTION_NAMES[offer.type]
     text = _("Your opponent seems to have changed their mind.")
     content = InfoBar.get_message_content(heading, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self._show_message(message)
Ejemplo n.º 9
0
 def offerWithdrawn (self, offer):
     log.debug("Human.offerWithdrawn: self=%s %s" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was withdrawn by your opponent") % ACTION_NAMES[offer.type]
     text = _("Your opponent seems to have changed their mind.")
     content = InfoBar.get_message_content(heading, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self.gmwidg.showMessage(message)
Ejemplo n.º 10
0
 def offerDeclined (self, offer):
     log.debug("Human.offerDeclined: self=%s %s\n" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was declined by your opponent") % ACTION_NAMES[offer.type]
     text = _("Resend %s?" % ACTION_NAMES[offer.type].lower())
     content = InfoBar.get_message_content(heading, text, gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         if response == gtk.RESPONSE_ACCEPT:
             #self.emit("offer", offer)
         message.dismiss()
     message = InfoBarMessage(gtk.MESSAGE_INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(_("Resend"), gtk.RESPONSE_ACCEPT))
     message.add_button(InfoBarMessageButton(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))
     self._show_message(message)
 
 def offerWithdrawn (self, offer):
     log.debug("Human.offerWithdrawn: self=%s %s\n" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was withdrawn by your opponent") % ACTION_NAMES[offer.type]
     text = _("Your opponent seems to have changed their mind.")
     content = InfoBar.get_message_content(heading, text, gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(gtk.MESSAGE_INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))
     self._show_message(message)
 
 def offerError (self, offer, error):
     log.debug("Human.offerError: self=%s error=%s %s\n" % (self, error, offer))
     assert offer.type in ACTION_NAMES
     actionName = ACTION_NAMES[offer.type]
     if error == ACTION_ERROR_NONE_TO_ACCEPT:
         heading = _("Unable to accept %s") % actionName.lower()
         text = _("Probably because it has been withdrawn.")
     elif error == ACTION_ERROR_NONE_TO_DECLINE or \
          error == ACTION_ERROR_NONE_TO_WITHDRAW:
         # If the offer was not there, it has probably already been either
         # declined or withdrawn.
         return
     else:
         heading = _("%s returns an error") % actionName
         text = ERROR_MESSAGES[error]
     
     content = InfoBar.get_message_content(heading, text, gtk.STOCK_DIALOG_WARNING)
     def response_cb (infobar, response, message):
         message.dismiss()
     message = InfoBarMessage(gtk.MESSAGE_WARNING, content, response_cb)
     message.add_button(InfoBarMessageButton(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))
     self._show_message(message)
 
 @glock.glocked
 def _show_message (self, message):
     self.gmwidg.showMessage(message)
Ejemplo n.º 11
0
 def response_cb (infobar, response, message):
     if response == gtk.RESPONSE_ACCEPT:
         #self.emit("accept", offer)
     elif response == gtk.RESPONSE_NO:
         #self.emit("decline", offer)
     message.dismiss()
 content = InfoBar.get_message_content(heading, text, gtk.STOCK_DIALOG_QUESTION)
 message = InfoBarMessage(gtk.MESSAGE_QUESTION, content, response_cb)
 message.add_button(InfoBarMessageButton(_("Accept"), gtk.RESPONSE_ACCEPT))
 message.add_button(InfoBarMessageButton(_("Decline"), gtk.RESPONSE_NO))
 message.add_button(InfoBarMessageButton(gtk.STOCK_CLOSE, gtk.RESPONSE_CANCEL))
 self._show_message(message)
Ejemplo n.º 12
0
 def offerDeclined (self, offer):
     log.debug("Human.offerDeclined: self=%s %s" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was declined by your opponent") % ACTION_NAMES[offer.type]
     text = _("Resend %s?" % ACTION_NAMES[offer.type].lower())
     content = InfoBar.get_message_content(heading, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         if response == Gtk.ResponseType.ACCEPT:
             self.emit("offer", offer)
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(_("Resend"), Gtk.ResponseType.ACCEPT))
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self.gmwidg.showMessage(message)
Ejemplo n.º 13
0
 def offerDeclined (self, offer):
     log.debug("Human.offerDeclined: self=%s %s" % (self, offer))
     assert offer.type in ACTION_NAMES
     heading = _("%s was declined by your opponent") % ACTION_NAMES[offer.type]
     text = _("Resend %s?" % ACTION_NAMES[offer.type].lower())
     content = InfoBar.get_message_content(heading, text, Gtk.STOCK_DIALOG_INFO)
     def response_cb (infobar, response, message):
         if response == Gtk.ResponseType.ACCEPT:
             self.emit("offer", offer)
         message.dismiss()
     message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
     message.add_button(InfoBarMessageButton(_("Resend"), Gtk.ResponseType.ACCEPT))
     message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
     self._show_message(message)
Ejemplo n.º 14
0
    def offer_callback(self, player, offer, gamemodel, gmwidg):
        if gamemodel.status != RUNNING:
            # If the offer has already been handled by Gamemodel and the game was
            # drawn, we need to do nothing
            return

        message = ""
        if offer.type == ABORT_OFFER:
            message = _("You sent an abort offer")
        elif offer.type == ADJOURN_OFFER:
            message = _("You sent an adjournment offer")
        elif offer.type == DRAW_OFFER:
            message = _("You sent a draw offer")
        elif offer.type == PAUSE_OFFER:
            message = _("You sent a pause offer")
        elif offer.type == RESUME_OFFER:
            message = _("You sent a resume offer")
        elif offer.type == TAKEBACK_OFFER:
            message = _("You sent an undo offer")
        elif offer.type == HURRY_ACTION:
            message = _("You asked your opponent to move")
        elif offer.type == FLAG_CALL:
            message = _("You sent flag call")
        else:
            return

        def response_cb(infobar, response, message):
            message.dismiss()
            return False

        content = InfoBar.get_message_content("", message,
                                              Gtk.STOCK_DIALOG_INFO)
        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        gmwidg.replaceMessages(message)

        return False
Ejemplo n.º 15
0
    def run_analyze(button, *args):
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]

        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        analyzer = gamemodel.spectators[HINT]
        gmwidg.menuitems["hint_mode"].active = True
        threat_PV = conf.get("ThreatPV", False)
        if threat_PV:
            old_inv_check_value = conf.get("inv_analyzer_check", True)
            conf.set("inv_analyzer_check", True)
            inv_analyzer = gamemodel.spectators[SPY]
            gmwidg.menuitems["spy_mode"].active = True

        title = _("Game analyzing in progress...")
        text = _("Do you want to abort it?")
        content = InfoBar.get_message_content(title, text, Gtk.STOCK_DIALOG_QUESTION)
        def response_cb (infobar, response, message):
            message.dismiss()
            abort()
        message = InfoBarMessage(Gtk.MessageType.QUESTION, content, response_cb)
        message.add_button(InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
        gmwidg.showMessage(message)

        def analyse_moves():
            from_current = conf.get("fromCurrent", True)
            start_ply = gmwidg.board.view.shown if from_current else 0
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards[start_ply:]:
                if stop_event.is_set():
                    break
                @idle_add
                def do():
                    gmwidg.board.view.setShownBoard(board)
                do()
                analyzer.setBoard(board)
                inv_analyzer.setBoard(board)
                time.sleep(move_time+0.1)

                ply = board.ply
                if ply-1 in gamemodel.scores and ply in gamemodel.scores: 
                    color = (ply-1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply-1]
                    score_str = prettyPrintScore(oldscore, olddepth)
                    oldscore = oldscore * -1 if color == BLACK else oldscore
                    moves, score, depth = gamemodel.scores[ply]
                    score = score * -1 if color == WHITE else score
                    diff = score-oldscore
                    if (diff > thresold and color==BLACK) or (diff < -1*thresold and color==WHITE):
                        if threat_PV:
                            try:
                                if ply-1 in gamemodel.spy_scores:
                                    oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[ply-1]
                                    score_str0 = prettyPrintScore(oldscore0, olddepth0)
                                    pv0 = listToMoves(gamemodel.boards[ply-1], ["--"] + oldmoves0, validate=True)
                                    if len(pv0) > 2:
                                        gamemodel.add_variation(gamemodel.boards[ply-1], pv0, comment="Treatening", score=score_str0)
                            except ParsingError as e:
                                # ParsingErrors may happen when parsing "old" lines from
                                # analyzing engines, which haven't yet noticed their new tasks
                                log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                    (' '.join(oldmoves),e))
                        try:
                            pv = listToMoves(gamemodel.boards[ply-1], oldmoves, validate=True)
                            gamemodel.add_variation(gamemodel.boards[ply-1], pv, comment="Better is", score=score_str)
                        except ParsingError as e:
                            # ParsingErrors may happen when parsing "old" lines from
                            # analyzing engines, which haven't yet noticed their new tasks
                            log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                (' '.join(oldmoves),e))

            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)
            if threat_PV:
                conf.set("inv_analyzer_check", old_inv_check_value)
            message.dismiss()
                        
        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        hide_window(None)

        return True
Ejemplo n.º 16
0
def game_ended(gamemodel, reason, gmwidg):
    log.debug("gamenanny.game_ended: reason=%s gmwidg=%s\ngamemodel=%s" %
              (reason, gmwidg, gamemodel))
    nameDic = {
        "white": gamemodel.players[WHITE],
        "black": gamemodel.players[BLACK],
        "mover": gamemodel.curplayer
    }
    if gamemodel.status == WHITEWON:
        nameDic["winner"] = gamemodel.players[WHITE]
        nameDic["loser"] = gamemodel.players[BLACK]
    elif gamemodel.status == BLACKWON:
        nameDic["winner"] = gamemodel.players[BLACK]
        nameDic["loser"] = gamemodel.players[WHITE]
    msg_one = reprResult_long[gamemodel.status] % nameDic
    msg_two = reprReason_long[reason] % nameDic
    if gamemodel.reason == WON_ADJUDICATION:
        color = BLACK if gamemodel.status == WHITEWON else WHITE
        invalid_move = gamemodel.players[color].invalid_move
        if invalid_move:
            msg_two += _(" invalid engine move: %s" % invalid_move)

    content = InfoBar.get_message_content(msg_one, msg_two,
                                          Gtk.STOCK_DIALOG_INFO)
    message = InfoBarMessage(Gtk.MessageType.INFO, content, None)

    callback = None
    if isinstance(gamemodel, ICGameModel):
        if gamemodel.hasLocalPlayer() and not gamemodel.examined:

            def status_changed(player, prop, message):
                make_sensitive_if_available(message.buttons[0], player)
                make_sensitive_if_playing(message.buttons[1], player)

            def callback(infobar, response, message):
                if response == 0:
                    gamemodel.remote_player.offerRematch()
                elif response == 1:
                    gamemodel.remote_player.observe()
                return False
            gmwidg.cids[gamemodel.remote_ficsplayer] = \
                gamemodel.remote_ficsplayer.connect("notify::status", status_changed, message)
            message.add_button(InfoBarMessageButton(_("Offer Rematch"), 0))
            message.add_button(
                InfoBarMessageButton(
                    _("Observe %s" % gamemodel.remote_ficsplayer.name), 1))
            status_changed(gamemodel.remote_ficsplayer, None, message)

        else:

            def status_changed(player, prop, button):
                make_sensitive_if_playing(button, player)

            def callback(infobar, response, message):
                if response in (0, 1):
                    gamemodel.players[response].observe()
                return False

            for i, player in enumerate(gamemodel.ficsplayers):
                button = InfoBarMessageButton(_("Observe %s" % player.name), i)
                message.add_button(button)
                gmwidg.cids[player] = player.connect("notify::status",
                                                     status_changed, button)
                status_changed(player, None, button)

    elif gamemodel.hasLocalPlayer():

        def callback(infobar, response, message):
            if response == 1:
                # newGameDialog uses ionest uses gamenanny uses newGameDialog...
                from pychess.widgets.newGameDialog import createRematch
                createRematch(gamemodel)
            elif response == 2:
                if gamemodel.ply > 1:
                    offer = Offer(TAKEBACK_OFFER, gamemodel.ply - 2)
                else:
                    offer = Offer(TAKEBACK_OFFER, gamemodel.ply - 1)
                if gamemodel.players[0].__type__ == LOCAL:
                    gamemodel.players[0].emit("offer", offer)
                else:
                    gamemodel.players[1].emit("offer", offer)
            return False

        if not gamemodel.isLoadedGame():
            message.add_button(InfoBarMessageButton(_("Play Rematch"), 1))
        if gamemodel.status in UNDOABLE_STATES and gamemodel.reason in UNDOABLE_REASONS:
            if gamemodel.ply == 1:
                message.add_button(InfoBarMessageButton(_("Undo one move"), 2))
            elif gamemodel.ply > 1:
                message.add_button(InfoBarMessageButton(
                    _("Undo two moves"), 2))

    message.callback = callback
    gmwidg.game_ended_message = message

    if len(key2gmwidg) > 0:
        gmwidg.replaceMessages(message)
        gmwidg.status("%s %s." % (msg_one, msg_two[0].lower() + msg_two[1:]))

    if reason == WHITE_ENGINE_DIED:
        engineDead(gamemodel.players[0], gmwidg)
    elif reason == BLACK_ENGINE_DIED:
        engineDead(gamemodel.players[1], gmwidg)

    if (isinstance(gamemodel, ICGameModel) and not gamemodel.isObservationGame()) or \
            gamemodel.isEngine2EngineGame():
        gamemodel.restart_analyzer(HINT)
        gamemodel.restart_analyzer(SPY)
        if not conf.get("hint_mode", False):
            gamemodel.pause_analyzer(HINT)
        if not conf.get("spy_mode", False):
            gamemodel.pause_analyzer(SPY)

    return False
Ejemplo n.º 17
0
            def coro():
                persp = perspective_manager.get_perspective("games")
                gmwidg = persp.cur_gmwidg()
                gamemodel = gmwidg.gamemodel

                old_check_value = conf.get("analyzer_check")
                conf.set("analyzer_check", True)
                if HINT not in gamemodel.spectators:
                    try:
                        yield from asyncio.wait_for(gamemodel.start_analyzer(HINT), 5.0)
                    except asyncio.TimeoutError:
                        log.error("Got timeout error while starting hint analyzer")
                        return
                    except Exception:
                        log.error("Unknown error while starting hint analyzer")
                        return
                analyzer = gamemodel.spectators[HINT]
                gmwidg.menuitems["hint_mode"].active = True
                threat_PV = conf.get("ThreatPV")
                if threat_PV:
                    old_inv_check_value = conf.get("inv_analyzer_check")
                    conf.set("inv_analyzer_check", True)
                    if SPY not in gamemodel.spectators:
                        try:
                            yield from asyncio.wait_for(gamemodel.start_analyzer(SPY), 5.0)
                        except asyncio.TimeoutError:
                            log.error("Got timeout error while starting spy analyzer")
                            return
                        except Exception:
                            log.error("Unknown error while starting spy analyzer")
                            return
                    inv_analyzer = gamemodel.spectators[SPY]
                    gmwidg.menuitems["spy_mode"].active = True

                title = _("Game analyzing in progress...")
                text = _("Do you want to abort it?")
                content = InfoBar.get_message_content(title, text, Gtk.STOCK_DIALOG_QUESTION)

                def response_cb(infobar, response, message):
                    conf.set("analyzer_check", old_check_value)
                    if threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()
                    abort()
                message = InfoBarMessage(Gtk.MessageType.QUESTION, content, response_cb)
                message.add_button(InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
                gmwidg.replaceMessages(message)

                @asyncio.coroutine
                def analyse_moves():
                    should_black = conf.get("shouldBlack")
                    should_white = conf.get("shouldWhite")
                    from_current = conf.get("fromCurrent")
                    start_ply = gmwidg.board.view.shown if from_current else 0
                    move_time = int(conf.get("max_analysis_spin"))
                    threshold = int(conf.get("variation_threshold_spin"))
                    for board in gamemodel.boards[start_ply:]:
                        if self.stop_event.is_set():
                            break

                        gmwidg.board.view.setShownBoard(board)
                        analyzer.setBoard(board)
                        if threat_PV:
                            inv_analyzer.setBoard(board)
                        yield from asyncio.sleep(move_time + 0.1)

                        ply = board.ply - gamemodel.lowply
                        color = (ply - 1) % 2
                        if ply - 1 in gamemodel.scores and ply in gamemodel.scores and (
                                (color == BLACK and should_black) or (color == WHITE and should_white)):
                            oldmoves, oldscore, olddepth = gamemodel.scores[ply - 1]
                            oldscore = oldscore * -1 if color == BLACK else oldscore
                            score_str = prettyPrintScore(oldscore, olddepth)
                            moves, score, depth = gamemodel.scores[ply]
                            score = score * -1 if color == WHITE else score
                            diff = score - oldscore
                            if ((diff > threshold and color == BLACK) or (diff < -1 * threshold and color == WHITE)) and (
                               gamemodel.moves[ply - 1] != parseAny(gamemodel.boards[ply - 1], oldmoves[0])):
                                if threat_PV:
                                    try:
                                        if ply - 1 in gamemodel.spy_scores:
                                            oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[ply - 1]
                                            score_str0 = prettyPrintScore(oldscore0, olddepth0)
                                            pv0 = listToMoves(gamemodel.boards[ply - 1], ["--"] + oldmoves0, validate=True)
                                            if len(pv0) > 2:
                                                gamemodel.add_variation(gamemodel.boards[ply - 1], pv0,
                                                                        comment="Threatening", score=score_str0, emit=False)
                                    except ParsingError as e:
                                        # ParsingErrors may happen when parsing "old" lines from
                                        # analyzing engines, which haven't yet noticed their new tasks
                                        log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" %
                                                  (' '.join(oldmoves), e))
                                try:
                                    pv = listToMoves(gamemodel.boards[ply - 1], oldmoves, validate=True)
                                    gamemodel.add_variation(gamemodel.boards[ply - 1], pv,
                                                            comment="Better is", score=score_str, emit=False)
                                except ParsingError as e:
                                    # ParsingErrors may happen when parsing "old" lines from
                                    # analyzing engines, which haven't yet noticed their new tasks
                                    log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" %
                                              (' '.join(oldmoves), e))

                    self.widgets["analyze_game"].hide()
                    self.widgets["analyze_ok_button"].set_sensitive(True)
                    conf.set("analyzer_check", old_check_value)
                    if threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()

                    gamemodel.emit("analysis_finished")

                create_task(analyse_moves())
                hide_window(None)

                return True
Ejemplo n.º 18
0
    def run_analyze(button, *args):
        gmwidg = gamewidget.cur_gmwidg()
        gamemodel = gameDic[gmwidg]

        old_check_value = conf.get("analyzer_check", True)
        conf.set("analyzer_check", True)
        analyzer = gamemodel.spectators[HINT]
        gmwidg.menuitems["hint_mode"].active = True
        threat_PV = conf.get("ThreatPV", False)
        if threat_PV:
            old_inv_check_value = conf.get("inv_analyzer_check", True)
            conf.set("inv_analyzer_check", True)
            inv_analyzer = gamemodel.spectators[SPY]
            gmwidg.menuitems["spy_mode"].active = True

        title = _("Game analyzing in progress...")
        text = _("Do you want to abort it?")
        content = InfoBar.get_message_content(title, text,
                                              Gtk.STOCK_DIALOG_QUESTION)

        def response_cb(infobar, response, message):
            message.dismiss()
            abort()

        message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                 response_cb)
        message.add_button(
            InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
        gmwidg.replaceMessages(message)

        def analyse_moves():
            from_current = conf.get("fromCurrent", True)
            start_ply = gmwidg.board.view.shown if from_current else 0
            move_time = int(conf.get("max_analysis_spin", 3))
            thresold = int(conf.get("variation_thresold_spin", 50))
            for board in gamemodel.boards[start_ply:]:
                if stop_event.is_set():
                    break

                @idle_add
                def do():
                    gmwidg.board.view.setShownBoard(board)

                do()
                analyzer.setBoard(board)
                if threat_PV:
                    inv_analyzer.setBoard(board)
                time.sleep(move_time + 0.1)

                ply = board.ply
                if ply - 1 in gamemodel.scores and ply in gamemodel.scores:
                    color = (ply - 1) % 2
                    oldmoves, oldscore, olddepth = gamemodel.scores[ply - 1]
                    score_str = prettyPrintScore(oldscore, olddepth)
                    oldscore = oldscore * -1 if color == BLACK else oldscore
                    moves, score, depth = gamemodel.scores[ply]
                    score = score * -1 if color == WHITE else score
                    diff = score - oldscore
                    if (diff > thresold
                            and color == BLACK) or (diff < -1 * thresold
                                                    and color == WHITE):
                        if threat_PV:
                            try:
                                if ply - 1 in gamemodel.spy_scores:
                                    oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[
                                        ply - 1]
                                    score_str0 = prettyPrintScore(
                                        oldscore0, olddepth0)
                                    pv0 = listToMoves(gamemodel.boards[ply -
                                                                       1],
                                                      ["--"] + oldmoves0,
                                                      validate=True)
                                    if len(pv0) > 2:
                                        gamemodel.add_variation(
                                            gamemodel.boards[ply - 1],
                                            pv0,
                                            comment="Treatening",
                                            score=score_str0)
                            except ParsingError as e:
                                # ParsingErrors may happen when parsing "old" lines from
                                # analyzing engines, which haven't yet noticed their new tasks
                                log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                    (' '.join(oldmoves),e))
                        try:
                            pv = listToMoves(gamemodel.boards[ply - 1],
                                             oldmoves,
                                             validate=True)
                            gamemodel.add_variation(gamemodel.boards[ply - 1],
                                                    pv,
                                                    comment="Better is",
                                                    score=score_str)
                        except ParsingError as e:
                            # ParsingErrors may happen when parsing "old" lines from
                            # analyzing engines, which haven't yet noticed their new tasks
                            log.debug("__parseLine: Ignored (%s) from analyzer: ParsingError%s" % \
                                (' '.join(oldmoves),e))

            widgets["analyze_game"].hide()
            widgets["analyze_ok_button"].set_sensitive(True)
            conf.set("analyzer_check", old_check_value)
            if threat_PV:
                conf.set("inv_analyzer_check", old_inv_check_value)
            message.dismiss()

        t = threading.Thread(target=analyse_moves, name=fident(analyse_moves))
        t.daemon = True
        t.start()
        hide_window(None)

        return True
Ejemplo n.º 19
0
            def coro():
                persp = perspective_manager.get_perspective("games")
                gmwidg = persp.cur_gmwidg()
                gamemodel = gmwidg.gamemodel

                old_check_value = conf.get("analyzer_check")
                conf.set("analyzer_check", True)
                if HINT not in gamemodel.spectators:
                    try:
                        yield from asyncio.wait_for(
                            gamemodel.start_analyzer(HINT), 5.0)
                    except asyncio.TimeoutError:
                        log.error(
                            "Got timeout error while starting hint analyzer")
                        return
                    except Exception:
                        log.error("Unknown error while starting hint analyzer")
                        return
                self.analyzer = gamemodel.spectators[HINT]
                gmwidg.menuitems["hint_mode"].active = True
                self.threat_PV = conf.get("ThreatPV")
                if self.threat_PV:
                    old_inv_check_value = conf.get("inv_analyzer_check")
                    conf.set("inv_analyzer_check", True)
                    if SPY not in gamemodel.spectators:
                        try:
                            yield from asyncio.wait_for(
                                gamemodel.start_analyzer(SPY), 5.0)
                        except asyncio.TimeoutError:
                            log.error(
                                "Got timeout error while starting spy analyzer"
                            )
                            return
                        except Exception:
                            log.error(
                                "Unknown error while starting spy analyzer")
                            return
                    inv_analyzer = gamemodel.spectators[SPY]
                    gmwidg.menuitems["spy_mode"].active = True

                title = _("Game analyzing in progress...")
                text = _("Do you want to abort it?")
                content = InfoBar.get_message_content(
                    title, text, Gtk.STOCK_DIALOG_QUESTION)

                def response_cb(infobar, response, message):
                    conf.set("analyzer_check", old_check_value)
                    if self.threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()
                    abort()

                message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                         response_cb)
                message.add_button(
                    InfoBarMessageButton(_("Abort"), Gtk.ResponseType.CANCEL))
                gmwidg.replaceMessages(message)

                @asyncio.coroutine
                def analyse_moves():
                    should_black = conf.get("shouldBlack")
                    should_white = conf.get("shouldWhite")
                    from_current = conf.get("fromCurrent")
                    start_ply = gmwidg.board.view.shown if from_current else 0
                    move_time = int(conf.get("max_analysis_spin"))
                    threshold = int(conf.get("variation_threshold_spin"))
                    for board in gamemodel.boards[start_ply:]:
                        if self.stop_event.is_set():
                            break

                        gmwidg.board.view.setShownBoard(board)
                        self.analyzer.setBoard(board)
                        if self.threat_PV:
                            inv_analyzer.setBoard(board)
                        yield from asyncio.sleep(move_time + 0.1)

                        ply = board.ply - gamemodel.lowply
                        color = (ply - 1) % 2
                        if ply - 1 in gamemodel.scores and ply in gamemodel.scores and (
                            (color == BLACK and should_black) or
                            (color == WHITE and should_white)):
                            oldmoves, oldscore, olddepth = gamemodel.scores[ply
                                                                            -
                                                                            1]
                            oldscore = oldscore * -1 if color == BLACK else oldscore
                            score_str = prettyPrintScore(oldscore, olddepth)
                            moves, score, depth = gamemodel.scores[ply]
                            score = score * -1 if color == WHITE else score
                            diff = score - oldscore
                            if ((diff > threshold and color == BLACK) or
                                (diff < -1 * threshold and color == WHITE)
                                ) and (gamemodel.moves[ply - 1] != parseAny(
                                    gamemodel.boards[ply - 1], oldmoves[0])):
                                if self.threat_PV:
                                    try:
                                        if ply - 1 in gamemodel.spy_scores:
                                            oldmoves0, oldscore0, olddepth0 = gamemodel.spy_scores[
                                                ply - 1]
                                            score_str0 = prettyPrintScore(
                                                oldscore0, olddepth0)
                                            pv0 = listToMoves(
                                                gamemodel.boards[ply - 1],
                                                ["--"] + oldmoves0,
                                                validate=True)
                                            if len(pv0) > 2:
                                                gamemodel.add_variation(
                                                    gamemodel.boards[ply - 1],
                                                    pv0,
                                                    comment="Threatening",
                                                    score=score_str0,
                                                    emit=False)
                                    except ParsingError as e:
                                        # ParsingErrors may happen when parsing "old" lines from
                                        # analyzing engines, which haven't yet noticed their new tasks
                                        log.debug(
                                            "__parseLine: Ignored (%s) from analyzer: ParsingError%s"
                                            % (' '.join(oldmoves), e))
                                try:
                                    pv = listToMoves(gamemodel.boards[ply - 1],
                                                     oldmoves,
                                                     validate=True)
                                    gamemodel.add_variation(
                                        gamemodel.boards[ply - 1],
                                        pv,
                                        comment="Better is",
                                        score=score_str,
                                        emit=False)
                                except ParsingError as e:
                                    # ParsingErrors may happen when parsing "old" lines from
                                    # analyzing engines, which haven't yet noticed their new tasks
                                    log.debug(
                                        "__parseLine: Ignored (%s) from analyzer: ParsingError%s"
                                        % (' '.join(oldmoves), e))

                    self.widgets["analyze_game"].hide()
                    self.widgets["analyze_ok_button"].set_sensitive(True)
                    conf.set("analyzer_check", old_check_value)
                    if self.threat_PV:
                        conf.set("inv_analyzer_check", old_inv_check_value)
                    message.dismiss()

                    gamemodel.emit("analysis_finished")

                create_task(analyse_moves())
                hide_window(None)

                return True
Ejemplo n.º 20
0
def game_ended (gamemodel, reason, gmwidg):
    log.debug("gamenanny.game_ended: reason=%s gmwidg=%s\ngamemodel=%s" % \
        (reason, gmwidg, gamemodel))
    nameDic = {"white": gamemodel.players[WHITE],
               "black": gamemodel.players[BLACK],
               "mover": gamemodel.curplayer}
    if gamemodel.status == WHITEWON:
        nameDic["winner"] = gamemodel.players[WHITE]
        nameDic["loser"] = gamemodel.players[BLACK]
    elif gamemodel.status == BLACKWON:
        nameDic["winner"] = gamemodel.players[BLACK]
        nameDic["loser"] = gamemodel.players[WHITE]
    m1 = reprResult_long[gamemodel.status] % nameDic
    m2 = reprReason_long[reason] % nameDic
    if gamemodel.reason == WON_ADJUDICATION:
        color = BLACK if gamemodel.status == WHITEWON else WHITE
        invalid_move = gamemodel.players[color].invalid_move
        if invalid_move:
            m2 += _(" invalid engine move: %s" % invalid_move)

    content = InfoBar.get_message_content(m1, m2, Gtk.STOCK_DIALOG_INFO)
    message = InfoBarMessage(Gtk.MessageType.INFO, content, None)

    callback = None
    if isinstance(gamemodel, ICGameModel):
        if gamemodel.hasLocalPlayer() and not gamemodel.examined:
            def status_changed (player, prop, message):
                make_sensitive_if_available(message.buttons[0], player)
                make_sensitive_if_playing(message.buttons[1], player)
            def callback (infobar, response, message):
                if response == 0:
                    gamemodel.remote_player.offerRematch()
                elif response == 1:
                    gamemodel.remote_player.observe()
                return False
            gmwidg.cids[gamemodel.remote_ficsplayer] = \
                gamemodel.remote_ficsplayer.connect("notify::status", status_changed, message)
            message.add_button(InfoBarMessageButton(_("Offer Rematch"), 0))
            message.add_button(InfoBarMessageButton(
                _("Observe %s" % gamemodel.remote_ficsplayer.name), 1))
            status_changed(gamemodel.remote_ficsplayer, None, message)

        else:
            def status_changed (player, prop, button):
                make_sensitive_if_playing(button, player)
            def callback (infobar, response, message):
                if response in (0, 1):
                    gamemodel.players[response].observe()
                return False
            for i, p in enumerate(gamemodel.ficsplayers):
                b = InfoBarMessageButton(_("Observe %s" % p.name), i)
                message.add_button(b)
                gmwidg.cids[p] = p.connect("notify::status", status_changed, b)
                status_changed(p, None, b)

    elif gamemodel.hasLocalPlayer():
        def callback (infobar, response, message):
            if response == 1:
                # newGameDialog uses ionest uses gamenanny uses newGameDialog...
                from pychess.widgets.newGameDialog import createRematch
                createRematch(gamemodel)
            elif response == 2:
                if gamemodel.ply > 1:
                    offer = Offer(TAKEBACK_OFFER, gamemodel.ply-2)
                else:
                    offer = Offer(TAKEBACK_OFFER, gamemodel.ply-1)
                if gamemodel.players[0].__type__ == LOCAL:
                    gamemodel.players[0].emit("offer", offer)
                else: gamemodel.players[1].emit("offer", offer)
            return False
        if not gamemodel.isLoadedGame():
            message.add_button(InfoBarMessageButton(_("Play Rematch"), 1))
        if gamemodel.status in UNDOABLE_STATES and gamemodel.reason in UNDOABLE_REASONS:
            if gamemodel.ply == 1:
                message.add_button(InfoBarMessageButton(_("Undo one move"), 2))
            elif gamemodel.ply > 1:
                message.add_button(InfoBarMessageButton(_("Undo two moves"), 2))

    message.callback = callback
    gmwidg.game_ended_message = message

    if len(key2gmwidg) > 0:
        gmwidg.replaceMessages(message)
        gmwidg.status("%s %s." % (m1,m2[0].lower()+m2[1:]))
    
    if reason == WHITE_ENGINE_DIED:
        engineDead(gamemodel.players[0], gmwidg)
    elif reason == BLACK_ENGINE_DIED:
        engineDead(gamemodel.players[1], gmwidg)

    if (isinstance(gamemodel, ICGameModel) and not gamemodel.isObservationGame()) or \
            gamemodel.isEngine2EngineGame():
        gamemodel.restart_analyzer(HINT)
        gamemodel.restart_analyzer(SPY)
        if not conf.get("hint_mode", False):
            gamemodel.pause_analyzer(HINT)
        if not conf.get("spy_mode", False):
            gamemodel.pause_analyzer(SPY)
    
    return False