Exemplo n.º 1
0
 def mEditGameComment(self, *args):
     if self._cancelDrag(break_pause=False):
         return
     game, gi = self.game, self.game.gameinfo
     kw = {'game': gi.name, 'id': game.getGameNumber(format=1)}
     cc = _("Comments for %(game)s %(id)s:\n\n") % kw
     c = game.gsaveinfo.comment or cc
     d = EditTextDialog(game.top, _("Comments for %(id)s") % kw, text=c)
     if d.status == 0 and d.button == 0:
         text = d.text
         if text.strip() == cc.strip():
             game.gsaveinfo.comment = ""
         else:
             game.gsaveinfo.comment = d.text
             # save to file
             fn = os.path.join(self.app.dn.config, "comments.txt")
             fn = os.path.normpath(fn)
             if not text.endswith(os.linesep):
                 text += os.linesep
             enc = locale.getpreferredencoding()
             try:
                 open(fn, 'a').write(text.encode(enc, 'replace'))
             except Exception as err:
                 d = MfxExceptionDialog(
                     self.top, err, text=_("Error while writing to file"))
             else:
                 d = MfxMessageDialog(
                     self.top,
                     title=_("%s Info") % TITLE,
                     bitmap="info",
                     text=_("Comments were appended to\n\n%(filename)s") %
                     {'filename': fn})
     self._setCommentMenu(bool(game.gsaveinfo.comment))
Exemplo n.º 2
0
    def _mahjonggShuffle(self):
        talon = self.s.talon
        rows = []
        cards = []

        for r in self.s.rows:
            if r.cards:
                rows.append(r)
                cards.append(r.cards[0])
        if not rows:
            return

        if self.app.opt.mahjongg_create_solvable == 0:
            self.playSample('turnwaste')
            old_state = self.enterState(self.S_FILL)
            self.saveSeedMove()
            for r in rows:
                self.moveMove(1, r, talon, frames=0)
            self.shuffleStackMove(talon)
            for r in rows:
                self.moveMove(1, talon, r, frames=0)
            self.leaveState(old_state)
            self.finishMove()
            return

        self.playSample('turnwaste')
        old_state = self.enterState(self.S_FILL)
        self.saveSeedMove()

        new_cards = self._shuffleHook2(rows, cards)
        if new_cards is None:
            if TOOLKIT != 'kivy':
                MfxMessageDialog(self.top,
                                 title=_('Warning'),
                                 text=_('''\
Sorry, I can\'t find
a solvable configuration.'''),
                                 bitmap='warning')

            self.leaveState(old_state)
            # self.finishMove()
            # hack
            am = self.moves.current[0]
            am.undo(self)  # restore random
            self.moves.current = []
            return

        self.stats.shuffle_moves += 1
        # move new_cards to talon
        for c in new_cards:
            for r in rows:
                if r.cards and r.cards[0] is c:
                    self.moveMove(1, r, talon, frames=0)
                    break
        # deal
        for r in rows:
            self.moveMove(1, talon, r, frames=0)

        self.leaveState(old_state)
        self.finishMove()
Exemplo n.º 3
0
 def _mStatsSave(self, player, filename, write_method):
     file = None
     if player is None:
         text = _("Demo statistics")
         filename = filename + "_demo"
     else:
         text = _("Your statistics")
     filename = os.path.join(self.app.dn.config, filename + ".txt")
     filename = os.path.normpath(filename)
     try:
         file = open(filename, "a")
         a = FileStatsFormatter(self.app, file)
         write_method(a, player)
     except EnvironmentError as ex:
         if file:
             file.close()
         MfxExceptionDialog(self.top,
                            ex,
                            text=_("Error while writing to file"))
     else:
         if file:
             file.close()
         MfxMessageDialog(self.top,
                          title=TITLE + _(" Info"),
                          bitmap="info",
                          text=text + _(" were appended to\n\n") + filename)
