def printResults(): scores = [] for i in xrange(len(engines)): points = sum(2 for j in xrange(len(engines)) if results[i][j] == WHITEWON) \ + sum(1 for j in xrange(len(engines)) if results[i][j] == DRAW) \ + sum(2 for j in xrange(len(engines)) if results[j][i] == BLACKWON) \ + sum(1 for j in xrange(len(engines)) if results[j][i] == DRAW) scores.append((points, i)) scores.sort(reverse=True) for points, i in scores: print discoverer.getName(engines[i]), ":", points/2, "½"*(points%2)
def printResults(): scores = [] for i in xrange(len(engines)): points = sum(2 for j in xrange(len(engines)) if results[i][j] == WHITEWON) \ + sum(1 for j in xrange(len(engines)) if results[i][j] == DRAW) \ + sum(2 for j in xrange(len(engines)) if results[j][i] == BLACKWON) \ + sum(1 for j in xrange(len(engines)) if results[j][i] == DRAW) scores.append((points, i)) scores.sort(reverse=True) for points, i in scores: print discoverer.getName( engines[i]), ":", points / 2, "½" * (points % 2)
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))
def startClicked(self, button): color = self.widgets["colorDock"].get_child().active if color == 2: color = random.choice([WHITE, BLACK]) opponent = self.widgets["opponentDock"].get_child().active difficulty = int(self.widgets["skillSlider"].get_value()) gamemodel = GameModel(TimeModel(5 * 60, 0)) name = conf.get("firstName", _("You")) player0tup = (LOCAL, Human, (color, name), name) if opponent == 0: name = conf.get("secondName", _("Guest")) player1tup = (LOCAL, Human, (1 - color, name), name) else: engine = discoverer.getEngineN(opponent - 1) name = discoverer.getName(engine) player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (engine, 1 - color, difficulty, variants[NORMALCHESS], 5 * 60, 0), name) if color == WHITE: ionest.generalStart(gamemodel, player0tup, player1tup) else: ionest.generalStart(gamemodel, player1tup, player0tup)
def start(discoverer): atexit.register(SubProcess.finishAllSubprocesses) pgnfile, gameno = queryGameno(sys.argv[1]) analyzer = queryAnalyzer(discoverer.getAnalyzers()) secs = queryTime() name1, name2 = pgnfile.get_player_names(gameno) print("%s will now analyze the game between %s and %s with %d seconds per move." % \ (discoverer.getName(analyzer), name1, name2, secs)) print() global game, values values = {} game = GameModel() game.setPlayers([DummyPlayer(), DummyPlayer()]) analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant) analyzer.connect('analyze', onAnalyze) game.spectators[HINT] = analyzer game.loadAndStart(sys.argv[1], pgn, gameno, -1) def cb(): if game.ply == game.lowply: on_finish() return False check_blund() return True GLib.timeout_add_seconds(secs, cb)
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)))
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)))
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)))
def start(discoverer): atexit.register(SubProcess.finishAllSubprocesses) pgnfile, gameno = queryGameno(sys.argv[1]) analyzer = queryAnalyzer(discoverer.getAnalyzers()) secs = queryTime() name1, name2 = pgnfile.get_player_names(gameno) print("%s will now analyze the game between %s and %s with %d seconds per move." % \ (discoverer.getName(analyzer), name1, name2, secs)) print() global game, values values = {} game = GameModel() game.setPlayers([DummyPlayer(), DummyPlayer()]) analyzer = discoverer.initAnalyzerEngine(analyzer, ANALYZING, game.variant) analyzer.connect('analyze', onAnalyze) game.spectators[HINT] = analyzer game.loadAndStart(sys.argv[1], pgn, gameno, -1) def cb(): if game.ply == game.lowply: on_finish() return False check_blund() return True glib.timeout_add_seconds(secs, cb)
def startClicked(self, button): color = self.widgets["colorDock"].get_child().active if color == 2: color = random.choice([WHITE, BLACK]) opponent = self.widgets["opponentDock"].get_child().active difficulty = int(self.widgets["skillSlider"].get_value()) gamemodel = GameModel(TimeModel(5 * 60, 0)) name = conf.get("firstName", _("You")) player0tup = (LOCAL, Human, (color, name), name) if opponent == 0: name = conf.get("secondName", _("Guest")) player1tup = (LOCAL, Human, (1 - color, name), name) else: engine = discoverer.getEngineN(opponent - 1) name = discoverer.getName(engine) player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (engine, 1 - color, difficulty, variants[NORMALCHESS], 5 * 60, 0), name) if color == WHITE: game_handler.generalStart(gamemodel, player0tup, player1tup) else: game_handler.generalStart(gamemodel, player1tup, player0tup)
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))
def queryAnalyzer(analyzers): print("PyChess found the following analyzers on your system:") for i, engine in enumerate(analyzers): print("[%d] %s" % (i, discoverer.getName(engine))) print() n = int(raw_input("What engine should be your analyzer? [n] ")) print() return analyzers[n]
def onResponse(dialog, res): cls.widgets["newgamedialog"].hide() cls.widgets["newgamedialog"].disconnect(handlerId) if res != gtk.RESPONSE_OK: return # 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 elif cls.widgets["blitzRadio"].get_active(): secs = cls.widgets["ngblitz min"].get_value_as_int()*60 incr = cls.widgets["ngblitz gain"].get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.widgets["ngrapid min"].get_value_as_int()*60 incr = cls.widgets["ngrapid gain"].get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.widgets["ngnormal min"].get_value_as_int()*60 incr = cls.widgets["ngnormal gain"].get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN (playerno-1) name = discoverer.getName(engine) playertups.append((ARTIFICIAL, discoverer.initPlayerEngine, (engine, color, diffi, variant, secs, incr), name)) else: playertups.append((LOCAL, Human, (color, ""), _("Human"))) if secs > 0: timemodel = TimeModel (secs, incr) else: timemodel = None gamemodel = GameModel (timemodel, variant) callback(gamemodel, playertups[0], playertups[1])
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))
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))
def printScoreboard(): names = [discoverer.getName(e)[:3] for e in engines] print("W\B", " ".join(names)) for i, nameA in enumerate(names): print(nameA, end=' ') for j, nameB in enumerate(names): if i == j: print(" # ", end=' ') elif results[i][j] == DRAW: print("½-½", end=' ') elif results[i][j] == WHITEWON: print("1-0", end=' ') elif results[i][j] == BLACKWON: print("0-1", end=' ') else: print(" . ", end=' ') print()
def createPlayerUIGlobals (discoverer): global playerItems global smallPlayerItems for variantClass in variants.values(): playerItems += [ [(ipeople, _("Human Being"))] ] smallPlayerItems += [ [(speople, _("Human Being"))] ] for engine in discoverer.getEngines().values(): name = discoverer.getName(engine) c = discoverer.getCountry(engine) path = addDataPrefix("flags/%s.png" % c) if c and os.path.isfile(path): flag_icon = gtk.gdk.pixbuf_new_from_file(path) else: flag_icon = inotebook for variant in discoverer.getEngineVariants(engine): playerItems[variant] += [(flag_icon, name)] smallPlayerItems[variant] += [(snotebook, name)]
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)))
def start(discoverer): global engines, results, minutes engines = discoverer.getEngines() n = len(engines) for i in range(n): results.append([None]*n) print() print("Your installed engines are:") for i, engine in enumerate(engines): name = discoverer.getName(engine) print("[%s] %s" % (name[:3], name)) print("The total amount of fights will be %d" % (n*(n-1))) print() minutes = int(raw_input("Please enter the clock minutes for each game [n]: ")) print("The games will last up to %d minutes." % (2*n*(n-1)*minutes)) print("You will be informed of the progress as the games finish.") print() runGame()
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 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 (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 != 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 elif cls.widgets["blitzRadio"].get_active(): secs = cls.ngblitz_min.get_value_as_int()*60 incr = cls.ngblitz_gain.get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.ngrapid_min.get_value_as_int()*60 incr = cls.ngrapid_gain.get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.ngnormal_min.get_value_as_int()*60 incr = cls.ngnormal_gain.get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN (playerno-1) name = discoverer.getName(engine) playertups.append((ARTIFICIAL, discoverer.initPlayerEngine, [engine, color, diffi, variant, secs, incr], 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) 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])
def onResponse(dialog, res): if res != Gtk.ResponseType.OK: cls.widgets["newgamedialog"].hide() cls.widgets["newgamedialog"].disconnect(handlerId) return # 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 elif cls.widgets["blitzRadio"].get_active(): secs = cls.ngblitz_min.get_value_as_int() * 60 incr = cls.ngblitz_gain.get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.ngrapid_min.get_value_as_int() * 60 incr = cls.ngrapid_gain.get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.ngnormal_min.get_value_as_int() * 60 incr = cls.ngnormal_gain.get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN(playerno - 1) name = discoverer.getName(engine) playertups.append( (ARTIFICIAL, discoverer.initPlayerEngine, [engine, color, diffi, variant, secs, incr], 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) if secs > 0: timemodel = TimeModel(secs, incr) else: timemodel = TimeModel() 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])
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 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(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 != 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 elif cls.widgets["blitzRadio"].get_active(): secs = cls.ngblitz_min.get_value_as_int() * 60 incr = cls.ngblitz_gain.get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.ngrapid_min.get_value_as_int() * 60 incr = cls.ngrapid_gain.get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.ngnormal_min.get_value_as_int() * 60 incr = cls.ngnormal_gain.get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN(playerno - 1) name = discoverer.getName(engine) playertups.append( (ARTIFICIAL, discoverer.initPlayerEngine, [engine, color, diffi, variant, secs, incr], 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) 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])
def __init__ (self, widgets): # Put engines in trees and combos engines = discoverer.getEngines() allstore = gtk.ListStore(gtk.gdk.Pixbuf, str) for engine in engines.values(): c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) allstore.append((flag_icon, discoverer.getName(engine))) tv = widgets["engines_treeview"] tv.set_model(allstore) tv.append_column(gtk.TreeViewColumn( _("Flag"), gtk.CellRendererPixbuf(), pixbuf=0)) tv.append_column(gtk.TreeViewColumn( _("Name"), gtk.CellRendererText(), text=1)) analyzers = list(discoverer.getAnalyzers()) ana_data = [] invana_data = [] for engine in analyzers: name = discoverer.getName(engine) c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) ana_data.append((flag_icon, name)) invana_data.append((flag_icon, name)) uistuff.createCombo(widgets["ana_combobox"], ana_data) uistuff.createCombo(widgets["inv_ana_combobox"], invana_data) # Save, load and make analyze combos active conf.set("ana_combobox", conf.get("ana_combobox", 0)) conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", 0)) def on_analyzer_check_toggled (check): widgets["analyzers_vbox"].set_sensitive(check.get_active()) widgets["hint_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["hint_mode"].set_sensitive(check.get_active()) widgets["analyzer_check"].connect("toggled", on_analyzer_check_toggled) uistuff.keep(widgets["analyzer_check"], "analyzer_check") def on_invanalyzer_check_toggled (check): widgets["inv_analyzers_vbox"].set_sensitive(check.get_active()) widgets["spy_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["spy_mode"].set_sensitive(check.get_active()) widgets["inv_analyzer_check"].connect("toggled", on_invanalyzer_check_toggled) uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check") # Put options in trees in add/edit dialog #======================================================================= # tv = widgets["optionview"] # tv.append_column(gtk.TreeViewColumn( # "Option", gtk.CellRendererText(), text=0)) # tv.append_column(gtk.TreeViewColumn( # "Value", gtk.CellRendererText(), text=1)) # # def edit (button): # # iter = widgets["engines_treeview"].get_selection().get_selected()[1] # if iter: row = allstore.get_path(iter)[0] # else: return # # engine = discoverer.getEngineN(row) # optionstags = engine.getElementsByTagName("options") # if not optionstags: # widgets["engine_options_expander"].hide() # else: # widgets["engine_options_expander"].show() # widgets["engine_options_expander"].set_expanded(False) # # optionsstore = gtk.ListStore(str, str) # tv = widgets["optionview"] # tv.set_model(optionsstore) # # for option in optionstags[0].childNodes: # if option.nodeType != option.ELEMENT_NODE: continue # optionsstore.append( [option.getAttribute("name"), # option.getAttribute("default")] ) # # widgets["engine_path_chooser"].set_title(_("Locate Engine")) # widgets["engine_path_chooser"].set_uri("file:///usr/bin/gnuchess") # # dialog = widgets["addconfig_engine"] # answer = dialog.run() # dialog.hide() # widgets["edit_engine_button"].connect("clicked", edit) #======================================================================= #widgets["remove_engine_button"].connect("clicked", remove) #widgets["add_engine_button"].connect("clicked", add) # Give widgets to kepper for combo in ("ana_combobox", "inv_ana_combobox"): def get_value (combobox): engine = list(discoverer.getAnalyzers())[combobox.get_active()] if engine.find('md5') != None: return engine.find('md5').text.strip() def set_value (combobox, value): engine = discoverer.getEngineByMd5(value) if not engine: combobox.set_active(0) else: try: index = list(discoverer.getAnalyzers()).index(engine) except ValueError: index = 0 combobox.set_active(index) uistuff.keep (widgets[combo], combo, get_value, set_value) # Init info box uistuff.makeYellow(widgets["analyzer_pref_infobox"]) widgets["analyzer_pref_infobox"].hide() def updatePrefInfobox (widget, *args): widgets["analyzer_pref_infobox"].show() widgets["ana_combobox"].connect("changed", updatePrefInfobox) widgets["analyzer_check"].connect("toggled", updatePrefInfobox) widgets["inv_ana_combobox"].connect("changed", updatePrefInfobox) widgets["inv_analyzer_check"].connect("toggled", updatePrefInfobox) widgets["preferences"].connect("hide", lambda *a: widgets["analyzer_pref_infobox"].hide())
def start_puzzle_from(filename, index=None): if filename.lower().endswith(".pgn"): if filename.startswith("lichess_study"): chessfile = PGNFile( protoopen(addDataPrefix("learn/puzzles/%s" % filename), encoding="utf-8")) else: 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) gamemodel.set_learn_data(PUZZLE, filename, index, len(records)) chessfile.loadToModel(rec, 0, gamemodel) 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: 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))
def __init__(self, widgets): # Put engines in trees and combos engines = discoverer.getEngines() allstore = gtk.ListStore(gtk.gdk.Pixbuf, str) for engine in engines.values(): c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) allstore.append((flag_icon, discoverer.getName(engine))) tv = widgets["engines_treeview"] tv.set_model(allstore) tv.append_column( gtk.TreeViewColumn(_("Flag"), gtk.CellRendererPixbuf(), pixbuf=0)) tv.append_column( gtk.TreeViewColumn(_("Name"), gtk.CellRendererText(), text=1)) analyzers = list(discoverer.getAnalyzers()) ana_data = [] invana_data = [] for engine in analyzers: name = discoverer.getName(engine) c = discoverer.getCountry(engine) if c: flag = addDataPrefix("flags/%s.png" % c) if not c or not os.path.isfile(flag): flag = addDataPrefix("flags/unknown.png") flag_icon = gtk.gdk.pixbuf_new_from_file(flag) ana_data.append((flag_icon, name)) invana_data.append((flag_icon, name)) uistuff.createCombo(widgets["ana_combobox"], ana_data) uistuff.createCombo(widgets["inv_ana_combobox"], invana_data) # Save, load and make analyze combos active conf.set("ana_combobox", conf.get("ana_combobox", 0)) conf.set("inv_ana_combobox", conf.get("inv_ana_combobox", 0)) def on_analyzer_check_toggled(check): widgets["analyzers_vbox"].set_sensitive(check.get_active()) widgets["hint_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["hint_mode"].set_sensitive(check.get_active()) widgets["analyzer_check"].connect("toggled", on_analyzer_check_toggled) uistuff.keep(widgets["analyzer_check"], "analyzer_check") def on_invanalyzer_check_toggled(check): widgets["inv_analyzers_vbox"].set_sensitive(check.get_active()) widgets["spy_mode"].set_active(check.get_active()) from pychess.Main import gameDic if gameDic: widgets["spy_mode"].set_sensitive(check.get_active()) widgets["inv_analyzer_check"].connect("toggled", on_invanalyzer_check_toggled) uistuff.keep(widgets["inv_analyzer_check"], "inv_analyzer_check") # Put options in trees in add/edit dialog #======================================================================= # tv = widgets["optionview"] # tv.append_column(gtk.TreeViewColumn( # "Option", gtk.CellRendererText(), text=0)) # tv.append_column(gtk.TreeViewColumn( # "Value", gtk.CellRendererText(), text=1)) # # def edit (button): # # iter = widgets["engines_treeview"].get_selection().get_selected()[1] # if iter: row = allstore.get_path(iter)[0] # else: return # # engine = discoverer.getEngineN(row) # optionstags = engine.getElementsByTagName("options") # if not optionstags: # widgets["engine_options_expander"].hide() # else: # widgets["engine_options_expander"].show() # widgets["engine_options_expander"].set_expanded(False) # # optionsstore = gtk.ListStore(str, str) # tv = widgets["optionview"] # tv.set_model(optionsstore) # # for option in optionstags[0].childNodes: # if option.nodeType != option.ELEMENT_NODE: continue # optionsstore.append( [option.getAttribute("name"), # option.getAttribute("default")] ) # # widgets["engine_path_chooser"].set_title(_("Locate Engine")) # widgets["engine_path_chooser"].set_uri("file:///usr/bin/gnuchess") # # dialog = widgets["addconfig_engine"] # answer = dialog.run() # dialog.hide() # widgets["edit_engine_button"].connect("clicked", edit) #======================================================================= #widgets["remove_engine_button"].connect("clicked", remove) #widgets["add_engine_button"].connect("clicked", add) # Give widgets to kepper for combo in ("ana_combobox", "inv_ana_combobox"): def get_value(combobox): engine = list(discoverer.getAnalyzers())[combobox.get_active()] if engine.find('md5') != None: return engine.find('md5').text.strip() def set_value(combobox, value): engine = discoverer.getEngineByMd5(value) if not engine: combobox.set_active(0) else: try: index = list(discoverer.getAnalyzers()).index(engine) except ValueError: index = 0 combobox.set_active(index) uistuff.keep(widgets[combo], combo, get_value, set_value) # Init info box uistuff.makeYellow(widgets["analyzer_pref_infobox"]) widgets["analyzer_pref_infobox"].hide() def updatePrefInfobox(widget, *args): widgets["analyzer_pref_infobox"].show() widgets["ana_combobox"].connect("changed", updatePrefInfobox) widgets["analyzer_check"].connect("toggled", updatePrefInfobox) widgets["inv_ana_combobox"].connect("changed", updatePrefInfobox) widgets["inv_analyzer_check"].connect("toggled", updatePrefInfobox) widgets["preferences"].connect( "hide", lambda *a: widgets["analyzer_pref_infobox"].hide())
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))
def onResponse(dialog, res): if res != Gtk.ResponseType.OK: cls.widgets["newgamedialog"].hide() cls.widgets["newgamedialog"].disconnect(handlerId) return # 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 elif cls.widgets["blitzRadio"].get_active(): secs = cls.ngblitz_min.get_value_as_int()*60 incr = cls.ngblitz_gain.get_value_as_int() elif cls.widgets["rapidRadio"].get_active(): secs = cls.ngrapid_min.get_value_as_int()*60 incr = cls.ngrapid_gain.get_value_as_int() elif cls.widgets["normalRadio"].get_active(): secs = cls.ngnormal_min.get_value_as_int()*60 incr = cls.ngnormal_gain.get_value_as_int() # Find players player0 = cls.widgets["whitePlayerCombobox"].get_active() player0 = playerItems[0].index(playerItems[variant_index][player0]) diffi0 = int(cls.widgets["skillSlider1"].get_value()) player1 = cls.widgets["blackPlayerCombobox"].get_active() player1 = playerItems[0].index(playerItems[variant_index][player1]) diffi1 = int(cls.widgets["skillSlider2"].get_value()) # Prepare players for ionest playertups = [] for i, playerno, diffi, color in ((0, player0, diffi0, WHITE), (1, player1, diffi1, BLACK)): if playerno > 0: engine = discoverer.getEngineN (playerno-1) name = discoverer.getName(engine) playertups.append((ARTIFICIAL, discoverer.initPlayerEngine, [engine, color, diffi, variant, secs, incr], 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) if secs > 0: timemodel = TimeModel (secs, incr) else: timemodel = TimeModel() 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])