예제 #1
0
 def select_dir(button):
     new_directory = dir_chooser_dialog.get_filename()
     engine = discoverer.getEngineByName(self.cur_engine)
     old_directory = engine.get("workingDirectory")
     if new_directory != old_directory and new_directory != self.default_workdir:
         engine["workingDirectory"] = new_directory
         discoverer.save()
예제 #2
0
 def comment_changed(widget):
     if self.cur_engine is not None and not self.selection:
         new_comment = self.widgets["engine_comment_entry"].get_text().strip()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_comment = engine.get("comment")
         if new_comment != old_comment:
             engine["comment"] = new_comment
예제 #3
0
 def args_changed(widget):
     if self.cur_engine is not None and not self.selection:
         new_args = self.widgets["engine_args_entry"].get_text().strip()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_args = engine.get("args")
         if new_args != old_args:
             engine["args"] = new_args.split()
예제 #4
0
 def selection_changed(treeselection):
     store, iter = self.tv.get_selection().get_selected()
     if iter:
         self.selection = True
         row = store.get_path(iter)[0]
         name = store[row][1]
         self.cur_engine = name
         engine = discoverer.getEngineByName(name)
         self.widgets['copy_engine_button'].set_sensitive(True)
         if "PyChess.py" in engine["command"]:
             self.widgets['remove_engine_button'].set_sensitive(False)
         else:
             self.widgets['remove_engine_button'].set_sensitive(True)
         self.widgets["engine_command_entry"].set_text(
             engine["command"])
         engine_chooser_dialog.set_filename(engine["command"])
         args = [] if engine.get("args") is None else engine.get("args")
         self.widgets["engine_args_entry"].set_text(' '.join(args))
         directory = engine.get("workingDirectory")
         d = directory if directory is not None else self.default_workdir
         dir_chooser_dialog.set_current_folder(d)
         self.widgets["engine_protocol_combo"].set_active(
             0 if engine["protocol"] == "uci" else 1)
         update_options()
         self.selection = False
예제 #5
0
 def on_all_engine_discovered(discoverer):
     engine = discoverer.getEngineByName(discoverer.getEngineLearn())
     if engine is None:
         engine = discoverer.getEngineN(-1)
     default_engine = engine.get("md5")
     conf.set("ana_combobox", default_engine)
     conf.set("inv_ana_combobox", default_engine)
예제 #6
0
 def level_changed(widget):
     if self.cur_engine is not None and not self.selection:
         new_level = widget.get_value()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_level = engine.get("level")
         if new_level != old_level:
             engine["level"] = int(new_level)
예제 #7
0
def start_endgame_from(pieces):
    fen = create_fen(pieces)

    timemodel = TimeModel(0, 0)
    gamemodel = LearnModel(timemodel)
    gamemodel.set_learn_data(ENDGAME, pieces)

    player_name = conf.get("firstName", _("You"))
    p0 = (LOCAL, Human, (WHITE, player_name), player_name)

    engine = discoverer.getEngineByName(discoverer.getEngineLearn())
    ponder_off = True
    engine_name = discoverer.getName(engine)
    p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
          (engine, BLACK, 20, variants[NORMALCHESS], 60, 0, 0,
           ponder_off), engine_name)

    def restart_analyzer(gamemodel):
        asyncio. async (gamemodel.restart_analyzer(HINT))

    gamemodel.connect("learn_success", restart_analyzer)

    def on_game_started(gamemodel):
        perspective.activate_panel("annotationPanel")
        asyncio. async (gamemodel.start_analyzer(
            HINT, force_engine=discoverer.getEngineLearn()))

    gamemodel.connect("game_started", on_game_started)

    perspective = perspective_manager.get_perspective("games")
    asyncio. async (perspective.generalStart(gamemodel,
                                             p0,
                                             p1,
                                             loaddata=(StringIO(fen),
                                                       fen_loader, 0, -1)))
예제 #8
0
def start_endgame_from(pieces):
        fen = create_fen(pieces)

        timemodel = TimeModel(0, 0)
        gamemodel = LearnModel(timemodel)
        gamemodel.set_learn_data(ENDGAME, pieces)

        player_name = conf.get("firstName", _("You"))
        p0 = (LOCAL, Human, (WHITE, player_name), player_name)

        engine = discoverer.getEngineByName(discoverer.getEngineLearn())
        ponder_off = True
        engine_name = discoverer.getName(engine)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 60, 0, 0, ponder_off), engine_name)

        def restart_analyzer(gamemodel):
            asyncio.async(gamemodel.restart_analyzer(HINT))
        gamemodel.connect("learn_success", restart_analyzer)

        def start_analyzer(gamemodel):
            asyncio.async(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn()))
        gamemodel.connect("game_started", start_analyzer)

        perspective = perspective_manager.get_perspective("games")
        asyncio.async(perspective.generalStart(gamemodel, p0, p1, loaddata=(StringIO(fen), fen_loader, 0, -1)))
예제 #9
0
    def startClicked(self, button):
        color = self.widgets["colorDock"].get_child().get_active()
        if color == 2:
            color = random.choice([WHITE, BLACK])

        opp = self.widgets["opponentDock"].get_child()
        tree_iter = opp.get_active_iter()
        if tree_iter is not None:
            model = opp.get_model()
            engine = model[tree_iter][1]

        opponent = self.widgets["opponentDock"].get_child().get_active()
        difficulty = int(self.widgets["skillSlider"].get_value())

        gamemodel = GameModel(TimeModel(5 * 60, 0))

        name = conf.get("firstName")
        player0tup = (LOCAL, Human, (color, name), name)
        if opponent == 0:
            name = conf.get("secondName")
            player1tup = (LOCAL, Human, (1 - color, name), name)
        else:
            engine = discoverer.getEngineByName(engine)
            name = discoverer.getName(engine)
            player1tup = (ARTIFICIAL, discoverer.initPlayerEngine,
                          (engine, 1 - color, difficulty,
                           variants[NORMALCHESS], 5 * 60, 0), name)

        perspective = perspective_manager.get_perspective("games")
        if color == WHITE:
            asyncio. async (perspective.generalStart(gamemodel, player0tup,
                                                     player1tup))
        else:
            asyncio. async (perspective.generalStart(gamemodel, player1tup,
                                                     player0tup))
예제 #10
0
 def select_dir(button):
     new_directory = dir_chooser_dialog.get_filename()
     engine = discoverer.getEngineByName(self.cur_engine)
     old_directory = engine.get("workingDirectory")
     if new_directory != old_directory and new_directory != self.default_workdir:
         engine["workingDirectory"] = new_directory
         discoverer.save()
예제 #11
0
    def startClicked(self, button):
        color = self.widgets["colorDock"].get_child().get_active()
        if color == 2:
            color = random.choice([WHITE, BLACK])

        opp = self.widgets["opponentDock"].get_child()
        tree_iter = opp.get_active_iter()
        if tree_iter is not None:
            model = opp.get_model()
            engine = model[tree_iter][1]

        opponent = self.widgets["opponentDock"].get_child().get_active()
        difficulty = int(self.widgets["skillSlider"].get_value())

        gamemodel = GameModel(TimeModel(5 * 60, 0))

        name = conf.get("firstName")
        player0tup = (LOCAL, Human, (color, name), name)
        if opponent == 0:
            name = conf.get("secondName")
            player1tup = (LOCAL, Human, (1 - color, name), name)
        else:
            engine = discoverer.getEngineByName(engine)
            name = discoverer.getName(engine)
            player1tup = (ARTIFICIAL, discoverer.initPlayerEngine,
                          (engine, 1 - color, difficulty,
                           variants[NORMALCHESS], 5 * 60, 0), name)

        perspective = perspective_manager.get_perspective("games")
        if color == WHITE:
            create_task(perspective.generalStart(gamemodel, player0tup, player1tup))
        else:
            create_task(perspective.generalStart(gamemodel, player1tup, player0tup))
예제 #12
0
 def level_changed(widget):
     if self.cur_engine is not None and not self.selection:
         new_level = widget.get_value()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_level = engine.get("level")
         if new_level != old_level:
             engine["level"] = int(new_level)
예제 #13
0
    def update_options(self, *args):
        if self.cur_engine is not None:
            # Initial reset
            self.options_store.clear()

            # Detection of the name of the engine to reload
            engines = discoverer.getEngines()
            names = [engine["name"] for engine in engines]
            if self.cur_engine not in names:
                self.cur_engine = engines[0]["name"]
            engine = discoverer.getEngineByName(self.cur_engine)
            if engine:
                options = engine.get("options")
                if options:
                    options.sort(key=lambda obj: obj['name'].lower()
                                 if 'name' in obj else '')
                    for option in options:
                        key = option["name"]
                        val = option
                        if option["type"] != "button":
                            val["default"] = option.get("default")
                            val["value"] = option.get("value", val["default"])
                            modified = val["value"] != val["default"]
                        else:
                            modified = False
                        self.options_store.append(
                            ["*" if modified else "", key, val])
예제 #14
0
 def args_changed(widget):
     if self.cur_engine is not None and not self.selection:
         new_args = self.widgets["engine_args_entry"].get_text().strip()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_args = engine.get("args")
         if new_args != old_args:
             engine["args"] = new_args.split()
