Example #1
0
def cb_gameended(game, reason):
    print("The game between %s and %s ended %s" % (tuple(game.players)+(reprResult[game.status],)))
    if game.status not in (DRAW, WHITEWON, BLACKWON):
        print("Something must have gone wrong. But we'll just try to continue!")
    else:
        i, j = current
        results[i][j] = game.status
        print("The current scores are:")
    printScoreboard()
    print()
    
    f = open("arena.pgn", "a+")
    save(f, game)
    
    runGame()
Example #2
0
            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)
Example #3
0
            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)
Example #4
0
    def row_activated(self, widget, path, col):
        rec, ply = self.get_record(path)
        if rec is None:
            return

        # Enable unfinished games to continue from newgamedialog
        if rec["Result"] not in UNDOABLE_STATES:
            newGameDialog.EnterNotationExtension.run()
            model = self.persp.chessfile.loadToModel(rec)
            text = pgn.save(StringIO(), model)
            newGameDialog.EnterNotationExtension.sourcebuffer.set_text(text)
            return

        self.gamemodel = GameModel()

        variant = rec["Variant"]
        if variant:
            self.gamemodel.tags["Variant"] = variant

        # Lichess exports study .pgn without White and Black tags
        wp = "" if rec["White"] is None else rec["White"]
        bp = "" if rec["Black"] is None else rec["Black"]
        p0 = (LOCAL, Human, (WHITE, wp), wp)
        p1 = (LOCAL, Human, (BLACK, bp), bp)
        self.persp.chessfile.loadToModel(rec, -1, self.gamemodel)

        self.gamemodel.endstatus = (self.gamemodel.status
                                    if self.gamemodel.status in UNDOABLE_STATES
                                    else None)
        self.gamemodel.status = WAITING_TO_START

        perspective_manager.activate_perspective("games")
        perspective = perspective_manager.get_perspective("games")
        create_task(perspective.generalStart(self.gamemodel, p0, p1))
Example #5
0
    def saveGamePGN(self, game):
        if game.practice_game:
            return True

        if conf.get("saveOwnGames", False) and not game.hasLocalPlayer():
            return True

        filename = conf.get("autoSaveFormat", "pychess")
        filename = filename.replace("#n1", game.tags["White"])
        filename = filename.replace("#n2", game.tags["Black"])
        year, month, day = parseDateTag(game.tags["Date"])
        year = '' if year is None else str(year)
        month = '' if month is None else str(month)
        day = '' if day is None else str(day)
        filename = filename.replace("#y", "%s" % year)
        filename = filename.replace("#m", "%s" % month)
        filename = filename.replace("#d", "%s" % day)
        pgn_path = conf.get("autoSavePath", os.path.expanduser("~")) + "/" + filename + ".pgn"
        append = True
        try:
            if not os.path.isfile(pgn_path):
                # create new file
                with open(pgn_path, "w"):
                    pass
            base_offset = os.path.getsize(pgn_path)

            # save to .sqlite
            database_path = os.path.splitext(pgn_path)[0] + '.sqlite'
            database.save(database_path, game, base_offset)

            # save to .scout
            from pychess.Savers.pgn import scoutfish_path
            if scoutfish_path is not None:
                pgn_text = pgn.save(StringIO(), game)

                tmp = tempfile.NamedTemporaryFile(mode="w", delete=False)
                pgnfile = tmp.name
                with tmp.file as f:
                    f.write(pgn_text)

                # create new .scout from pgnfile we are importing
                args = [scoutfish_path, "make", pgnfile, "%s" % base_offset]
                output = subprocess.check_output(args, stderr=subprocess.STDOUT)

                # append it to our existing one
                if output.decode().find(u"Processing...done") > 0:
                    old_scout = os.path.splitext(pgn_path)[0] + '.scout'
                    new_scout = os.path.splitext(pgnfile)[0] + '.scout'

                    with open(old_scout, "ab") as file1, open(new_scout, "rb") as file2:
                        file1.write(file2.read())

            # TODO: do we realy want to update .bin ? It can be huge/slow!

            # save to .pgn
            game.save(pgn_path, pgn, append)

            return True
        except IOError:
            return False
