Example #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)
Example #2
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)
Example #3
0
 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)
Example #4
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)
Example #5
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)
Example #6
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)
Example #7
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)
Example #8
0
    def nonoWhileExamine(self, bm):
        label = Gtk.Label(_("You can't touch this! You are examining a game."))

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #9
0
    def our_seeks_removed(self, glm):
        label = Gtk.Label(label=_("Your seeks have been removed"))

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #10
0
    def our_seeks_removed(self, glm):
        label = Gtk.Label(label=_("Your seeks have been removed"))

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #11
0
    def nonoWhileExamine(self, bm):
        label = Gtk.Label(_("You can't touch this! You are examining a game."))

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #12
0
    def player_on_noplay(self, bm, player):
        text = _(" noplay listing you")
        content = get_infobarmessage_content(player, text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #13
0
    def matchDeclined(self, bm, player):
        text = _(" has declined your offer for a match")
        content = get_infobarmessage_content(player, text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #14
0
 def player_lagged (self, bm, player):
     if player in self.gamemodel.ficsplayers:
         content = get_infobarmessage_content(player,
                                              _(" has lagged for 30 seconds"),
                                              self.gamemodel.ficsgame.game_type)
         def response_cb (infobar, response, message):
             message.dismiss()
             return False
         message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
         message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                 Gtk.ResponseType.CANCEL))
         self.showMessage(message)
     return False
Example #15
0
    def matchDeclined(self, bm, player):
        text = _(" has declined your offer for a match")
        content = get_infobarmessage_content(player, text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #16
0
 def player_lagged (self, bm, player):
     if player in self.gamemodel.ficsplayers:
         content = get_infobarmessage_content(player,
                                              _(" has lagged for 30 seconds"),
                                              self.gamemodel.ficsgame.game_type)
         def response_cb (infobar, response, message):
             message.dismiss()
             return False
         message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
         message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                 Gtk.ResponseType.CANCEL))
         self.showMessage(message)
     return False
Example #17
0
    def player_on_noplay(self, bm, player):
        text = _(" noplay listing you")
        content = get_infobarmessage_content(player, text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #18
0
    def onChallengeAdd(self, challenges, challenge):
        log.debug("%s" % challenge,
                  extra={"task": (self.connection.username, "onChallengeAdd")})
        SoundTab.playAction("aPlayerChecks")

        # TODO: differentiate between challenges and manual-seek-accepts
        # (wait until seeks are comparable FICSSeek objects to do this)
        # Related: http://code.google.com/p/pychess/issues/detail?id=206
        if challenge.adjourned:
            text = _(" would like to resume your adjourned <b>%(time)s</b> " +
                     "<b>%(gametype)s</b> game.") % \
                {"time": challenge.display_timecontrol,
                 "gametype": challenge.game_type.display_text}
        else:
            text = _(" challenges you to a <b>%(time)s</b> %(rated)s <b>%(gametype)s</b> game") \
                % {"time": challenge.display_timecontrol,
                   "rated": challenge.display_rated.lower(),
                   "gametype": challenge.game_type.display_text}
            if challenge.color:
                text += _(" where <b>%(player)s</b> plays <b>%(color)s</b>.") \
                    % {"player": challenge.player.name,
                       "color": _("white") if challenge.color == "white" else _("black")}
            else:
                text += "."
        content = get_infobarmessage_content(challenge.player,
                                             text,
                                             gametype=challenge.game_type)

        def callback(infobar, response, message):
            if response == Gtk.ResponseType.ACCEPT:
                self.connection.om.acceptIndex(challenge.index)
            elif response == Gtk.ResponseType.NO:
                self.connection.om.declineIndex(challenge.index)
            message.dismiss()
            return False

        message = InfoBarMessage(Gtk.MessageType.QUESTION, content, callback)
        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.messages[hash(challenge)] = message
        self.infobar.push_message(message)

        txi = self.store.prepend([
            challenge,
            challenge.player.getIcon(gametype=challenge.game_type),
            self.chaPix,
            challenge.player.name + challenge.player.display_titles(),
            challenge.player_rating, challenge.display_rated,
            challenge.game_type.display_text, challenge.display_timecontrol,
            challenge.sortable_time,
            self.textcolor_normal(),
            get_challenge_tooltip_text(challenge)
        ])
        self.challenges[hash(challenge)] = txi
        self.__updateActiveSeeksLabel()
        self.widgets["seektreeview"].scroll_to_cell(self.store.get_path(txi))
Example #19
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)
Example #20
0
    def req_not_fit_formula(self, bm, player, formula):
        content = get_infobarmessage_content2(
            player, _(" uses a formula not fitting your match request:"),
            formula)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #21
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)
Example #22
0
    def req_not_fit_formula(self, bm, player, formula):
        content = get_infobarmessage_content2(
            player, _(" uses a formula not fitting your match request:"),
            formula)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, content, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #23
