Example #1
0
    def __init__(self, game):
        super(InstructionScreen, self).__init__(game)
        self.__mMenuItems = []
        self.__mMenuItems.append(Button("back", 0.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.MenuScreen.MenuScreen(self.mGame))))

        self.__crystalPos = b2Vec2(9.5,5.8)
        self.__crystalDirection = b2Vec2(0,1)
        self.__crystalBlingTimer = 4.0
        self.__crystalTimer = 1.0
        self.crystal = Animation(Resources.getInstance().mCrystal, 5, 1, 0.6, self.mCamera.getScaledSize(0.6,0.6), False, True)

        self.portal = Animation(Resources.getInstance().mSwirlSheet, 3, 2, 0.6, self.mCamera.getScaledSize(1.5,1.5), False, True)

        self.__walkPos = b2Vec2(1,3)
        self.__walkTimer = 2.0
        self.__walkDirection = b2Vec2(1,0)
        self.playerWalk = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), True, True)

        self.__jumpPos = b2Vec2(9.5,3)
        self.__jumpStartPos = self.__jumpPos.copy()
        self.__jumpTimer = 0.5
        self.__jumpWaitTimer = 0.2
        self.__jumpDirection = b2Vec2(0,-1)
        self.playerjump = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), False, False)

        self.__gravityPos = b2Vec2(3, 6)
        self.__gravityTimer = 1.0
        self.__gravityDirection = b2Vec2(0,-1)
        self.playergravity = Animation(Resources.getInstance().mPxl, 4, 2, 0.4, self.mCamera.getScaledSize(1, 1), False, False)
Example #2
0
    def __init__(self, game):
        super(EndScreen, self).__init__(game, False)
        SoundManager.getInstance().playEndMusic()

        #fonts
        self.textFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x * 0.6)
        self.headerFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x)
        self.titleFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x * 2.0)

        self.modelsize = self.mCamera.getModelCoords(b2Vec2(Pgl.width, Pgl.height))
        self.mDone = False
        self.mTimer = 0

        texts = [
                 [self.titleFont, (200,160,160), "pxlgrvty", 0],
                 [self.headerFont, (170,170,170), "Programming:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Graphics:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Audio/FX:", 25],
                 [self.textFont, (255,255,255), "Rickard Hansson", 0],
                 [self.headerFont, (170,170,170), "Music:", 25],
                 [self.textFont, (255,255,255), "anamanaguchi - helix nebula", 0],
                 [self.textFont, (255,255,255), "anamanaguchi - video challenge", 0],
                 [self.textFont, (255,255,255), "electric children - spring retrospective", 0],
                 [self.textFont, (255,255,255), "teknoaxe - chiptune does dubstep", 0],
                 [self.textFont, (255,255,255), "roccow - chipho instrumental", 0],
                 [self.textFont, (255,255,255), "sycamore drive - kicks", 0]]

        self.titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y))
        self.text = Text(texts, self.titlepos, 1, Pgl.app.surface)
        self.endtext = self.headerFont.render("thanks for playing!", 1, (170,170,170))
        self.endsize = self.headerFont.size("thanks for playeing!")
        self.endpos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x/2.0, self.modelsize.y/2.0))
Example #3
0
    def __initializeFromGame(self):
        if self.mLevelInt < Level.Level.countLevels():
            self.mButtons.append(Button("next", 13.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.GameScreen.GameScreen(self.mGame, self.mLevelInt+1))))
        else:
            self.mButtons.append(Button("end", 13.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.EndScreen.EndScreen(self.mGame))))

        self.mButtons.append(Button("retry", 11, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.GameScreen.GameScreen(self.mGame, self.mLevelInt))))

        if self.mCurrentTime.isFaster(self.mTime):
            self.mTime = self.mCurrentTime
            found = False

            data = None
            try:
                with open(Resources.getInstance().resource_path("assets/state/time.json"), "rb") as readstate:
                    decryptedData = self.__mCrypt.decrypt(readstate.read())
                    data = json.loads(decryptedData)

                    for time in data:
                        if time["ID"] == str(self.mLevelInt):
                            found = True
                            time["TIME"] = self.mCurrentTime.toString()

                    if not found:
                        data.append({"ID":"%s" % str(self.mLevelInt), "TIME":"%s" % self.mCurrentTime.toString()})
            except Exception:
                pass

            if data == None:
                data = '[{"ID":"%s", "TIME":"%s"}]' % (str(self.mLevelInt), self.mCurrentTime.toString())

            with open(Resources.getInstance().resource_path("assets/state/time.json"), "wb+") as writestate:
                writestate.write(self.__mCrypt.encrypt(json.dumps(data)))
Example #4
0
 def calculateAverageConceptVectorDistance(self, concepts, filterName='DSM'):
     '''
     This function calculates the average concept vector distance, based on the vector representing a cui.
     
     '''
     feats = dict()
     if (filterName=='ALL'):
         feats.update(self.calculateAverageConceptVectorDistance(concepts, 'DSM'))
         feats.update(self.calculateAverageConceptVectorDistance(concepts, 'DSM+1'))
         feats.update(self.calculateAverageConceptVectorDistance(concepts, 'MED'))
     else:
         subset = list(set(self.getSubsetOfConcepts(concepts, filterName)))
         maxDist = 0
         dists = []
         
         for cui in subset:
             for cui2 in subset:
                 try:
                     concept = cui.split(';')[0]
                     wVector= Resources.getConceptVectors_dsm().vectorize(concept, remove_oov=True)
                     concept2 = cui2.split(';')[0]
                     wVector2= Resources.getConceptVectors_dsm().vectorize(concept2, remove_oov=True)
                     cosDist = spatial.distance.cosine(wVector, wVector2)
                     if not math.isnan(cosDist):
                         dists.append(cosDist)
                     if (cosDist) > maxDist:
                         maxDist = cosDist
                 except:
                     continue
                 
         feats[filterName+'maxConceptVectorDist'] = round(maxDist,3)
         if bool(dists):
             feats[filterName+'avgConceptVectorDist'] = round(np.mean(dists),3)
     return feats
Example #5
0
def main():
    documents, words, vectors, max_words, total_words = parse_input()
    Resources.set_resources(documents, words, vectors, max_words, total_words)

    for arg in sys.argv[1:]:
        if arg == "--files-only":
            print("Generating files")

            for i, request in enumerate(Resources.requests):
                print("Writing {} request...".format(request))
                result = perform_query(request)
                result = list(filter(lambda res: res[1] > 0, result))

                s = "Š—Š°ŠæрŠ¾Ń {}:\nŠ ŠµŠ·ŃƒŠ»ŃŒŃ‚Š°Ń‚Ń‹ (Š½Š°Š·Š²Š°Š½ŠøŠµ | ŠŗŠ¾ŃŃ„Ń„ŠøцŠøŠµŠ½Ń‚ сŠ¾Š¾Ń‚Š²ŠµŃ‚стŠ²Šøя)\n\n" \
                    "{}".format(request, "\n".join(
                        list(map(lambda item: " | ".join(map(lambda elem: str(elem), item)), result))
                    ))

                with open("out/{}.txt".format(i + 1), encoding="utf-8", mode="w") as f:
                    f.write(s)

            print("Files generated, exiting.")
            return

    run_app()
Example #6
0
 def isPsychiatric(self, cui, lexiconName, includePreambled=True):
     '''
     From the prespecified lexicon, find if a cui can be considered psychiatric
     '''   
     pureCUI = self.cuiFilter(cui, includePreambled)
     if (pureCUI in Resources.getLexiconFilter(lexiconName)):
         return (True, cui+";"+Resources.getLexiconFilter(lexiconName)[pureCUI])
     return (False, None)