예제 #15
0
 def selection_changed(treeselection):
     store, iter = self.tv.get_selection().get_selected()
     if iter:
         self.selection = True
         path = store.get_path(iter)
         indices = path.get_indices()
         row = indices[0]
         name = store[row][1]
         self.cur_engine = name
         engine = discoverer.getEngineByName(name)
         self.widgets['copy_engine_button'].set_sensitive(True)
         if "PyChess.py" in engine["command"]:
             self.widgets['remove_engine_button'].set_sensitive(False)
         else:
             self.widgets['remove_engine_button'].set_sensitive(True)
         self.widgets["engine_command_entry"].set_text(engine["command"])
         engine_chooser_dialog.set_filename(engine["command"])
         args = [] if engine.get("args") is None else engine.get("args")
         self.widgets["engine_args_entry"].set_text(' '.join(args))
         directory = engine.get("workingDirectory")
         d = directory if directory is not None else self.default_workdir
         dir_chooser_dialog.set_current_folder(d)
         self.widgets["engine_protocol_combo"].set_active(0 if engine["protocol"]=="uci" else 1)
         update_options()
         self.selection = False
예제 #16
0
    def row_activated(self, widget, path, col):
        if path is None:
            return
        pieces = ENDGAMES[path[0]][0]

        fen = self.create_fen(pieces)

        timemodel = TimeModel(0, 0)
        gamemodel = GameModel(timemodel)
        gamemodel.set_practice_game()

        name = conf.get("firstName", _("You"))
        p0 = (LOCAL, Human, (WHITE, name), name)

        engine = discoverer.getEngineByName(stockfish_name)
        name = discoverer.getName(engine)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 60, 0, 0, True), name)

        perspective = perspective_manager.get_perspective("games")
        asyncio. async (perspective.generalStart(gamemodel,
                                                 p0,
                                                 p1,
                                                 loaddata=(StringIO(fen),
                                                           fen_loader, 0, -1)))
예제 #17
0
        def protocol_changed(widget):
            if self.cur_engine is not None and not self.add and not self.selection:
                active = self.widgets["engine_protocol_combo"].get_active()
                new_protocol = "uci" if active == 0 else "xboard"
                engine = discoverer.getEngineByName(self.cur_engine)
                old_protocol = engine["protocol"]
                if new_protocol != old_protocol:
                    command = engine.get("command")
                    engine_command = []
                    vm_command = engine.get("vm_command")
                    if vm_command is not None:
                        engine_command.append(vm_command)
                        vm_args = engine.get("vm_args")
                        if vm_args is not None:
                            engine_command.append(", ".join(vm_args))
                    engine_command.append(command)

                    # is the new protocol supported by the engine?
                    if new_protocol == "uci":
                        check_ok = is_uci(engine_command)
                    else:
                        check_ok = is_cecp(engine_command)

                    if check_ok:
                        # discover engine options for new protocol
                        engine["protocol"] = new_protocol
                        engine["recheck"] = True
                        discoverer.discover()
                    else:
                        # restore the original protocol
                        widgets["engine_protocol_combo"].set_active(
                            0 if old_protocol == "uci" else 1)
예제 #18
0
 def on_all_engine_discovered(discoverer):
     engine = discoverer.getEngineByName(discoverer.getEngineLearn())
     if engine is None:
         engine = discoverer.getEngineN(-1)
     default_engine = engine.get("md5")
     conf.set("ana_combobox", default_engine)
     conf.set("inv_ana_combobox", default_engine)
예제 #19
0
    def update_options(self, *args):
        if self.cur_engine is not None:
            # Initial reset
            self.options_store.clear()

            # Detection of the name of the engine to reload
            engines = discoverer.getEngines()
            names = [engine["name"] for engine in engines]
            if self.cur_engine not in names:
                self.cur_engine = engines[0]["name"]
            engine = discoverer.getEngineByName(self.cur_engine)
            if engine:
                options = engine.get("options")
                if options:
                    options.sort(key=lambda obj: obj['name'].lower() if 'name' in obj else '')
                    for option in options:
                        key = option["name"]
                        val = option
                        if option["type"] != "button":
                            val["default"] = option.get("default")
                            val["value"] = option.get("value", val["default"])
                            modified = val["value"] != val["default"]
                        else:
                            modified = False
                        self.options_store.append(["*" if modified else "", key, val])
예제 #20
0
        def protocol_changed(widget):
            if self.cur_engine is not None and not self.add and not self.selection:
                active = self.widgets["engine_protocol_combo"].get_active()
                new_protocol = "uci" if active == 0 else "xboard"
                engine = discoverer.getEngineByName(self.cur_engine)
                old_protocol = engine["protocol"]
                if new_protocol != old_protocol:
                    command = engine.get("command")
                    engine_command = []
                    vm_command = engine.get("vm_command")
                    if vm_command is not None:
                        engine_command.append(vm_command)
                        vm_args = engine.get("vm_args")
                        if vm_args is not None:
                            engine_command.append(", ".join(vm_args))
                    engine_command.append(command)

                    # is the new protocol supported by the engine?
                    if new_protocol == "uci":
                        check_ok = is_uci(engine_command)
                    else:
                        check_ok = is_cecp(engine_command)

                    if check_ok:
                        # discover engine options for new protocol
                        engine["protocol"] = new_protocol
                        engine["recheck"] = True
                        discoverer.discover()
                    else:
                        # restore the original protocol
                        widgets["engine_protocol_combo"].set_active(
                            0 if old_protocol == "uci" else 1)
예제 #21
0
 def vm_args_changed(widget):
     if self.cur_engine is not None:
         new_args = self.widgets["vm_args_entry"].get_text().strip()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_args = engine.get("vm_args")
         if new_args != old_args:
             engine["vm_args"] = new_args.split()
             discoverer.save()
예제 #22
0
 def vm_args_changed(widget):
     if self.cur_engine is not None:
         new_args = self.widgets["vm_args_entry"].get_text().strip()
         engine = discoverer.getEngineByName(self.cur_engine)
         old_args = engine.get("vm_args")
         if new_args != old_args:
             engine["vm_args"] = new_args.split()
             discoverer.save()
예제 #23
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                if new_engine:
                    try:
                        uci = is_uci(new_engine)
                        if not uci:
                            if not is_cecp(new_engine):
                                # restore the original
                                engine = discoverer.getEngineByName(
                                    self.cur_engine)
                                engine_chooser_dialog.set_filename(
                                    engine["command"])
                                print("Maybe not a chess engine")
                                return
                        path, binname = os.path.split(new_engine)
                        for e in discoverer.getEngines():
                            if e["name"] == binname:
                                binname = e["name"] + "(1)"
                                break
                        self.widgets["engine_command_entry"].set_text(
                            new_engine)
                        self.widgets["engine_protocol_combo"].set_active(
                            0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")

                        active = self.widgets[
                            "engine_protocol_combo"].get_active()
                        protocol = "uci" if active == 0 else "xboard"

                        discoverer.addEngine(binname, new_engine, protocol)
                        self.cur_engine = binname
                        glock_connect_after(discoverer, "engine_discovered",
                                            update_store)
                        self.add = False
                        discoverer.discover()
                    except:
                        print("There is something wrong with this executable")
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])
            engine_chooser_dialog.hide()
예제 #24
0
        def selection_changed(treeselection):
            store, tv_iter = self.tv.get_selection().get_selected()
            if tv_iter:
                self.selection = True
                path = store.get_path(tv_iter)
                indices = path.get_indices()
                row = indices[0]
                name = store[row][1]
                self.cur_engine = name
                engine = discoverer.getEngineByName(name)
                if "PyChess.py" in engine["command"]:
                    self.widgets["remove_engine_button"].set_sensitive(False)
                else:
                    self.widgets["remove_engine_button"].set_sensitive(True)
                self.widgets["engine_command_entry"].set_text(
                    engine["command"])
                engine_chooser_dialog.set_filename(engine["command"])
                args = [] if engine.get("args") is None else engine.get("args")
                self.widgets["engine_args_entry"].set_text(" ".join(args))

                vm = engine.get("vm_command")
                self.widgets["vm_command_entry"].set_text(
                    vm if vm is not None else "")
                args = [] if engine.get("vm_args") is None else engine.get(
                    "vm_args")
                self.widgets["vm_args_entry"].set_text(" ".join(args))

                directory = engine.get("workingDirectory")
                dir_choice = (directory if directory is not None else
                              self.default_workdir)
                dir_chooser_dialog.set_current_folder(dir_choice)
                self.widgets["engine_protocol_combo"].set_active(
                    0 if engine["protocol"] == "uci" else 1)

                self.widgets["engine_country_combo"].set_active(0)
                country = discoverer.getCountry(engine)
                idx = 0
                for iso in ISO3166_LIST:
                    if iso.iso2 == country:
                        self.widgets["engine_country_combo"].set_active(idx)
                        break
                    idx += 1

                comment = engine.get("comment")
                self.widgets["engine_comment_entry"].set_text(
                    comment if comment is not None else "")

                level = engine.get("level")
                try:
                    level = int(level)
                except Exception:
                    level = ENGINE_DEFAULT_LEVEL
                self.widgets["engine_level_scale"].set_value(level)

                self.update_options()
                self.selection = False