0
 def opp_not_out_of_time (self, bm):
     if self.gamemodel.remote_player.time <= 0:
         content = get_infobarmessage_content2(
             self.gamemodel.remote_ficsplayer,
             _(" is lagging heavily but hasn't disconnected"),
             _("Continue to wait for opponent, or try to adjourn the game?"),
             gametype=self.gamemodel.ficsgame.game_type)
         def response_cb (infobar, response, message):
             if response == 2:
                 self.gamemodel.connection.client.run_command("adjourn")
             message.dismiss()
             return False
         message = InfoBarMessage(Gtk.MessageType.QUESTION, content, response_cb)
         message.add_button(InfoBarMessageButton(_("Wait"), Gtk.ResponseType.CANCEL))
         message.add_button(InfoBarMessageButton(_("Adjourn"), 2))
         self.showMessage(message)
     return False
Example #24
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)
Example #25
0
    def on_seek_updated(self, glm, message_text):
        if "manual accept" in message_text:
            message_text.replace("to manual accept", _("to manual accept"))
        elif "automatic accept" in message_text:
            message_text.replace("to automatic accept",
                                 _("to automatic accept"))
        if "rating range now" in message_text:
            message_text.replace("rating range now", _("rating range now"))
        label = Gtk.Label(label=_("Seek updated") + ": " + message_text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(
            InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #26
0
    def on_seek_updated(self, glm, message_text):
        if "manual accept" in message_text:
            message_text.replace("to manual accept", _("to manual accept"))
        elif "automatic accept" in message_text:
            message_text.replace("to automatic accept",
                                 _("to automatic accept"))
        if "rating range now" in message_text:
            message_text.replace("rating range now", _("rating range now"))
        label = Gtk.Label(label=_("Seek updated") + ": " + message_text)

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

        message = InfoBarMessage(Gtk.MessageType.INFO, label, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                Gtk.ResponseType.CANCEL))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #27
0
    def onChallengeAdd(self, challenges, challenge):
        log.debug("%s" % challenge,
                  extra={"task": (self.connection.username, "onChallengeAdd")})
        SoundTab.playAction("aPlayerChecks")

        # TODO: differentiate between challenges and manual-seek-accepts
        # (wait until seeks are comparable FICSSeek objects to do this)
        # Related: http://code.google.com/p/pychess/issues/detail?id=206
        if challenge.adjourned:
            text = _(" would like to resume your adjourned <b>%(time)s</b> " +
                     "<b>%(gametype)s</b> game.") % \
                {"time": challenge.display_timecontrol,
                 "gametype": challenge.game_type.display_text}
        else:
            text = _(" challenges you to a <b>%(time)s</b> %(rated)s <b>%(gametype)s</b> game") \
                % {"time": challenge.display_timecontrol,
                   "rated": challenge.display_rated.lower(),
                   "gametype": challenge.game_type.display_text}
            if challenge.color:
                text += _(" where <b>%(player)s</b> plays <b>%(color)s</b>.") \
                    % {"player": challenge.player.name,
                       "color": _("white") if challenge.color == "white" else _("black")}
            else:
                text += "."
        content = get_infobarmessage_content(challenge.player,
                                             text,
                                             gametype=challenge.game_type)

        def callback(infobar, response, message):
            if response == Gtk.ResponseType.ACCEPT:
                self.connection.om.acceptIndex(challenge.index)
            elif response == Gtk.ResponseType.NO:
                self.connection.om.declineIndex(challenge.index)
            message.dismiss()
            return False

        message = InfoBarMessage(Gtk.MessageType.QUESTION, content, callback)
        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.messages[hash(challenge)] = message
        self.infobar.push_message(message)

        txi = self.store.prepend(
            [challenge, challenge.player.getIcon(gametype=challenge.game_type),
             self.chaPix, challenge.player.name +
             challenge.player.display_titles(), challenge.player_rating,
             challenge.display_rated, challenge.game_type.display_text,
             challenge.display_timecontrol, challenge.sortable_time,
             self.textcolor_normal(), get_challenge_tooltip_text(challenge)])
        self.challenges[hash(challenge)] = txi
        self.__updateActiveSeeksLabel()
        self.widgets["seektreeview"].scroll_to_cell(self.store.get_path(txi))
Example #28
0
    def tooManySeeks(self, bm):
        label = Gtk.Label(label=_(
            "You may only have 3 outstanding seeks at the same time. If you want \
            to add a new seek you must clear your currently active seeks. Clear your seeks?"))
        label.set_width_chars(80)
        label.props.xalign = 0
        label.set_line_wrap(True)

        def response_cb(infobar, response, message):
            if response == Gtk.ResponseType.YES:
                self.connection.client.run_command("unseek")
            message.dismiss()
            return False

        message = InfoBarMessage(Gtk.MessageType.QUESTION, label, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_YES,
                                                Gtk.ResponseType.YES))
        message.add_button(InfoBarMessageButton(Gtk.STOCK_NO,
                                                Gtk.ResponseType.NO))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #29