Example #6
0
    def saveGamePGN(self, game):
        if conf.get("saveOwnGames") and not game.hasLocalPlayer():
            return True

        filename = conf.get("autoSaveFormat")
        filename = filename.replace("#n1", game.tags["White"])
        filename = filename.replace("#n2", game.tags["Black"])
        year, month, day = parseDateTag(game.tags["Date"])
        year = "" if year is None else str(year)
        month = "" if month is None else str(month)
        day = "" if day is None else str(day)
        filename = filename.replace("#y", "%s" % year)
        filename = filename.replace("#m", "%s" % month)
        filename = filename.replace("#d", "%s" % day)
        pgn_path = conf.get("autoSavePath") + "/" + filename + ".pgn"
        append = True
        try:
            if not os.path.isfile(pgn_path):
                # create new file
                with open(pgn_path, "w"):
                    pass
            base_offset = os.path.getsize(pgn_path)

            # save to .sqlite
            database_path = os.path.splitext(pgn_path)[0] + ".sqlite"
            database.save(database_path, game, base_offset)

            # save to .scout
            from pychess.Savers.pgn import scoutfish_path

            if scoutfish_path is not None:
                pgn_text = pgn.save(StringIO(), game)

                tmp = tempfile.NamedTemporaryFile(
                    mode="w", encoding="utf-8", delete=False
                )
                pgnfile = tmp.name
                with tmp.file as f:
                    f.write(pgn_text)

                # create new .scout from pgnfile we are importing
                args = [scoutfish_path, "make", pgnfile, "%s" % base_offset]
                output = subprocess.check_output(args, stderr=subprocess.STDOUT)

                # append it to our existing one
                if output.decode().find(u"Processing...done") > 0:
                    old_scout = os.path.splitext(pgn_path)[0] + ".scout"
                    new_scout = os.path.splitext(pgnfile)[0] + ".scout"

                    with open(old_scout, "ab") as file1, open(new_scout, "rb") as file2:
                        file1.write(file2.read())

            # TODO: do we realy want to update .bin ? It can be huge/slow!

            # save to .pgn
            game.save(pgn_path, pgn, append)

            return True
        except IOError:
            return False
Example #7
0
def paste(gamemodel):
    output = StringIO()
    text = pgn.save(output, gamemodel)
    values = {'apikey': APIKEY,
              'pgn': text,
              "name": "PyChess",
              'sandbox': 'false'}

    data = urlencode(values).encode('utf-8')
    req = Request(URL, data)
    try:
        response = urlopen(req, timeout=10)
    except URLError as err:
        if hasattr(err, 'reason'):
            print('We failed to reach the server.')
            print('Reason: ', err.reason)
        elif hasattr(err, 'code'):
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', err.code)
    else:
        ID = response.read()
        link = "http://www.chesspastebin.com/?p=%s" % int(ID)
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(link, -1)
        #print(text)
        #print(clipboard.wait_for_text())
        msg_dialog = Gtk.MessageDialog(type=Gtk.MessageType.INFO,
                                       buttons=Gtk.ButtonsType.OK)
        msg = _(
            "Game shared at ") + '<a href="%s">chesspastebin.com</a>' % link
        msg_dialog.set_markup(msg)
        msg_dialog.format_secondary_text(_("(Link is available on clipboard.)"))
        msg_dialog.connect("response", lambda msg_dialog, a: msg_dialog.hide())
        msg_dialog.show()