Example #7
0
    def __init__(self, camera, world):
        self.mCamera = camera
        self.mWorld = world
        
        self.mUI = Sprite(Resources.getInstance().mUI, self.mCamera.getScaledSize(4,1))

        self.timefont = Resources.getInstance().getScaledFont(self.mCamera.scale.x)
        self.timesize = self.timefont.size("00:00:00")
 def isSnomedDefined(self, cui, includePreambled=True):
     '''
     From the internal list, find if a cui can be considered psychiatric
     '''    
     pureCUI = self.cuiFilter(cui, includePreambled)
     if (pureCUI in Resources.getSnomedFilter()):
         return (True, cui+";"+Resources.getSnomedFilter()[pureCUI])
     return (False, None)
Example #9
0
 def __init__(self):
     """
     self.action_sequence = []
     self.board = [None] * 21
     self.shop = [None] * 5
     self.items = [None] * 10
     """
     self.resources = Resources()
 def isRemotelyPsychiatric(self, cui, includePreambled=True):
     '''
     From the internal list, find if a cui can be considered psychiatric, or one step away from it 
     (because of it being a concept related to psychiatric)
     '''
     pureCUI = self.cuiFilter(cui, includePreambled)
     if pureCUI  in Resources.getDSMdev1():
         return (True, cui+";"+Resources.getDSMdev1()[pureCUI])
     return (False, None)
Example #11
0
    def __updateLevelLockState(self):
        with open(Resources.getInstance().resource_path("assets/state/state.json"), "rb") as state:
            decryptedData = self.__mCrypt.decrypt(state.read())
            lvldata = json.loads(decryptedData)

        if int(lvldata["LVL"]) <= self.mCurrentLevel:
            with open(Resources.getInstance().resource_path("assets/state/state.json"), "wb") as data:
                lvl = min(self.mCurrentLevel+1, self.mMaxLevels)
                data.write(self.__mCrypt.encrypt('{"LVL":"%s"}' % (str(lvl))))
Example #12
0
    def __init__(self, host, user, password, port):
        #paramiko.util.log_to_file(Resources.getLogName())
        self.id = random.randint(1, 999)
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.client.connect(hostname=host, username=user, password=password, port=port)
        Resources.logCommand('Set ' + self.server + ' connection', 'Connection id: ' + str(self.id))

        self.lastExecutionTime = datetime.datetime.now()
        self.connectionClosed  = False
        Timer(600.0, lambda: self.checkLastTimeExecution()).start()

        print('Set ' + self.server + ' connection', 'Connection id: ' + str(self.id))
Example #13
0
    def executeCommand(self, command):
        self.isExecuting = True
        self.lastExecutionTime = datetime.datetime.now()

        stdin, stdout, stderr = self.client.exec_command(command)
        response = stdout.read() + stderr.read()
        Resources.logCommand(command, response, 'Connection: ' + self.server + ', id: ' + str(self.id))

        #printMessage(response)
        #mila.printMessage(response)

        self.isExecuting = False
        return response
Example #14
0
 def __init__(self, game, playMusic=True):
     self.mGame = game
     Pgl.app.setUpdaterate(int(Updaterate.FAST))
     pygame.mouse.set_visible(False)
             
     if playMusic: SoundManager.getInstance().playMenuMusic()
 
     #set input & camera
     self.mGame.input = MenuInput(self)
     self.mCamera = Camera(Pgl.width, Pgl.height)
     self.modelsize = self.mCamera.getModelCoords(b2Vec2(Pgl.width, Pgl.height))
     
     #fonts
     self.screenFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 3.0)
     self.titleFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x * 2.0)
     self.infoFont = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 2)
     
     #graphics
     self.arrow = Sprite(Resources.getInstance().mArrow) 
     self.arrow.setSize(self.mCamera.getScaledSize((self.arrow.getWidth()/float(self.arrow.getHeight())) * 0.5, 0.5))
     self.menubutton = Animation(Resources.getInstance().mMenuButton, 2, 1, 0, self.mCamera.getScaledSize(1, 1), False, False)
     self.levelbutton = Animation(Resources.getInstance().mLevelButton, 2, 1, 0, self.mCamera.getScaledSize(1, 1), False, False)
     self.checkbutton = Animation(Resources.getInstance().mCheckButton, 2, 1, 0, self.mCamera.getScaledSize(1, 1), False, False)
     self.lock = Sprite(Resources.getInstance().mLock)
     self.lock.setSize(self.mCamera.getScaledSize((self.lock.getWidth()/float(self.lock.getHeight())) * 0.2, 0.2))
Example #15
0
def GetProduction(player, wy, wx):
    Log.Save(player.username + " take production on: " + str(wy) + " " + str(wx) + "\n") 
    Utility.SendMsg(player, Colors.COLOR_GREEN + "Fortress on field: " + str(wy) + ", " + str(wx) + " produce:\n")
    resource = Resources()
    resource.Init()
    for y in range(Map.end):
        for x in range(Map.end):
            building = Map.Get(Pos(wy, wx, y, x))
            if isinstance(building, Buildings.Building):
                resource = Buildings.GetProduction(resource, building)
    for iType, iAmount in resource.iteritems():
        if iAmount > 0:
            player.resources[iType] += iAmount
            Utility.SendMsg(player,  iType.color + iType.name + " = " + str(iAmount) + "\n")
Example #16
0
    def get_grouped_qid(self, norm_q_vec, grouped_questions, simThreshold):
        for k, q_tokens_list in grouped_questions.items():
            for t_list in q_tokens_list:
                if not Resources.getWordVectors().vectorize(t_list,
                                                            remove_oov=True):
                    continue
                if np.dot(
                        norm_q_vec,
                        Reach.normalize(
                            np.mean(Resources.getWordVectors().vectorize(
                                t_list, remove_oov=True),
                                    axis=0))) >= simThreshold:
                    return k

        return None
Example #17
0
	def __init__(self, xmlDir):

		self.manifest = self.loadManifestFile(xmlDir + '/manifest.xml')

		print "Loading threat sources..."
		self.threatSources = ThreatSources()
		for threat_source in self.manifest['threat_sources']:
			self.threatSources.addFromXMLFile(xmlDir + "/" + threat_source)

		print "Loading vulnerability catalog..."
		self.vulnerabilityCatalog = VulnerabilityCatalog()
		for vulnerability_catalog in self.manifest['vulnerability_catalogs']:
			self.vulnerabilityCatalog.addFromXMLFile(xmlDir + "/" + vulnerability_catalog)

		print "Loading threat catalog..."
		self.threatCatalog = ThreatCatalog()
		for threat_catalog in self.manifest['threat_catalogs']:
			self.threatCatalog.addFromXMLFile(xmlDir + "/" + threat_catalog)

		print "Loading controls catalog..."
		self.controlsCatalog = ControlCatalog()
		for controls_catalog in self.manifest['controls_catalogs']:
			self.controlsCatalog.addFromXMLFile(xmlDir + "/" + controls_catalog)

		print "Loading resources..."
		self.resources = Resources()
		for resource in self.manifest['resources']:
			self.resources.addFromXMLFile(xmlDir + "/" + resource)

		print "Loading information sources..."
		self.informationSources = InformationSources(self.threatSources, self.threatCatalog, self.vulnerabilityCatalog, self.resources)
		for information_source in self.manifest['information_sources']:
			self.informationSources.addFromXMLFile(xmlDir + "/" + information_source)