예제 #25
0
def start_puzzle_game(gamemodel, filename, records, index, rec, from_lesson=False):
    gamemodel.set_learn_data(PUZZLE, filename, index, len(records), from_lesson=from_lesson)

    engine = discoverer.getEngineByName(discoverer.getEngineLearn())
    ponder_off = True

    color = gamemodel.boards[0].color

    w_name = "" if rec["White"] is None else rec["White"]
    b_name = "" if rec["Black"] is None else rec["Black"]

    player_name = conf.get("firstName")
    engine_name = discoverer.getName(engine)

    if rec["Event"].startswith("Lichess Practice"):
        w_name = player_name if color == WHITE else engine_name
        b_name = engine_name if color == WHITE else player_name

    opp_name = engine_name if rec["Event"].startswith("Lichess Practice") else b_name

    if color == WHITE:
        p0 = (LOCAL, Human, (WHITE, w_name), w_name)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), b_name)
    else:
        p0 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, WHITE, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), w_name)
        p1 = (LOCAL, Human, (BLACK, b_name), b_name)

    def on_game_started(gamemodel, name, color):
        perspective.activate_panel("annotationPanel")
        create_task(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn()))
        gamemodel.players[1 - color].name = name
        gamemodel.emit("players_changed")
    gamemodel.connect("game_started", on_game_started, opp_name, color)

    def goal_checked(gamemodle):
        if gamemodel.reason == PRACTICE_GOAL_REACHED:
            if from_lesson:
                progress = lessons_solving_progress[gamemodel.source]
            else:
                progress = puzzles_solving_progress[gamemodel.source]

            progress[gamemodel.current_index] = 1

            if from_lesson:
                lessons_solving_progress[gamemodel.source] = progress
            else:
                puzzles_solving_progress[gamemodel.source] = progress
    gamemodel.connect("goal_checked", goal_checked)

    gamemodel.variant.need_initial_board = True
    gamemodel.status = WAITING_TO_START

    perspective = perspective_manager.get_perspective("games")
    create_task(perspective.generalStart(gamemodel, p0, p1))
예제 #26
0
def start_puzzle_game(gamemodel, filename, records, index, rec, from_lesson=False):
    gamemodel.set_learn_data(PUZZLE, filename, index, len(records), from_lesson=from_lesson)

    engine = discoverer.getEngineByName(discoverer.getEngineLearn())
    ponder_off = True

    color = gamemodel.boards[0].color

    w_name = "" if rec["White"] is None else rec["White"]
    b_name = "" if rec["Black"] is None else rec["Black"]

    player_name = conf.get("firstName", _("You"))
    engine_name = discoverer.getName(engine)

    if rec["Event"].startswith("Lichess Practice"):
        w_name = player_name if color == WHITE else engine_name
        b_name = engine_name if color == WHITE else player_name

    opp_name = engine_name if rec["Event"].startswith("Lichess Practice") else b_name

    if color == WHITE:
        p0 = (LOCAL, Human, (WHITE, w_name), w_name)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), b_name)
    else:
        p0 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, WHITE, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), w_name)
        p1 = (LOCAL, Human, (BLACK, b_name), b_name)

    def on_game_started(gamemodel, name, color):
        perspective.activate_panel("annotationPanel")
        asyncio.async(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn()))
        gamemodel.players[1 - color].name = name
        gamemodel.emit("players_changed")
    gamemodel.connect("game_started", on_game_started, opp_name, color)

    def goal_checked(gamemodle):
        if gamemodel.reason == PRACTICE_GOAL_REACHED:
            if from_lesson:
                progress = lessons_solving_progress[gamemodel.source]
            else:
                progress = puzzles_solving_progress[gamemodel.source]

            progress[gamemodel.current_index] = 1

            if from_lesson:
                lessons_solving_progress[gamemodel.source] = progress
            else:
                puzzles_solving_progress[gamemodel.source] = progress
    gamemodel.connect("goal_checked", goal_checked)

    gamemodel.variant.need_initial_board = True
    gamemodel.status = WAITING_TO_START

    perspective = perspective_manager.get_perspective("games")
    asyncio.async(perspective.generalStart(gamemodel, p0, p1))
예제 #27
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == gtk.RESPONSE_OK:
                new_engine = engine_chooser_dialog.get_filename()
                if new_engine:
                    try:
                        uci = is_uci(new_engine)
                        if not uci:
                            if not is_cecp(new_engine):
                                # restore the original
                                engine = discoverer.getEngineByName(self.cur_engine)
                                engine_chooser_dialog.set_filename(engine["command"])
                                print "Maybe not a chess engine"
                                return
                        path, binname = os.path.split(new_engine)
                        for e in discoverer.getEngines():
                            if e["name"] == binname:
                                binname = e["name"] + "(1)"
                                break
                        self.widgets["engine_name_entry"].set_text(binname)
                        self.widgets["engine_command_entry"].set_text(new_engine)
                        self.widgets["engine_protocol_combo"].set_active(0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")
                        
                        name = self.widgets["engine_name_entry"].get_text().strip()
                        active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if active==0 else "xboard"
                        
                        discoverer.addEngine(name, new_engine, protocol)
                        self.cur_engine = name
                        glock_connect_after(discoverer, "engine_discovered", update_store)
                        self.add = False
                        discoverer.start()
                    except:
                        print "There is something wrong with this executable"
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])
            engine_chooser_dialog.hide()
예제 #28
0
 def remove(button):
     if self.cur_engine is not None:
         self.widgets['remove_engine_button'].set_sensitive(False)
         engine = discoverer.getEngineByName(self.cur_engine)
         discoverer.removeEngine(self.cur_engine)
         discoverer.save()
         update_store(discoverer)
         # Notify playerCombos in NewGameTasker
         discoverer.emit("all_engines_discovered")
         ts = self.tv.get_selection()
         ts.select_path((0, ))
예제 #29
0
 def remove(button):
     if self.cur_engine is not None:
         self.widgets['remove_engine_button'].set_sensitive(False)
         engine = discoverer.getEngineByName(self.cur_engine)
         discoverer.removeEngine(self.cur_engine)
         discoverer.save()
         update_store(discoverer)
         # Notify playerCombos in NewGameTasker
         discoverer.emit("all_engines_discovered")
         ts = self.tv.get_selection()
         ts.select_path((0,))
예제 #30
0
 def on_playerCombobox_changed(widget, skill_hbox, skill_level):
     position = widget.get_active()
     skill_hbox.props.visible = position > 0
     if position > 0:
         tree_iter = widget.get_active_iter()
         if tree_iter is not None:
             engine_name = widget.get_model()[tree_iter][1]
             engine = discoverer.getEngineByName(engine_name)
             if engine:
                 pref_level = engine.get("level")
                 if pref_level:
                     skill_level.set_value(pref_level)
예제 #31
0
 def on_playerCombobox_changed(widget, skill_hbox, skill_level):
     position = widget.get_active()
     skill_hbox.props.visible = position > 0
     if position > 0:
         tree_iter = widget.get_active_iter()
         if tree_iter is not None:
             engine_name = widget.get_model()[tree_iter][1]
             engine = discoverer.getEngineByName(engine_name)
             if engine:
                 pref_level = engine.get("level")
                 if pref_level:
                     skill_level.set_value(pref_level)
예제 #32
0
 def name_edited(renderer, path, new_name):
     if self.cur_engine is not None:
         old_name = self.cur_engine
         if new_name and new_name != old_name:
             names = [engine["name"] for engine in discoverer.getEngines()]
             if new_name not in names:
                 engine = discoverer.getEngineByName(self.cur_engine)
                 engine["name"] = new_name
                 discoverer.save()
                 self.cur_engine = new_name
                 update_store()                        
                 # Notify playerCombos in NewGameTasker
                 discoverer.emit("all_engines_discovered")
예제 #33
0
 def name_edited(renderer, path, new_name):
     if self.cur_engine is not None:
         old_name = self.cur_engine
         if new_name and new_name != old_name:
             names = [engine["name"] for engine in discoverer.getEngines()]
             if new_name not in names:
                 engine = discoverer.getEngineByName(self.cur_engine)
                 engine["name"] = new_name
                 discoverer.save()
                 self.cur_engine = new_name
                 update_store()                        
                 # Notify playerCombos in NewGameTasker
                 discoverer.emit("all_engines_discovered")
예제 #34
0
 def engine_default_options(button):
     if self.cur_engine is not None and not self.selection:
         engine = discoverer.getEngineByName(self.cur_engine)
         options = engine.get("options")
         if options:
             dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO)
             dialog.set_markup(_("Do you really want to restore the default options of the engine ?"))
             response = dialog.run()
             dialog.destroy()
             if response == Gtk.ResponseType.YES:
                 for option in options:
                     if "default" in option:
                         option["value"] = option["default"]
                 self.update_options()