Exemplo n.º 4
0
    def requestCompatibleCardsetType(self, id):
        gi = self.getGameInfo(id)
        #
        cs, cs_update_flag = self.getCompatibleCardset(gi, self.cardset)
        if cs is self.cardset:
            return 0
        if cs is not None:
            self.loadCardset(cs, update=1)
            return 1
        #
        t = self.checkCompatibleCardsetType(gi, self.cardset)
        MfxMessageDialog(self.top,
                         title=_("Incompatible ") + CARDSET,
                         bitmap="warning",
                         text=_('''The currently selected %s %s
is not compatible with the game
%s

Please select a %s type %s.
''') % (CARDSET, self.cardset.name, gi.name, t[0], CARDSET),
                         strings=(_("&OK"), ),
                         default=0)
        cs = self.__selectCardsetDialog(t)
        if cs is None:
            return -1
        self.loadCardset(cs, id=id)
        return 1
Exemplo n.º 5
0
def help_credits(app, timeout=0, sound=True):
    if sound:
        app.audio.playSample("credits")
    t = ""
    if TOOLKIT == "tk":
        t = "Tcl/Tk"
    elif TOOLKIT == "gtk":
        t = "PyGTK"
    elif TOOLKIT == "kde":
        t = "pyKDE"
    elif TOOLKIT == "wx":
        t = "wxPython"
    elif TOOLKIT == "kivy":
        t = "kivy"
    d = MfxMessageDialog(
        app.top, title=_("Credits"), timeout=timeout,
        text=TITLE+_(''' credits go to:

Volker Weidner for getting me into Solitaire
Guido van Rossum for the initial example program
T. Kirk for lots of contributed games and cardsets
Carl Larsson for the background music
The Gnome AisleRiot team for parts of the documentation
Natascha

The Python, %s, SDL & Linux crews
for making this program possible''') % t,
        image=app.gimages.logos[3], image_side="right",
        separator=True)
    return d.status
Exemplo n.º 6
0
 def mEditGameComment(self, *args):
     if self._cancelDrag(break_pause=False): return
     game, gi = self.game, self.game.gameinfo
     t = " " + game.getGameNumber(format=1)
     cc = _("Comments for %s:\n\n") % (gi.name + t)
     c = game.gsaveinfo.comment or cc
     d = EditTextDialog(game.top, _("Comments for ") + t, text=c)
     if d.status == 0 and d.button == 0:
         text = d.text
         if text.strip() == cc.strip():
             game.gsaveinfo.comment = ""
         else:
             game.gsaveinfo.comment = d.text
             # save to file
             fn = os.path.join(self.app.dn.config, "comments.txt")
             fn = os.path.normpath(fn)
             if not text.endswith(os.linesep):
                 text += os.linesep
             enc = locale.getpreferredencoding()
             try:
                 fd = open(fn, 'a')
                 fd.write(text.encode(enc, 'replace'))
             except Exception, err:
                 d = MfxExceptionDialog(
                     self.top, err, text=_("Error while writing to file"))
             else:
                 if fd: fd.close()
                 d = MfxMessageDialog(
                     self.top,
                     title=TITLE + _(" Info"),
                     bitmap="info",
                     text=_("Comments were appended to\n\n") + fn)
Exemplo n.º 7
0
Arquivo: app.py Projeto: jnumm/PySolFC
    def requestCompatibleCardsetType(self, id):
        gi = self.getGameInfo(id)
        #
        cs, cs_update_flag = self.getCompatibleCardset(gi, self.cardset)
        if cs is self.cardset:
            return 0
        if cs is not None:
            self.loadCardset(cs, update=1)
            return 1
        #
        t = self.checkCompatibleCardsetType(gi, self.cardset)
        MfxMessageDialog(
            self.top, title=_("Incompatible cardset"),
            bitmap="warning",
            text=_('''The currently selected cardset %(cardset)s
is not compatible with the game
%(game)s

Please select a %(correct_type)s type cardset.
''') % {'cardset': self.cardset.name, 'game': gi.name, 'correct_type': t[0]},
            strings=(_("&OK"),), default=0)
        cs = self.__selectCardsetDialog(t)
        if cs is None:
            return -1
        self.loadCardset(cs, id=id)
        return 1