Example #18
0
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)

        self.window = parent
        self.setIcon(QtGui.QIcon("assets/images/icon.png"))
        self.iconMenu = QtGui.QMenu(parent)
        self.setContextMenu(self.iconMenu)

        confs = Resources.getConfigs()

        #self.quitAction.setShortcut(QKeySequence(self.tr("Ctrl+Q")))

        for instance in confs:
            if confs[instance]['PARAMS']:
                name = confs[instance]['PARAMS']['name']
                itemMenu = QtGui.QMenu(self.iconMenu)
                itemMenu.setTitle(name)
                self.iconMenu.addMenu(itemMenu)

                detailsItem = itemMenu.addAction("Show Details")
                self.connect(detailsItem, QtCore.SIGNAL('triggered()'), partial(self.instanceDetails, confs[instance]))

                for env in confs[instance]:
                    if env != 'PARAMS':
                        conf = confs[instance][env]

                        subItemMenu = itemMenu.addAction("Connect " + env)
                        file = GenerateShScripts.generateSh(conf)
                        #self.connect(subItemMenu, QtCore.SIGNAL('triggered()'), partial(self.instanceAction, conf))
                        self.connect(subItemMenu, QtCore.SIGNAL('triggered()'), partial(self.runShFile, file))

        quitAction = QtGui.QAction("&Quit", self, triggered=QtGui.qApp.quit)
        self.iconMenu.addAction(quitAction)
        self.show()
Example #19
0
    def get_group_id(self, questions, qTokens, simThreshold=0.9):

        vec = Resources.getWordVectors().vectorize(qTokens, remove_oov=True)
        if not vec:
            return None

        qVec = Reach.normalize(np.mean(vec, axis=0))
        mostSimQ = None
        maxSim = 0.0

        for groupId, groupQTokens in questions.items():
            for cur_q_tokens in groupQTokens:
                cur_vec = self.expSet.getWordVectors().vectorize(
                    cur_q_tokens, remove_oov=True)
                if not cur_vec:
                    continue
                curSim = np.dot(qVec, Reach.normalize(np.mean(cur_vec,
                                                              axis=0)))
                if curSim > maxSim:
                    maxSim = curSim
                    mostSimQ = groupId

        if maxSim >= simThreshold:
            return mostSimQ
        else:
            return None
Example #20
0
 def __init__(self):
     """
     pygame.init() does initialize parts of the sound, but according to the
     documentation for the mixer module, safest way is to do mixer.pre_init,
     then pygame.init and then mixer.init. The controller also makes sure any
     resources needed in the game are preloaded.
     """
     self.__options = Options.load()
     self.__resources = Resources()
     pygame.mixer.pre_init(frequency = 44100, buffer = 2048) 
     pygame.init()
     pygame.mixer.init(frequency = 44100, buffer = 2048)
     self.__graphics = Graphics(self.__resources, self.__options)
     # Load all graphics and sound effects before the game is started
     self.__resources.preload_all()
     self.__logic = None
Example #21
0
    def countLevels(self):
        lvls = 0
        for filename in os.listdir(Resources.getInstance().resource_path("assets/levels")):
            if filename.endswith(".lvl"):
                lvls += 1

        return lvls
Example #22
0
    def __readLevelLockState(self):
            lvldata = None

            try:
                with open(Resources.getInstance().resource_path("assets/state/state.json"), "rb") as state:
                    decryptedData = self.__mCrypt.decrypt(state.read())
                    lvldata = json.loads(decryptedData)

                    try:
                        return lvldata["LVL"]
                    except:
                        raise IOError
            except (IOError):
                with open(Resources.getInstance().resource_path("assets/state/state.json"), "wb+") as state:
                    data = self.__mCrypt.encrypt('{"LVL":"1"}')
                    state.write(data)
                    return 1
Example #23
0
    def __init__(self):
        GameObject.init_object(self)

        # Components definitions
        self.transform = Transform(Vector2(100, 100, 1), Vector2(0, 0, 0),
                                   Vector2(0, 0, 0))
        self.sprite = Resources.load("pompier.png")
        self.sprite = pygame.transform.scale(self.sprite, (100, 100))
Example #24
0
 def isMedBrand(self, cui, includePreambled=True):
     '''
     Check if a concept is a medication as present in RxNorm linked to UMLS.
     '''
     medFilter, _, _ = Resources.getMedFilter()
     pureCUI = self.cuiFilter(cui, includePreambled)
     if pureCUI in medFilter:
         return (True, cui+";"+ medFilter[pureCUI])
     return (False,None)
Example #25
0
    def getVectorizedConcepts(self, concepts):
        """
        Vectorizes a list of Concept Unique Identifiers into an array of concept vectors of identical size.

        @param concepts: A list of CUIS.
        @return: A list of vectors, each one of which represents a concept.
        """

        return Resources.getConceptVectors_dsm().vectorize(concepts, remove_oov=False)
Example #26
0
    def playMusic(self, seed = 0):
        if Pgl.options.music:
            if self.MUSIC_PLAYING == MusicID.BG: return
            seed = 1 if seed > self.NUMBER_OF_SONGS else seed
            song = "bg%s" % str(seed)
            self.MUSIC_PLAYING = MusicID.BG
            self.CURRENTSONG = seed

            print(Resources.getInstance())

            pygame.mixer.music.set_volume(Pgl.options.musicvolume / 100.0)
            pygame.mixer.music.load(Resources.getInstance().resource_path("assets/audio/music/bg/%s.ogg" % song))
            pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
            pygame.event.set_allowed(pygame.constants.USEREVENT)
            pygame.mixer.music.play()

        else:
            self.stopMusic()
Example #27
0
    def __init__(self):
        GameObject.init_object(self)

        # Components definitions
        self.transform = Transform(Vector2(0, 0, 0), Vector2(0, 0, 0),
                                   Vector2(0, 0, 0))
        self.sprite = Resources.load("flamme.png")
        self.sprite = pygame.transform.scale(self.sprite, (50, 50))
        self.animator = AnimatorController()
Example #28
0
 def isActiveComponent(self, cui, includePreambled=True):
     '''
     Check if a concept is an active component of a medicine, according to the ATC ontology linked to UMLSs
     '''
     _, activeCompFilter, _ = Resources.getMedFilter()
     pureCUI = self.cuiFilter(cui, includePreambled)
     if pureCUI in activeCompFilter:
         return (True, cui+";"+ activeCompFilter[pureCUI])
     return (False,None)
Example #29
0
 def playMenuMusic(self):
     if Pgl.options.music:
         if self.MUSIC_PLAYING == MusicID.MENU: return
         pygame.mixer.music.set_volume(int(Pgl.options.musicvolume) / 100.0)
         pygame.mixer.music.load(Resources.getInstance().resource_path("assets/audio/music/menu.ogg"))
         pygame.mixer.music.play(-1)
         self.MUSIC_PLAYING = MusicID.MENU
     else:
         self.stopMusic()
Example #30
0
 def calculateAverageWordVectorDistance(self, concepts, filterName='DSM'):
     '''
     This function calculates the average word vector distance, based on the words that a concept is encompassed by.
     
     '''
     feats = dict()
     if (filterName=='ALL'):
         feats.update(self.calculateAverageWordVectorDistance(concepts, 'DSM'))
         feats.update(self.calculateAverageWordVectorDistance(concepts, 'DSM+1'))
         feats.update(self.calculateAverageWordVectorDistance(concepts, 'MED'))
     else:
         subset = list(set(self.getSubsetOfConcepts(concepts, filterName)))
         maxDist = 0
         dists = []
         
         for cui in subset:
             cumulDist = 0
             cnt = 0
             for cui2 in subset:
                 try:
                     words = cui.split(';')[1].lower().split(' ')
                     wVector= np.mean(Resources.getWordVectors().vectorize(words, remove_oov=True), axis=0)
                     words = cui2.split(';')[1].lower().split(' ')
                     wVector2= np.mean(Resources.getWordVectors().vectorize(words, remove_oov=True), axis=0)
                     cosDist = spatial.distance.cosine(wVector, wVector2)
                     if not math.isnan(cosDist):
                         cumulDist += cosDist
                         cnt += 1
                 except:
                     continue
             try:
                 if (cnt != 0):
                     dists.append(cumulDist/cnt)
                 if (cumulDist/cnt) > maxDist:
                     maxDist = cumulDist/cnt
             except:
                 continue
         
         feats[filterName + 'maxWordVectorDist'] = round(maxDist,3)
         if bool(dists):
             feats[filterName + 'avgWordVectorDist'] = round(np.mean(dists),3)
     return feats