예제 #35
0
        def selection_changed(treeselection):
            store, tv_iter = self.tv.get_selection().get_selected()
            if tv_iter:
                self.selection = True
                path = store.get_path(tv_iter)
                indices = path.get_indices()
                row = indices[0]
                name = store[row][1]
                self.cur_engine = name
                engine = discoverer.getEngineByName(name)
                if "PyChess.py" in engine["command"]:
                    self.widgets['remove_engine_button'].set_sensitive(False)
                else:
                    self.widgets['remove_engine_button'].set_sensitive(True)
                self.widgets["engine_command_entry"].set_text(engine["command"])
                engine_chooser_dialog.set_filename(engine["command"])
                args = [] if engine.get("args") is None else engine.get("args")
                self.widgets["engine_args_entry"].set_text(' '.join(args))

                vm = engine.get("vm_command")
                self.widgets["vm_command_entry"].set_text(vm if vm is not None else "")
                args = [] if engine.get("vm_args") is None else engine.get("vm_args")
                self.widgets["vm_args_entry"].set_text(' '.join(args))

                directory = engine.get("workingDirectory")
                dir_choice = directory if directory is not None else self.default_workdir
                dir_chooser_dialog.set_current_folder(dir_choice)
                self.widgets["engine_protocol_combo"].set_active(0 if engine["protocol"] == "uci" else 1)

                self.widgets["engine_country_combo"].set_active(0)
                country = discoverer.getCountry(engine)
                idx = 0
                for iso in ISO3166_LIST:
                    if iso.iso2 == country:
                        self.widgets["engine_country_combo"].set_active(idx)
                        break
                    idx += 1

                comment = engine.get("comment")
                self.widgets["engine_comment_entry"].set_text(comment if comment is not None else "")

                level = engine.get("level")
                try:
                    level = int(level) if level else defaultEngineLevel
                except Exception:
                    level = defaultEngineLevel
                self.widgets["engine_level_scale"].set_value(level)

                self.update_options()
                self.selection = False
예제 #36
0
        def remove(button):
            if self.cur_engine is not None:
                self.widgets['remove_engine_button'].set_sensitive(False)
                engine = discoverer.getEngineByName(self.cur_engine)
                discoverer.removeEngine(self.cur_engine)
                discoverer.save()

                selection = self.tv.get_selection()
                result = selection.get_selected()
                if result is not None:
                    model, iter = result
                    model.remove(iter)

                # Notify playerCombos in NewGameTasker
                discoverer.emit("all_engines_discovered")
예제 #37
0
        def remove(button):
            if self.cur_engine is not None:
                self.widgets['remove_engine_button'].set_sensitive(False)
                engine = discoverer.getEngineByName(self.cur_engine)
                discoverer.removeEngine(self.cur_engine)
                discoverer.save()

                selection = self.tv.get_selection()
                result = selection.get_selected()
                if result is not None:
                    model, ts_iter = result
                    model.remove(ts_iter)

                # Notify playerCombos in NewGameTasker
                discoverer.emit("all_engines_discovered")
예제 #38
0
 def update_options(*args):
     if self.cur_engine is not None:
         engines = discoverer.getEngines()
         names = [engine["name"] for engine in engines]
         # After deleting an engine we will select first
         if self.cur_engine not in names:
             self.cur_engine = engines[0]["name"]
         engine = discoverer.getEngineByName(self.cur_engine)
         options = engine.get("options")
         if options:
             self.options_store.clear()
             for option in options:
                 key = option["name"]
                 val = option
                 if option["type"] != "button":
                     val["default"] = option.get("default")
                     val["value"] = option.get("value", val["default"])
                 self.options_store.append([key, val])
예제 #39
0
 def update_options(*args):
     if self.cur_engine is not None:
         engines = discoverer.getEngines()
         names = [engine["name"] for engine in engines]
         # After deleting an engine we will select first
         if self.cur_engine not in names:
             self.cur_engine = engines[0]["name"]
         engine = discoverer.getEngineByName(self.cur_engine)
         options = engine.get("options")
         if options:
             self.options_store.clear()
             for option in options:
                 key = option["name"]
                 val = option
                 if option["type"] != "button":
                     val["default"] = option.get("default")
                     val["value"] = option.get("value", val["default"])
                 self.options_store.append([key, val])
예제 #40
0
def start_endgame_from(pieces):
        fen = create_fen(pieces)

        timemodel = TimeModel(0, 0)
        gamemodel = GameModel(timemodel)
        gamemodel.set_practice_game()
        gamemodel.practice = ("endgame", pieces)

        name = conf.get("firstName", _("You"))
        p0 = (LOCAL, Human, (WHITE, name), name)

        engine = discoverer.getEngineByName(stockfish_name)
        name = discoverer.getName(engine)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 60, 0, 0, True), name)

        perspective = perspective_manager.get_perspective("games")
        asyncio.async(perspective.generalStart(
            gamemodel, p0, p1, loaddata=(StringIO(fen), fen_loader, 0, -1)))
예제 #41
0
        def country_changed(widget):
            if self.cur_engine is not None and not self.selection:
                engine = discoverer.getEngineByName(self.cur_engine)
                old_country = discoverer.getCountry(engine)
                new_country = ISO3166_LIST[widget.get_active()].iso2
                if old_country != new_country:
                    engine["country"] = new_country

                    # Refresh the flag in the tree view
                    path = addDataPrefix("flags/%s.png" % new_country)
                    if not os.path.isfile(path):
                        path = addDataPrefix("flags/unknown.png")
                    item = self.tv.get_selection().get_selected()
                    if item is not None:
                        model, ts_iter = item
                        model[ts_iter][0] = get_pixbuf(path)

                        # Notify playerCombos in NewGameTasker
                        discoverer.emit("all_engines_discovered")
예제 #42
0
        def country_changed(widget):
            if self.cur_engine is not None and not self.selection:
                engine = discoverer.getEngineByName(self.cur_engine)
                old_country = discoverer.getCountry(engine)
                new_country = ISO3166_LIST[widget.get_active()].iso2
                if old_country != new_country:
                    engine["country"] = new_country

                    # Refresh the flag in the tree view
                    path = addDataPrefix("flags/%s.png" % new_country)
                    if not os.path.isfile(path):
                        path = addDataPrefix("flags/unknown.png")
                    item = self.tv.get_selection().get_selected()
                    if item is not None:
                        model, ts_iter = item
                        model[ts_iter][0] = get_pixbuf(path)

                        # Notify playerCombos in NewGameTasker
                        discoverer.emit("all_engines_discovered")
예제 #43
0
 def protocol_changed(widget):
     if self.cur_engine is not None and not self.add and not self.selection:
         active = self.widgets["engine_protocol_combo"].get_active()
         new_protocol = "uci" if active==0 else "xboard"
         engine = discoverer.getEngineByName(self.cur_engine)
         old_protocol = engine["protocol"]
         if new_protocol != old_protocol:
             engine_command = engine_chooser_dialog.get_filename()
             # is the new protocol supported by the engine?
             if new_protocol == "uci":
                 ok = is_uci(engine_command)
             else:
                 ok = is_cecp(engine_command)
             if ok:
                 # discover engine options for new protocol
                 engine["protocol"] = new_protocol
                 engine["recheck"] = True
                 discoverer.discover()
             else:
                 # restore the original protocol
                 widgets["engine_protocol_combo"].set_active(0 if old_protocol=="uci" else 1)
예제 #44
0
def start_puzzle_from(filename):
    chessfile = PGNFile(protoopen(addDataPrefix("lectures/%s" % filename)))
    chessfile.limit = 1000
    importer = PgnImport(chessfile)
    chessfile.init_tag_database(importer)
    records, plys = chessfile.get_records()

    rec = records[random.randrange(0, len(records))]

    timemodel = TimeModel(0, 0)
    gamemodel = GameModel(timemodel)
    gamemodel.set_practice_game()
    gamemodel.practice = ("puzzle", filename)

    chessfile.loadToModel(rec, 0, gamemodel)

    # TODO: change colors according to FEN!
    name = rec["White"]
    p0 = (LOCAL, Human, (WHITE, name), name)

    engine = discoverer.getEngineByName(stockfish_name)
    name = rec["Black"]
    ponder_off = True
    p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
          (engine, BLACK, 20, variants[NORMALCHESS], 60, 0, 0,
           ponder_off), name)

    def fix_name(gamemodel, name):
        asyncio. async (gamemodel.start_analyzer(HINT,
                                                 force_engine=stockfish_name))
        gamemodel.players[1].name = name
        gamemodel.emit("players_changed")

    gamemodel.connect("game_started", fix_name, name)

    gamemodel.variant.need_initial_board = True
    gamemodel.status = WAITING_TO_START

    perspective = perspective_manager.get_perspective("games")
    asyncio. async (perspective.generalStart(gamemodel, p0, p1))
예제 #45
0
 def protocol_changed(widget):
     if self.cur_engine is not None and not self.add and not self.selection:
         active = self.widgets["engine_protocol_combo"].get_active()
         new_protocol = "uci" if active == 0 else "xboard"
         engine = discoverer.getEngineByName(self.cur_engine)
         old_protocol = engine["protocol"]
         if new_protocol != old_protocol:
             engine_command = engine_chooser_dialog.get_filename()
             # is the new protocol supported by the engine?
             if new_protocol == "uci":
                 check_ok = is_uci(engine_command)
             else:
                 check_ok = is_cecp(engine_command)
             if check_ok:
                 # discover engine options for new protocol
                 engine["protocol"] = new_protocol
                 engine["recheck"] = True
                 discoverer.discover()
             else:
                 # restore the original protocol
                 widgets["engine_protocol_combo"].set_active(
                     0 if old_protocol == "uci" else 1)