Exemplo n.º 8
0
 def errorDialog(self, msg):
     MfxMessageDialog(
         self.parent,
         title=TITLE + " HTML Problem",
         text=msg,
         # bitmap="warning"
         # FIXME: this interp don't have images
         strings=(_("&OK"), ),
         default=0)
Exemplo n.º 9
0
    def fatal_no_cardsets(app):
        app.wm_withdraw()
        MfxMessageDialog(app.top, title=_("%s installation error") % TITLE,
                         text=_('''No cardsets were found!!!

Cardsets should be installed into:
%(dir)s

Please check your %(app)s installation.
''') % {'dir': getprefdir(PACKAGE) + '/cardsets/', 'app': TITLE},
            bitmap="error", strings=(_("&Quit"),))
Exemplo n.º 10
0
    def fatal_no_cardsets(app):
        app.wm_withdraw()
        MfxMessageDialog(app.top, title=_("%s installation error") % TITLE,
                         text=_('''No cardsets were found!!!

Main data directory is:
%(dir)s

Please check your %(app)s installation.
''') % {'dir': app.dataloader.dir, 'app': TITLE},
                     bitmap="error", strings=(_("&Quit"),))
Exemplo n.º 11
0
 def _mNewGameBySeed(self, seed, origin):
     try:
         random = constructRandom(seed)
         if random is None:
             return
         id = self.game.id
         if not self.app.getGameInfo(id):
             raise ValueError
     except (ValueError, TypeError), ex:
         d = MfxMessageDialog(self.top,
                              title=_("Invalid game number"),
                              text=_("Invalid game number\n") + str(seed),
                              bitmap="error")
         return
Exemplo n.º 12
0
    def requestCompatibleCardsetTypeDialog(self, cardset, gi, t):
        MfxMessageDialog(self.top,
                         title=_("Incompatible cardset"),
                         bitmap="warning",
                         text=_('''The currently selected cardset %(cardset)s
        is not compatible with the game
        %(game)s

        Please select a %(correct_type)s type cardset.
        ''') % {
                             'cardset': cardset.name,
                             'game': gi.name,
                             'correct_type': t[0]
                         },
                         strings=(_("&OK"), ),
                         default=0)
Exemplo n.º 13
0
 def _mStatsSave(self, player, filename, write_method):
     if player is None:
         text = _("Demo statistics were appended to\n\n%(filename)s")
         filename = filename + "_demo"
     else:
         text = _("Your statistics were appended to\n\n%(filename)s")
     filename = os.path.join(self.app.dn.config, filename + ".txt")
     filename = os.path.normpath(filename)
     try:
         a = FileStatsFormatter(self.app, open(filename, "a"))
         write_method(a, player)
     except EnvironmentError as ex:
         MfxExceptionDialog(self.top, ex,
                            text=_("Error while writing to file"))
     else:
         MfxMessageDialog(
             self.top, title=_("%s Info") % TITLE, bitmap="info",
             text=text % {'filename': filename})
Exemplo n.º 14
0
def help_html(app, document, dir_, top=None):
    global help_html_viewer, help_html_index
    if not document:
        return None
    if top is None:
        top = app.top
    try:
        doc = app.dataloader.findFile(document, dir_)
        if help_html_index is None:
            document, dir_ = "index.html", "html"
            help_html_index = app.dataloader.findFile(document, dir_)
    except EnvironmentError:
        MfxMessageDialog(app.top,
                         title=TITLE + _(" HTML Problem"),
                         text=_("Cannot find help document\n") + document,
                         bitmap="warning")
        return None
    # print doc, help_html_index
    try:
        viewer = help_html_viewer
        # if viewer.parent.winfo_parent() != top._w:
        #    viewer.destroy()
        #    viewer = None
        viewer.updateHistoryXYView()
        viewer.display(doc, relpath=0)
    except Exception:
        # traceback.print_exc()
        top = make_help_toplevel(app, title=TITLE + _(" Help"))
        if top.winfo_screenwidth() < 800 or top.winfo_screenheight() < 600:
            # maximized = 1
            top.wm_minsize(300, 150)
        else:
            # maximized = 0
            top.wm_minsize(400, 200)
        viewer = HTMLViewer(top, app, help_html_index)
        viewer.display(doc)
    # wm_map(top, maximized=maximized)
    viewer.parent.wm_deiconify()
    viewer.parent.tkraise()
    help_html_viewer = viewer
    return viewer