Example #31
0
 def getActiveComponent(self, cui, includePreambled=True):
     '''
     Get a list of active components (From ATC ontology in UMLS) related to an RxNorm medication in the UMLS
     '''
     _, activeCompFilter, medRelFilter = Resources.getMedFilter()
     pureCUI = self.cuiFilter(cui, includePreambled)
     if pureCUI not in medRelFilter:
         return []
     cui2_list = medRelFilter.get(pureCUI,[])
     cui2_list = [cui2+";"+activeCompFilter[cui2] for cui2 in cui2_list]
     return cui2_list
Example #32
0
    def __readLevel(self):
        parser = self.__mCrypt.dectryptParser(self.mCurrentLevel)
        self.mCurrentTileset = parser.get("level", "tileset")
        self.mBackground = parser.get("level", "bg")
        bgcolor = pygame.image.load(Resources.getInstance().resource_path("assets/gfx/%s" % self.mBackground))
        self.mBackgroundcolor = bgcolor.get_at((0, 0))
        self.mPickupData = parser.get("objects", "pickups")
        self.mEnemyData = parser.get("objects", "enemies")
        self.mBoxData = parser.get("objects", "boxes")

        #Mapcollision
        #check for pictures first
        if os.path.exists(Resources.getInstance().resource_path("assets/levels/level%d.png" % self.mCurrentLevel)):
            self.mMap = pygame.image.load(Resources.getInstance().resource_path("assets/levels/level%d.png" % self.mCurrentLevel))
            self.mWidth, self.mHeight = self.mMap.get_size()
            self.mMapType = MapType.PICTURE
        else: #check for lvl-file
            self.mMap = parser.get("level", "map").replace(" ", "").split("\n")
            self.mWidth = len(self.mMap[0])
            self.mHeight = len(self.mMap)
            self.mMapType = MapType.TEXT
Example #33
0
    def __readPlayerTime(self):
        pTime = None
        found = False

        try:
            with open(Resources.getInstance().resource_path("assets/state/time.json"), "rb") as state:
                decryptedData = self.__mCrypt.decrypt(state.read())
                pTime = json.loads(decryptedData)

            for time in pTime:
                if time["ID"] == str(self.mLevelInt):
                    pTime = time["TIME"]
                    found = True
                    break
        except Exception:
            with open(Resources.getInstance().resource_path("assets/state/time.json"), "wb+") as writer:
                writer.write(self.__mCrypt.encrypt("[]"))

        if not found:
            pTime = "00:00:00"

        return pTime
Example #34
0
    def render(self, delta):
        Pgl.app.surface.fill((67,80,129))
        
        btnToDraw = self.menubutton
        for btn in self.__mMenuItems:
            viewpos = self.mCamera.getViewCoords(b2Vec2(btn.x, btn.y))
            btnToDraw.setSize(self.mCamera.getScaledSize(btn.size.x, btn.size.y))
            
            color = None
            if btn.mActive:
                btnToDraw.freeze(1, 0)
                color = (255,255,255)
            else:
                btnToDraw.freeze(0, 0)
                color = (141,60,1)
                
            btnToDraw.draw(delta, viewpos)
                   
            btntxt = self.screenFont.render(str(btn.mText), 0, color)
            size = self.screenFont.size(str(btn.mText))
            txtpos = self.mCamera.getViewCoords(b2Vec2(btn.x + btn.size.x / 2 - (size[0] / self.mCamera.scale.x) / 2.0, btn.y + btn.size.y / 2 - (size[1] / self.mCamera.scale.y) / 2.0))
            Pgl.app.surface.blit(btntxt, (txtpos.x, txtpos.y))
            
        #texts and animations
        title = self.titleFont.render("instructions", 0, (255,255,255))
        size = self.titleFont.size("instructions")
        titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y / 6))
        Pgl.app.surface.blit(title, (titlepos.x - size[0] / 2.0, titlepos.y - size[1] / 2.0))

        self.crystal.draw(delta, self.mCamera.getViewCoords(self.__crystalPos))
        crystalinfo = Resources.getInstance().getScaledFont(self.mCamera.scale.x).render("=", 0, (255,255,255))
        Pgl.app.surface.blit(crystalinfo, self.mCamera.getViewCoords(b2Vec2(11, 5.8)))
        
        self.portal.draw(delta, self.mCamera.getViewCoords(b2Vec2(12.5, 5.3)))
        portalinfo = self.infoFont.render("collect crystals to open portals", 0, (255,255,255))
        Pgl.app.surface.blit(portalinfo, self.mCamera.getViewCoords(b2Vec2(8,7)))

        self.playerWalk.draw(delta, self.mCamera.getViewCoords(self.__walkPos))
        moveinfo = self.infoFont.render("w,a,s,d - to move around!", 0, (255,255,255))
        Pgl.app.surface.blit(moveinfo, self.mCamera.getViewCoords(b2Vec2(1,4)))
        
        self.playerjump.draw(delta, self.mCamera.getViewCoords(self.__jumpPos))
        jumpinfo = self.infoFont.render("spacebar to jump!", 0, (255,255,255))
        Pgl.app.surface.blit(jumpinfo, self.mCamera.getViewCoords(b2Vec2(8,4)))
        
        self.playergravity.draw(delta, self.mCamera.getViewCoords(self.__gravityPos))
        gravinfo = self.infoFont.render("arrowkeys to shift gravity!", 0, (255,255,255))
        Pgl.app.surface.blit(gravinfo, self.mCamera.getViewCoords(b2Vec2(1,7)))
        
        self.arrow.draw()
        
Example #35
0
def perform_query(request: str) -> list:
    documents, words, vectors, max_words = Resources.get_resources()
    res, cur_words = analyse_text(request, max_words)
    result = []

    if Resources.USE_VECTOR:
        # Š’ŠµŠŗтŠ¾Ń€Š½Š°Ń Š¼Š¾Š“ŠµŠ»ŃŒ
        request_vector = count_document_vector(list(res.values())[0]["words"], words, max_words, len(documents))
        for name, vector in vectors.items():
            result.append([name, cosine(vector, request_vector)])
    else:
        # ŠÆŠ·Ń‹ŠŗŠ¾Š²Š°Ń Š¼Š¾Š“ŠµŠ»ŃŒ
        for doc_name, doc_data in documents.items():
            result.append([doc_name, count_probability(doc_data, list(res.values())[0], Resources.LAMBDA)])

    result.sort(key=lambda x: x[1], reverse=True)
    return result
Example #36
0
    def dectryptParser(self, lvlid):
        parser = configparser.ConfigParser()

        #create temp-file
        # fd, temp_path = tempfile.mkstemp(suffix=".lvl", dir="assets/levels/")

        #open crypted file, write the decrypted data to tempfile
        # with open(temp_path, "w+") as w:
        #     with open("assets/levels/decrypted/level%d.lvl" % lvlid, "rb") as reader:
        #         w.write(self.decrypt(reader.read()))

        #parse the decrypted file
        # parser.read(temp_path)
        parser.read(Resources.getInstance().resource_path("assets/levels/decrypted/level%d.lvl" % lvlid))

        #close/remove
        # os.close(fd)
        # os.remove(temp_path)

        return parser