0
    def opp_not_out_of_time(self, bm):
        if self.gamemodel.remote_player.time <= 0:
            content = get_infobarmessage_content2(
                self.gamemodel.remote_ficsplayer,
                _(" is lagging heavily but hasn't disconnected"),
                _("Continue to wait for opponent, or try to adjourn the game?"
                  ),
                gametype=self.gamemodel.ficsgame.game_type)

            def response_cb(infobar, response, message):
                if response == 2:
                    self.gamemodel.connection.client.run_command("adjourn")
                message.dismiss()
                return False

            message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                     response_cb)
            message.add_button(
                InfoBarMessageButton(_("Wait"), Gtk.ResponseType.CANCEL))
            message.add_button(InfoBarMessageButton(_("Adjourn"), 2))

            @idle_add
            def do_opp_not_out_of_time():
                self.showMessage(message)

            do_opp_not_out_of_time()
        return False
Example #30
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)
    def _infobar_adjourned_message(self, game, player):
        if player not in self.messages:
            text = _(" with whom you have an adjourned <b>%(timecontrol)s</b> "
                     + "<b>%(gametype)s</b> game is online.") % {
                         "timecontrol": game.display_timecontrol,
                         "gametype": game.game_type.display_text,
                     }
            content = get_infobarmessage_content(player,
                                                 text,
                                                 gametype=game.game_type)

            def callback(infobar, response, message):
                log.debug(
                    "%s" % player,
                    extra={
                        "task": (
                            self.connection.username,
                            "_infobar_adjourned_message.callback",
                        )
                    },
                )
                if response == Gtk.ResponseType.ACCEPT:
                    self.connection.client.run_command("match %s" %
                                                       player.name)
                elif response == Gtk.ResponseType.HELP:
                    self.connection.adm.queryMoves(game)
                else:
                    try:
                        self.messages[player].dismiss()
                        del self.messages[player]
                    except KeyError:
                        pass
                return False

            message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                     callback)
            message.add_button(
                InfoBarMessageButton(_("Request Continuation"),
                                     Gtk.ResponseType.ACCEPT))
            message.add_button(
                InfoBarMessageButton(_("Examine Adjourned Game"),
                                     Gtk.ResponseType.HELP))
            message.add_button(
                InfoBarMessageButton(Gtk.STOCK_CLOSE, Gtk.ResponseType.CANCEL))
            make_sensitive_if_available(message.buttons[0], player)
            self.messages[player] = message
            self.infobar.push_message(message)
Example #32
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)
Example #33
0
    def _infobar_adjourned_message(self, game, player):
        if player not in self.messages:
            text = _(" with whom you have an adjourned <b>%(timecontrol)s</b> " +
                     "<b>%(gametype)s</b> game is online.") % \
                {"timecontrol": game.display_timecontrol,
                 "gametype": game.game_type.display_text}
            content = get_infobarmessage_content(player,
                                                 text,
                                                 gametype=game.game_type)

            def callback(infobar, response, message):
                log.debug(
                    "%s" % player,
                    extra={"task": (self.connection.username,
                                    "_infobar_adjourned_message.callback")})
                if response == Gtk.ResponseType.ACCEPT:
                    self.connection.client.run_command("match %s" %
                                                       player.name)
                elif response == Gtk.ResponseType.HELP:
                    self.connection.adm.queryMoves(game)
                else:
                    try:
                        self.messages[player].dismiss()
                        del self.messages[player]
                    except KeyError:
                        pass
                return False

            message = InfoBarMessage(Gtk.MessageType.QUESTION, content,
                                     callback)
            message.add_button(InfoBarMessageButton(
                _("Request Continuation"), Gtk.ResponseType.ACCEPT))
            message.add_button(InfoBarMessageButton(
                _("Examine Adjourned Game"), Gtk.ResponseType.HELP))
            message.add_button(InfoBarMessageButton(Gtk.STOCK_CLOSE,
                                                    Gtk.ResponseType.CANCEL))
            make_sensitive_if_available(message.buttons[0], player)
            self.messages[player] = message
            self.infobar.push_message(message)