Exemplo n.º 15
0
 def _mNewGameBySeed(self, seed, origin):
     try:
         random = constructRandom(seed)
         if random is None:
             return
         id = self.game.id
         if not self.app.getGameInfo(id):
             raise ValueError
     except (ValueError, TypeError):
         MfxMessageDialog(self.top, title=_("Invalid game number"),
                          text=_("Invalid game number\n") + str(seed),
                          bitmap="error")
         return
     f = self.game.nextGameFlags(id, random)
     if f & 17 == 0:
         return
     random.origin = origin
     if f & 15 == 0:
         self.game.endGame()
         self.game.newGame(random=random)
     else:
         self.game.endGame()
         self.game.quitGame(id, random=random)
Exemplo n.º 16
0
def pysol_init(app, args):

    # init commandline options (undocumented)
    opts = parse_option(args)
    if not opts:
        return 1
        sys.exit(1)
    opts, filename = opts
    if filename:
        app.commandline.loadgame = filename
    app.commandline.game = opts['game']
    if opts['gameid'] is not None:
        try:
            app.commandline.gameid = int(opts['gameid'])
        except ValueError:
            print_err(_('invalid game id: ') + opts['gameid'])

    # try to create the config directory
    for d in (
            app.dn.config,
            app.dn.savegames,
            os.path.join(app.dn.config, "music"),
            # os.path.join(app.dn.config, "screenshots"),
            os.path.join(app.dn.config, "tiles"),
            os.path.join(app.dn.config, "tiles", "stretch"),
            os.path.join(app.dn.config, "tiles", "save-aspect"),
            os.path.join(app.dn.config, "cardsets"),
            os.path.join(app.dn.config, "plugins"),
    ):
        if not os.path.exists(d):
            try:
                os.makedirs(d)
            except:
                traceback.print_exc()
                pass

    # init DataLoader
    f = os.path.join("html-src", "license.html")
    app.dataloader = DataLoader(args[0], f)

    # init toolkit 1)
    top = MfxRoot(className=TITLE)
    app.top = top
    app.top_bg = top.cget("bg")
    app.top_cursor = top.cget("cursor")

    # load options
    try:
        app.loadOptions()
    except:
        traceback.print_exc()
        pass

    # init toolkit 2)
    init_root_window(top, app)

    # prepare the progress bar
    app.loadImages1()
    if not app.progress_images:
        app.progress_images = (loadImage(app.gimages.logos[0]),
                               loadImage(app.gimages.logos[1]))
    app.wm_withdraw()

    # create the progress bar
    title = _("Welcome to %s") % TITLE
    color = app.opt.colors['table']
    if app.tabletile_index > 0:
        color = "#008200"
    app.intro.progress = PysolProgressBar(app,
                                          top,
                                          title=title,
                                          color=color,
                                          images=app.progress_images,
                                          norm=2.0)
    app.intro.progress.update(step=1)

    # init games database
    def progressCallback(*args):
        app.intro.progress.update(step=1)

    GAME_DB.setCallback(progressCallback)
    import pysollib.games
    if not opts['french-only']:
        import pysollib.games.ultra
        import pysollib.games.mahjongg
        import pysollib.games.special
        pysollib.games.special.no_use()

    # try to load plugins
    if not opts["noplugins"]:
        for dir in (os.path.join(app.dataloader.dir, "games"),
                    os.path.join(app.dataloader.dir,
                                 "plugins"), app.dn.plugins):
            try:
                app.loadPlugins(dir)
            except:
                pass
    GAME_DB.setCallback(None)

    # init audio 1)
    app.audio = None
    sounds = {
        'pss': PysolSoundServerModuleClient,
        'pygame': PyGameAudioClient,
        'oss': OSSAudioClient,
        'win': Win32AudioClient
    }
    if opts["nosound"] or SOUND_MOD == 'none':
        app.audio = AbstractAudioClient()
    elif opts['sound-mod']:
        c = sounds[opts['sound-mod']]
        app.audio = c()
    elif SOUND_MOD == 'auto':
        for c in (PyGameAudioClient, PysolSoundServerModuleClient,
                  OSSAudioClient, Win32AudioClient, AbstractAudioClient):
            try:
                app.audio = c()
                app.audio.startServer()
                app.audio.connectServer(app)
            except:
                pass
            else:
                # success
                break
    else:
        c = sounds[SOUND_MOD]
        app.audio = c()
        app.audio.startServer()
        app.audio.connectServer(app)

    # update sound_mode
    if isinstance(app.audio, PysolSoundServerModuleClient):
        app.opt.sound_mode = 1
    else:
        app.opt.sound_mode = 0

    # check games
    if len(app.gdb.getGamesIdSortedByName()) == 0:
        app.wm_withdraw()
        app.intro.progress.destroy()
        d = MfxMessageDialog(top,
                             title=_("%s installation error") % TITLE,
                             text=_('''
No games were found !!!

Main data directory is:
%s

Please check your %s installation.
''') % (app.dataloader.dir, TITLE),
                             bitmap="error",
                             strings=(_("&Quit"), ))
        return 1

    # init cardsets
    app.initCardsets()
    cardset = None
    c = app.opt.cardset.get(0)
    if c:
        cardset = app.cardset_manager.getByName(c[0])
        if cardset and c[1]:
            cardset.updateCardback(backname=c[1])
    if not cardset:
        cardset = app.cardset_manager.get(0)
    if app.cardset_manager.len() == 0 or not cardset:
        fatal_no_cardsets(app)
        return 3

    # init tiles
    manager = app.tabletile_manager
    tile = Tile()
    tile.color = app.opt.colors['table']
    tile.name = "None"
    tile.filename = None
    manager.register(tile)
    app.initTiles()
    if app.opt.tabletile_name:  # and top.winfo_screendepth() > 8:
        for tile in manager.getAll():
            if app.opt.tabletile_name == tile.basename:
                app.tabletile_index = tile.index
                break

    # init samples and music resources
    app.initSamples()
    app.initMusic()

    # init audio 2)
    if not app.audio.CAN_PLAY_SOUND:
        app.opt.sound = 0
    app.audio.updateSettings()
    # start up the background music
    if app.audio.CAN_PLAY_MUSIC:
        music = app.music_manager.getAll()
        if music:
            app.music_playlist = list(music)[:]
            app.miscrandom.shuffle(app.music_playlist)
            if 1:
                for m in app.music_playlist:
                    if m.name.lower() == "bye_for_now":
                        app.music_playlist.remove(m)
                        app.music_playlist.insert(0, m)
                        break
            app.audio.playContinuousMusic(app.music_playlist)

    # prepare other images
    app.loadImages2()
    app.loadImages3()
    app.loadImages4()

    # load cardset
    progress = app.intro.progress
    if not app.loadCardset(cardset, progress=progress, update=1):
        for cardset in app.cardset_manager.getAll():
            progress.reset()
            if app.loadCardset(cardset, progress=progress, update=1):
                break
        else:
            fatal_no_cardsets(app)
            return 3

    # ok
    return 0
Exemplo n.º 17
0
        filename = os.path.join(self.app.dn.config, filename + ".txt")
        filename = os.path.normpath(filename)
        try:
            file = open(filename, "a")
            a = FileStatsFormatter(self.app, file)
            write_method(a, player)
        except EnvironmentError, ex:
            if file: file.close()
            d = MfxExceptionDialog(self.top,
                                   ex,
                                   text=_("Error while writing to file"))
        else:
            if file: file.close()
            d = MfxMessageDialog(self.top,
                                 title=TITLE + _(" Info"),
                                 bitmap="info",
                                 text=text + _(" were appended to\n\n") +
                                 filename)

    def mPlayerStats(self, *args, **kw):
        mode = kw.get("mode", 101)
        demo = 0
        gameid = None
        while mode > 0:
            if mode > 1000:
                demo = not demo
                mode = mode % 1000
            #
            d = Struct(status=-1, button=-1)
            if demo:
                player = None