Example #37
0
    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.setWindowIcon(QIcon("resources/img/icon.png"))

        # create objects
        self.CLineView = QLabel("\nHi! Have a nice day!")
        self.CLineView.setAlignment(Qt.AlignBottom | Qt.AlignLeft)
        self.CLineView.setContentsMargins(15, 10, 10, 10)
        self.CLineEdit = CLineEdit()

        self.setObjectName("Window")
        self.CLineEdit.setObjectName("inputCommand")
        self.CLineView.setObjectName("commandBox")
        self.setStyleSheet(Resources.readStyleSheet('window.pss'))


        rightPanel = QGridLayout()
        test = QLabel("\nCheck")
        button3 = QPushButton("3")
        button4 = QPushButton("4")
        button5 = QPushButton("5")
        button6 = QPushButton("6")

        # layout
        #layout = QVBoxLayout()
        layout = QGridLayout()
        layout.addWidget(self.CLineView, 0, 0)
        layout.addWidget(self.CLineEdit, 1, 0)

        #layout.addLayout(rightPanel, 0, 1)
        #rightPanel.addWidget(test)
        #rightPanel.addWidget(button3)
        #rightPanel.addWidget(button4)
        #rightPanel.addWidget(button5)
        #rightPanel.addWidget(button6)

        self.setLayout(layout)

        # connections
        self.connect(self.CLineEdit, SIGNAL("enterPressed"), self.commandExecute)
        self.connect(self.CLineEdit, SIGNAL("ctrlSpacePressed"), self.deactivate)
Example #38
0
    def get_grouped_questions(self, trainSet, simThreshold):

        grouped_questions = defaultdict(
            list
        )  #{id:[list of similar questions, where each item is a list of covered tokens in the question]}
        questions_type = defaultdict(lambda: defaultdict(int))
        grouped_questions_cat = defaultdict(set)

        for d in trainSet:
            cur_segment = self.segmenter.segment(d.getTextObject())
            for qap in cur_segment:
                qid = len(grouped_questions.keys())
                cur_q_tokens = d.getTextObject().get_covered_tokens(
                    qap.begQue, qap.endQue)

                if any(cur_q_tokens in val
                       for val in grouped_questions.values()):
                    continue
                qVec = Resources.getWordVectors().vectorize(cur_q_tokens,
                                                            remove_oov=True)
                if not qVec:
                    continue
                norm_q_vec = Reach.normalize(np.mean(qVec, axis=0))

                k = self.get_grouped_qid(norm_q_vec, grouped_questions,
                                         simThreshold)
                if k is not None:
                    qid = k

                grouped_questions[qid].append(cur_q_tokens)
                ansType, cat = self.get_ans_type(qap.answers)

                if not ansType:
                    continue

                questions_type[qid][ansType] += 1

                if cat:
                    grouped_questions_cat[qid].add(cat)

        return (grouped_questions, questions_type, grouped_questions_cat)
Example #39
0
 def __init__(self, world, camera):
     self.mWorld = world
     self.mCamera = camera
             
     #debugrender only
     self.debug = DebugDraw(self.mCamera)
     self.mWorld.physWorld.renderer = self.debug
     self.debug.AppendFlags(self.debug.e_shapeBit)
     
     #font
     self.fpsfont = Resources.getInstance().getScaledFont(20)
     
     #renders
     self.objectRender = ObjectRender(self.mCamera, self.mWorld.level.mObjects)
     self.playerRender = PlayerRender(self.mCamera, self.mWorld.player)
     self.tileRender = TileRender(self.mCamera, self.mWorld.level)
     self.enemyRender = EnemyRender(self.mCamera, self.mWorld.level.mEnemies)
     self.swirlRender = SwirlRender(self.mCamera, self.mWorld.level)
     self.fxRender = EffectRender(self.mCamera)
     self.bgRender = BackgroundRender(self.mCamera, self.mWorld.level)
     self.uiRender = UIRender(self.mCamera, self.mWorld)     
Example #40
0
    def __init__(self, game, levelInt, currentTime = None):
        Id.getInstance().resetId()

        self.__mCrypt = Crypt()
        self.mCurrentTime = currentTime

        self.mLevelInt = levelInt
        self.mButtons = []
        self.mTime = Time(self.__readPlayerTime())

        if currentTime != None:
            super(LevelTimeScreen, self).__init__(game, False)
            self.__initializeFromGame()
        else:
            super(LevelTimeScreen, self).__init__(game)
            self.__initializeFromMenu()

        self.medallions = Animation(Resources.getInstance().mMedallions, 3, 3, 0, self.mCamera.getScaledSize(3, 3), False, False)
        self.mLevelTimes = [Time(x) for x in self.__readLevelTimes()]
        self.mButtons.append(Button("back", 0.5, 8.5, b2Vec2(2,1), lambda: self.mGame.setScreen(screen.LevelScreen.LevelScreen(self.mGame))))

        self.achivedMedallion = self.__calculateMedallion()
    def __init__(self, title='Tooltip', command='', res='This is a QWidget', id=None, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.id = id

        #self.t = ToolTipAnimation()
        #self.t.start()

        width = 300
        height = 200

        resolution = QDesktopWidget().screenGeometry()
        self.setGeometry(resolution.width() - width, resolution.height() - height, width, height)

        pos_x = resolution.width() - width * (TooltipManage.getCountToolTips() / 3 + 1)
        pos_y = resolution.height() - height * (TooltipManage.getCountToolTips() % 3 + 1)
        self.move(pos_x, pos_y)

        self.setWindowTitle(title)
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
        self.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
        self.setToolTip('This is a QWidget')
        self.setObjectName("toolTipWindow")
        self.setStyleSheet(Resources.read(join('resources', 'styles', 'tooltip.pss')))

        self.CComamnd = QtGui.QLabel(command+':')
        self.CComamnd.setFixedHeight(50)
        self.CComamnd.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
        self.CComamnd.setObjectName('command')

        self.CLineView = QtGui.QLabel(res)
        self.CLineView.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
        self.CLineView.setContentsMargins(15, 0, 0, 0)
        self.CLineView.setObjectName('commandResult')

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.CComamnd)
        layout.addWidget(self.CLineView)
        self.setLayout(layout)
        QtGui.QToolTip.setFont(QtGui.QFont('OldEnglish', 10))
Example #42
0
    def __init__(self, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, parent)

        self.window = parent
        self.setIcon(QtGui.QIcon("assets/images/icon.png"))
        self.iconMenu = QtGui.QMenu(parent)
        self.setContextMenu(self.iconMenu)

        confs = Resources.getConfigs()

        #self.quitAction.setShortcut(QKeySequence(self.tr("Ctrl+Q")))

        for instance in confs:
            if confs[instance]['PARAMS']:
                name = confs[instance]['PARAMS']['name']
                itemMenu = QtGui.QMenu(self.iconMenu)
                itemMenu.setTitle(name)
                self.iconMenu.addMenu(itemMenu)

                detailsItem = itemMenu.addAction("Show Details")
                self.connect(detailsItem, QtCore.SIGNAL('triggered()'),
                             partial(self.instanceDetails, confs[instance]))

                for env in confs[instance]:
                    if env != 'PARAMS':
                        conf = confs[instance][env]

                        subItemMenu = itemMenu.addAction("Connect " + env)
                        file = GenerateShScripts.generateSh(conf)
                        #self.connect(subItemMenu, QtCore.SIGNAL('triggered()'), partial(self.instanceAction, conf))
                        self.connect(subItemMenu, QtCore.SIGNAL('triggered()'),
                                     partial(self.runShFile, file))

        quitAction = QtGui.QAction("&Quit", self, triggered=QtGui.qApp.quit)
        self.iconMenu.addAction(quitAction)
        self.show()
