예제 #1
0
 def test1(self):
     c = Config()
     
     c.from_dict({
         'static_files': {
             'root':'/path/to/root/',
             'filter':'*.jpg'
             },
            
         
         'users':{
             'id_property':'email',
             'data_dir':'/data/system/userdata/'
             },
         
         })
         
     self.assertDictEqual(c.get('users'), {
             'id_property':'email',
             'data_dir':'/data/system/userdata/'
             })
             
     self.assertDictEqual(c.get('static_files'), {
             'root':'/path/to/root/',
             'filter':'*.jpg'
             })
예제 #2
0
 def SetAllSoundFxObjectVolumes(
     self,
     volume=None
 ):  #MFH - single function to go through all sound objects (and iterate through all sound lists) and set object volume to the given volume
     #MFH TODO - set every sound object's volume here...
     if volume is None:
         self.sfxVolume = Config.get("audio", "SFX_volume")
         self.crowdVolume = Config.get("audio", "crowd_volume")
         volume = self.sfxVolume
     self.starDingSound.setVolume(volume)
     self.bassDrumSound.setVolume(volume)
     self.T1DrumSound.setVolume(volume)
     self.T2DrumSound.setVolume(volume)
     self.T3DrumSound.setVolume(volume)
     self.CDrumSound.setVolume(volume)
     for s in self.acceptSounds:
         s.setVolume(volume)
     for s in self.cancelSounds:
         s.setVolume(volume)
     self.rockSound.setVolume(volume)
     self.starDeActivateSound.setVolume(volume)
     self.starActivateSound.setVolume(volume)
     self.battleUsedSound.setVolume(volume)
     self.rescueSound.setVolume(volume)
     self.coOpFailSound.setVolume(volume)
     self.crowdSound.setVolume(self.crowdVolume)
     self.starReadySound.setVolume(volume)
     self.clapSound.setVolume(volume)
     self.failSound.setVolume(volume)
     self.starSound.setVolume(volume)
     self.startSound.setVolume(volume)
     self.selectSound1.setVolume(volume)
     self.selectSound2.setVolume(volume)
     self.selectSound3.setVolume(volume)
예제 #3
0
파일: Data.py 프로젝트: EdPassos/fofix
 def SetAllSoundFxObjectVolumes(
     self, volume=None
 ):  # MFH - single function to go through all sound objects (and iterate through all sound lists) and set object volume to the given volume
     # MFH TODO - set every sound object's volume here...
     if volume is None:
         self.sfxVolume = Config.get("audio", "SFX_volume")
         self.crowdVolume = Config.get("audio", "crowd_volume")
         volume = self.sfxVolume
     self.starDingSound.setVolume(volume)
     self.bassDrumSound.setVolume(volume)
     self.T1DrumSound.setVolume(volume)
     self.T2DrumSound.setVolume(volume)
     self.T3DrumSound.setVolume(volume)
     self.CDrumSound.setVolume(volume)
     for s in self.acceptSounds:
         s.setVolume(volume)
     for s in self.cancelSounds:
         s.setVolume(volume)
     self.rockSound.setVolume(volume)
     self.starDeActivateSound.setVolume(volume)
     self.starActivateSound.setVolume(volume)
     self.battleUsedSound.setVolume(volume)
     self.rescueSound.setVolume(volume)
     self.coOpFailSound.setVolume(volume)
     self.crowdSound.setVolume(self.crowdVolume)
     self.starReadySound.setVolume(volume)
     self.clapSound.setVolume(volume)
     self.failSound.setVolume(volume)
     self.starSound.setVolume(volume)
     self.startSound.setVolume(volume)
     self.selectSound1.setVolume(volume)
     self.selectSound2.setVolume(volume)
     self.selectSound3.setVolume(volume)
예제 #4
0
 def __init__(self):
     config = Config()
     self.myclient = pymongo.MongoClient(
         config.get('database', 'host'), int(config.get('database',
                                                        'port')))
     self.mydb = self.myclient[config.get('database', 'db_name')]
     self.mydb.authenticate(config.get('database', 'user'),
                            config.get('database', 'password'))
예제 #5
0
def get_dbcon():
    db = MySQLdb.connect(host=Config.get('Database', 'Host'),
                         user=Config.get('Database', 'User'),
                         passwd=Config.get('Database', 'Password'),
                         db=Config.get('Database', 'Database'),
                         charset='utf8')
    cur = db.cursor()
    cur.execute('SET NAMES utf8mb4')
    return db, cur
예제 #6
0
파일: Resource.py 프로젝트: vemel/fofix
    def __init__(self,
                 target,
                 name,
                 function,
                 resultQueue,
                 loaderSemaphore,
                 onLoad=None,
                 onCancel=None):
        Thread.__init__(self)
        self.semaphore = loaderSemaphore
        self.target = target
        self.name = name
        self.function = function
        self.resultQueue = resultQueue
        self.result = None
        self.onLoad = onLoad
        self.onCancel = onCancel
        self.exception = None
        self.time = 0.0
        self.canceled = False

        #myfingershurt: the following should be global and done ONCE:
        self.logLoadings = Config.get("game", "log_loadings")

        if target and name:
            setattr(target, name, None)
예제 #7
0
파일: Resource.py 프로젝트: vemel/fofix
    def setPriority(self, pid=None, priority=2):
        """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
            2 is normal priority.  Default sets the priority of the current
            python process but can take any valid process ID. """

        import win32api, win32process, win32con

        priorityClasses = [
            win32process.IDLE_PRIORITY_CLASS,
            win32process.BELOW_NORMAL_PRIORITY_CLASS,
            win32process.NORMAL_PRIORITY_CLASS,
            win32process.ABOVE_NORMAL_PRIORITY_CLASS,
            win32process.HIGH_PRIORITY_CLASS,
            win32process.REALTIME_PRIORITY_CLASS
        ]

        threadPriorities = [
            win32process.THREAD_PRIORITY_IDLE,
            #win32process.THREAD_PRIORITY_ABOVE_IDLE,
            #win32process.THREAD_PRIORITY_LOWEST,
            win32process.THREAD_PRIORITY_BELOW_NORMAL,
            win32process.THREAD_PRIORITY_NORMAL,
            win32process.THREAD_PRIORITY_ABOVE_NORMAL,
            win32process.THREAD_PRIORITY_HIGHEST,
            win32process.THREAD_PRIORITY_TIME_CRITICAL
        ]

        pid = win32api.GetCurrentProcessId()
        tid = win32api.GetCurrentThread()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, priorityClasses[priority])
        win32process.SetThreadPriority(tid, threadPriorities[priority])
        if Config.get('performance', 'restrict_to_first_processor'):
            win32process.SetProcessAffinityMask(handle, 1)
async def get_ts_daily_adjusted(symbol: str, config: Config, cache: bool = True) -> pd.DataFrame:
    """Returns time series data for the given symbol using the Alpha Vantage api in an
    async method."""
    ts = TimeSeries(key=config.get('key', 'ALPHA_VANTAGE'),
                    output_format='pandas')
    try:
        data, _ = await ts.get_daily_adjusted(symbol, outputsize='full')
    except ValueError as e:
        if 'higher API call' in str(e):
            raise ce.RateLimited
        elif 'Invalid API call' in str(e):
            raise ce.UnknownAVType
        else:
            raise
    idx = pd.date_range(min(data.index), max(data.index))
    data = data.reindex(idx[::-1])
    data['4. close'].fillna(method='backfill', inplace=True)
    data['5. adjusted close'].fillna(method='backfill', inplace=True)
    data['6. volume'].fillna(0.0, inplace=True)
    data['7. dividend amount'].fillna(0.0, inplace=True)
    data.apply(lambda x: x.fillna(data['4. close'], inplace=True)
               if x.name in ['1. open',
                             '2. high',
                             '3. low']
               else x.fillna(1.0, inplace=True))
    data.index.name = 'date'
    data = meta_label_columns(data, symbol)
    if cache:
        save_data(name_generator(
            symbol, IngestTypes.TimeSeriesDailyAdjusted), data)
    await ts.close()
    return data
예제 #9
0
    def setPriority(self, pid = None, priority = 2):
        """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
            2 is normal priority.  Default sets the priority of the current
            python process but can take any valid process ID. """

        import win32api, win32process, win32con

        priorityClasses = [win32process.IDLE_PRIORITY_CLASS,
                           win32process.BELOW_NORMAL_PRIORITY_CLASS,
                           win32process.NORMAL_PRIORITY_CLASS,
                           win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                           win32process.HIGH_PRIORITY_CLASS,
                           win32process.REALTIME_PRIORITY_CLASS]

        threadPriorities = [win32process.THREAD_PRIORITY_IDLE,
                            #win32process.THREAD_PRIORITY_ABOVE_IDLE,
                            #win32process.THREAD_PRIORITY_LOWEST,
                            win32process.THREAD_PRIORITY_BELOW_NORMAL,
                            win32process.THREAD_PRIORITY_NORMAL,
                            win32process.THREAD_PRIORITY_ABOVE_NORMAL,
                            win32process.THREAD_PRIORITY_HIGHEST,
                            win32process.THREAD_PRIORITY_TIME_CRITICAL]

        pid = win32api.GetCurrentProcessId()
        tid = win32api.GetCurrentThread()
        handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
        win32process.SetPriorityClass(handle, priorityClasses[priority])
        win32process.SetThreadPriority(tid, threadPriorities[priority])
        if Config.get('performance', 'restrict_to_first_processor'):
            win32process.SetProcessAffinityMask(handle, 1)
