def to_unicode(s): if isinstance(s, unicode): return s try: s = unicode(s, 'utf-8') except UnicodeDecodeError, err: print_err(err) s = unicode(s, 'utf-8', 'ignore')
def parse_option(argv): prog_name = argv[0] try: optlist, args = getopt.getopt(argv[1:], "g:i:hD:", ["game=", "gameid=", "french-only", "noplugins", "nosound", "sound-mod=", "help"]) except getopt.GetoptError, err: print_err(_("%s\ntry %s --help for more information") % (err, prog_name), 0) return None
def _getOption(self, section, key, t): config = self._config try: if config[section][key] is None: # invalid value return None if t == 'bool': val = config[section].as_bool(key) elif t == 'int': val = config[section].as_int(key) elif t == 'float': val = config[section].as_float(key) elif t == 'list': val = config[section][key] assert isinstance(val, (list, tuple)) else: # str val = config[section][key] except KeyError: val = None except: print_err('load option error: %s: %s' % (section, key)) traceback.print_exc() val = None return val
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 p0, p1, p2 = TITLE+_(" Demo"), TITLE+_(" Demo "), "" else: player = self.app.opt.player p0, p1, p2 = player, "", _(" for ") + player n = self.game.gameinfo.name # if mode == 100: d = Status_StatsDialog(self.top, game=self.game) elif mode == 101: header = p1 + _("Statistics for ") + n d = SingleGame_StatsDialog(self.top, header, self.app, player, gameid=self.game.id) gameid = d.selected_game elif mode == 102: header = p1 + _("Statistics") + p2 d = AllGames_StatsDialog(self.top, header, self.app, player) gameid = d.selected_game elif mode == 103: header = p1 + _("Full log") + p2 d = FullLog_StatsDialog(self.top, header, self.app, player) elif mode == 104: header = p1 + _("Session log") + p2 d = SessionLog_StatsDialog(self.top, header, self.app, player) elif mode == 105: header = p1 + TOP_TITLE + _(" for ") + n d = Top_StatsDialog(self.top, header, self.app, player, gameid=self.game.id) elif mode == 106: header = _("Game Info") d = GameInfoDialog(self.top, header, self.app) elif mode == 107: header = _("Statistics progression") d = ProgressionDialog(self.top, header, self.app, player, gameid=self.game.id) elif mode == 202: # print stats to file write_method = FileStatsFormatter.writeStats self._mStatsSave(player, "stats", write_method) elif mode == 203: # print full log to file write_method = FileStatsFormatter.writeFullLog self._mStatsSave(player, "log", write_method) elif mode == 204: # print session log to file write_method = FileStatsFormatter.writeSessionLog self._mStatsSave(player, "log", write_method) elif mode == 301: # reset all player stats if self.game.areYouSure(_("Reset all statistics"), _("Reset ALL statistics and logs for player\n%s ?") % p0, confirm=1, default=1): self.app.stats.resetStats(player, 0) self.game.updateStatus(stats=self.app.stats.getStats(self.app.opt.player, self.game.id)) elif mode == 302: # reset player stats for current game if self.game.areYouSure(_("Reset game statistics"), _('Reset statistics and logs for player\n%s\nand game\n%s ?') % (p0, n), confirm=1, default=1): self.app.stats.resetStats(player, self.game.id) self.game.updateStatus(stats=self.app.stats.getStats(self.app.opt.player, self.game.id)) elif mode == 401: # start a new game with a gameid if gameid and gameid != self.game.id: self.game.endGame() self.game.quitGame(gameid) elif mode == 402: # start a new game with a gameid / gamenumber ## TODO pass else: print_err("stats problem: %s %s %s" % (mode, demo, player)) pass if d.status != 0: break mode = d.button
def load(self, filename): # create ConfigObj instance try: config = configobj.ConfigObj(filename, configspec=configspec, encoding=self._config_encoding) except configobj.ParseError: traceback.print_exc() config = configobj.ConfigObj(configspec=configspec, encoding=self._config_encoding) self._config = config # create sections for section in ( 'general', 'sound_samples', 'fonts', 'colors', 'timeouts', 'cardsets', 'games_geometry', ): if section not in config: config[section] = {} # add initial comment if not os.path.exists(filename): config.initial_comment = ['-*- coding: %s -*-' % self._config_encoding] return # validation vdt = validate.Validator() res = config.validate(vdt) ##from pprint import pprint; pprint(res) if res is not True: for section, data in res.items(): if data is True: continue for key, value in data.items(): if value is False: print_err('config file: validation error: ' 'section: "%s", key: "%s"' % (section, key)) config[section][key] = None # general for key, t in self.GENERAL_OPTIONS: val = self._getOption('general', key, t) if val == 'None': setattr(self, key, None) elif val is not None: setattr(self, key, val) settings.TRANSLATE_GAME_NAMES = self.translate_game_names recent_gameid = self._getOption('general', 'recent_gameid', 'list') if recent_gameid is not None: try: self.recent_gameid = [int(i) for i in recent_gameid] except: traceback.print_exc() favorite_gameid = self._getOption('general', 'favorite_gameid', 'list') if favorite_gameid is not None: try: self.favorite_gameid = [int(i) for i in favorite_gameid] except: traceback.print_exc() visible_buttons = self._getOption('general', 'visible_buttons', 'list') if visible_buttons is not None: for key in TOOLBAR_BUTTONS: self.toolbar_vars[key] = (key in visible_buttons) # sound_samples for key in self.sound_samples: val = self._getOption('sound_samples', key, 'bool') if val is not None: self.sound_samples[key] = val # fonts for key in self.fonts: if key == 'default': continue val = self._getOption('fonts', key, 'str') if val is not None: try: val[1] = int(val[1]) except: traceback.print_exc() else: val = tuple(val) self.fonts[key] = val # colors for key in self.colors: val = self._getOption('colors', key, 'str') if val is not None: self.colors[key] = val # timeouts for key in self.timeouts: val = self._getOption('timeouts', key, 'float') if val is not None: self.timeouts[key] = val # cardsets for key in self.cardset: val = self._getOption('cardsets', str(key), 'list') if val is not None: try: self.cardset[int(key)] = val except: traceback.print_exc() # games_geometry for key, val in config['games_geometry'].items(): try: val = [int(i) for i in val] assert len(val) == 2 self.games_geometry[int(key)] = val except: traceback.print_exc()
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", "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 games if not opts['french-only']: import games.ultra import games.mahjongg import games.special # 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
-g --game=GAMENAME start game GAMENAME -i --gameid=GAMEID --french-only --sound-mod=MOD --nosound disable sound support --noplugins disable load plugins -h --help display this help and exit FILE - file name of a saved game MOD - one of following: pss(default), pygame, oss, win """) % prog_name return None if len(args) > 1: print_err( _("too many files\ntry %s --help for more information") % prog_name, 0) return None filename = args and args[0] or None if filename and not os.path.isfile(filename): print_err( _("invalid file name\ntry %s --help for more information") % prog_name, 0) return None return opts, filename # ************************************************************************ # * # ************************************************************************ def pysol_init(app, args):