Example #43
0
    def render(self, delta):
        Pgl.app.surface.fill((67,80,129))

        #header
        title = self.titleFont.render("level %s" % str(self.mLevelInt), 0, (255,255,255))
        size = self.titleFont.size("level %s" % str(self.mLevelInt))
        titlepos = self.mCamera.getViewCoords(b2Vec2(self.modelsize.x / 2.0, self.modelsize.y / 6))
        Pgl.app.surface.blit(title, (titlepos.x - size[0] / 2.0, titlepos.y - size[1] / 2.0))

        #current runningtime (if comming from gamescreen)
        if self.mCurrentTime != None:
            current = Resources.getInstance().getScaledFont(self.mCamera.mScale.x / 1.5).render("Current time:", 0, (255, 255, 255))
            currentsize = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 1.5).size("Current time:")
            ctime = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 1.5).render(self.mCurrentTime.toString(), 0, (255,74,20))
            currentpos = self.mCamera.getViewCoords(b2Vec2(5, 3.3))
            ctimepos = self.mCamera.getViewCoords(b2Vec2(5.5, 3.3))
            Pgl.app.surface.blit(current, currentpos)
            Pgl.app.surface.blit(ctime, (ctimepos.x + currentsize[0], ctimepos.y))

        #besttime
        best = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 1.5).render("Best time:", 0, (255, 255, 255))
        bestsize = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 1.5).size("Best time:")
        time = Resources.getInstance().getScaledFont(self.mCamera.scale.x / 1.5).render(self.mTime.toString(), 0, (255,74,20))
        bestpos = self.mCamera.getViewCoords(b2Vec2(5, 3.8))
        timepos = self.mCamera.getViewCoords(b2Vec2(5.5, 3.8))
        Pgl.app.surface.blit(best, bestpos)
        Pgl.app.surface.blit(time, (timepos.x + bestsize[0], timepos.y))

        #buttons
        btnToDraw = self.menubutton
        for btn in self.mButtons:
            viewpos = self.mCamera.getViewCoords(b2Vec2(btn.x, btn.y))
            btnToDraw.setSize(self.mCamera.getScaledSize(btn.size.x, btn.size.y))

            color = None
            if btn.mActive:
                btnToDraw.freeze(1, 0)
                color = (255,255,255)
            else:
                btnToDraw.freeze(0, 0)
                color = (141,60,1)

            btnToDraw.draw(delta, viewpos)

            btntxt = self.screenFont.render(str(btn.mText), 0, color)
            size = self.screenFont.size(str(btn.mText))
            txtpos = self.mCamera.getViewCoords(b2Vec2(btn.x + btn.size.x / 2 - (size[0] / self.mCamera.scale.x) / 2.0, btn.y + btn.size.y / 2 - (size[1] / self.mCamera.scale.y) / 2.0))
            Pgl.app.surface.blit(btntxt, (txtpos.x, txtpos.y))

        #small medallions
        for x in range(len(self.mLevelTimes)):
            self.medallions.freeze(x, 1)

            timetxt = self.infoFont.render(self.mLevelTimes[x].toString(), 0 , (255,255,255))
            pos = self.mCamera.getViewCoords(b2Vec2(9, 5+x))
            Pgl.app.surface.blit(timetxt, (pos.x, pos.y))

            self.medallions.setSize(self.mCamera.getScaledSize(1,1))
            self.medallions.draw(delta, self.mCamera.getViewCoords(b2Vec2(8,4.6+x)))

        self.medallions.freeze(self.achivedMedallion.x, self.achivedMedallion.y)
        self.medallions.setSize(self.mCamera.getScaledSize(3,3))
        self.medallions.draw(delta, self.mCamera.getViewCoords(b2Vec2(4.9,4.6)))
        self.arrow.draw()
Example #44
0
    def getVectorizedWords(self, words):

        return {str(idx): k for idx, k in enumerate(np.mean(Resources.getWordVectors().vectorize(words, remove_oov=True), axis=0))}
Example #45
0
    def levelUpdate(self, level):
        self.mTiles = level.mAllTiles
        self.mTileSprite = Animation(pygame.image.load(Resources.getInstance().resource_path("assets/gfx/tiles/%s" % level.mCurrentTileset)).convert_alpha(), 3, 11, 0, self.mCamera.getScaledSize(1,1))

        width = int(level.mWidth * self.mCamera.scale.x)
        height = int(level.mHeight * self.mCamera.scale.y)

        scale = self.mCamera.getScaledSize(1,1)
        self.sf = pygame.Surface((width, height), flags=pygame.SRCALPHA);
        self.mCamera.displacement = b2Vec2(0,0);

        for tile in self.mTiles:

            viewpos = self.mCamera.getViewCoords(b2Vec2(tile.position.x - 0.5, tile.position.y - 0.5))

            #walls
            if tile.tiletype == TileType.TL:
                self.mTileSprite.freeze(0,0)
            elif tile.tiletype == TileType.T:
                self.mTileSprite.freeze(1,0)
            elif tile.tiletype == TileType.TR:
                self.mTileSprite.freeze(2,0)
            elif tile.tiletype == TileType.L:
                self.mTileSprite.freeze(0,1)
            elif tile.tiletype == TileType.M:
                random.seed(tile.position.x / tile.position.y)
                if random.randint(0,9) > 3:
                    self.mTileSprite.freeze(1,1)
                else:
                    self.mTileSprite.freeze(2,7)
            elif tile.tiletype == TileType.R:
                self.mTileSprite.freeze(2,1)
            elif tile.tiletype == TileType.BL:
                self.mTileSprite.freeze(0,2)
            elif tile.tiletype == TileType.B:
                self.mTileSprite.freeze(1,2)
            elif tile.tiletype == TileType.BR:
                self.mTileSprite.freeze(2,2)

            #grass
            elif tile.tiletype == TileType.GL:
                self.mTileSprite.freeze(0,3)
            elif tile.tiletype == TileType.GM:
                self.mTileSprite.freeze(1,3)
            elif tile.tiletype == TileType.GR:
                self.mTileSprite.freeze(2,3)

            #edge
            elif tile.tiletype == TileType.ETL:
                self.mTileSprite.freeze(0,4)
            elif tile.tiletype == TileType.ET:
                self.mTileSprite.freeze(1,4)
            elif tile.tiletype == TileType.ETR:
                self.mTileSprite.freeze(2,4)
            elif tile.tiletype == TileType.EL:
                self.mTileSprite.freeze(0,5)
            elif tile.tiletype == TileType.EM:
                self.mTileSprite.freeze(1,5)
            elif tile.tiletype == TileType.ER:
                self.mTileSprite.freeze(2,5)
            elif tile.tiletype == TileType.EBL:
                self.mTileSprite.freeze(0,6)
            elif tile.tiletype == TileType.EB:
                self.mTileSprite.freeze(1,6)
            elif tile.tiletype == TileType.EBR:
                self.mTileSprite.freeze(2,6)

            #single
            elif tile.tiletype == TileType.S:
                self.mTileSprite.freeze(1,5)
            elif tile.tiletype == TileType.SG:
                self.mTileSprite.freeze(1,7)
            elif tile.tiletype == TileType.SL:
                self.mTileSprite.freeze(0,8)
            elif tile.tiletype == TileType.SM:
                self.mTileSprite.freeze(1,8)
            elif tile.tiletype == TileType.SR:
                self.mTileSprite.freeze(2,8)
            elif tile.tiletype == TileType.SGL:
                self.mTileSprite.freeze(0,9)
            elif tile.tiletype == TileType.SGM:
                self.mTileSprite.freeze(1,9)
            elif tile.tiletype == TileType.SGR:
                self.mTileSprite.freeze(2,9)
            elif tile.tiletype == TileType.SVB:
                self.mTileSprite.freeze(0,10)
            elif tile.tiletype == TileType.SVM:
                self.mTileSprite.freeze(1,10)
            elif tile.tiletype == TileType.SVT:
                self.mTileSprite.freeze(2,10)

            elif tile.tiletype == TileType.GRAVITYZONE:
                self.mTileSprite.freeze(2,7)


            area = self.mTileSprite.getRect()
            toDraw = self.mTileSprite.image.subsurface(area)
            toDraw = pygame.transform.scale(toDraw, (int(scale.x), int(scale.y)))
            self.sf.blit(toDraw, (viewpos.x, viewpos.y))
