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 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) chessfile.loadToModel(rec, 0, gamemodel) start_puzzle_game(gamemodel, filename, records, index, rec)
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 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_lesson_from(filename, index=None): chessfile = PGNFile(protoopen(addDataPrefix("learn/lessons/%s" % filename))) chessfile.limit = 1000 chessfile.init_tag_database() records, plys = chessfile.get_records() progress = lessons_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, -1, gamemodel) if len(gamemodel.moves) > 0: start_lesson_game(gamemodel, filename, chessfile, records, index, rec) else: start_puzzle_game(gamemodel, filename, records, index, rec, from_lesson=True)
def coro(): gamemodel = GameModel(TimeModel(1, 0)) player0tup = (LOCAL, Human, (WHITE, "w"), "w") player1tup = (LOCAL, Human, (BLACK, "b"), "b") def on_game_end(game, state, event): event.set() event = asyncio.Event() gamemodel.connect("game_ended", on_game_end, event) def on_players_changed(game): # fill fools mate moves to players move queue p0 = game.players[0] p0.move_queue.put_nowait(Move(newMove(F2, F3))) p0.move_queue.put_nowait(Move(newMove(G2, G4))) p1 = gamemodel.players[1] p1.move_queue.put_nowait(Move(newMove(E7, E5))) p1.move_queue.put_nowait(Move(newMove(D8, H4))) gamemodel.connect("players_changed", on_players_changed) asyncio. async (self.games_persp.generalStart( gamemodel, player0tup, player1tup)) # waiting for game end ... yield from event.wait() fen = "rnb1kbnr/pppp1ppp/8/4p3/6Pq/5P2/PPPPP2P/RNBQKBNR w KQkq - 1 3" self.assertEqual(gamemodel.boards[-1].board.asFen(), fen) # Now save our game to pychess.pgn self.games_persp.saveGamePGN(gamemodel)
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 runGame(): a, b = findMatch() if a == None: print("All games have now been played. Here are the final scores:") printResults() mainloop.quit() return current[0] = a current[1] = b game = GameModel(TimeModel(minutes * 60, 0)) game.connect('game_started', cb_gamestarted) game.connect('game_ended', cb_gameended) p0 = discoverer.initPlayerEngine(engines[a], WHITE, 8, variants[NORMALCHESS], secs=minutes * 60, incr=0, forcePonderOff=True) p1 = discoverer.initPlayerEngine(engines[b], BLACK, 8, variants[NORMALCHESS], secs=minutes * 60, incr=0, forcePonderOff=True) game.setPlayers([p0, p1]) game.start()
def coro(variant): self.game = GameModel(TimeModel(60, 0), variant) self.game.setPlayers([self.p0, self.p1]) def on_game_end(game, state, event): event.set() event = asyncio.Event() self.game.connect("game_ended", on_game_end, event) self.p0.prestart() self.p1.prestart() if self.game.variant.need_initial_board: for player in self.game.players: player.setOptionInitialBoard(self.game) print(variant.name) self.game.start() yield from event.wait() pgn = StringIO() print(save(pgn, self.game)) self.assertIsNone(self.p0.invalid_move) self.assertIsNone(self.p1.invalid_move)
def row_activated(self, widget, path, col): if path is None: return filename = addDataPrefix("lectures/%s" % LESSONS[path[0]][0]) chessfile = PGNFile(protoopen(filename)) self.importer = PgnImport(chessfile) chessfile.init_tag_database(self.importer) records, plys = chessfile.get_records() rec = records[random.randrange(0, len(records))] print(rec) timemodel = TimeModel(0, 0) gamemodel = GameModel(timemodel) gamemodel.set_lesson_game() chessfile.loadToModel(rec, -1, gamemodel) name = conf.get("firstName", _("You")) p0 = (LOCAL, Human, (WHITE, name), name) name = "pychessbot" p1 = (LOCAL, Human, (BLACK, name), name) gamemodel.status = WAITING_TO_START perspective = perspective_manager.get_perspective("games") asyncio. async (perspective.generalStart(gamemodel, p0, p1))
def onGamePreview(self, adm, ficsgame): log.debug("Archived panel onGamePreview: %s" % ficsgame) timemodel = TimeModel(ficsgame.minutes * 60, ficsgame.inc) gamemodel = ICGameModel(self.connection, ficsgame, timemodel) # The players need to start listening for moves IN this method if they # want to be noticed of all moves the FICS server sends us from now on. # Hence the lazy loading is skipped. wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer player0tup = (REMOTE, ICPlayer, (gamemodel, wplayer.name, -1, WHITE, wplayer.long_name(), wplayer.getRatingByGameType(ficsgame.game_type)), wplayer.long_name()) player1tup = (REMOTE, ICPlayer, (gamemodel, bplayer.name, -1, BLACK, bplayer.long_name(), bplayer.getRatingByGameType(ficsgame.game_type)), bplayer.long_name()) perspective = perspective_manager.get_perspective("games") create_task( perspective.generalStart( gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.pgn), pgn, 0, -1))) gamemodel.connect("game_started", self.on_game_start, ficsgame)
def createRematch(gamemodel): """ If gamemodel contains only LOCAL or ARTIFICIAL players, this starts a new game, based on the info in gamemodel """ if gamemodel.timed: secs = gamemodel.timemodel.intervals[0][WHITE] gain = gamemodel.timemodel.gain else: secs = 0 gain = 0 newgamemodel = GameModel(TimeModel(secs, gain), variant=gamemodel.variant) wp = gamemodel.players[WHITE] bp = gamemodel.players[BLACK] if wp.__type__ == LOCAL: player1tup = (wp.__type__, wp.__class__, (BLACK, repr(wp)), repr(wp)) if bp.__type__ == LOCAL: player0tup = (bp.__type__, bp.__class__, (WHITE, repr(wp)), repr(bp)) else: engine = discoverer.getEngineByMd5(bp.md5) player0tup = (ARTIFICIAL, discoverer.initPlayerEngine, (engine, WHITE, bp.strength, gamemodel.variant, secs, gain), repr(bp)) else: player0tup = (bp.__type__, bp.__class__, (WHITE, repr(bp)), repr(bp)) engine = discoverer.getEngineByMd5(wp.md5) player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (engine, BLACK, wp.strength, gamemodel.variant, secs, gain), repr(wp)) ionest.generalStart(newgamemodel, player0tup, player1tup)
def __init__(self, timemodel=None, variant=NormalChess): GObject.GObject.__init__(self) Thread.__init__(self, name=fident(self.run)) self.daemon = True self.variant = variant self.boards = [variant.board(setup=True)] self.moves = [] self.scores = {} self.players = [] self.gameno = None self.variations = [self.boards] self.status = WAITING_TO_START self.reason = UNKNOWN_REASON if timemodel is None: self.timemodel = TimeModel() else: self.timemodel = timemodel self.connections = defaultdict(list) # mainly for IC subclasses now = datetime.datetime.now() self.tags = { "Event": _("Local Event"), "Site": _("Local Site"), "Round": 1, "Year": now.year, "Month": now.month, "Day": now.day, "Time": "%02d:%02d:00" % (now.hour, now.minute), "Result": "*", } self.endstatus = None self.timed = self.timemodel.secs != 0 or self.timemodel.gain != 0 if self.timed: self.tags["TimeControl"] = \ "%d+%d" % (self.timemodel.minutes*60, self.timemodel.gain) # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set # on the gamemodel, but simply written or read during saving/ # loading from pgn. If you want to know the time left for a player, # check the time model. # Keeps track of offers, so that accepts can be spotted self.offers = {} # True if the game has been changed since last save self.needsSave = False # The uri the current game was loaded from, or None if not a loaded game self.uri = None self.spectators = {} self.applyingMoveLock = RLock() self.undoLock = RLock() self.undoQueue = Queue()
def onObserveGameCreated(self, bm, ficsgame): log.debug("FICS.onObserveGameCreated: %s" % ficsgame) timemodel = TimeModel(ficsgame.minutes * 60, ficsgame.inc) gamemodel = ICGameModel(self.connection, ficsgame, timemodel) gamemodel.connect("game_started", self.onGameModelStarted, ficsgame) # The players need to start listening for moves IN this method if they # want to be noticed of all moves the FICS server sends us from now on wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer player0tup = ( REMOTE, ICPlayer, ( gamemodel, wplayer.name, ficsgame.gameno, WHITE, wplayer.long_name(), wplayer.getRatingForCurrentGame(), ), wplayer.long_name(), ) player1tup = ( REMOTE, ICPlayer, ( gamemodel, bplayer.name, ficsgame.gameno, BLACK, bplayer.long_name(), bplayer.getRatingForCurrentGame(), ), bplayer.long_name(), ) perspective = perspective_manager.get_perspective("games") create_task( perspective.generalStart( gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.pgn), pgn, 0, -1), )) if ficsgame.relation == IC_POS_OBSERVING_EXAMINATION: if 1: # int(self.connection.lvm.variablesBackup["kibitz"]) == 0: self.connection.cm.whisper( _("You have to set kibitz on to see bot messages here.")) self.connection.fm.finger(bplayer.name) self.connection.fm.finger(wplayer.name) elif ficsgame.relation == IC_POS_EXAMINATING: gamemodel.examined = True if not self.connection.ICC: allob = "allob " + str(ficsgame.gameno) gamemodel.connection.client.run_command(allob)
def do(discoverer): game = GameModel(TimeModel(60,0)) #game.connect('game_started', cb_gamestarted2) game.connect('game_ended', lambda *a: mainloop.quit()) p0 = discoverer.initPlayerEngine(discoverer.getEngines()['rybka'], WHITE, 7, variants[NORMALCHESS], 60) p1 = discoverer.initPlayerEngine(discoverer.getEngines()['gnuchess'], BLACK, 7, variants[NORMALCHESS], 60) game.setPlayers([p0,p1]) game.start()
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 loadFilesAndRun(uris): for uri in uris: loader = ionest.enddir[uri[uri.rfind(".") + 1:]] timemodel = TimeModel(0, 0) gamemodel = GameModel(timemodel) white_name = _("White") black_name = _("Black") p0 = (LOCAL, Human, (WHITE, white_name), white_name) p1 = (LOCAL, Human, (BLACK, black_name), black_name) ionest.generalStart(gamemodel, p0, p1, (uri, loader, 0, -1))
def loadFileAndRun(uri): parts = splitUri(uri) uri = parts[1] if len(parts) == 2 else parts[0] loader = enddir[uri[uri.rfind(".") + 1:]] timemodel = TimeModel(0, 0) gamemodel = GameModel(timemodel) white_name = _("White") black_name = _("Black") p0 = (LOCAL, Human, (WHITE, white_name), white_name) p1 = (LOCAL, Human, (BLACK, black_name), black_name) game_handler.generalStart(gamemodel, p0, p1, (uri, loader, 0, -1))
def start_lesson_from(filename, index=None): if filename.startswith("lichess_study"): chessfile = PGNFile( protoopen(addDataPrefix("learn/lessons/%s" % filename), encoding="utf-8")) else: chessfile = PGNFile( protoopen(addDataPrefix("learn/lessons/%s" % filename))) chessfile.limit = 1000 chessfile.init_tag_database() records, plys = chessfile.get_records() progress = lessons_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(LESSON, filename, index, len(records)) chessfile.loadToModel(rec, -1, gamemodel) color = gamemodel.boards[0].color player_name = conf.get("firstName", _("You")) w_name = player_name if color == WHITE else "PyChess" b_name = "PyChess" if color == WHITE else player_name p0 = (LOCAL, Human, (WHITE, w_name), w_name) p1 = (LOCAL, Human, (BLACK, b_name), b_name) def learn_success(gamemodel): chessfile.loadToModel(rec, -1, gamemodel) progress = lessons_solving_progress[gamemodel.source] progress[gamemodel.current_index] = 1 lessons_solving_progress[gamemodel.source] = progress asyncio. async (gamemodel.restart_analyzer(HINT)) gamemodel.connect("learn_success", learn_success) 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) gamemodel.status = WAITING_TO_START perspective = perspective_manager.get_perspective("games") asyncio. async (perspective.generalStart(gamemodel, p0, p1))
def start_lecture_game(self): timemodel = TimeModel(0, 0) gamemodel = GameModel(timemodel) gamemodel.set_offline_lecture() white_name = black_name = "pychessbot" p0 = (LOCAL, Human, (WHITE, white_name), white_name) p1 = (LOCAL, Human, (BLACK, black_name), black_name) perspective = perspective_manager.get_perspective("games") asyncio.async(perspective.generalStart(gamemodel, p0, p1)) return gamemodel
def onPlayGameCreated(self, bm, ficsgame): log.debug("FICS.onPlayGameCreated: %s" % ficsgame) for message in self.messages: message.dismiss() del self.messages[:] if self.connection.ICC: for button in self.quick_seek_buttons: button.set_active(False) timemodel = TimeModel(ficsgame.minutes * 60, ficsgame.inc) gamemodel = ICGameModel(self.connection, ficsgame, timemodel) gamemodel.connect("game_started", self.onGameModelStarted, ficsgame) wplayer, bplayer = ficsgame.wplayer, ficsgame.bplayer # We start if wplayer.name.lower() == self.connection.getUsername().lower(): player0tup = (LOCAL, Human, (WHITE, wplayer.long_name(), wplayer.name, wplayer.getRatingForCurrentGame()), wplayer.long_name()) player1tup = (REMOTE, ICPlayer, (gamemodel, bplayer.name, ficsgame.gameno, BLACK, bplayer.long_name(), bplayer.getRatingForCurrentGame()), bplayer.long_name()) # She starts else: player1tup = (LOCAL, Human, (BLACK, bplayer.long_name(), bplayer.name, bplayer.getRatingForCurrentGame()), bplayer.long_name()) player0tup = (REMOTE, ICPlayer, (gamemodel, wplayer.name, ficsgame.gameno, WHITE, wplayer.long_name(), wplayer.getRatingForCurrentGame()), wplayer.long_name()) perspective = perspective_manager.get_perspective("games") if not ficsgame.board.fen: create_task( perspective.generalStart(gamemodel, player0tup, player1tup)) else: create_task( perspective.generalStart( gamemodel, player0tup, player1tup, (StringIO(ficsgame.board.fen), fen, 0, -1)))
def loadFileAndRun(uri): if uri in [None, '']: return False parts = splitUri(uri) uri = parts[1] if len(parts) == 2 else parts[0] loader = enddir[uri[uri.rfind(".") + 1:]] timemodel = TimeModel(0, 0) gamemodel = GameModel(timemodel) white_name = _("White") black_name = _("Black") p0 = (LOCAL, Human, (WHITE, white_name), white_name) p1 = (LOCAL, Human, (BLACK, black_name), black_name) perspective = perspective_manager.get_perspective("games") create_task(perspective.generalStart(gamemodel, p0, p1, (uri, loader, 0, -1))) return True
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_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))
def createRematch (gamemodel): if gamemodel.timemodel: secs = gamemodel.timemodel.intervals[0][WHITE] gain = gamemodel.timemodel.gain newgamemodel = GameModel(TimeModel(secs, gain), gamemodel.variant) else: secs = 0 gain = 0 newgamemodel = GameModel(variant=gamemodel.variant) wp = gamemodel.players[WHITE] bp = gamemodel.players[BLACK] if wp.__type__ == LOCAL: player1tup = (wp.__type__, wp.__class__, (BLACK, ""), repr(wp)) if bp.__type__ == LOCAL: player0tup = (bp.__type__, bp.__class__, (WHITE, ""), repr(bp)) else: binname = bp.engine.path.split("/")[-1] if binname == "python": binname = bp.engine.args[1].split("/")[-1] xmlengine = discoverer.getEngines()[binname] player0tup = (ARTIFICIAL, discoverer.initPlayerEngine, (xmlengine, WHITE, bp.strength, gamemodel.variant, secs, gain), repr(bp)) else: player0tup = (bp.__type__, bp.__class__, (WHITE, ""), repr(bp)) binname = wp.engine.path.split("/")[-1] if binname == "python": binname = wp.engine.args[1].split("/")[-1] xmlengine = discoverer.getEngines()[binname] player1tup = (ARTIFICIAL, discoverer.initPlayerEngine, (xmlengine, BLACK, wp.strength, gamemodel.variant, secs, gain), repr(wp)) ionest.generalStart(newgamemodel, player0tup, player1tup)
def __init__(self, timemodel=None, variant=NormalBoard): GObject.GObject.__init__(self) self.daemon = True self.variant = variant self.boards = [variant(setup=True)] self.moves = [] self.scores = {} self.spy_scores = {} self.players = [] self.gameno = None self.variations = [self.boards] self.terminated = False self.status = WAITING_TO_START self.reason = UNKNOWN_REASON self.curColor = WHITE # support algorithm for new players # type apparent : DecisionSupportAlgorithm self.support_algorithm = DecisionSupportAlgorithm() if timemodel is None: self.timemodel = TimeModel() else: self.timemodel = timemodel self.timemodel.gamemodel = self self.connections = collections.defaultdict( list) # mainly for IC subclasses self.analyzer_cids = {} self.examined = False now = datetime.datetime.now() self.tags = collections.defaultdict(str) self.tags["Event"] = _("Local Event") self.tags["Site"] = _("Local Site") self.tags["Date"] = "%04d.%02d.%02d" % (now.year, now.month, now.day) self.tags["Round"] = "1" self.endstatus = None self.zero_reached_cid = None self.timed = self.timemodel.minutes != 0 or self.timemodel.gain != 0 if self.timed: self.zero_reached_cid = self.timemodel.connect( 'zero_reached', self.zero_reached) if self.timemodel.moves == 0: self.tags["TimeControl"] = "%d%s%d" % ( self.timemodel.minutes * 60, "+" if self.timemodel.gain >= 0 else "-", abs(self.timemodel.gain)) else: self.tags["TimeControl"] = "%d/%d" % ( self.timemodel.moves, self.timemodel.minutes * 60) # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set # on the gamemodel, but simply written or read during saving/ # loading from pgn. If you want to know the time left for a player, # check the time model. # Keeps track of offers, so that accepts can be spotted self.offers = {} # True if the game has been changed since last save self.needsSave = False # The uri the current game was loaded from, or None if not a loaded game self.uri = None # Link to additiona info self.info = None self.spectators = {} self.undoQueue = Queue() # learn_type set by LearnModel.set_learn_data() self.offline_lecture = False self.puzzle_game = False self.lesson_game = False self.end_game = False self.solved = False
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])
def __init__(self, timemodel=None, variant=NormalBoard): GObject.GObject.__init__(self) self.daemon = True self.variant = variant self.boards = [variant(setup=True)] self.moves = [] self.scores = {} self.spy_scores = {} self.players = [] self.gameno = None self.variations = [self.boards] self.terminated = False self.status = WAITING_TO_START self.reason = UNKNOWN_REASON self.curColor = WHITE if timemodel is None: self.timemodel = TimeModel() else: self.timemodel = timemodel self.timemodel.gamemodel = self self.connections = defaultdict(list) # mainly for IC subclasses self.analyzer_cids = {} self.examined = False now = datetime.datetime.now() self.tags = { "Event": _("Local Event"), "Site": _("Local Site"), "Round": 1, "Year": now.year, "Month": now.month, "Day": now.day, "Time": "%02d:%02d:00" % (now.hour, now.minute), "Result": "*", } self.endstatus = None self.zero_reached_cid = None self.timed = self.timemodel.minutes != 0 or self.timemodel.gain != 0 if self.timed: self.zero_reached_cid = self.timemodel.connect( 'zero_reached', self.zero_reached) if self.timemodel.moves == 0: self.tags["TimeControl"] = "%d+%d" % (self.timemodel.minutes * 60, self.timemodel.gain) else: self.tags["TimeControl"] = "%d/%d" % ( self.timemodel.moves, self.timemodel.minutes * 60) # Notice: tags["WhiteClock"] and tags["BlackClock"] are never set # on the gamemodel, but simply written or read during saving/ # loading from pgn. If you want to know the time left for a player, # check the time model. # Keeps track of offers, so that accepts can be spotted self.offers = {} # True if the game has been changed since last save self.needsSave = False # The uri the current game was loaded from, or None if not a loaded game self.uri = None # Link to additiona info self.info = None self.spectators = {} self.undoQueue = Queue() self.offline_lecture = False self.practice_game = False self.lesson_game = False
def start_lecture_from(filename, index=None): if index is None: index = 0 # connection.client.run_command("examine") timemodel = TimeModel(0, 0) gamemodel = LearnModel(timemodel) gamemodel.set_learn_data(LECTURE, filename, index) white_name = black_name = "PyChess" p0 = (LOCAL, Human, (WHITE, white_name), white_name) p1 = (LOCAL, Human, (BLACK, black_name), black_name) def on_game_started(gamemodel): perspective.activate_panel("chatPanel") gamemodel.connect("game_started", on_game_started) perspective = perspective_manager.get_perspective("games") asyncio. async (perspective.generalStart(gamemodel, p0, p1)) def lecture_steps(lecture_file): with open(lecture_file, "r") as f: for line in f: yield line return lecture_file = addDataPrefix("learn/lectures/%s" % filename) steps = lecture_steps(lecture_file) @asyncio.coroutine def coro(gamemodel, steps): exit_lecture = False inside_bsetup = False paused = False moves_played = 0 KIBITZ, BACKWARD, BSETUP, BSETUP_DONE, FEN, TOMOVE, WCASTLE, BCASTLE, \ WNAME, BNAME, REVERT, WAIT, MOVE = range(13) while True: try: step = next(steps) print(step) parts = step.strip().split() command = None param = "" if parts[0] == "k" or parts[0] == "kibitz": command = KIBITZ param = " ".join(parts[1:]) elif parts[0] == "back": command = BACKWARD param = int(parts[1]) if len(parts) > 1 else 1 elif parts[0] == "bsetup": if len(parts) == 1: command = BSETUP else: if parts[1] == "done": command = BSETUP_DONE elif parts[1] == "fen": command = FEN param = parts[2] elif parts[1] == "tomove": command = TOMOVE param = "w" if parts[2].lower()[0] == "w" else "b" elif parts[1] == "wcastle": command = WCASTLE param = parts[2] elif parts[1] == "bcastle": command = BCASTLE param = parts[2] elif parts[0] == "tomove": command = TOMOVE param = "w" if parts[1].lower()[0] == "w" else "b" elif parts[0] == "wname": command = WNAME param = parts[1] elif parts[0] == "bname": command = BNAME param = parts[1] elif parts[0] == "revert": command = REVERT elif len(parts) == 1 and parts[0].isdigit(): command = WAIT param = int(parts[0]) else: command = MOVE param = parts[0] if not inside_bsetup and command == BSETUP: inside_bsetup = True pieces = "" color = "" castl = "" ep = "" elif inside_bsetup and command == BSETUP_DONE: inside_bsetup = False wait_sec = int(param) if command == WAIT else 2 if inside_bsetup: wait_sec = -1 while wait_sec >= 0: if gamemodel.lecture_exit_event.is_set(): gamemodel.lecture_exit_event.clear() exit_lecture = True break if gamemodel.lecture_skip_event.is_set(): gamemodel.lecture_skip_event.clear() paused = False break if gamemodel.lecture_pause_event.is_set(): gamemodel.lecture_pause_event.clear() paused = True yield from asyncio.sleep(0.1) if not paused: wait_sec = wait_sec - 0.1 if exit_lecture: gamemodel.players[0].putMessage("Lecture exited.") break if command != WAIT: if command == KIBITZ: gamemodel.players[0].putMessage(param) if command == BACKWARD: gamemodel.undoMoves(param) moves_played -= param if command == MOVE: board = gamemodel.getBoardAtPly(gamemodel.ply) move = parseAny(board, param) gamemodel.curplayer.move_queue.put_nowait(move) moves_played += 1 elif command == REVERT: gamemodel.undoMoves(moves_played) moves_played = 0 elif command == BNAME: gamemodel.players[BLACK].name = param gamemodel.emit("players_changed") elif command == WNAME: gamemodel.players[WHITE].name = param gamemodel.emit("players_changed") elif command == FEN: pieces = param elif command == TOMOVE: color = param elif command == WCASTLE: if param == "both": castl += "KQ" elif param == "kside": castl += "K" elif param == "qside": castl += "Q" elif command == BCASTLE: if param == "both": castl += "kq" elif param == "kside": castl += "k" elif param == "qside": castl += "q" elif command == BSETUP_DONE: if not castl: castl = "-" if not ep: ep = "-" fen = "%s %s %s %s 0 1" % (pieces, color, castl, ep) curplayer = gamemodel.curplayer gamemodel.status = RUNNING gamemodel.loadAndStart(StringIO(fen), fen_loader, 0, -1, first_time=False) curplayer.move_queue.put_nowait("int") gamemodel.emit("game_started") moves_played = 0 except StopIteration: # connection.client.run_command("kibitz That concludes this lecture.") break asyncio. async (coro(gamemodel, steps))
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])