예제 #10
0
def cmd_pq(update: Update, context: CallbackContext):
    ci, fro, fron, froi = cifrofron(update)
    msg = update.message
    if (not msg.reply_to_message) or (msg.reply_to_message.from_user.id !=
                                      context.bot.id):
        cmdreply(context.bot, ci, '<send that as a reply to my message!>')
        return

    repl = msg.reply_to_message
    replid = repl.message_id

    if (repl.sticker or not repl.text):
        cmdreply(context.bot, ci, '<only regular text messages are supported>')
        return
    if (replid in pqed_messages) or (already_pqd(repl.text)):
        cmdreply(context.bot, ci, '<message already forwarded>')
        return
    if replid in command_replies:
        cmdreply(context.bot, ci, '<that is a silly thing to forward!>')
        return
    if pq_limit_check(froi) >= 5:
        cmdreply(context.bot, ci, '<slow down a little!>')
        return
    context.bot.forwardMessage(chat_id=Config.get('Telegram', 'QuoteChannel'),
                               from_chat_id=ci,
                               message_id=replid)
    pqed_messages.add(replid)
    log_pq(ci, froi, repl.text)
async def get_cc_daily(symbol: str, config: Config, market: str = 'USD',
                       sanitize: bool = True, cache: bool = True) -> pd.DataFrame:
    """Returns CryptoCurrency data for the given symbol using the Alpha Vantage api in an
    async method."""
    cc = CryptoCurrencies(key=config.get('key', 'ALPHA_VANTAGE'),
                          output_format='pandas')
    try:
        data, _ = await cc.get_digital_currency_daily(symbol, market)
    except ValueError as e:
        if 'higher API call' in str(e):
            raise ce.RateLimited
        elif 'Invalid API call' in str(e):
            raise ce.UnknownAVType
        else:
            raise
    if sanitize:
        data = data[~(data.index >= datetime.now().date().strftime('%Y%m%d'))]
        cols = [x for x in data.columns if 'b. ' in x]
        data = data.drop(cols, axis=1)
    data = meta_label_columns(data, symbol)
    if cache:
        save_data(name_generator(
            symbol, IngestTypes.CryptoCurrenciesDaily), data)
    await cc.close()
    return data
예제 #12
0
def _get_hot_slice_by_threads(rlbb, nav_slice):
    ops_and_scores = rlbb.with_scores[nav_slice] if rlbb else []

    ops = [Comment(id=id) for (id, score) in ops_and_scores]

    max_from_thread = 3

    # Got the OPs, now I need to bulk fetch the top replies.
    pipeline = redis.pipeline()
    for comment in ops:
        pipeline.get(comment.redis_score.key)

    for comment in ops:
        pipeline.zrevrange(comment.popular_replies.key, 0, max_from_thread - 1, withscores=True)

    results = pipeline.execute()

    op_scores, pop_reply_lists = results[:len(ops)], results[len(ops):]

    ids = []

    if ops_and_scores:
        # Lowest score sets the threshold, but replies get a "boost" factor
        cutoff = ops_and_scores[-1][1] / Config.get('reply_boost', 1)
        for op, op_score, pop_replies in zip(ops, op_scores, pop_reply_lists):
            items = [(int(id), float(score or 0)) for (id,score) in [(op.id, op_score)] + pop_replies]
            items.sort(key=lambda (id, score): -score)
            ids += [id for (id, score) in items if score >= cutoff][:max_from_thread]

    return ids
예제 #13
0
def should_reply(bot, msg, ci, txt=None):
    if msg and msg.reply_to_message and msg.reply_to_message.from_user.id == bot.id:
        return True and can_send_message(bot, ci)
    if not txt:
        txt = msg.text
    if txt and (Config.get('Chat', 'Keyword') in txt.lower()):
        return True and can_send_message(bot, ci)
    rp = option_get_float(ci, 'reply_prob', 1, 0.02)
    return (uniform(0, 1) < rp) and can_send_message(bot, ci)
예제 #14
0
 def outfun(*args, **kwargs):
     db = MySQLdb.connect(host=Config.get('Database', 'Host'),
                          user=Config.get('Database', 'User'),
                          passwd=Config.get('Database', 'Password'),
                          db=Config.get('Database', 'Database'),
                          charset='utf8')
     try:
         with db as cur:
             cur = db.cursor()
             cur.execute('SET NAMES utf8mb4')
             ret = infun(cur, *args, **kwargs)
             db.commit()
             if cur in cursor_oncommit:
                 for act in cursor_oncommit[cur]:
                     act[0][act[1]] = act[2]
             return ret
     finally:
         db.close()
예제 #15
0
def setup_logging():
    verbose = Config.getboolean('Logging', 'VerboseStdout')
    console = logging.StreamHandler()
    console.setLevel(logging.INFO if verbose else logging.WARNING)
    logfile = logging.FileHandler(Config.get('Logging', 'Logfile'))
    logfile.setLevel(logging.INFO)
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO,
        handlers=[console, logfile])
예제 #16
0
    def __init__(self, dataPath = os.path.join("..", "data")):
        self.resultQueue = Queue()
        self.dataPaths = [dataPath]
        self.loaderSemaphore = BoundedSemaphore(value = 1)
        self.loaders = []

        #myfingershurt: the following should be global, and only done at startup.  Not every damn time a file is loaded.
        self.songPath = []
        self.baseLibrary = Config.get("setlist", "base_library")
        #evilynux - Support for songs in ~/.fretsonfire/songs (GNU/Linux and MacOS X)
        if self.baseLibrary == "None" and os.name == "posix":
            path = os.path.expanduser("~/." + Version.PROGRAM_UNIXSTYLE_NAME)
            if os.path.isdir(path):
                self.baseLibrary = path
                Config.set("setlist", "base_library", path)

        if self.baseLibrary and os.path.isdir(self.baseLibrary):
            self.songPath = [self.baseLibrary]

        self.logLoadings = Config.get("game", "log_loadings")
예제 #17
0
파일: Resource.py 프로젝트: vemel/fofix
    def __init__(self, dataPath=os.path.join("..", "data")):
        self.resultQueue = Queue()
        self.dataPaths = [dataPath]
        self.loaderSemaphore = BoundedSemaphore(value=1)
        self.loaders = []

        #myfingershurt: the following should be global, and only done at startup.  Not every damn time a file is loaded.
        self.songPath = []
        self.baseLibrary = Config.get("setlist", "base_library")
        #evilynux - Support for songs in ~/.fretsonfire/songs (GNU/Linux and MacOS X)
        if self.baseLibrary == "None" and os.name == "posix":
            path = os.path.expanduser("~/." + Version.PROGRAM_UNIXSTYLE_NAME)
            if os.path.isdir(path):
                self.baseLibrary = path
                Config.set("setlist", "base_library", path)

        if self.baseLibrary and os.path.isdir(self.baseLibrary):
            self.songPath = [self.baseLibrary]

        self.logLoadings = Config.get("game", "log_loadings")
예제 #18
0
파일: Resource.py 프로젝트: vemel/fofix
 def run(self):
     self.semaphore.acquire()
     game_priority = Config.get("performance", "game_priority")
     # Reduce priority on posix
     if os.name == "posix":
         # evilynux - Beware, os.nice _decreases_ priority, hence the reverse logic
         os.nice(5 - game_priority)
     elif os.name == "nt":
         self.setPriority(priority=game_priority)
     self.load()
     self.semaphore.release()
     self.resultQueue.put(self)
예제 #19
0
 def process_photo_reply(_context):
     put(ci, ocrtext)
     if (Config.get('Chat', 'Keyword') in ocrtext.lower()):
         logging.info('sending reply')
         sendreply(_context.bot,
                   ci,
                   fro,
                   froi,
                   fron,
                   replyto=update.message.message_id,
                   conversation=update.message.chat,
                   user=update.message.from_user)
예제 #20
0
 def run(self):
     self.semaphore.acquire()
     game_priority = Config.get("performance", "game_priority")
     # Reduce priority on posix
     if os.name == "posix":
         # evilynux - Beware, os.nice _decreases_ priority, hence the reverse logic
         os.nice(5 - game_priority)
     elif os.name == "nt":
         self.setPriority(priority = game_priority)
     self.load()
     self.semaphore.release()
     self.resultQueue.put(self)