Example #46
0
class Controller:
    
    #
    #
    def __init__(self):
        """
        pygame.init() does initialize parts of the sound, but according to the
        documentation for the mixer module, safest way is to do mixer.pre_init,
        then pygame.init and then mixer.init. The controller also makes sure any
        resources needed in the game are preloaded.
        """
        self.__options = Options.load()
        self.__resources = Resources()
        pygame.mixer.pre_init(frequency = 44100, buffer = 2048) 
        pygame.init()
        pygame.mixer.init(frequency = 44100, buffer = 2048)
        self.__graphics = Graphics(self.__resources, self.__options)
        # Load all graphics and sound effects before the game is started
        self.__resources.preload_all()
        self.__logic = None

    def main(self):
        self.main_menu()

    def play_game(self):
        """
        Initialize the game logic and handle whatever the game logic returns
        from a run of the game. 
        """
        self.__logic = GameLogic(self.__graphics, self.__resources, 
                                 self.__options)
        self.__logic.add_player()
        levels = level_convert()
        status = CLEARED
        #
        # Play the levels
        #
        for i in range(len(levels)):
            lev = levels[i]
            # Background music
            # TODO: Different music for different levels
            if self.__options.music:
                pygame.mixer.music.load(join(MP3_PATH,"cruising.mp3"))
                pygame.mixer.music.set_volume(0.8)
                pygame.mixer.music.play()

            # Prepare the level
            self.__logic.clear()
            self.__graphics.reset_distance()
            self.__graphics.set_scroll(5)
            self.__logic.set_level(lev)
            
            status = self.__logic.game_loop()
            if status != CLEARED:
                break
            # Last level cleared = game cleared!
            if i != len(levels)-1:
                self.level_cleared()

        # Turn off the music, since game is obviously over
        pygame.mixer.music.stop()

        #
        # Depending on how the game went, show some information, or not.
        #
        if status == CLEARED:
            self.game_cleared()
            self.main_menu()
        elif status == DIED:
            self.game_over()
        elif status == ABORTED:
            self.main_menu()
        else:
            self.quit()

#
# Menus below
#

    def main_menu(self):
        o = self.__options
        entries = ["Start game", "Instructions", "Options", "Quit"]
        funs = [lambda _: self.play_game(), lambda _: self.instructions()
               ,lambda _: self.options(), lambda _: self.quit()]
        active = 0
        self.__graphics.main_menu(entries, active)
        keys = [o.up, o.down, o.confirm]
        kpress = wait_for_key(keys)
        while kpress in [o.up, o.down]:
            if kpress == o.up and active > 0:
                active -= 1
            elif kpress == o.down and active < len(entries) - 1:
                active += 1
            self.__graphics.main_menu(entries, active)
            kpress = wait_for_key(keys)
        if kpress == o.confirm:
            f = funs[active]
            f(0)
        else:
            self.quit()

    # TODO: Collect and print stats from the level, too
    def level_cleared(self):
        self.__graphics.paint_level_cleared()
        anykey()

    # TODO: Highscores and stuff
    def game_cleared(self):
        self.__graphics.paint_game_cleared()
        anykey()

    # Shows an options menu and allows setting various game parameters
    def options(self, active = 0):
        o = self.__options
        key_opts = [ ("Left:", o.left), ("Down:", o.down), ("Up:", o.up)
                   , ("Right:", o.right), ("Fire:", o.fire)
                   , ("Abort:", o.abort), ("Confirm:", o.confirm)
                   ]
        bool_opts = [ ("Fullscreen: ", o.fullscreen), ("Music: ", o.music)
                    , ("Sound effects: ", o.sfx)
                    ]
        self.__graphics.paint_options(key_opts, bool_opts, active, False)
        keys = [o.up, o.down, o.confirm, o.abort]
        kpress = wait_for_key(keys)
        while kpress in [o.up, o.down]:
            if kpress == o.up and active > 0:
                active -= 1
            elif kpress == o.down and active < 9:
                active += 1
            self.__graphics.paint_options(key_opts, bool_opts, active, False)
            kpress = wait_for_key(keys)

        if kpress == o.confirm:
            # Key options
            if active < len(key_opts):
                # Paint selection and wait for input
                self.__graphics.paint_options(key_opts, bool_opts, active, True)
                key = anykey()
                # Only keys that are not already assigned may be chosen
                if key not in self.__options.get_all_keys():
                    self.__options.set_index(active, key)
                    self.__options.save()
            
            # Boolean options, just reverse the value
            else:
                fs = self.__options.fullscreen
                val = self.__options.get_index(active)
                self.__options.set_index(active, not val)
                # If the fullscreen option was changed, reinitialize the
                # graphics
                if fs != self.__options.fullscreen:
                    pygame.display.quit()
                    self.__graphics = Graphics(self.__resources, self.__options)
            self.options(active)
        elif kpress == o.abort:
            self.main_menu()
        else: # event == QUIT
            self.quit()

    # TODO: A describing text about the gameplay
    def instructions(self):
        opts = self.__options
        enemies = all_ships()
        funs = [lambda _: self.__graphics.paint_instructions_keys(),
                lambda _: self.__graphics.paint_instructions_ship(),
                lambda _: self.__graphics.paint_instructions_enemies(enemies) ]
        active = 0
        kpress = None 
        while active >= 0 and active <= 2 and kpress != QUIT:
            screen = funs[active]
            screen(0)
            kpress = wait_for_key([opts.left, opts.right])
            if kpress == opts.left: 
                active -= 1
            elif kpress == opts.right:
                active += 1
        if kpress == QUIT:
            self.quit()
        else:
            self.main_menu()

    def game_over(self):
        self.__graphics.game_over()
        # There is an option of restarting without going through the main menu
        if yn_key():
            self.play_game()
        else:
            self.main_menu()

    def quit(self):
        self.__options.save()
        pygame.mixer.quit()
        pygame.quit()
 def resources(self):
     return Resources(self._connect)
Example #48
0
 def __init__(self, name, resources=None):
     self.name = name
     self.resources = []
     if resources != None:
         self.resources = Resources().validate(resources)