Example #34
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
Example #35
0
    def tooManySeeks(self, bm):
        label = Gtk.Label(label=_(
            "You may only have 3 outstanding seeks at the same time. If you want \
            to add a new seek you must clear your currently active seeks. Clear your seeks?"))
        label.set_width_chars(80)
        label.props.xalign = 0
        label.set_line_wrap(True)

        def response_cb(infobar, response, message):
            if response == Gtk.ResponseType.YES:
                self.connection.client.run_command("unseek")
            message.dismiss()
            return False

        message = InfoBarMessage(Gtk.MessageType.QUESTION, label, response_cb)
        message.add_button(InfoBarMessageButton(Gtk.STOCK_YES,
                                                Gtk.ResponseType.YES))
        message.add_button(InfoBarMessageButton(Gtk.STOCK_NO,
                                                Gtk.ResponseType.NO))
        self.messages.append(message)
        self.infobar.push_message(message)
Example #36
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
Example #37
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
Example #38
0
 def __init__(self, message_type, content, callback, player, text):
     InfoBarMessage.__init__(self, message_type, content, callback)
     self.player = player
     self.text = text
Example #39
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
Example #40
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
Example #41
0
def play_or_add_move(view, board, move):
    if board.board.next is None:
        # at the end of variation or main line
        if not view.shownIsMainLine():
            # add move to existing variation
            view.model.add_move2variation(
                board, move, view.shown_variation_idx)
            view.shown += 1
        else:
            # create new variation
            new_vari = view.model.add_variation(board, (move, ))
            view.setShownBoard(new_vari[-1])
    else:
        # inside variation or main line
        if board.board.next.lastMove == move.move:
            # replay mainline move
            view.shown += 1
            if view.model.lesson_game:
                incr = 1 if len(view.model.moves) == board.ply + 1 else 2
                view.model.ply_played += incr
                # view.model.players[0].putMessage(_("Good move!") if incr == 2 else _("Well done!"))
                # view.model.emit("game_changed", board.ply + incr)
                play_sound(move, board)

                def callback(infobar, response, message):
                    if response == 1:
                        view.setShownBoard(board)
                        message.dismiss()
                    return False

                content = get_message_content(_("Good move!") if incr == 2 else _("Well done!"), "", Gtk.STOCK_DIALOG_INFO)
                message = InfoBarMessage(Gtk.MessageType.INFO, content, callback)
                message.add_button(InfoBarMessageButton(_("OK let's go on!"), 1))
                view.game_widget.replaceMessages(message)

                board = view.model.getBoardAtPly(board.ply + incr)
                view.setShownBoard(board)
                if incr == 1:
                    view.model.checkStatus()
        elif board.board.next.children:
            if view.model.lesson_game:
                view.model.players[0].putMessage(_("You can do it better!"))
                view.setShownBoard(board)
                return
            # try to find this move in variations
            for i, vari in enumerate(board.board.next.children):
                for node in vari:
                    if type(node) != str and node.lastMove == move.move and node.plyCount == board.ply + 1:
                        # replay variation move
                        view.setShownBoard(node.pieceBoard)
                        return
            # create new variation
            new_vari = view.model.add_variation(board, (move, ))
            view.setShownBoard(new_vari[-1])
        else:
            if view.model.lesson_game:
                # view.model.players[0].putMessage(_("You can do it better!"))
                play_sound(move, board)
                # view.setShownBoard(board)
                # return

                def callback(infobar, response, message):
                    if response == 1:
                        view.setShownBoard(board)
                        message.dismiss()
                    return False

                content = get_message_content(_("You can do it better!"), "", Gtk.STOCK_DIALOG_INFO)
                message = InfoBarMessage(Gtk.MessageType.INFO, content, callback)
                message.add_button(InfoBarMessageButton(_("Retry"), 1))
                view.game_widget.replaceMessages(message)
            # create new variation
            new_vari = view.model.add_variation(board, (move, ))
            view.setShownBoard(new_vari[-1])
Example #42
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
Example #43
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
Example #44
0
 def __init__(self, message_type, content, callback, player, text):
     InfoBarMessage.__init__(self, message_type, content, callback)
     self.player = player
     self.text = text