예제 #21
0
파일: Player.py 프로젝트: vemel/fofix
    def __init__(self, name, number):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Player class init (Player.py)...")

        self.name     = name

        self.reset()
        self.keyList     = None

        self.progressKeys = []
        self.drums        = []
        self.keys         = []
        self.soloKeys     = []
        self.soloShift    = None
        self.soloSlide    = False
        self.actions      = []
        self.yes          = []
        self.no           = []
        self.conf         = []
        self.up           = []
        self.down         = []
        self.left         = []
        self.right        = []
        self.controller   = -1
        self.controlType  = -1

        self.guitarNum    = None
        self.number       = number

        self.bassGrooveEnabled = False
        self.currentTheme = 1

        self.lefty       = _playerDB.execute('SELECT `lefty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.twoChordMax = _playerDB.execute('SELECT `twochord` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.drumflip    = _playerDB.execute('SELECT `drumflip` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.assistMode  = _playerDB.execute('SELECT `assist` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.autoKick    = _playerDB.execute('SELECT `autokick` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neck        = _playerDB.execute('SELECT `neck` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.neckType    = _playerDB.execute('SELECT `necktype` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self.whichPart   = _playerDB.execute('SELECT `part` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._upname      = _playerDB.execute('SELECT `upname` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        self._difficulty  = _playerDB.execute('SELECT `difficulty` FROM `players` WHERE `name` = ?', [self.name]).fetchone()[0]
        #MFH - need to store selected practice mode and start position here
        self.practiceMode = False
        self.practiceSpeed = 1.0
        self.practiceSection = None
        self.startPos = 0.0

        self.hopoFreq = None
예제 #22
0
def changeconfiguration():
    section = request.form.get('section')
    key = request.form.get('key')
    value = request.form.get('value')

    # solution for checkboxes
    if value is None:
        value = "False"

    Config.update(section, key, value)
    # check if logging changed
    if section == "logging":
        deque_handler.setnrentries(int(Config.get('logging', 'maxlogentries')))
    return redirect(url_for('.showconfiguration'))
예제 #23
0
파일: Player.py 프로젝트: vemel/fofix
def deleteControl(control):
    VFS.unlink(_makeControllerIniName(control))
    defaultUsed = -1
    for i in range(4):
        get = Config.get("game", "control%d" % i)
        if get == control:
            if i == 0:
                Config.set("game", "control%d" % i, "defaultg")
                defaultUsed = 0
            else:
                Config.set("game", "control%d" % i, None)
        if get == "defaultg" and defaultUsed > -1:
            Config.set("game", "control%d" % i, None)
    loadControls()
예제 #24
0
 def test5(self):
     s = Config()
     s.from_dict({
             'root':'/path/to/root/',
             'filter':'*.jpg'
             })
         
     c = Config()
     c.set('static_files', s)
     
     self.assertDictEqual(c.get('static_files'), {
             'root':'/path/to/root/',
             'filter':'*.jpg'
             })
예제 #25
0
파일: Player.py 프로젝트: vemel/fofix
def setNewKeyMapping(engine, config, section, option, key):
    oldKey = config.get(section, option)
    config.set(section, option, key)
    keyCheckerMode = Config.get("game", "key_checker_mode")
    if key == "None" or key is None:
        return True
    b = isKeyMappingOK(config, option)
    if b != 0:
        if keyCheckerMode > 0:
            from views import Dialogs
            Dialogs.showMessage(engine, _("This key conflicts with the following keys: %s") % str(b))
        if keyCheckerMode == 2:   #enforce no conflicts!
            config.set(section, option, oldKey)
        return False
    return True
예제 #26
0
파일: Shader.py 프로젝트: vemel/fofix
    def checkIfEnabled(self):
        if Config.get("video","shader_use"):
            if self.enabled:
                self.turnon = True
            else:
                self.set(os.path.join(Version.dataPath(), "shaders"))
        else:
            self.turnon = False

        if self.turnon:
            for i in self.shaders.keys():
                try:
                    value = Config.get("video","shader_"+i)
                    if value != "None":
                        if value == "theme":
                            if isTrue(Config.get("theme","shader_"+i).lower()):
                                value = i
                            else:
                                continue
                        self.assigned[i] = value
                except KeyError:
                    continue
            return True
        return False
예제 #27
0
 def updateHandicapValue(self):
     self.handicapValue = 100.0
     slowdown = Config.get("audio", "speed_factor")
     earlyHitHandicap = 1.0  #self.earlyHitWindowSizeHandicap #akedrou - replace when implementing handicap.
     for j in range(len(HANDICAPS)):
         if (self.handicap >> j) & 1 == 1:
             if j == 1:  #scalable
                 if slowdown != 1:
                     if slowdown < 1:
                         cut = (100.0**slowdown) / 100.0
                     else:
                         cut = (100.0 * slowdown) / 100.0
                     self.handicapValue *= cut
                 if earlyHitHandicap != 1.0:
                     self.handicapValue *= earlyHitHandicap
             else:
                 self.handicapValue *= HANDICAPS[j]
예제 #28
0
 def updateHandicapValue(self):
     self.handicapValue = 100.0
     slowdown = Config.get("audio","speed_factor")
     earlyHitHandicap      = 1.0 #self.earlyHitWindowSizeHandicap #akedrou - replace when implementing handicap.
     for j in range(len(HANDICAPS)):
         if (self.handicap>>j)&1 == 1:
             if j == 1: #scalable
                 if slowdown != 1:
                     if slowdown < 1:
                         cut = (100.0**slowdown)/100.0
                     else:
                         cut = (100.0*slowdown)/100.0
                     self.handicapValue *= cut
                 if earlyHitHandicap != 1.0:
                     self.handicapValue *= earlyHitHandicap
             else:
                 self.handicapValue *= HANDICAPS[j]
예제 #29
0
    def __init__(self, target, name, function, resultQueue, loaderSemaphore, onLoad = None, onCancel = None):
        Thread.__init__(self)
        self.semaphore   = loaderSemaphore
        self.target      = target
        self.name        = name
        self.function    = function
        self.resultQueue = resultQueue
        self.result      = None
        self.onLoad      = onLoad
        self.onCancel    = onCancel
        self.exception   = None
        self.time        = 0.0
        self.canceled    = False

        #myfingershurt: the following should be global and done ONCE:
        self.logLoadings = Config.get("game", "log_loadings")

        if target and name:
            setattr(target, name, None)
예제 #30
0
    def get_ngsi(self):
        ngsi = {
            "type": "Property",
            "value": "NA",  # value set to NA as it cannot be null in ngsi-ld
        }
        enable_na = Config.get('semanticenrichment', 'enablena')
        if enable_na == "False":
            if self.lastValue != 'NA':
                ngsi['qoi:hasAbsoluteValue'] = {
                    "type": "Property",
                    "value": self.lastValue
                }
            if self.rp.value() != 'NA':
                ngsi['qoi:hasRatedValue'] = {
                    "type": "Property",
                    "value": self.rp.value()
                }
        else:
            ngsi['qoi:hasAbsoluteValue'] = {
                "type": "Property",
                "value": self.lastValue
            }
            ngsi['qoi:hasRatedValue'] = {
                "type": "Property",
                "value": self.rp.value()
            }

        for submetric in self.submetrics:
            ngsi[submetric.name] = submetric.get_ngsi()

        # check if metric contains entries if na values are not enables
        if enable_na == "False":
            if len(ngsi) <= 2:
                return None

        return ngsi
예제 #31
0
파일: Data.py 프로젝트: EdPassos/fofix
    def __init__(self, resource, svg):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Data class init (Data.py)...")
        self.logLoadings = Config.get("game", "log_loadings")

        self.logImageNotFound = Config.get("log", "log_image_not_found")

        self.resource = resource
        self.svg = svg

        self.sfxVolume = Config.get("audio", "SFX_volume")
        self.crowdVolume = Config.get("audio", "crowd_volume")

        # Get theme
        themename = Config.get("coffee", "themename")
        self.themeLabel = themename
        self.themeCoOp = False

        self.players = None
        self.players = Player.loadPlayers()

        # myfingershurt: check for existence of theme path
        themepath = os.path.join(Version.dataPath(), "themes")
        self.themepath = themepath
        self.path = Version.dataPath()

        if not self.checkImgDrawing(os.path.join("themes", themename, "notes", "notes.png")):
            # myfingershurt: here need to ensure an existing theme is selected
            themes = []
            defaultTheme = None  # myfingershurt
            allthemes = os.listdir(themepath)
            for name in allthemes:
                if self.checkImgDrawing(os.path.join("themes", name, "notes", "notes.png")):
                    themes.append(name)
                    if name == "MegaLight V4":  # myfingershurt
                        defaultTheme = name  # myfingershurt
            if defaultTheme != "MegaLight V4":  # myfingershurt
                defaultTheme = themes[0]  # myfingershurt
            # not a valid theme if notes.png isn't there!  Force default theme:
            Config.set("coffee", "themename", defaultTheme)
            # re-init Data with new default
            themename = defaultTheme
            self.themeLabel = themename

        if not os.path.exists(os.path.join(Version.dataPath(), "themes", themename, "vocals")):
            self.vocalPath = "vocals"
        else:
            self.vocalPath = os.path.join("themes", themename, "vocals")

        self.theme = 2
        self.themeCoOp = True

        self.fontScreenBottom = (
            0.75
        )  # from our current viewport's constant 3:4 aspect ratio (which is always stretched to fill the video resolution)

        self.loadPartImages()
        # myfingershurt: multi-OS compatibility file access fixes using os.path.join()
        # load font customization images

        # Worldrave - Use new defined Star3 and star4. Using star1 and star2 as a fallback.

        # MFH - no more custom glyphs, these are wasting memory.
        # MFH - but we do need these star1-4 images anyway.  Leaving them loaded here in the Data object.
        self.loadImgDrawing(self, "star1", os.path.join("themes", themename, "star1.png"), textureSize=(128, 128))
        self.loadImgDrawing(self, "star2", os.path.join("themes", themename, "star2.png"), textureSize=(128, 128))

        # MFH - let's not rely on errors here if we don't have to...
        if not self.loadImgDrawing(
            self, "star3", os.path.join("themes", themename, "star3.png"), textureSize=(128, 128)
        ):
            self.star3 = self.star1
        if not self.loadImgDrawing(
            self, "star4", os.path.join("themes", themename, "star4.png"), textureSize=(128, 128)
        ):
            self.star4 = self.star2

        if self.loadImgDrawing(
            self, "starPerfect", os.path.join("themes", themename, "starperfect.png"), textureSize=(128, 128)
        ):
            self.perfectStars = True
            self.maskStars = False
        else:
            self.starPerfect = self.star2
            self.fcStars = False
            self.starFC = self.star2
            self.maskStars = True
            self.perfectStars = False

        if self.perfectStars:
            if self.loadImgDrawing(
                self, "starFC", os.path.join("themes", themename, "starfc.png"), textureSize=(128, 128)
            ):
                self.fcStars = True
            else:
                self.starFC = self.starPerfect
                self.fcStars = False

        # load misc images
        self.loadImgDrawing(
            self, "loadingImage", os.path.join("themes", themename, "loadingbg.png"), textureSize=(256, 256)
        )
        self.loadImgDrawing(self, "optionsBG", os.path.join("themes", themename, "menu", "optionsbg.png"))
        if self.loadImgDrawing(self, "submenuSelect", os.path.join("themes", themename, "submenuselect.png")):
            subSelectImgW = self.submenuSelect.width1()
            self.submenuSelectFound = True
            self.subSelectWFactor = 640.000 / subSelectImgW
            self.subSelectImgH = self.submenuSelect.height1()
        else:
            self.submenuSelectFound = False
            self.loadImgDrawing(self, "submenuSelect", os.path.join("themes", themename, "menu", "selected.png"))
            self.subSelectWFactor = 0
        # load all the data in parallel
        # asciiOnly = not bool(Language.language) or Language.language == "Custom"
        # reversed  = _("__lefttoright__") == "__righttoleft__" and True or False
        asciiOnly = True
        reversed = False
        scale = 1
        # evilynux - Load bigger fonts so they're nicer when scaled, scaling readjusted
        fontSize = [44, 132, 34, 32, 30]
        w, h = [int(s) for s in Config.get("video", "resolution").split("x")]
        aspectRatio = float(w) / float(h)

        self.fontList = [
            ["font1", "font", "default.ttf", fontSize[4]],
            ["font2", "bigFont", "title.ttf", fontSize[1]],
            ["font3", "pauseFont", "pause.ttf", fontSize[2]],
            ["font4", "scoreFont", "score.ttf", fontSize[3]],
            ["font5", "streakFont", "streak.ttf", fontSize[3]],
            ["font6", "loadingFont", "loading.ttf", fontSize[3]],
            ["font7", "songFont", "song.ttf", fontSize[4]],
            ["font8", "songListFont", "songlist.ttf", fontSize[3]],
            ["font9", "shadowFont", "songlist.ttf", fontSize[3]],
            ["font10", "streakFont2", "streakphrase.ttf", fontSize[2]],
        ]
        for f in self.fontList:
            if self.fileExists(os.path.join("themes", themename, "fonts", f[2])):
                fn = resource.fileName(os.path.join("themes", themename, "fonts", f[2]))
                f[0] = lambda: Font(
                    fn,
                    f[3],
                    scale=scale * 0.5,
                    reversed=reversed,
                    systemFont=not asciiOnly,
                    outline=False,
                    aspectRatio=aspectRatio,
                )
                resource.load(self, f[1], f[0], synch=True)
            elif self.fileExists(os.path.join("themes", themename, "fonts", "default.ttf")):
                Log.debug("Theme font not found: " + f[2])
                fn = resource.fileName(os.path.join("themes", themename, "fonts", "default.ttf"))
                f[0] = lambda: Font(
                    fn,
                    f[3],
                    scale=scale * 0.5,
                    reversed=reversed,
                    systemFont=not asciiOnly,
                    outline=False,
                    aspectRatio=aspectRatio,
                )
                resource.load(self, f[1], f[0], synch=True)
            else:
                Log.debug("Default theme font not found: %s - using built-in default" % str(f[2]))
                fn = resource.fileName(os.path.join("fonts", "default.ttf"))
                f[0] = lambda: Font(
                    fn,
                    f[3],
                    scale=scale * 0.5,
                    reversed=reversed,
                    systemFont=not asciiOnly,
                    outline=False,
                    aspectRatio=aspectRatio,
                )
                resource.load(self, f[1], f[0], synch=True)

        self.fontDict = {
            "font": self.font,
            "bigFont": self.bigFont,
            "pauseFont": self.pauseFont,
            "scoreFont": self.scoreFont,
            "streakFont": self.streakFont,
            "songFont": self.songFont,
            "streakFont2": self.streakFont2,
            "songListFont": self.songListFont,
            "shadowFont": self.shadowFont,
            "loadingFont": self.loadingFont,
        }

        assert self.fontDict["font"] == self.font

        # load sounds asynchronously
        resource.load(self, "screwUpsounds", self.loadScrewUpsounds)
        resource.load(self, "screwUpsoundsBass", self.loadScrewUpsoundsBass)
        resource.load(self, "screwUpsoundsDrums", self.loadScrewUpsoundsDrums)
        resource.load(self, "acceptSounds", self.loadAcceptSounds)
        resource.load(self, "cancelSounds", self.loadBackSounds)

        # loadSoundEffect asynchronously
        self.syncSounds = [
            ["bassDrumSound", "bassdrum.ogg"],
            ["battleUsedSound", "battleused.ogg"],
            ["CDrumSound", "crash.ogg"],
            ["clapSound", "clapsound.ogg"],
            ["coOpFailSound", "coopfail.ogg"],
            # ["crowdSound","crowdcheers.ogg"],
            ["failSound", "failsound.ogg"],
            ["rescueSound", "rescue.ogg"],
            ["rockSound", "rocksound.ogg"],
            ["selectSound1", "select1.ogg"],
            ["selectSound2", "select2.ogg"],
            ["selectSound3", "select3.ogg"],
            ["starActivateSound", "staractivate.ogg"],
            ["starDeActivateSound", "stardeactivate.ogg"],
            ["starDingSound", "starding.ogg"],
            ["starLostSound", "starlost.ogg"],
            ["starReadySound", "starpowerready.ogg"],
            ["starSound", "starpower.ogg"],
            ["startSound", "start.ogg"],
            ["T1DrumSound", "tom01.ogg"],
            ["T2DrumSound", "tom02.ogg"],
            ["T3DrumSound", "tom03.ogg"],
        ]
        for self.sounds in self.syncSounds:
            if self.fileExists(os.path.join("themes", themename, "sounds", self.sounds[1])):
                self.loadSoundEffect(self, self.sounds[0], os.path.join("themes", themename, "sounds", self.sounds[1]))
            elif self.fileExists(os.path.join("sounds", self.sounds[1])):
                Log.debug("Theme sound not found: " + self.sounds[1])
                self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds", self.sounds[1]))
            else:
                Log.warn("File " + self.sounds[1] + " not found using default instead.")
                self.loadSoundEffect(self, self.sounds[0], os.path.join("sounds", "default.ogg"))

        # TODO: Simplify crowdSound stuff so it can join the rest of us.
        # MFH - fallback on sounds/crowdcheers.ogg, and then starpower.ogg. Note if the fallback crowdcheers was used or not.
        if self.fileExists(os.path.join("themes", themename, "sounds", "crowdcheers.ogg")):
            self.loadSoundEffect(
                self, "crowdSound", os.path.join("themes", themename, "sounds", "crowdcheers.ogg"), crowd=True
            )
            self.cheerSoundFound = 2
        elif self.fileExists(os.path.join("sounds", "crowdcheers.ogg")):
            self.loadSoundEffect(self, "crowdSound", os.path.join("sounds", "crowdcheers.ogg"), crowd=True)
            self.cheerSoundFound = 1
            Log.warn(themename + "/sounds/crowdcheers.ogg not found -- using data/sounds/crowdcheers.ogg instead.")
        else:
            self.cheerSoundFound = 0
            Log.warn("crowdcheers.ogg not found -- no crowd cheering.")
예제 #32
0
    def __init__(self):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Input class init (Input.py)...")

        Task.__init__(self)
        self.mouse                = pygame.mouse
        self.mouseListeners       = []
        self.keyListeners         = []
        self.systemListeners      = []
        self.priorityKeyListeners = []
        self.controls             = Controls()
        self.activeGameControls   = []
        self.p2Nav                = self.controls.p2Nav
        self.type1                = self.controls.type[0]
        self.keyCheckerMode       = Config.get("game","key_checker_mode")
        self.disableKeyRepeat()

        self.gameGuitars = 0
        self.gameDrums   = 0
        self.gameMics    = 0
        self.gameBots    = 0

        # Initialize joysticks
        pygame.joystick.init()
        self.joystickNames = {}
        self.joystickAxes  = {}
        self.joystickHats  = {}

        self.joysticks = [pygame.joystick.Joystick(id) for id in range(pygame.joystick.get_count())]
        for j in self.joysticks:
            j.init()
            self.joystickNames[j.get_id()] = j.get_name()
            self.joystickAxes[j.get_id()]  = [0] * j.get_numaxes()
            self.joystickHats[j.get_id()]  = [(0, 0)] * j.get_numhats()
        Log.debug("%d joysticks found." % len(self.joysticks))

        # Enable music events
        Audio.Music.setEndEvent(MusicFinished)
        #Audio.Music.setEndEvent()   #MFH - no event required?

        # Custom key names
        self.getSystemKeyName = pygame.key.name
        pygame.key.name       = self.getKeyName

        self.midi = []
        if haveMidi:
            pygame.midi.init()
            for i in range(pygame.midi.get_count()):
                interface, name, is_input, is_output, is_opened = pygame.midi.get_device_info(i)
                Log.debug("Found MIDI device: %s on %s" % (name, interface))
                if not is_input:
                    Log.debug("MIDI device is not an input device.")
                    continue
                try:
                    self.midi.append(pygame.midi.Input(i))
                    Log.debug("Device opened as device number %d." % len(self.midi))
                except pygame.midi.MidiException:
                    Log.error("Error opening device for input.")
            if len(self.midi) == 0:
                Log.debug("No MIDI input ports found.")
        else:
            Log.notice("MIDI input support is not available; install at least pygame 1.9 to get it.")
예제 #33
0
 def refreshBaseLib(self):
     self.baseLibrary = Config.get("setlist", "base_library")
     if self.baseLibrary and os.path.isdir(self.baseLibrary):
         self.songPath = [self.baseLibrary]
예제 #34
0
파일: Player.py 프로젝트: vemel/fofix
    def __init__(self):

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("Controls class init (Player.py)...")
        self.controls = []
        self.controls.append(Config.get("game", "control0"))
        self.controls.append(Config.get("game", "control1"))
        self.controls.append(Config.get("game", "control2"))
        self.controls.append(Config.get("game", "control3"))
        self.config = []
        self.controlList = []
        self.maxplayers = 0
        self.guitars    = 0
        self.drums      = 0
        self.mics       = 0
        self.overlap    = []

        self.p2Nav = Config.get("game", "p2_menu_nav")
        self.drumNav = Config.get("game", "drum_navigation")

        self.keyCheckerMode = Config.get("game","key_checker_mode")

        if VFS.isfile(_makeControllerIniName(self.controls[0])):
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[0])), type = 1))
            if VFS.isfile(_makeControllerIniName(self.controls[1])) and self.controls[1] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[1])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control1", None)
                self.controls[1] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[2])) and self.controls[2] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[2])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control2", None)
                self.controls[2] = "None"
            if VFS.isfile(_makeControllerIniName(self.controls[3])) and self.controls[3] != "None":
                self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName(self.controls[3])), type = 1))
            else:
                self.config.append(None)
                Config.set("game", "control3", None)
                self.controls[3] = "None"
        else:
            confM = None
            if Microphone.supported:
                confM = Config.load(VFS.resolveRead(_makeControllerIniName("defaultm")), type = 1)
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultg")), type = 1))
            self.config.append(Config.load(VFS.resolveRead(_makeControllerIniName("defaultd")), type = 1))
            self.config.append(confM)
            self.config.append(None)
            Config.set("game", "control0", "defaultg")
            Config.set("game", "control1", "defaultd")
            self.controls = ["defaultg", "defaultd"]
            if confM is not None:
                Config.set("game", "control2", "defaultm")
                self.controls.append("defaultm")
            else:
                Config.set("game", "control2", None)
                self.controls.append("None")
            Config.set("game", "control3", None)
            self.controls.append("None")

        self.type       = []
        self.analogKill = []
        self.analogSP   = []
        self.analogSPThresh = []
        self.analogSPSense  = []
        self.analogDrum = [] #FIXME: Analog Drum
        self.analogSlide = []
        self.analogFX   = [] #FIXME: Analog FX
        self.twoChord   = []
        self.micDevice  = []  #stump
        self.micTapSensitivity = []
        self.micPassthroughVolume = []

        self.flags = 0

        for i in self.config:
            if i:
                type = i.get("controller", "type")
                if type == 5:
                    self.mics += 1
                elif type > 1:
                    self.guitars += 1
                else:
                    self.drums += 1
                self.type.append(type)
                self.analogKill.append(i.get("controller", "analog_kill"))
                self.analogSP.append(i.get("controller", "analog_sp"))
                self.analogSPThresh.append(i.get("controller", "analog_sp_threshold"))
                self.analogSPSense.append(i.get("controller", "analog_sp_sensitivity"))
                self.analogDrum.append(i.get("controller", "analog_drum")) #FIXME: Analog Drum
                self.analogSlide.append(i.get("controller", "analog_slide"))
                self.analogFX.append(i.get("controller", "analog_fx")) #FIXME: Analog FX
                self.micDevice.append(i.get("controller", "mic_device"))  #stump
                self.micTapSensitivity.append(i.get("controller", "mic_tap_sensitivity"))
                self.micPassthroughVolume.append(i.get("controller", "mic_passthrough_volume"))
                self.twoChord.append(i.get("controller", "two_chord_max"))
                self.controlList.append(i.get("controller", "name"))
            else:
                self.type.append(None)
                self.analogKill.append(None)
                self.analogSP.append(None)
                self.analogFX.append(None) #FIXME: Analog FX
                self.twoChord.append(None)

        def keycode(name, config):
            if not config:
                return "None"
            k = config.get("controller", name)
            if k == "None":
                return "None"
            try:
                return int(k)
            except:
                return getattr(pygame, k)

        self.controlMapping = {}
        global menuUp, menuDown, menuNext, menuPrev, menuYes, menuNo
        global drum1s, drum2s, drum3s, drum4s, drum5s, bassdrums
        global key1s, key2s, key3s, key4s, key5s, keysolos, action1s, action2s, kills
        menuUp = []
        menuDown = []
        menuNext = []
        menuPrev = []
        menuYes = []
        menuNo = []
        drum1s = []
        drum2s = []
        drum3s = []
        drum4s = []
        drum5s = []
        bassdrums = []
        key1s = []
        key2s = []
        key3s = []
        key4s = []
        key5s = []
        keysolos = []
        action1s = []
        action2s = []
        kills = []

        for i, config in enumerate(self.config):
            if self.type[i] in DRUMTYPES: #drum set
                drum1s.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                drum2s.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                drum3s.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                drum4s.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                drum5s.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                bassdrums.extend([CONTROLS[i][DRUMBASS], CONTROLS[i][DRUMBASSA]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    if self.drumNav:
                        menuUp.extend([CONTROLS[i][DRUM2], CONTROLS[i][DRUM2A]])
                        if self.type[i] == 3:
                            menuDown.extend([CONTROLS[i][DRUM4], CONTROLS[i][DRUM4A]])
                        else:
                            menuDown.extend([CONTROLS[i][DRUM3], CONTROLS[i][DRUM3A]])
                        menuYes.extend([CONTROLS[i][DRUM5], CONTROLS[i][DRUM5A]])
                        menuNo.extend([CONTROLS[i][DRUM1], CONTROLS[i][DRUM1A]])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
            elif self.type[i] in MICTYPES:  #stump: it's a mic
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.append(CONTROLS[i][UP])
                    menuDown.append(CONTROLS[i][DOWN])
                    menuNext.append(CONTROLS[i][RIGHT])
                    menuPrev.append(CONTROLS[i][LEFT])
                    menuYes.append(CONTROLS[i][START])
                    menuNo.append(CONTROLS[i][CANCEL])
            elif self.type[i] in GUITARTYPES:
                if self.type[i] == 0:
                    key1s.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A]])
                else:
                    key1s.extend([CONTROLS[i][KEY1]])
                key2s.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A]])
                key3s.extend([CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                key4s.extend([CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                key5s.extend([CONTROLS[i][KEY5], CONTROLS[i][KEY5A]])
                keysolos.extend([CONTROLS[i][KEY1A], CONTROLS[i][KEY2A], CONTROLS[i][KEY3A], CONTROLS[i][KEY4A], CONTROLS[i][KEY5A]])
                action1s.extend([CONTROLS[i][ACTION1]])
                action2s.extend([CONTROLS[i][ACTION2]])
                kills.extend([CONTROLS[i][KILL]])
                if self.p2Nav == 1 or (self.p2Nav == 0 and i == 0):
                    menuUp.extend([CONTROLS[i][ACTION1], CONTROLS[i][UP]])
                    menuDown.extend([CONTROLS[i][ACTION2], CONTROLS[i][DOWN]])
                    menuNext.extend([CONTROLS[i][RIGHT], CONTROLS[i][KEY4], CONTROLS[i][KEY4A]])
                    menuPrev.extend([CONTROLS[i][LEFT], CONTROLS[i][KEY3], CONTROLS[i][KEY3A]])
                    menuYes.extend([CONTROLS[i][KEY1], CONTROLS[i][KEY1A], CONTROLS[i][START]])
                    menuNo.extend([CONTROLS[i][KEY2], CONTROLS[i][KEY2A], CONTROLS[i][CANCEL]])

            if self.type[i] == 3:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_5a", config):            CONTROLS[i][DRUM4A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_5", config):             CONTROLS[i][DRUM4],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] == 2:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_1a", config):            CONTROLS[i][DRUM5A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][DRUM1A],
                  keycode("key_3a", config):            CONTROLS[i][DRUM2A],
                  keycode("key_4a", config):            CONTROLS[i][DRUM3A],
                  keycode("key_action2", config):       CONTROLS[i][DRUMBASSA],
                  keycode("key_1", config):             CONTROLS[i][DRUM5],
                  keycode("key_2", config):             CONTROLS[i][DRUM1],
                  keycode("key_3", config):             CONTROLS[i][DRUM2],
                  keycode("key_4", config):             CONTROLS[i][DRUM3],
                  keycode("key_action1", config):       CONTROLS[i][DRUMBASS],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            elif self.type[i] > -1:
                controlMapping = { #akedrou - drums do not need special declarations!
                  keycode("key_left", config):          CONTROLS[i][LEFT],
                  keycode("key_right", config):         CONTROLS[i][RIGHT],
                  keycode("key_up", config):            CONTROLS[i][UP],
                  keycode("key_down", config):          CONTROLS[i][DOWN],
                  keycode("key_cancel", config):        CONTROLS[i][CANCEL],
                  keycode("key_star", config):          CONTROLS[i][STAR],
                  keycode("key_kill", config):          CONTROLS[i][KILL],
                  keycode("key_1a", config):            CONTROLS[i][KEY1A], #order is important. This minimizes key conflicts.
                  keycode("key_2a", config):            CONTROLS[i][KEY2A],
                  keycode("key_3a", config):            CONTROLS[i][KEY3A],
                  keycode("key_4a", config):            CONTROLS[i][KEY4A],
                  keycode("key_5a", config):            CONTROLS[i][KEY5A],
                  keycode("key_1", config):             CONTROLS[i][KEY1],
                  keycode("key_2", config):             CONTROLS[i][KEY2],
                  keycode("key_3", config):             CONTROLS[i][KEY3],
                  keycode("key_4", config):             CONTROLS[i][KEY4],
                  keycode("key_5", config):             CONTROLS[i][KEY5],
                  keycode("key_action2", config):       CONTROLS[i][ACTION2],
                  keycode("key_action1", config):       CONTROLS[i][ACTION1],
                  keycode("key_start", config):         CONTROLS[i][START],
                }
            else:
                controlMapping = {}
            controlMapping = self.checkMapping(controlMapping, i)
            self.controlMapping.update(controlMapping)

        self.reverseControlMapping = dict((value, key) for key, value in self.controlMapping.iteritems() )

        # Multiple key support
        self.heldKeys = {}
def main(config_path: str):
    config = Config.get(input_conf=load_json_file(file_path=config_path))
    paths_evaluation_results = evaluate(config=config)
    plot(config=config, score_paths=paths_evaluation_results)
예제 #36
0
def showlog():
    return render_template('log.html',
                           logmessages=deque_handler.get_entries(),
                           maxentries=int(
                               Config.get('logging', 'maxlogentries')))
예제 #37
0
def has_flagged_words(text):
    """
    Returns True if @text has flagged words.
    """
    return any(
        (flag_word in text) for flag_word in Config.get('autoflag_words', []))
예제 #38
0
파일: Credits.py 프로젝트: EdPassos/fofix
    def __init__(self, engine, songName=None):
        self.engine = engine
        self.time = 0.0
        self.offset = 0.5  # akedrou - this seems to fix the delay issue, but I'm not sure why. Return here!
        self.speedDiv = 20000.0
        self.speedDir = 1.0
        self.doneList = []
        self.themename = Config.get("coffee", "themename")

        nf = self.engine.data.font
        ns = 0.002
        bs = 0.001
        hs = 0.003
        c1 = (1, 1, 0.5, 1)
        c2 = (1, 0.75, 0, 1)
        self.text_size = nf.getLineSpacing(scale=hs)

        # akedrou - Translatable Strings:
        self.bank = {}
        self.bank["intro"] = [
            _("Frets on Fire X is a progression of MFH-mod,"),
            _("which was built on Alarian's mod,"),
            _("which was built on UltimateCoffee's Ultimate mod,"),
            _("which was built on RogueF's RF_mod 4.15,"),
            _("which was, of course, built on Frets on Fire 1.2.451,"),
            _("which was created by Unreal Voodoo"),
        ]
        self.bank["noOrder"] = [_("No particular order")]
        self.bank["accessOrder"] = [_("In order of project commit access")]
        self.bank["coders"] = [_("Active Coders")]
        self.bank["otherCoding"] = [_("Programming")]
        self.bank["graphics"] = [_("Graphic Design")]
        self.bank["3d"] = [_("3D Textures")]
        self.bank["logo"] = [_("FoFiX Logo Design")]
        self.bank["hollowmind"] = [_("Hollowmind Necks")]
        self.bank["themes"] = [_("Included Themes")]
        self.bank["shaders"] = [_("Shaders")]
        self.bank["sounds"] = [_("Sound Design")]
        self.bank["translators"] = [_("Translators")]
        self.bank["honorary"] = [_("Honorary Credits")]
        self.bank["codeHonor"] = [_("Without whom this game would not exist")]
        self.bank["giveThanks"] = [_("Special Thanks to")]
        self.bank["community"] = [_("nwru and all of the community at fretsonfire.net")]
        self.bank["other"] = [_("Other Contributors:")]
        self.bank["tutorial"] = [
            _("Jurgen FoF tutorial inspired by adam02"),
            _("Drum test song tutorial by Heka"),
            _("Drum Rolls practice tutorial by venom426"),
        ]
        self.bank["disclaimer"] = [
            _("If you have contributed to this game and are not credited,"),
            _("please let us know what and when you contributed."),
        ]
        self.bank["thanks"] = [_("Thank you for your contribution.")]
        self.bank["oversight"] = [
            _("Please keep in mind that it is not easy to trace down and"),
            _("credit every single person who contributed; if your name is"),
            _("not included, it was not meant to slight you."),
            _("It was an oversight."),
        ]
        # evilynux - Theme strings
        self.bank["themeCreators"] = [_("%s theme credits:") % self.themename]
        self.bank["themeThanks"] = [_("%s theme specific thanks:") % self.themename]
        # Languages
        self.bank["french"] = [_("French")]
        self.bank["french90"] = [_("French (reform 1990)")]
        self.bank["german"] = [_("German")]
        self.bank["italian"] = [_("Italian")]
        self.bank["piglatin"] = [_("Pig Latin")]
        self.bank["portuguese-b"] = [_("Portuguese (Brazilian)")]
        self.bank["russian"] = [_("Russian")]
        self.bank["spanish"] = [_("Spanish")]
        self.bank["swedish"] = [_("Swedish")]

        self.videoLayer = False
        self.background = None

        vidSource = os.path.join(Version.dataPath(), "themes", self.themename, "menu", "credits.ogv")
        if os.path.isfile(vidSource):
            try:
                self.vidPlayer = VideoLayer(self.engine, vidSource, mute=True, loop=True)
            except (IOError, VideoPlayerError):
                Log.error("Error loading credits video:")
            else:
                self.vidPlayer.play()
                self.engine.view.pushLayer(self.vidPlayer)
                self.videoLayer = True

        if not self.videoLayer and not self.engine.loadImgDrawing(
            self, "background", os.path.join("themes", self.themename, "menu", "credits.png")
        ):
            self.background = None

        if not self.engine.loadImgDrawing(
            self, "topLayer", os.path.join("themes", self.themename, "menu", "creditstop.png")
        ):
            self.topLayer = None

        space = Text(nf, hs, c1, "center", " ")
        self.credits = [
            Picture(self.engine, "fofix_logo.png", 0.10),
            Text(nf, ns, c1, "center", "%s" % Version.version()),
            space,
        ]

        # evilynux: Main FoFiX credits (taken from CREDITS).
        self.parseText("CREDITS")
        self.credits.extend([space, space, space])
        # evilynux: Theme credits (taken from data/themes/<theme name>/CREDITS).
        self.parseText(os.path.join("data", "themes", self.themename, "CREDITS"))

        self.credits.extend(
            [
                space,
                space,
                Text(nf, ns, c1, "left", _("Made with:")),
                Text(
                    nf, ns, c2, "right", "Python " + sys.version.split(" ")[0]
                ),  # stump: the version that's actually in use
                Text(nf, bs, c2, "right", "http://www.python.org"),
                space,
                Text(
                    nf, ns, c2, "right", "PyGame " + pygame.version.ver.replace("release", "")
                ),  # stump: the version that's actually in use
                Text(nf, bs, c2, "right", "http://www.pygame.org"),
                space,
                Text(
                    nf, ns, c2, "right", "PyOpenGL " + OpenGL.__version__
                ),  # evilynux: the version that's actually in use
                Text(nf, bs, c2, "right", "http://pyopengl.sourceforge.net"),
                space,
                Text(nf, ns, c2, "right", "Illusoft Collada module 0.3.159"),
                Text(nf, bs, c2, "right", "http://colladablender.illusoft.com"),
                space,
                Text(nf, ns, c2, "right", "MXM Python Midi Package 0.1.4"),
                Text(nf, bs, c2, "right", "http://www.mxm.dk/products/public/pythonmidi"),
                space,
                space,
                Text(nf, bs, c1, "center", _("Source Code available under the GNU General Public License")),
                Text(nf, bs, c2, "center", "http://code.google.com/p/fofix"),
                space,
                space,
                Text(nf, bs, c1, "center", _("Copyright 2006, 2007 by Unreal Voodoo")),
                Text(nf, bs, c1, "center", _("Copyright 2008-2013 by Team FoFiX")),
                space,
                space,
            ]
        )
예제 #39
0
    def __init__(self, instrument, coOpType = False):
        self.coOpType = coOpType
        logClassInits = Config.get("game", "log_class_inits")
        if logClassInits == 1:
            Log.debug("ScoreCard class init...")
        self.starScoring = Config.get("game", "star_scoring")
        self.updateOnScore = Config.get("performance", "star_score_updates")
        self.avMult = 0.0
        self.hitAccuracy = 0.0
        self.score  = 0
        if instrument == [5]:
            self.baseScore = 0
        else:
            self.baseScore = 50
        self.notesHit = 0
        self.percNotesHit = 0
        self.notesMissed = 0
        self.instrument = instrument # 0 = Guitar, 2 = Bass, 4 = Drum
        self.bassGrooveEnabled = False
        self.hiStreak = 0
        self._streak  = 0
        self.cheats = []
        self.scalable = []
        self.earlyHitWindowSizeHandicap = 1.0
        self.handicap = 0
        self.longHandicap  = ""
        self.handicapValue = 100.0
        self.totalStreakNotes = 0
        self.totalNotes = 0
        self.totalPercNotes = 0
        self.cheatsApply = False
        self.stars = 0
        self.starRatio = 0.0
        self.star = [0 for i in range(7)]
        if self.starScoring == 1: #GH-style (mult thresholds, hit threshold for 5/6 stars)
            self.star[5] = 2.8
            self.star[4] = 2.0
            self.star[3] = 1.2
            self.star[2] = 0.4
            self.star[1] = 0.2 #akedrou - GH may start with 1 star, but why do we need to?
            self.star[0] = 0.0
        elif self.starScoring > 1: #RB-style (mult thresholds, optional 100% gold star)
            if self.starScoring == 4:
                if self.instrument[0] == Song.BASS_PART and not self.coOpType:
                    self.star[6] = 6.78
                    self.star[5] = 4.62
                    self.star[4] = 2.77
                    self.star[3] = 0.90
                    self.star[2] = 0.50
                    self.star[1] = 0.21
                    self.star[0] = 0.0
                else:
                    if self.instrument[0] == Song.DRUM_PART and not self.coOpType:
                        self.star[6] = 4.29
                    elif self.instrument[0] == Song.VOCAL_PART and not self.coOpType:
                        self.star[6] = 4.18
                    else:
                        self.star[6] = 4.52
                    self.star[5] = 3.08
                    self.star[4] = 1.85
                    self.star[3] = 0.77
                    self.star[2] = 0.46
                    self.star[1] = 0.21
                    self.star[0] = 0.0
            else:
                self.star[5] = 3.0
                self.star[4] = 2.0
                self.star[3] = 1.0
                self.star[2] = 0.5
                self.star[1] = 0.25
                self.star[0] = 0.0
                if self.coOpType:
                    self.star[6] = 4.8
                elif self.instrument[0] == Song.BASS_PART: # bass
                    self.star[6] = 4.8
                elif self.instrument[0] == Song.DRUM_PART: # drum
                    self.star[6] = 4.65
                else:
                    self.star[6] = 5.3
        else: #hit accuracy thresholds
            self.star[6] = 100
            self.star[5] = 95
            self.star[4] = 75
            self.star[3] = 50
            self.star[2] = 30
            self.star[1] = 10
            self.star[0] = 0

        self.endingScore = 0    #MFH
        self.endingStreakBroken = False   #MFH
        self.endingAwarded = False    #MFH
        self.lastNoteEvent = None    #MFH
        self.lastNoteTime  = 0.0
        self.freestyleWasJustActive = False  #MFH
예제 #40
0
    def __init__(self, engine):
        self.engine              = engine

        self.logClassInits = Config.get("game", "log_class_inits")
        if self.logClassInits == 1:
            Log.debug("MainMenu class init (MainMenu.py)...")

        self.time                = 0.0
        self.nextLayer           = None
        self.visibility          = 0.0
        self.active              = False

        self.showStartupMessages = False

        self.gfxVersionTag = Config.get("game", "gfx_version_tag")

        self.chosenNeck = Config.get("game", "default_neck")
        exists = 0

        if engine.loadImgDrawing(self, "ok", os.path.join("necks",self.chosenNeck+".png")):
            exists = 1
        elif engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_"+self.chosenNeck+".png")):
            exists = 1

        #MFH - fallback logic now supports a couple valid default neck filenames
        #MFH - check for Neck_1
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","Neck_1.png")):
                Config.set("game", "default_neck", "1")
                Log.warn("Default chosen neck not valid; fallback Neck_1.png forced.")
                exists = 1

        #MFH - check for defaultneck
        if exists == 0:
            if engine.loadImgDrawing(self, "ok", os.path.join("necks","defaultneck.png")):
                Log.warn("Default chosen neck not valid; fallback defaultneck.png forced.")
                Config.set("game", "default_neck", "defaultneck")
                exists = 1
            else:
                Log.error("Default chosen neck not valid; fallbacks Neck_1.png and defaultneck.png also not valid!")

        #Get theme
        self.theme       = self.engine.data.theme
        self.themeCoOp   = self.engine.data.themeCoOp
        self.themename   = self.engine.data.themeLabel
        self.useSoloMenu = self.engine.theme.use_solo_submenu

        allowMic = True

        self.menux = self.engine.theme.menuPos[0]
        self.menuy = self.engine.theme.menuPos[1]

        self.rbmenu = self.engine.theme.menuRB

        #MFH
        self.main_menu_scale = self.engine.theme.main_menu_scaleVar
        self.main_menu_vspacing = self.engine.theme.main_menu_vspacingVar

        if not self.engine.loadImgDrawing(self, "background", os.path.join("themes",self.themename,"menu","mainbg.png")):
            self.background = None
        self.engine.loadImgDrawing(self, "BGText", os.path.join("themes",self.themename,"menu","maintext.png"))
        self.engine.loadImgDrawing(self, "optionsBG", os.path.join("themes",self.themename,"menu","optionsbg.png"))
        self.engine.loadImgDrawing(self, "optionsPanel", os.path.join("themes",self.themename,"menu","optionspanel.png"))

        #racer: added version tag
        if self.gfxVersionTag or self.engine.theme.versiontag == True:
            if not self.engine.loadImgDrawing(self, "version", os.path.join("themes",self.themename,"menu","versiontag.png")):
                if not self.engine.loadImgDrawing(self, "version", "versiontag.png"): #falls back on default versiontag.png in data\ folder
                    self.version = None
        else:
            self.version = None

        #myfingershurt: random main menu music function, menu.ogg and menuXX.ogg (any filename with "menu" as the first 4 letters)
        self.files = None
        filepath = self.engine.getPath(os.path.join("themes",self.themename,"sounds"))
        if os.path.isdir(filepath):
            self.files = []
            allfiles = os.listdir(filepath)
            for name in allfiles:
                if os.path.splitext(name)[1] == ".ogg":
                    if string.find(name,"menu") > -1:
                        self.files.append(name)


        if self.files:
            i = random.randint(0,len(self.files)-1)
            filename = self.files[i]
            sound = os.path.join("themes",self.themename,"sounds",filename)
            self.menumusic = True
            engine.menuMusic = True

            self.song = Audio.Music(self.engine.resource.fileName(sound))
            self.song.setVolume(self.engine.config.get("audio", "menu_volume"))
            self.song.play(0)  #no loop
        else:
            self.menumusic = False

        self.opt_text_color     = self.engine.theme.opt_text_colorVar
        self.opt_selected_color = self.engine.theme.opt_selected_colorVar

        trainingMenu = [
          (_("Tutorials"), self.showTutorial),
          (_("Practice"), lambda: self.newLocalGame(mode1p = 1)),
        ]

        self.opt_bkg_size = [float(i) for i in self.engine.theme.opt_bkg_size]
        self.opt_text_color = self.engine.theme.hexToColor(self.engine.theme.opt_text_colorVar)
        self.opt_selected_color = self.engine.theme.hexToColor(self.engine.theme.opt_selected_colorVar)

        if self.BGText:
            strCareer = ""
            strQuickplay = ""
            strSolo = ""
            strMultiplayer = ""
            strTraining = ""
            strSettings = ""
            strQuit = ""
        else:
            strCareer = "Career"
            strQuickplay = "Quickplay"
            strSolo = "Solo"
            strMultiplayer = "Multiplayer"
            strTraining = "Training"
            strSettings = "Settings"
            strQuit = "Quit"

        multPlayerMenu = [
            (_("Face-Off"),     lambda: self.newLocalGame(players = 2,             maxplayers = 4)),
            (_("Pro Face-Off"), lambda: self.newLocalGame(players = 2, mode2p = 1, maxplayers = 4)),
            (_("Party Mode"),   lambda: self.newLocalGame(             mode2p = 2)),
            (_("FoFiX Co-Op"),  lambda: self.newLocalGame(players = 2, mode2p = 3, maxplayers = 4, allowMic = allowMic)),
            (_("RB Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 4, maxplayers = 4, allowMic = allowMic)),
            (_("GH Co-Op"),     lambda: self.newLocalGame(players = 2, mode2p = 5, maxplayers = 4)),
            (_("GH Battle"),    lambda: self.newLocalGame(players = 2, mode2p = 6, allowDrum = False)), #akedrou- so you can block drums
          ]

        if not self.useSoloMenu:

            mainMenu = [
              (strCareer, lambda:   self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (strQuickplay, lambda:        self.newLocalGame(allowMic = allowMic)),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]

        else:

            soloMenu = [
              (_("Solo Tour"), lambda: self.newLocalGame(mode1p = 2, allowMic = allowMic)),
              (_("Quickplay"), lambda: self.newLocalGame(allowMic = allowMic)),
            ]

            mainMenu = [
              ((strSolo,"solo"), soloMenu),
              ((strMultiplayer,"multiplayer"), multPlayerMenu),
              ((strTraining,"training"),    trainingMenu),
              ((strSettings,"settings"),  self.settingsMenu),
              (strQuit,        self.quit),
            ]


        w, h, = self.engine.view.geometry[2:4]

        self.menu = Menu(self.engine, mainMenu, onClose = lambda: self.engine.view.popLayer(self), pos = (self.menux, .75-(.75*self.menuy)))

        engine.mainMenu = self    #Points engine.mainMenu to the one and only MainMenu object instance

        ## whether the main menu has come into view at least once
        self.shownOnce = False
예제 #41
0
파일: Resource.py 프로젝트: vemel/fofix
 def refreshBaseLib(self):
     self.baseLibrary = Config.get("setlist", "base_library")
     if self.baseLibrary and os.path.isdir(self.baseLibrary):
         self.songPath = [self.baseLibrary]
예제 #42
0
def has_flagged_words(text):
    """
    Returns True if @text has flagged words.
    """
    return any((flag_word in text) for flag_word in Config.get('autoflag_words', []))
예제 #43
0
    def __init__(self, instrument, coOpType=False):
        self.coOpType = coOpType
        logClassInits = Config.get("game", "log_class_inits")
        if logClassInits == 1:
            Log.debug("ScoreCard class init...")
        self.starScoring = Config.get("game", "star_scoring")
        self.updateOnScore = Config.get("performance", "star_score_updates")
        self.avMult = 0.0
        self.hitAccuracy = 0.0
        self.score = 0
        if instrument == [5]:
            self.baseScore = 0
        else:
            self.baseScore = 50
        self.notesHit = 0
        self.percNotesHit = 0
        self.notesMissed = 0
        self.instrument = instrument  # 0 = Guitar, 2 = Bass, 4 = Drum
        self.bassGrooveEnabled = False
        self.hiStreak = 0
        self._streak = 0
        self.cheats = []
        self.scalable = []
        self.earlyHitWindowSizeHandicap = 1.0
        self.handicap = 0
        self.longHandicap = ""
        self.handicapValue = 100.0
        self.totalStreakNotes = 0
        self.totalNotes = 0
        self.totalPercNotes = 0
        self.cheatsApply = False
        self.stars = 0
        self.starRatio = 0.0
        self.star = [0 for i in range(7)]
        if self.starScoring == 1:  #GH-style (mult thresholds, hit threshold for 5/6 stars)
            self.star[5] = 2.8
            self.star[4] = 2.0
            self.star[3] = 1.2
            self.star[2] = 0.4
            self.star[
                1] = 0.2  #akedrou - GH may start with 1 star, but why do we need to?
            self.star[0] = 0.0
        elif self.starScoring > 1:  #RB-style (mult thresholds, optional 100% gold star)
            if self.starScoring == 4:
                if self.instrument[0] == Song.BASS_PART and not self.coOpType:
                    self.star[6] = 6.78
                    self.star[5] = 4.62
                    self.star[4] = 2.77
                    self.star[3] = 0.90
                    self.star[2] = 0.50
                    self.star[1] = 0.21
                    self.star[0] = 0.0
                else:
                    if self.instrument[
                            0] == Song.DRUM_PART and not self.coOpType:
                        self.star[6] = 4.29
                    elif self.instrument[
                            0] == Song.VOCAL_PART and not self.coOpType:
                        self.star[6] = 4.18
                    else:
                        self.star[6] = 4.52
                    self.star[5] = 3.08
                    self.star[4] = 1.85
                    self.star[3] = 0.77
                    self.star[2] = 0.46
                    self.star[1] = 0.21
                    self.star[0] = 0.0
            else:
                self.star[5] = 3.0
                self.star[4] = 2.0
                self.star[3] = 1.0
                self.star[2] = 0.5
                self.star[1] = 0.25
                self.star[0] = 0.0
                if self.coOpType:
                    self.star[6] = 4.8
                elif self.instrument[0] == Song.BASS_PART:  # bass
                    self.star[6] = 4.8
                elif self.instrument[0] == Song.DRUM_PART:  # drum
                    self.star[6] = 4.65
                else:
                    self.star[6] = 5.3
        else:  #hit accuracy thresholds
            self.star[6] = 100
            self.star[5] = 95
            self.star[4] = 75
            self.star[3] = 50
            self.star[2] = 30
            self.star[1] = 10
            self.star[0] = 0

        self.endingScore = 0  #MFH
        self.endingStreakBroken = False  #MFH
        self.endingAwarded = False  #MFH
        self.lastNoteEvent = None  #MFH
        self.lastNoteTime = 0.0
        self.freestyleWasJustActive = False  #MFH
예제 #44
0
    def __init__(self, engine, libraryName = None, songName = None):
        Scene.__init__(self, engine)

        self.engine.world.sceneName = "SongChoosingScene"

        Song.updateSongDatabase(self.engine)

        self.wizardStarted = False
        self.libraryName   = libraryName
        self.songName      = songName
        if not self.libraryName:
            self.libraryName = self.engine.config.get("setlist", "selected_library")
            if not self.libraryName:
                self.libraryName = Song.DEFAULT_LIBRARY
        if not self.songName:
            self.songName = self.engine.config.get("setlist", "selected_song")
        self.gameMode = self.engine.world.gameMode
        self.careerMode = (self.gameMode == CAREER)
        self.practiceMode = (self.gameMode == PRACTICE)
        self.gameMode2p = self.engine.world.multiMode
        self.autoPreview = not self.engine.config.get("audio", "disable_preview")
        self.sortOrder   = self.engine.config.get("game", "sort_order")
        self.tut = self.engine.world.tutorial
        self.playerList  = self.players

        self.gameStarted = False

        self.gamePlayers = len(self.playerList)
        self.parts = [None for i in self.playerList]
        self.diffs = [None for i in self.playerList]

        self.time       = 0
        self.lastTime   = 0
        self.mode       = 0
        self.moreInfo   = False
        self.moreInfoTime = 0
        self.miniLobbyTime = 0
        self.selected   = 0
        self.camera     = Camera()
        self.cameraOffset = 0.0
        self.song       = None
        self.songLoader = None
        self.loaded     = False
        text            = _("Initializing Setlist...")
        if self.engine.cmdPlay == 2:
            text = _("Checking Command-Line Settings...")
        elif len(self.engine.world.songQueue) > 0:
            text = _("Checking Setlist Settings...")
        elif len(self.engine.world.songQueue) == 0:
            self.engine.world.playingQueue = False
        self.splash     = Dialogs.showLoadingSplashScreen(self.engine, text)
        self.items      = []
        self.cmdPlay    = False
        self.queued     = True

        self.loadStartTime = time.time()

        if self.tut == True:
            self.library = self.engine.tutorialFolder
        else:
            self.library    = os.path.join(self.engine.config.get("setlist", "base_library"), self.libraryName)
            if not os.path.isdir(self.engine.resource.fileName(self.library)):
                self.library = self.engine.resource.fileName(os.path.join(self.engine.config.get("setlist", "base_library"), Song.DEFAULT_LIBRARY))

        self.searchText = ""

        #user configurables and input management
        self.listingMode       = 0     #with libraries or List All
        self.preloadSongLabels = False
        self.showCareerTiers   = 1+(self.careerMode and 1 or 0) #0-Never; 1-Career Only; 2-Always
        self.scrolling        = 0
        self.scrollDelay      = self.engine.config.get("game", "scroll_delay")
        self.scrollRate       = self.engine.config.get("game", "scroll_rate")
        self.scrollTime       = 0
        self.scroller         = [lambda: None, self.scrollUp, self.scrollDown]
        self.scoreDifficulty  = Song.difficulties[self.engine.config.get("game", "songlist_difficulty")]
        self.scorePart        = Song.parts[self.engine.config.get("game", "songlist_instrument")]
        self.sortOrder        = self.engine.config.get("game", "sort_order")
        self.queueFormat      = self.engine.config.get("game", "queue_format")
        self.queueOrder       = self.engine.config.get("game", "queue_order")
        self.queueParts       = self.engine.config.get("game", "queue_parts")
        self.queueDiffs       = self.engine.config.get("game", "queue_diff")
        self.nilShowNextScore = self.engine.config.get("songlist",  "nil_show_next_score")

        #theme information
        self.themename = self.engine.data.themeLabel
        self.theme = self.engine.data.theme

        #theme configurables
        self.setlistStyle      = self.engine.theme.setlist.setlistStyle    #0 = Normal; 1 = List; 2 = Circular
        self.headerSkip        = self.engine.theme.setlist.headerSkip      #items taken up by header (non-static only)
        self.footerSkip        = self.engine.theme.setlist.footerSkip      #items taken up by footer (non-static only)
        self.itemSize          = self.engine.theme.setlist.itemSize        #delta (X, Y) (0..1) for each item (non-static only)
        self.labelType         = self.engine.theme.setlist.labelType       #Album covers (0) or CD labels (1)
        self.labelDistance     = self.engine.theme.setlist.labelDistance   #number of labels away to preload
        self.showMoreLabels    = self.engine.theme.setlist.showMoreLabels  #whether or not additional unselected labels are rendered on-screen
        self.texturedLabels    = self.engine.theme.setlist.texturedLabels  #render the art as a texture?
        self.itemsPerPage      = self.engine.theme.setlist.itemsPerPage    #number of items to show on screen
        self.followItemPos     = (self.itemsPerPage+1)/2
        self.showLockedSongs   = self.engine.theme.setlist.showLockedSongs #whether or not to even show locked songs
        self.showSortTiers     = self.engine.theme.setlist.showSortTiers   #whether or not to show sorting tiers - career tiers take precedence.
        self.selectTiers       = self.engine.theme.setlist.selectTiers     #whether or not tiers should be selectable as a quick setlist.

        if self.engine.cmdPlay == 2:
            self.songName = Config.get("setlist", "selected_song")
            self.libraryName = Config.get("setlist", "selected_library")
            self.cmdPlay = self.checkCmdPlay()
            if self.cmdPlay:
                Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
                return
        elif len(self.engine.world.songQueue) > 0:
            Dialogs.hideLoadingSplashScreen(self.engine, self.splash)
            return

        #variables for setlist management (Not that this is necessary here - just to see what exists.)
        self.songLoader       = None #preview handling
        self.tiersPresent     = False
        self.startingSelected = self.songName
        self.selectedIndex    = 0
        self.selectedItem     = None
        self.selectedOffset   = 0.0
        self.previewDelay     = 1000
        self.previewLoaded    = False
        self.itemRenderAngles = [0.0]
        self.itemLabels       = [None]
        self.xPos             = 0
        self.yPos             = 0
        self.pos              = 0

        self.infoPage         = 0

        self.menu_force_reload   = False
        self.menu_text_color     = (1, 1, 1)
        self.menu_selected_color = (.66, .66, 0)
        self.menu_text_pos       = (.2, .31)
        self.menu = Menu(self.engine, [ConfigChoice(self.engine, self.engine.config, "game", "queue_format", autoApply = True),
                                       ConfigChoice(self.engine, self.engine.config, "game", "queue_order", autoApply = True),
                                       ConfigChoice(self.engine, self.engine.config, "game", "queue_parts", autoApply = True),
                                       ConfigChoice(self.engine, self.engine.config, "game", "queue_diff", autoApply = True),
                                       ActiveConfigChoice(self.engine, self.engine.config, "game", "sort_order", onChange = self.forceReload),
                                       ActiveConfigChoice(self.engine, self.engine.config, "game", "sort_direction", onChange = self.forceReload),
                                       ActiveConfigChoice(self.engine, self.engine.config, "game", "songlist_instrument", onChange = self.forceReload),
                                       ActiveConfigChoice(self.engine, self.engine.config, "game", "songlist_difficulty", onChange = self.forceReload),
                                       ], name = "setlist", fadeScreen = False, onClose = self.resetQueueVars, font = self.engine.data.pauseFont, \
                         pos = self.menu_text_pos, textColor = self.menu_text_color, selectedColor = self.menu_selected_color)

        #now, load the first library
        self.loadLibrary()

        #load the images
        self.loadImages()
예제 #45
0
from other.exceptions import BrokerError
from other.logging import DequeLoggerHandler
from semanticenrichment import SemanticEnrichment

# Configure logging
logger = logging.getLogger('semanticenrichment')
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s',
                              '%Y-%m-%dT%H:%M:%SZ')

file_handler = logging.FileHandler('semanticenrichment.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

deque_handler = DequeLoggerHandler(int(Config.get('logging', 'maxlogentries')))
deque_handler.setLevel(logging.DEBUG)
deque_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(deque_handler)
logger.info("logger ready")

bp = Blueprint('semanticenrichment',
               __name__,
               static_url_path='',
               static_folder='static',
               template_folder='html')
bp2 = Blueprint('',
                __name__,
                static_url_path='',
예제 #46
0
 def test3(self):
     c = Config()
     
     c.set('test','value')
         
     self.assertEqual(c.get('test'), 'value')
예제 #47
0
파일: Player.py 프로젝트: vemel/fofix
def renameControl(control, newname):
    VFS.rename(_makeControllerIniName(control), _makeControllerIniName(newname))
    for i in range(4):
        if Config.get("game", "control%d" % i) == control:
            Config.set("game", "control%d" % i, newname)
    loadControls()
예제 #48
0
    #Lysdestic - Change resolution from CLI
    if resolution is not None:
        Config.set("video", "resolution", resolution)

    #Lysdestic - Alter theme from CLI
    if theme is not None:
        Config.set("coffee", "themename", theme)

    engine = GameEngine(config)
    engine.cmdPlay = 0

    # Check for a valid invocation of one-shot mode.
    if playing is not None:
        Log.debug('Validating song directory for one-shot mode.')
        library = Config.get("setlist","base_library")
        basefolder = os.path.join(Version.dataPath(),library,"songs",playing)
        if not (os.path.exists(os.path.join(basefolder, "song.ini")) and (os.path.exists(os.path.join(basefolder, "notes.mid")) or os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))) and (os.path.exists(os.path.join(basefolder, "song.ogg")) or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
            Log.warn("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode." % playing)
            engine.startupMessages.append(_("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode.") % playing)
            playing = None

    # Set up one-shot mode if the invocation is valid for it.
    if playing is not None:
        Log.debug('Entering one-shot mode.')
        Config.set("setlist", "selected_song", playing)
        engine.cmdPlay = 1
        if difficulty is not None:
            engine.cmdDiff = int(difficulty)
        if part is not None:
            engine.cmdPart = int(part)