Example #49
0
class Player():
    def __init__(self, connection):
        self.connection = connection
        self.loggedIn = False
        self.state = State.INIT
    
    def InitUserInfo(self):
        self.info = UserInfo()
        mainData.users_info.append((self.username, self.info))
    
    def LoadUserInfo(self):
        for username_arg, info_arg in mainData.users_info:
            if username_arg == self.username:
                self.info = info_arg
        
    def InitResources(self):
        self.resources = Resources()
        self.resources.Init(700, 12, 12, 2)
        mainData.resources.append((self.username, self.resources))
        
    def LoadResources(self):
        for username_arg, resources_arg in mainData.resources:
            if username_arg == self.username:
                self.resources = resources_arg
    
    def ShowResources(self):
        self.info.CheckLastBuild()
        self.info.CheckLastRecruit()
        
        Utility.SendMsg(self, Colors.COLOR_GREEN + "Resources:\n")
        for resType, resAmount in self.resources.iteritems():
            Utility.SendMsg(self, resType.color + resType.name + " = " + str(resAmount) + "\n")
        
        Utility.SendMsg(self, Colors.COLOR_GREEN + "UserInfo:\n") 
        Utility.SendMsg(self, Colors.COLOR_GOLD + "buildingsBuildToday: " + str(self.info.buildingsBuildToday) + "\n")
        Utility.SendMsg(self, Colors.COLOR_BROWN + "unitsRecruitedToday: " + str(self.info.unitsRecruitedToday) + "\n")
        Utility.SendMsg(self, Colors.COLOR_STEEL + "maxNumberOfUnits: " + str(self.info.maxNumberOfUnits) + "\n")
        Utility.SendMsg(self, Colors.COLOR_VIOLET + "numberOfUnits: " + str(self.info.numberOfUnits) + "\n")   
        
    def Pay(self, cost, percent):
        for resType, resAmount in cost.iteritems():
            pAmount = int(resAmount * percent/100.0)
            resDiff = pAmount - self.resources[resType]
            if resDiff > 0:
                Utility.SendMsg(self, Colors.COLOR_RED + "You need " + str(resDiff) + " more " + resType.name + "!\n" )
                return False
        for resType, resAmount in cost.iteritems():
            pAmount = int(resAmount * percent/100.0)
            self.resources[resType] -= pAmount
        return True
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
Example #50
0
 def InitResources(self):
     self.resources = Resources()
     self.resources.Init(700, 12, 12, 2)
     mainData.resources.append((self.username, self.resources))
Example #51
0
 def playEndMusic(self):
     pygame.mixer.music.set_volume(int(Pgl.options.musicvolume) / 100.0)
     pygame.mixer.music.load(Resources.getInstance().resource_path("assets/audio/music/end.ogg"))
     pygame.mixer.music.play()
     self.MUSIC_PLAYING = MusicID.END
Example #52
0
import os
import sys
import threading

os.environ['SDL_VIDEO_CENTERED'] = '1'

import pygame
from pygame.locals import *

from Input import Input
from Resources import Resources
from GameObject import GameObject

pygame.init()
Resources.init()
GameObject.init()


class Engine:
    def __init__(self, size, fps, caption):
        # Game parameters
        pygame.display.set_caption(caption)
        self.ROOT = pygame.display.set_mode(size)
        self.UPDATE_RATE = fps

        # Preparation before starting engine
        self.clock = pygame.time.Clock()

        # Start engine
        self.engine_loop()
Example #53
0
from Pptx import Pptx
from Resources import Resources
from glob import glob
from random import choice

themes = glob('Themes/*.pptx')

assunto = input('Qual assunto que eu tenho que fazer? Seu preguiƧoso! ')

ppt = Pptx(assunto, choice(themes))

rs = Resources(assunto)
lista = rs.get_text()
rs.get_images(len(lista))
images = glob(f'Images/{assunto}/*.jpg')

ppt.add_title_slide()

for c in range(len(lista)):

    ppt.add_context(lista[c] + '.', images[c])

ppt.add_thanks_for_watching_slide()

ppt.save()
Example #54
0
    def __init__(self):
        if self.INSTANCE is not None:
            raise ValueError("already instantiated")

        self.NUMBER_OF_SONGS = len([file for file in os.listdir(Resources.getInstance().resource_path("assets/audio/music/bg/")) if file.endswith(".ogg")])
Example #55
0
 def initialize(self):
     self.SOUNDS = [Resources.getInstance().mJump,
                    Resources.getInstance().mFleshExplosion,
                    Resources.getInstance().mPickup]
     self.MUSIC_PLAYING = -1
Example #56
0
from Application import Application

if __name__ == '__main__':
	# input parameter
	queryfile = "desc.51-100.short.txt"
	model = int(sys.argv[1])
	database = int(sys.argv[2])
	outputfile = sys.argv[3]

	# System file parameter
	docfile ="doclist.txt"
	stemfile ='stem-classes.lst.txt'
	stopfile ="stoplist.txt"

	# Loading the resources
	resources = Resources(database)
	resources.loadDocList(docfile)
	resources.loadStemClasses(stemfile)
	resources.loadStopList(stopfile)
	resources.loadQuerys(queryfile)

	"""
	q57=None
	for q in resources.querys:
		if q.id == '62':
			q57 =q
	resources.querys = [q57]
	print q57
	"""
	#Create Applications based on input parameter
	app = Application(resources,model,database,outputfile)
Example #57
0
class PlayerControl:
    def __init__(self):
        """
        self.action_sequence = []
        self.board = [None] * 21
        self.shop = [None] * 5
        self.items = [None] * 10
        """
        self.resources = Resources()

    def buyChampion(self, store_index):
        """
        Buys the nth champion from the left in the store.
        """
        pyautogui.moveTo(578 + 201 * store_index, 1000)
        pyautogui.mouseDown()
        time.sleep(0.05)
        pyautogui.mouseUp()

    def sellChampion(self, bench_idx):
        """
        Sells the nth champion from the left on the bench.
        """
        pyautogui.moveTo(420 + 122 * bench_index1, 775)
        pyautogui.press("e")

    def reroll(self):
        """
        Presses the reroll button via default hotkey.
        """
        pyautogui.press("d")
        self.resources.increaseGoldBy(-2)

    def levelUp(self):
        """
        Presses the level up button via default hotkey.
        """
        pyautogui.press("f")
        self.resources.increaseXpBy(4)

    def boardIndexToPosition(self, board_index):
        """
        Translates board index (0-20) to screen position in 1920x1080 resolution.
        """
        if board_index < 7:
            return (540 + 145 * board_index, 667)
        elif board_index < 14:
            return (493 + 138 * (board_index % 7), 573)
        else:
            return (575 + 133 * (board_index % 7), 488)

    def placeChampOnBoard(self, bench_index, board_index):
        """
        Places champion from given bench position to given board position.
        """
        pyautogui.moveTo(420 + 122 * bench_index, 775)
        board_position = self.boardIndexToPosition(board_index)
        pyautogui.mouseDown()
        pyautogui.moveTo(board_position[0], board_position[1], duration=0.15)
        pyautogui.mouseUp()

    def placeChampOnBench(self, board_index, bench_index):
        """
        Places champion from given board position to given bench position.
        """
        pyautogui.moveTo(self.boardIndexToPosition(board_index))
        pyautogui.mouseDown()
        pyautogui.moveTo(420 + 122 * bench_index, 775, duration=0.15)
        pyautogui.mouseUp()

    def reorderChampOnBench(self, bench_index1, bench_index2):
        """
        Places champion from given bench position to another given bench position.
        """
        pyautogui.moveTo(420 + 122 * bench_index1, 775)
        pyautogui.mouseDown()
        pyautogui.moveTo(420 + 122 * bench_index2, 775, duration=0.15)
        pyautogui.mouseUp()

    def reorderChampOnBoard(self, board_index1, board_index2):
        """
        Places champion from given board position to another given board position.
        """
        pyautogui.moveTo(self.boardIndexToPosition(board_index1))
        board_position = self.boardIndexToPosition(board_index2)
        pyautogui.mouseDown()
        pyautogui.moveTo(board_position[0], board_position[1], duration=0.15)
        pyautogui.mouseUp()