예제 #46
0
        def onResponse(dialog, response):
            if response == COPY:
                clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
                clipboard.set_text(cls.get_fen(), -1)
                # print("put clipboard:", clipboard.wait_for_text())
                return
            elif response == CLEAR:
                cls.board_control.emit("action", "SETUP", True)
                cls.ini_widgets(True)
                # print("clear")
                return
            elif response == PASTE:
                clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
                text = clipboard.wait_for_text()
                # print("got clipboard:", text)
                if text is None or len(text.split()) < 2:
                    return
                try:
                    lboard = cls.setupmodel.variant(setup=text).board
                    cls.ini_widgets(lboard.asFen())
                    cls.board_control.emit("action", "SETUP", text)
                except SyntaxError as e:
                    d = Gtk.MessageDialog(mainwindow(),
                                          type=Gtk.MessageType.WARNING,
                                          buttons=Gtk.ButtonsType.OK,
                                          message_format=e.args[0])
                    if len(e.args) > 1:
                        d.format_secondary_text(e.args[1])
                    d.connect("response", lambda d, a: d.hide())
                    d.show()
                return
            elif response == INITIAL:
                lboard = cls.setupmodel.variant(setup=FEN_START).board
                cls.ini_widgets(lboard.asFen())
                cls.board_control.emit("action", "SETUP", FEN_START)
                return
            elif response != Gtk.ResponseType.OK:
                cls.widgets["newgamedialog"].hide()
                cls.widgets["newgamedialog"].disconnect(handlerId)
                return

            if hasattr(cls, "board_control"):
                cls.board_control.emit("action", "CLOSE", None)

            # Find variant
            if cls.widgets["playNormalRadio"].get_active():
                variant_index = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant_index = conf.get("ngvariant1", FISCHERRANDOMCHESS)
            else:
                variant_index = conf.get("ngvariant2", LOSERSCHESS)
            variant = variants[variant_index]

            # Find time
            if cls.widgets["notimeRadio"].get_active():
                secs = 0
                incr = 0
                moves = 0
            elif cls.widgets["blitzRadio"].get_active():
                secs = cls.ngblitz_min.get_value_as_int() * 60
                incr = cls.ngblitz_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["rapidRadio"].get_active():
                secs = cls.ngrapid_min.get_value_as_int() * 60
                incr = cls.ngrapid_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["normalRadio"].get_active():
                secs = cls.ngnormal_min.get_value_as_int() * 60
                incr = cls.ngnormal_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["classicalRadio"].get_active():
                secs = cls.ngclassical_min.get_value_as_int() * 60
                incr = 0
                moves = cls.ngclassical_moves.get_value_as_int()

            # Find players
            player0combo = cls.widgets["whitePlayerCombobox"]
            player0 = player0combo.get_active()

            tree_iter = player0combo.get_active_iter()
            if tree_iter is not None:
                model = player0combo.get_model()
                name0 = model[tree_iter][1]

            diffi0 = int(cls.widgets["skillSlider1"].get_value())

            player1combo = cls.widgets["blackPlayerCombobox"]
            player1 = player1combo.get_active()

            tree_iter = player1combo.get_active_iter()
            if tree_iter is not None:
                model = player1combo.get_model()
                name1 = model[tree_iter][1]

            diffi1 = int(cls.widgets["skillSlider2"].get_value())

            # Prepare players
            playertups = []
            for i, playerno, name, diffi, color in ((0, player0, name0, diffi0,
                                                     WHITE),
                                                    (1, player1, name1, diffi1,
                                                     BLACK)):
                if playerno > 0:
                    engine = discoverer.getEngineByName(name)
                    playertups.append(
                        (ARTIFICIAL, discoverer.initPlayerEngine,
                         [engine, color, diffi, variant, secs, incr,
                          moves], name))
                else:
                    if not playertups or playertups[0][0] != LOCAL:
                        name = conf.get("firstName", _("You"))
                    else:
                        name = conf.get("secondName", _("Guest"))
                    playertups.append((LOCAL, Human, (color, name), name))

            # Set forcePonderOff initPlayerEngine param True in engine-engine games
            if playertups[0][0] == ARTIFICIAL and playertups[1][
                    0] == ARTIFICIAL:
                playertups[0][2].append(True)
                playertups[1][2].append(True)

            timemodel = TimeModel(secs, incr, moves=moves)
            gamemodel = GameModel(timemodel, variant)

            if not validate(gamemodel):
                return
            else:
                cls.widgets["newgamedialog"].hide()
                cls.widgets["newgamedialog"].disconnect(handlerId)
                callback(gamemodel, playertups[0], playertups[1])
예제 #47
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                binname = os.path.split(new_engine)[1]
                ext = os.path.splitext(new_engine)[1]

                # Verify if the engine already exists under the same name
                if new_engine != "":
                    for eng in discoverer.getEngines():
                        if eng["command"] == new_engine:
                            msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                        buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                            msg_dia.format_secondary_text(_("The engine is already installed under the same name"))
                            msg_dia.run()
                            msg_dia.hide()
                            new_engine = ""
                            break

                # Detect the host application
                if new_engine != "":
                    vm_name = None
                    vm_args = None
                    vmpath = ""

                    # Scripting
                    for vm in VM_LIST:
                        if ext == vm.ext:
                            vm_name = vm.name
                            vm_args = vm.args
                            break

                    # Wine for Windows application under Linux
                    if vm_name is None and new_engine.lower().endswith(".exe") and sys.platform != "win32":
                        vm_name = "wine"

                    # Check that the interpreter is available
                    if vm_name is not None:
                        vmpath = shutil.which(vm_name, mode=os.R_OK | os.X_OK)
                        if vmpath is None:
                            msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                        buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                            msg_dia.format_secondary_text(vm_name + _(" is not installed"))
                            msg_dia.run()
                            msg_dia.hide()
                            new_engine = ""

                # Next checks
                if new_engine:
                    vm_ext_list = [vm.ext for vm in VM_LIST]
                    if ext not in vm_ext_list and not os.access(new_engine, os.X_OK):
                        msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>%s is not marked executable in the filesystem</b></big>" %
                                             new_engine))
                        msg_dia.format_secondary_text(_("Try chmod a+x %s" % new_engine))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return

                    try:
                        engine_command = []
                        if vmpath:
                            engine_command.append(vmpath)
                        if vm_args is not None:
                            engine_command.append(vm_args)
                        engine_command.append(new_engine)

                        # Search the engines based on the most expectable protocol
                        refeng = discoverer.getReferencedEngine(binname)
                        if refeng is not None and refeng["protocol"] == "xboard":
                            checkers = [is_cecp, is_uci]
                        else:
                            checkers = [is_uci, is_cecp]

                        uci = False
                        for checker in checkers:
                            check_ok = checker(engine_command)
                            if check_ok:
                                uci = checker is is_uci
                                break
                            else:
                                continue

                        if not check_ok:
                            # restore the original
                            engine = discoverer.getEngineByName(self.cur_engine)
                            engine_chooser_dialog.set_filename(engine["command"])
                            msg_dia = Gtk.MessageDialog(mainwindow(),
                                                        type=Gtk.MessageType.ERROR,
                                                        buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(
                                _("<big><b>Unable to add %s</b></big>" %
                                  new_engine))
                            msg_dia.format_secondary_text(_("There is something wrong with this executable"))
                            msg_dia.run()
                            msg_dia.hide()
                            engine_chooser_dialog.hide()
                            self.add = False
                            engine_chooser_dialog.hide()
                            return

                        self.widgets["engine_command_entry"].set_text(new_engine)
                        self.widgets["engine_protocol_combo"].set_active(0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")

                        # active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if uci else "xboard"

                        if vm_args is not None:
                            vm_args = vm_args.split(",")
                        # print(binname, new_engine, protocol, vm_name, vm_args)
                        discoverer.addEngine(binname, new_engine, protocol, vm_name, vm_args)
                        self.cur_engine = binname
                        self.add = False
                        discoverer.discover()
                    except Exception:
                        msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                        msg_dia.format_secondary_text(_("There is something wrong with this executable"))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])

            engine_chooser_dialog.hide()
예제 #48
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                if new_engine.lower().endswith(
                        ".exe") and sys.platform != "win32":
                    vm_name = "wine"
                    vmpath = searchPath(vm_name, access=os.R_OK | os.X_OK)
                    if vmpath is None:
                        msg_dia = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, \
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" % \
                                             new_engine))
                        msg_dia.format_secondary_text(_("wine not installed"))
                        msg_dia.run()
                        msg_dia.hide()
                        new_engine = ""
                    else:
                        vmpath += " "
                else:
                    vm_name = None
                    vmpath = ""

                if new_engine:
                    try:
                        # Some engines support CECP and UCI, but variant engines are CECP,
                        # so we better to start with CECP this case
                        variant_engines = ("fmax", "sjaakii", "sjeng")
                        if any((True for eng in variant_engines
                                if eng in new_engine.lower())):
                            checkers = [is_cecp, is_uci]
                        else:
                            checkers = [is_uci, is_cecp]
                        uci = False
                        for checker in checkers:
                            check_ok = checker(vmpath + new_engine)
                            if check_ok:
                                uci = checker is is_uci
                                break
                            else:
                                continue
                            if not check_ok:
                                # restore the original
                                engine = discoverer.getEngineByName(
                                    self.cur_engine)
                                engine_chooser_dialog.set_filename(
                                    engine["command"])
                                msg_dia = Gtk.MessageDialog(
                                    type=Gtk.MessageType.ERROR,
                                    buttons=Gtk.ButtonsType.OK)
                                msg_dia.set_markup(
                                    _("<big><b>Unable to add %s</b></big>" %
                                      new_engine))
                                msg_dia.format_secondary_text(
                                    _("There is something wrong with this executable"
                                      ))
                                msg_dia.run()
                                msg_dia.hide()
                                engine_chooser_dialog.hide()
                                return
                        binname = os.path.split(new_engine)[1]
                        for eng in discoverer.getEngines():
                            if eng["name"] == binname:
                                binname = eng["name"] + "(1)"
                                break
                        self.widgets["engine_command_entry"].set_text(
                            new_engine)
                        self.widgets["engine_protocol_combo"].set_active(
                            0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")

                        active = self.widgets[
                            "engine_protocol_combo"].get_active()
                        protocol = "uci" if uci else "xboard"

                        discoverer.addEngine(binname, new_engine, protocol,
                                             vm_name)
                        self.cur_engine = binname
                        self.add = False
                        discoverer.discover()
                    except:
                        msg_dia = Gtk.MessageDialog(type=Gtk.MessageType.ERROR, \
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" % \
                                             new_engine))
                        msg_dia.format_secondary_text(
                            _("There is something wrong with this executable"))
                        msg_dia.run()
                        msg_dia.hide()
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])
            engine_chooser_dialog.hide()