Example #8
0
def paste(gamemodel):
    dialog = Gtk.MessageDialog(mainwindow(),
                               type=Gtk.MessageType.QUESTION,
                               buttons=Gtk.ButtonsType.YES_NO)
    if gamemodel.status in UNDOABLE_STATES:
        text = _(
            "The current game is over. First, please verify the properties of the game."
        )
    else:
        text = _(
            "The current game is not terminated. Its export may have a limited interest."
        )
    text += "\n\n" + _(
        "Should %s publicly publish your game as PGN on chesspastebin.com ?"
    ) % NAME
    dialog.set_markup(text)
    response = dialog.run()
    dialog.destroy()
    if response != Gtk.ResponseType.YES:
        return

    output = StringIO()
    text = pgn.save(output, gamemodel)
    values = {
        'apikey': APIKEY,
        'pgn': text,
        "name": "PyChess",
        'sandbox': 'false'
    }

    data = urlencode(values).encode('utf-8')
    req = Request(URL, data)
    try:
        response = urlopen(req, timeout=10)
    except URLError as err:
        if hasattr(err, 'reason'):
            print('We failed to reach the server.')
            print('Reason: ', err.reason)
        elif hasattr(err, 'code'):
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', err.code)
    else:
        ID = response.read()
        link = "http://www.chesspastebin.com/?p=%s" % int(ID)
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(link, -1)
        # print(text)
        # print(clipboard.wait_for_text())
        msg_dialog = Gtk.MessageDialog(mainwindow(),
                                       type=Gtk.MessageType.INFO,
                                       buttons=Gtk.ButtonsType.OK)
        msg = _(
            "Game shared at ") + '<a href="%s">chesspastebin.com</a>' % link
        msg_dialog.set_markup(msg)
        msg_dialog.format_secondary_text(
            _("(Link is available on clipboard.)"))
        msg_dialog.connect("response", lambda msg_dialog, a: msg_dialog.hide())
        msg_dialog.show()
Example #9
0
def paste(gamemodel):
    dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.QUESTION, buttons=Gtk.ButtonsType.YES_NO)
    if gamemodel.status in UNDOABLE_STATES:
        text = _("The current game is over. First, please verify the properties of the game.")
    else:
        text = _("The current game is not terminated. Its export may have a limited interest.")
    text += "\n\n" + _("Should %s publicly publish your game as PGN on chesspastebin.com ?") % NAME
    dialog.set_markup(text)
    response = dialog.run()
    dialog.destroy()
    if response != Gtk.ResponseType.YES:
        return

    output = StringIO()
    text = pgn.save(output, gamemodel)
    values = {'apikey': APIKEY,
              'pgn': text,
              "name": "PyChess",
              'sandbox': 'false'}

    data = urlencode(values).encode('utf-8')
    req = Request(URL, data)
    try:
        response = urlopen(req, timeout=10)
    except URLError as err:
        if hasattr(err, 'reason'):
            print('We failed to reach the server.')
            print('Reason: ', err.reason)
        elif hasattr(err, 'code'):
            print('The server couldn\'t fulfill the request.')
            print('Error code: ', err.code)
    else:
        ID = response.read()
        link = "http://www.chesspastebin.com/?p=%s" % int(ID)
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(link, -1)
        # print(text)
        # print(clipboard.wait_for_text())
        msg_dialog = Gtk.MessageDialog(mainwindow(), type=Gtk.MessageType.INFO,
                                       buttons=Gtk.ButtonsType.OK)
        msg = _(
            "Game shared at ") + '<a href="%s">chesspastebin.com</a>' % link
        msg_dialog.set_markup(msg)
        msg_dialog.format_secondary_text(_("(Link is available on clipboard.)"))
        msg_dialog.connect("response", lambda msg_dialog, a: msg_dialog.hide())
        msg_dialog.show()
Example #10
0
 def copy_pgn(self):
     output = StringIO()
     clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
     clipboard.set_text(pgn.save(output, self.gamemodel), -1)
Example #11
0
 def copy_pgn(self):
     output = StringIO()
     clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
     clipboard.set_text(pgn.save(output, self.gamemodel), -1)