예제 #49
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check",
                    "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=False)
        uistuff.keep(widgets["analyzer_check"],
                     "analyzer_check",
                     first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), mainwindow(), Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), mainwindow(),
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"],
                            data,
                            name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        if sys.platform == "win32":
            # Let Stockfish to be default analyzer in Windows installer
            default = discoverer.getEngineN(-1).get("md5")
        else:
            engine = discoverer.getEngineByName("stockfish")
            if engine is None:
                engine = discoverer.getEngineN(-1)
            default = engine.get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (
                            gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(
            widgets["analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after(
            "toggled", on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(
                check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio. async (gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(
            widgets["inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after(
            "toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(
                combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value, lambda combobox, value: anal_combo_set_value(
                combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"],
                     "max_analysis_spin",
                     first_value=3)
        uistuff.keep(self.widgets["infinite_analysis"],
                     "infinite_analysis",
                     first_value=False)
예제 #50
0
 def setUp(self):
     self.engine = discoverer.getEngineByName("PyChess.py")
예제 #51
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                vm_name = None
                vm_args = None
                vmpath = ""
                if new_engine.lower().endswith(
                        ".exe") and sys.platform != "win32":
                    vm_name = "wine"
                    vmpath = shutil.which(vm_name, mode=os.R_OK | os.X_OK)
                    if vmpath is None:
                        msg_dia = Gtk.MessageDialog(type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(
                            _("<big><b>Unable to add %s</b></big>" %
                              new_engine))
                        msg_dia.format_secondary_text(_("wine not installed"))
                        msg_dia.run()
                        msg_dia.hide()
                        new_engine = ""

                for vm in VM_LIST:
                    ext = os.path.splitext(new_engine)[1]
                    if ext == vm.ext:
                        vm_name = vm.name
                        vm_args = vm.args
                        vmpath = shutil.which(vm_name, mode=os.R_OK | os.X_OK)
                        if vmpath is None:
                            msg_dia = Gtk.MessageDialog(
                                type=Gtk.MessageType.ERROR,
                                buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(
                                _("<big><b>Unable to add %s</b></big>" %
                                  new_engine))
                            msg_dia.format_secondary_text(
                                vm_name + _(" is not installed"))
                            msg_dia.run()
                            msg_dia.hide()
                            new_engine = ""
                        break

                if new_engine:
                    vm_ext_list = [vm.ext for vm in VM_LIST]
                    if ext not in vm_ext_list and not os.access(
                            new_engine, os.X_OK):
                        msg_dia = Gtk.MessageDialog(type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(
                            _("<big><b>%s is not marked executable in the filesystem</b></big>"
                              % new_engine))
                        msg_dia.format_secondary_text(
                            _("Try chmod a+x %s" % new_engine))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return

                    try:
                        engine_command = []
                        if vmpath:
                            engine_command.append(vmpath)
                        if vm_args is not None:
                            engine_command.append(vm_args)
                        engine_command.append(new_engine)
                        # Some engines support CECP and UCI, but main variant engines are CECP,
                        # so we better to start with CECP this case
                        variant_engines = ("fmax", "sjaakii", "sjeng")
                        if any((True for eng in variant_engines
                                if eng in new_engine.lower())):
                            checkers = [is_cecp, is_uci]
                        else:
                            checkers = [is_uci, is_cecp]

                        uci = False
                        for checker in checkers:
                            check_ok = checker(engine_command)
                            if check_ok:
                                uci = checker is is_uci
                                break
                            else:
                                continue
                            if not check_ok:
                                # restore the original
                                engine = discoverer.getEngineByName(
                                    self.cur_engine)
                                engine_chooser_dialog.set_filename(
                                    engine["command"])
                                msg_dia = Gtk.MessageDialog(
                                    type=Gtk.MessageType.ERROR,
                                    buttons=Gtk.ButtonsType.OK)
                                msg_dia.set_markup(
                                    _("<big><b>Unable to add %s</b></big>" %
                                      new_engine))
                                msg_dia.format_secondary_text(
                                    _("There is something wrong with this executable"
                                      ))
                                msg_dia.run()
                                msg_dia.hide()
                                engine_chooser_dialog.hide()
                                self.add = False
                                engine_chooser_dialog.hide()
                                return

                        binname = os.path.split(new_engine)[1]
                        for eng in discoverer.getEngines():
                            if eng["name"] == binname:
                                binname = eng["name"] + "(1)"
                                break

                        self.widgets["engine_command_entry"].set_text(
                            new_engine)
                        self.widgets["engine_protocol_combo"].set_active(
                            0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")

                        # active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if uci else "xboard"

                        if vm_args is not None:
                            vm_args = vm_args.split(",")
                        # print(binname, new_engine, protocol, vm_name, vm_args)
                        discoverer.addEngine(binname, new_engine, protocol,
                                             vm_name, vm_args)
                        self.cur_engine = binname
                        self.add = False
                        discoverer.discover()
                    except:
                        msg_dia = Gtk.MessageDialog(type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(
                            _("<big><b>Unable to add %s</b></big>" %
                              new_engine))
                        msg_dia.format_secondary_text(
                            _("There is something wrong with this executable"))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])

            engine_chooser_dialog.hide()
예제 #52
0
 def setUp(self):
     self.engine = discoverer.getEngineByName("PyChess.py")
예제 #53
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                if new_engine.lower().endswith(".exe") and sys.platform != "win32":
                    vm_name = "wine" 
                    vmpath = searchPath(vm_name, access=os.R_OK|os.X_OK)
                    if vmpath is None:
                        d = Gtk.MessageDialog(
                                type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                        d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                        d.format_secondary_text(_("wine not installed"))
                        d.run()
                        d.hide()
                        new_engine = ""
                    else:
                        vmpath += " "
                else:
                    vm_name = None
                    vmpath = ""
                
                if new_engine:
                    try:
                        # Some engines support CECP and UCI, but variant engines are CECP,
                        # so we better to start with CECP this case
                        variant_engines = ("fmax", "sjaakii", "sjeng")
                        if any((True for e in variant_engines if e in new_engine.lower())):
                            checkers = [is_cecp, is_uci]
                        else:
                            checkers = [is_uci, is_cecp]
                        uci = False
                        for checker in checkers:
                            ok = checker(vmpath + new_engine)
                            if ok:
                                uci = checker is is_uci
                                break
                            else:
                                continue
                            if not ok:
                                # restore the original
                                engine = discoverer.getEngineByName(self.cur_engine)
                                engine_chooser_dialog.set_filename(engine["command"])
                                d = Gtk.MessageDialog(
                                        type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                                d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                                d.format_secondary_text(_("There is something wrong with this executable"))
                                d.run()
                                d.hide()
                                engine_chooser_dialog.hide()
                                return
                        path, binname = os.path.split(new_engine)
                        for e in discoverer.getEngines():
                            if e["name"] == binname:
                                binname = e["name"] + "(1)"
                                break
                        self.widgets["engine_command_entry"].set_text(new_engine)
                        self.widgets["engine_protocol_combo"].set_active(0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")
                        
                        active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if uci else "xboard"
                        
                        discoverer.addEngine(binname, new_engine, protocol, vm_name)
                        self.cur_engine = binname
                        self.add = False
                        discoverer.discover()
                    except:
                        d = Gtk.MessageDialog(
                                type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                        d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                        d.format_secondary_text(_("There is something wrong with this executable"))
                        d.run()
                        d.hide()
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])
            engine_chooser_dialog.hide()
예제 #54
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                if new_engine.lower().endswith(".exe"):
                    vm_name = "wine" 
                    vmpath = searchPath(vm_name, access=os.R_OK|os.X_OK)
                    if vmpath is None:
                        d = Gtk.MessageDialog(
                                type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                        d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                        d.format_secondary_text(_("wine not installed"))
                        d.run()
                        d.hide()
                        new_engine = ""
                    else:
                        vmpath += " "
                else:
                    vm_name = None
                    vmpath = ""
                
                if new_engine:
                    try:
                        uci = is_uci(vmpath + new_engine)
                        if not uci:
                            if not is_cecp(vmpath + new_engine):
                                # restore the original
                                engine = discoverer.getEngineByName(self.cur_engine)
                                engine_chooser_dialog.set_filename(engine["command"])
                                d = Gtk.MessageDialog(
                                        type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                                d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                                d.format_secondary_text(_("There is something wrong with this executable"))
                                d.run()
                                d.hide()
                                engine_chooser_dialog.hide()
                                return
                        path, binname = os.path.split(new_engine)
                        for e in discoverer.getEngines():
                            if e["name"] == binname:
                                binname = e["name"] + "(1)"
                                break
                        self.widgets["engine_command_entry"].set_text(new_engine)
                        self.widgets["engine_protocol_combo"].set_active(0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")
                        
                        active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if active==0 else "xboard"
                        
                        discoverer.addEngine(binname, new_engine, protocol, vm_name)
                        self.cur_engine = binname
                        glock_connect_after(discoverer, "engine_discovered", update_store)
                        self.add = False
                        discoverer.discover()
                    except:
                        d = Gtk.MessageDialog(
                                type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.OK)
                        d.set_markup(_("<big><b>Unable to add %s</b></big>" % new_engine))
                        d.format_secondary_text(_("There is something wrong with this executable"))
                        d.run()
                        d.hide()
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])
            engine_chooser_dialog.hide()
예제 #55
0
    def __init__(self, widgets):
        self.widgets = widgets

        # Options on by default
        for key in ("opening_check", "endgame_check", "online_egtb_check", "inv_analyzer_check"):
            uistuff.keep(widgets[key], key, first_value=False)
        uistuff.keep(widgets["analyzer_check"], "analyzer_check", first_value=True)

        # Opening book
        default_path = os.path.join(addDataPrefix("pychess_book.bin"))
        path = conf.get("opening_file_entry", default_path)
        conf.set("opening_file_entry", path)

        book_chooser_dialog = Gtk.FileChooserDialog(
            _("Select book file"), mainwindow(), Gtk.FileChooserAction.OPEN,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        book_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            book_chooser_dialog)

        filter = Gtk.FileFilter()
        filter.set_name(_("Opening books"))
        filter.add_pattern("*.bin")
        book_chooser_dialog.add_filter(filter)
        book_chooser_button.set_filename(path)

        self.widgets["bookChooserDock"].add(book_chooser_button)
        book_chooser_button.show()

        def select_new_book(button):
            new_book = book_chooser_dialog.get_filename()
            if new_book:
                conf.set("opening_file_entry", new_book)
            else:
                # restore the original
                book_chooser_dialog.set_filename(path)

        book_chooser_button.connect("file-set", select_new_book)

        def on_opening_check_toggled(check):
            self.widgets["opening_hbox"].set_sensitive(check.get_active())

        self.widgets["opening_check"].connect_after("toggled",
                                                    on_opening_check_toggled)

        # Endgame
        default_path = os.path.join(getDataPrefix())
        egtb_path = conf.get("egtb_path", default_path)
        conf.set("egtb_path", egtb_path)

        egtb_chooser_dialog = Gtk.FileChooserDialog(
            _("Select Gaviota TB path"), mainwindow(),
            Gtk.FileChooserAction.SELECT_FOLDER,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN,
             Gtk.ResponseType.OK))
        egtb_chooser_button = Gtk.FileChooserButton.new_with_dialog(
            egtb_chooser_dialog)
        egtb_chooser_button.set_current_folder(egtb_path)

        self.widgets["egtbChooserDock"].add(egtb_chooser_button)
        egtb_chooser_button.show()

        def select_egtb(button):
            new_directory = egtb_chooser_dialog.get_filename()
            if new_directory != egtb_path:
                conf.set("egtb_path", new_directory)

        egtb_chooser_button.connect("current-folder-changed", select_egtb)

        def on_endgame_check_toggled(check):
            self.widgets["endgame_hbox"].set_sensitive(check.get_active())

        self.widgets["endgame_check"].connect_after("toggled",
                                                    on_endgame_check_toggled)

        # Analyzing engines
        from pychess.widgets import newGameDialog
        data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
        uistuff.createCombo(widgets["ana_combobox"], data, name="ana_combobox")
        uistuff.createCombo(widgets["inv_ana_combobox"], data, name="inv_ana_combobox")

        def update_analyzers_store(discoverer):
            data = [(item[0], item[1]) for item in newGameDialog.analyzerItems]
            uistuff.updateCombo(widgets["ana_combobox"], data)
            uistuff.updateCombo(widgets["inv_ana_combobox"], data)

        discoverer.connect_after("all_engines_discovered",
                                 update_analyzers_store)
        update_analyzers_store(discoverer)

        # Save, load and make analyze combos active

        engine = discoverer.getEngineByName(discoverer.getEngineLearn())
        if engine is None:
            engine = discoverer.getEngineN(-1)
        default = engine.get("md5")
        conf.set("ana_combobox", conf.get("ana_combobox", default))
        conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", default))

        def on_analyzer_check_toggled(check):
            self.widgets["analyzers_vbox"].set_sensitive(check.get_active())
            from pychess.widgets.gamewidget import widgets
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(HINT))
                        if not widgets["hint_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(HINT)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(HINT)

        self.widgets["analyzers_vbox"].set_sensitive(widgets["analyzer_check"].get_active())
        self.widgets["analyzer_check"].connect_after("toggled", on_analyzer_check_toggled)

        def on_invanalyzer_check_toggled(check):
            self.widgets["inv_analyzers_vbox"].set_sensitive(check.get_active())
            perspective = perspective_manager.get_perspective("games")
            if len(perspective.gamewidgets) != 0:
                if check.get_active():
                    for gmwidg in perspective.gamewidgets:
                        asyncio.async(gmwidg.gamemodel.restart_analyzer(SPY))
                        if not widgets["spy_mode"].get_active():
                            gmwidg.gamemodel.pause_analyzer(SPY)
                else:
                    for gmwidg in perspective.gamewidgets:
                        gmwidg.gamemodel.remove_analyzer(SPY)

        self.widgets["inv_analyzers_vbox"].set_sensitive(widgets["inv_analyzer_check"].get_active())
        self.widgets["inv_analyzer_check"].connect_after("toggled", on_invanalyzer_check_toggled)

        # Give widgets to keeper

        uistuff.keep(
            self.widgets["ana_combobox"], "ana_combobox", anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "hint_mode", "analyzer_check", HINT))
        uistuff.keep(
            self.widgets["inv_ana_combobox"], "inv_ana_combobox",
            anal_combo_get_value,
            lambda combobox, value: anal_combo_set_value(combobox, value, "spy_mode", "inv_analyzer_check", SPY))

        uistuff.keep(self.widgets["max_analysis_spin"], "max_analysis_spin", first_value=3)
        uistuff.keep(self.widgets["infinite_analysis"], "infinite_analysis", first_value=False)
예제 #56
0
        def add(button):
            self.add = True
            response = engine_chooser_dialog.run()

            if response == Gtk.ResponseType.OK:
                new_engine = engine_chooser_dialog.get_filename()
                vm_name = None
                vm_args = None
                vmpath = ""
                if new_engine.lower().endswith(".exe") and sys.platform != "win32":
                    vm_name = "wine"
                    vmpath = shutil.which(vm_name, mode=os.R_OK | os.X_OK)
                    if vmpath is None:
                        msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" %
                                             new_engine))
                        msg_dia.format_secondary_text(_("wine not installed"))
                        msg_dia.run()
                        msg_dia.hide()
                        new_engine = ""

                for vm in VM_LIST:
                    ext = os.path.splitext(new_engine)[1]
                    if ext == vm.ext:
                        vm_name = vm.name
                        vm_args = vm.args
                        vmpath = shutil.which(vm_name, mode=os.R_OK | os.X_OK)
                        if vmpath is None:
                            msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                        buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" %
                                                 new_engine))
                            msg_dia.format_secondary_text(vm_name + _(" is not installed"))
                            msg_dia.run()
                            msg_dia.hide()
                            new_engine = ""
                        break

                if new_engine:
                    vm_ext_list = [vm.ext for vm in VM_LIST]
                    if ext not in vm_ext_list and not os.access(new_engine, os.X_OK):
                        msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>%s is not marked executable in the filesystem</b></big>" %
                                             new_engine))
                        msg_dia.format_secondary_text(_("Try chmod a+x %s" % new_engine))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return

                    try:
                        engine_command = []
                        if vmpath:
                            engine_command.append(vmpath)
                        if vm_args is not None:
                            engine_command.append(vm_args)
                        engine_command.append(new_engine)
                        # Some engines support CECP and UCI, but main variant engines are CECP,
                        # so we better to start with CECP this case
                        variant_engines = ("fmax", "sjaakii", "sjeng")
                        if any((True
                                for eng in variant_engines
                                if eng in new_engine.lower())):
                            checkers = [is_cecp, is_uci]
                        else:
                            checkers = [is_uci, is_cecp]

                        uci = False
                        for checker in checkers:
                            check_ok = checker(engine_command)
                            if check_ok:
                                uci = checker is is_uci
                                break
                            else:
                                continue

                        if not check_ok:
                            # restore the original
                            engine = discoverer.getEngineByName(
                                self.cur_engine)
                            engine_chooser_dialog.set_filename(engine[
                                "command"])
                            msg_dia = Gtk.MessageDialog(mainwindow(),
                                                        type=Gtk.MessageType.ERROR,
                                                        buttons=Gtk.ButtonsType.OK)
                            msg_dia.set_markup(
                                _("<big><b>Unable to add %s</b></big>" %
                                  new_engine))
                            msg_dia.format_secondary_text(_(
                                "There is something wrong with this executable"))
                            msg_dia.run()
                            msg_dia.hide()
                            engine_chooser_dialog.hide()
                            self.add = False
                            engine_chooser_dialog.hide()
                            return

                        binname = os.path.split(new_engine)[1]
                        for eng in discoverer.getEngines():
                            if eng["name"] == binname:
                                binname = eng["name"] + "(1)"
                                break

                        self.widgets["engine_command_entry"].set_text(new_engine)
                        self.widgets["engine_protocol_combo"].set_active(0 if uci else 1)
                        self.widgets["engine_args_entry"].set_text("")

                        # active = self.widgets["engine_protocol_combo"].get_active()
                        protocol = "uci" if uci else "xboard"

                        if vm_args is not None:
                            vm_args = vm_args.split(",")
                        # print(binname, new_engine, protocol, vm_name, vm_args)
                        discoverer.addEngine(binname, new_engine, protocol, vm_name, vm_args, "unknown")
                        self.cur_engine = binname
                        self.add = False
                        discoverer.discover()
                    except Exception:
                        msg_dia = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.ERROR,
                                                    buttons=Gtk.ButtonsType.OK)
                        msg_dia.set_markup(_("<big><b>Unable to add %s</b></big>" %
                                             new_engine))
                        msg_dia.format_secondary_text(_(
                            "There is something wrong with this executable"))
                        msg_dia.run()
                        msg_dia.hide()
                        self.add = False
                        engine_chooser_dialog.hide()
                        return
                else:
                    # restore the original
                    engine = discoverer.getEngineByName(self.cur_engine)
                    engine_chooser_dialog.set_filename(engine["command"])

            engine_chooser_dialog.hide()
예제 #57
0
        def onResponse(dialog, response):
            if response == COPY:
                clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
                clipboard.set_text(cls.get_fen(), -1)
                # print("put clipboard:", clipboard.wait_for_text())
                return
            elif response == CLEAR:
                cls.board_control.emit("action", "SETUP", None, True)
                cls.ini_widgets(True)
                # print("clear")
                return
            elif response == PASTE:
                clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
                text = clipboard.wait_for_text()
                # print("got clipboard:", text)
                if text is None or len(text.split()) < 2:
                    return
                try:
                    lboard = cls.setupmodel.variant(setup=text).board
                    cls.ini_widgets(lboard.asFen())
                    cls.board_control.emit("action", "SETUP", None, text)
                except SyntaxError as e:
                    d = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.WARNING,
                                          buttons=Gtk.ButtonsType.OK,
                                          message_format=e.args[0])
                    if len(e.args) > 1:
                        d.format_secondary_text(e.args[1])
                    d.connect("response", lambda d, a: d.hide())
                    d.show()
                return
            elif response == INITIAL:
                lboard = cls.setupmodel.variant(setup=FEN_START).board
                cls.ini_widgets(lboard.asFen())
                cls.board_control.emit("action", "SETUP", None, FEN_START)
                return
            elif response != Gtk.ResponseType.OK:
                cls.widgets["newgamedialog"].hide()
                cls.widgets["newgamedialog"].disconnect(handlerId)
                return

            if hasattr(cls, "board_control"):
                cls.board_control.emit("action", "CLOSE", None, None)

            # Find variant
            if cls.widgets["playNormalRadio"].get_active():
                variant_index = NORMALCHESS
            elif cls.widgets["playVariant1Radio"].get_active():
                variant_index = conf.get("ngvariant1")
            else:
                variant_index = conf.get("ngvariant2")
            variant = variants[variant_index]

            # Find time
            if cls.widgets["notimeRadio"].get_active():
                secs = 0
                incr = 0
                moves = 0
            elif cls.widgets["blitzRadio"].get_active():
                secs = cls.ngblitz_min.get_value_as_int() * 60
                incr = cls.ngblitz_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["rapidRadio"].get_active():
                secs = cls.ngrapid_min.get_value_as_int() * 60
                incr = cls.ngrapid_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["normalRadio"].get_active():
                secs = cls.ngnormal_min.get_value_as_int() * 60
                incr = cls.ngnormal_gain.get_value_as_int()
                moves = 0
            elif cls.widgets["classicalRadio"].get_active():
                secs = cls.ngclassical_min.get_value_as_int() * 60
                incr = 0
                moves = cls.ngclassical_moves.get_value_as_int()

            # Find players
            player0combo = cls.widgets["whitePlayerCombobox"]
            player0 = player0combo.get_active()

            tree_iter = player0combo.get_active_iter()
            if tree_iter is not None:
                model = player0combo.get_model()
                name0 = model[tree_iter][1]

            diffi0 = int(cls.widgets["skillSlider1"].get_value())

            player1combo = cls.widgets["blackPlayerCombobox"]
            player1 = player1combo.get_active()

            tree_iter = player1combo.get_active_iter()
            if tree_iter is not None:
                model = player1combo.get_model()
                name1 = model[tree_iter][1]

            diffi1 = int(cls.widgets["skillSlider2"].get_value())

            # Prepare players
            playertups = []
            for i, playerno, name, diffi, color in ((0, player0, name0, diffi0, WHITE),
                                                    (1, player1, name1, diffi1, BLACK)):
                if playerno > 0:
                    engine = discoverer.getEngineByName(name)
                    playertups.append((ARTIFICIAL, discoverer.initPlayerEngine,
                                       [engine, color, diffi, variant, secs,
                                        incr, moves], name))
                else:
                    if not playertups or playertups[0][0] != LOCAL:
                        name = conf.get("firstName")
                    else:
                        name = conf.get("secondName")
                    playertups.append((LOCAL, Human, (color, name), name))

            # Set forcePonderOff initPlayerEngine param True in engine-engine games
            if playertups[0][0] == ARTIFICIAL and playertups[1][
                    0] == ARTIFICIAL:
                playertups[0][2].append(True)
                playertups[1][2].append(True)

            timemodel = TimeModel(secs, incr, moves=moves)
            gamemodel = GameModel(timemodel, variant)

            if not validate(gamemodel):
                return
            else:
                cls.widgets["newgamedialog"].hide()
                cls.widgets["newgamedialog"].disconnect(handlerId)
                callback(gamemodel, playertups[0], playertups[1])
예제 #58
0
def start_puzzle_from(filename, index=None):
    if filename.lower().endswith(".pgn"):
        chessfile = PGNFile(protoopen(addDataPrefix("learn/puzzles/%s" % filename)))
        chessfile.limit = 1000
        chessfile.init_tag_database()
    elif filename.lower().endswith(".olv"):
        chessfile = OLVFile(protoopen(addDataPrefix("learn/puzzles/%s" % filename), encoding="utf-8"))

    records, plys = chessfile.get_records()

    progress = puzzles_solving_progress.get(filename, [0] * chessfile.count)

    if index is None:
        index = progress.index(0)

    rec = records[index]

    timemodel = TimeModel(0, 0)
    gamemodel = LearnModel(timemodel)

    chessfile.loadToModel(rec, 0, gamemodel)
    gamemodel.set_learn_data(PUZZLE, filename, index, len(records))

    engine = discoverer.getEngineByName(discoverer.getEngineLearn())
    ponder_off = True

    color = gamemodel.boards[0].color

    w_name = "" if rec["White"] is None else rec["White"]
    b_name = "" if rec["Black"] is None else rec["Black"]

    player_name = conf.get("firstName", _("You"))
    engine_name = discoverer.getName(engine)

    if rec["Event"].startswith("Lichess Practice"):
        w_name = player_name if color == WHITE else engine_name
        b_name = engine_name if color == WHITE else player_name

    opp_name = engine_name if rec["Event"].startswith("Lichess Practice") else b_name

    if color == WHITE:
        p0 = (LOCAL, Human, (WHITE, w_name), w_name)
        p1 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, BLACK, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), b_name)
    else:
        p0 = (ARTIFICIAL, discoverer.initPlayerEngine,
              (engine, WHITE, 20, variants[NORMALCHESS], 20, 0, 0, ponder_off), w_name)
        p1 = (LOCAL, Human, (BLACK, b_name), b_name)

    def start_analyzer(gamemodel, name, color):
        asyncio.async(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn()))
        gamemodel.players[1 - color].name = name
        gamemodel.emit("players_changed")
    gamemodel.connect("game_started", start_analyzer, opp_name, color)

    def goal_checked(gamemodle):
        if gamemodel.reason == PRACTICE_GOAL_REACHED:
            progress = puzzles_solving_progress[gamemodel.source]
            progress[gamemodel.current_index] = 1
            puzzles_solving_progress[gamemodel.source] = progress
    gamemodel.connect("goal_checked", goal_checked)

    gamemodel.variant.need_initial_board = True
    gamemodel.status = WAITING_TO_START

    perspective = perspective_manager.get_perspective("games")
    asyncio.async(perspective.generalStart(gamemodel, p0, p1))