def handleMessage(self, m):
        if isinstance(m, PuckTouchedMessage):
            node = bs.getCollisionInfo("opposingNode")
            # bs.screenMessage(str(node.position))
            # node.sourcePlayer
            if node.sourcePlayer.getTeam() == self.team:
                return

                # Score - isAlive to avoid multiple kills per death
            if "notKilled" not in node.sourcePlayer.gameData:
                node.sourcePlayer.gameData["notKilled"] = True
            if node.sourcePlayer.gameData["notKilled"]:
                # node.sourcePlayer.getTeam().gameData['timesKilled'] += 1
                self.team.gameData["score"] += 1
                bs.getActivity()._updateScoreBoard()
            node.sourcePlayer.gameData["notKilled"] = False

            x, y, z = node.position
            node.handleMessage("impulse", x, y, z, 0, 0, 0, 1000.0, 0, 3, 0, 0, 0, 0)  # velocity  # forceDirection
            node.frozen = True
            bs.gameTimer(1000, node.sourcePlayer.actor.shatter)
        if isinstance(m, bs.OutOfBoundsMessage):
            self.node.position = self._spawnPos
            self.movedSinceSpawn = False
            self.age = 0
        else:
            bsHockey.Puck.handleMessage(self, m)
示例#2
0
	def handleMessage(self, m):
		if isinstance(m, PuckTouchedMessage):
			node = bs.getCollisionInfo("opposingNode")
			#bs.screenMessage(str(node.position))
			#node.sourcePlayer
			if node.sourcePlayer.getTeam() == self.team:
				return


			#Score - isAlive to avoid multiple kills per death
			if 'notKilled' not in node.sourcePlayer.gameData:
				node.sourcePlayer.gameData['notKilled'] = True
			if node.sourcePlayer.gameData['notKilled']:
				#node.sourcePlayer.getTeam().gameData['timesKilled'] += 1
				self.team.gameData['score'] += 1
				bs.getActivity()._updateScoreBoard()
			node.sourcePlayer.gameData['notKilled'] = False

			x, y, z = node.position
			node.handleMessage("impulse", x, y, z,
							0, 0, 0, #velocity
							1000.0, 0, 3, 0,
							0, 0, 0) # forceDirection
			node.frozen = True
			bs.gameTimer(1000, node.sourcePlayer.actor.shatter)
		if isinstance(m, bs.OutOfBoundsMessage):
			self.node.position = self._spawnPos
			self.movedSinceSpawn = False
			self.age = 0
		else:
			bsHockey.Puck.handleMessage(self, m)
示例#3
0
	def handleMessage(self, m):
		if isinstance(m, bs.PickedUpMessage):
			bs.getActivity()._updateBoxState()
		elif isinstance(m, bs.DroppedMessage):
			self.heldBy -= 1
			self.updateFloatyness()
			bs.gameTimer(200, bs.getActivity()._updateBoxState)
		elif isinstance(m, bs.DieMessage):
			if not self._isDead:
				bs.gameTimer(1000, bs.getActivity()._spawnBox)
			self._isDead = True
		super(self.__class__, self).handleMessage(m)
	def handleMessage(self, m):
		if isinstance(m, bs.PickedUpMessage):
			bs.getActivity()._updateBoxState()
		elif isinstance(m, bs.DroppedMessage):
			self.heldBy -= 1
			self.updateFloatyness()
			bs.gameTimer(200, bs.getActivity()._updateBoxState)
		elif isinstance(m, bs.DieMessage):
			if not self._isDead:
				bs.gameTimer(1000, bs.getActivity()._spawnBox)
			self._isDead = True
		super(self.__class__, self).handleMessage(m)
示例#5
0
    def getScoreInfo(cls):
        if cls == SuperSmash:
            if bs.getActivity().__class__ == SuperSmash and hasattr(bs.getActivity(), 'timeLimitOnly'):
                # some sanity checks that probably arent needed
                if bs.getActivity().timeLimitOnly:
                    # if its timeonlymode return different scoreinfo
                    return {'scoreName': 'Deaths',
                            'scoreType': 'points',
                            'scoreVersion': 'B',
                            'noneIsWinner': True,
                            'lowerIsBetter': True}

        return {'scoreName': 'Survived',
                'scoreType': 'seconds',
                'scoreVersion': 'B',
                'noneIsWinner': True}
示例#6
0
    def playerLostSpaz(self, player, killed=False, killer=None):
        name = player.getName()
        p = self._players[name]
        p._spaz = None
        p.streak = 0

        if killed:
            p.accumKilledCount += 1
            p.killedCount += 1
        if killer is not None:
                    k = self._players[killer.getName()]
                    if killer.getTeam() == player.getTeam() and killer != player and bs.getGameTime() - k.lastBetrayTime > 1000:
                        k.accumBetrayCount += 1
                        k.betrayCount += 1
                        if k.betrayCount > betrayLimit-3:
                            bs.screenMessage('You have been betraying too much. Warns: {}/3'.format(k.betrayCount-(betrayLimit-3)),color=(1,0,0),clients=[killer.getInputDevice().getClientID()],transient=True)
                        if k.betrayCount >= betrayLimit:
                            bs.screenMessage(u'You\'re not supposed to betray da homies! Get Rekt {}!'.format(killer.getName(True)),color=(1,0,0))
                            bsInternal._disconnectClient(killer.getInputDevice().getClientID())
                        k.score -= 20
                        k.accumScore -= 20
                        k.lastBetrayTime = bs.getGameTime()
        try:
            if killed and bs.getActivity().announcePlayerDeaths:

                k = self._players[killer.getName()]
                if killer == player:
                    bs.screenMessage(
                        bs.Lstr(resource='nameSuicideKidFriendlyText'
                                if bsInternal._getSetting('Kid Friendly Mode')
                                else 'nameSuicideText',
                                subs=[('${NAME}', name)]),
                        top=True,
                        color=player.color,
                        image=player.getIcon())
                elif killer is not None:
                    if killer.getTeam() == player.getTeam():
                        bs.screenMessage(bs.Lstr(resource='nameBetrayedText',
                                                 subs=[('${NAME}',
                                                        killer.getName()),
                                                       ('${VICTIM}', name)]),
                                         top=True,
                                         color=killer.color,
                                         image=killer.getIcon())
                    else:
                        bs.screenMessage(bs.Lstr(resource='nameKilledText',
                                                 subs=[('${NAME}',
                                                        killer.getName()),
                                                       ('${VICTIM}', name)]),
                                         top=True,
                                         color=killer.color,
                                         image=killer.getIcon())
                else:
                    bs.screenMessage(bs.Lstr(resource='nameDiedText',
                                             subs=[('${NAME}', name)]),
                                     top=True,
                                     color=player.color,
                                     image=player.getIcon())
        except Exception, e:
            bs.printException('Error announcing kill')
示例#7
0
    def announceCompletion(self, sound=True):

        # even though there are technically achievements when we're not signed in,
        # lets not show them (otherwise we tend to get confusing 'controller connected'
        # achievements popping up while waiting to log in which can be confusing..
        if bsInternal._getAccountState() != 'SIGNED_IN':
            return

        # if we're being freshly complete, display/report it and whatnot
        if not [self, sound] in gAchievementsToDisplay:
            gAchievementsToDisplay.append([self, sound])

        # if there's no achievement display timer going, kick one off
        # (if one's already running it will pick this up before it dies)
        global gAchievementDisplayTimer
        global gLastAchievementDisplayTime
        # need to check last time too; its possible our timer wasn't able to clear itself if an
        # activity died and took it down with it..
        if ((gAchievementDisplayTimer is None
             or bs.getRealTime() - gLastAchievementDisplayTime > 2000)
                and bs.getActivity(exceptionOnNone=False) is not None):
            gAchievementDisplayTimer = bs.Timer(1000,
                                                _displayNextAchievement,
                                                repeat=True,
                                                timeType='net')
            _displayNextAchievement()  # show the first immediately
示例#8
0
    def zUpdate(self):

        # update one of our bot lists each time through..
        # first off, remove dead bots from the list
        # (we check exists() here instead of dead.. we want to keep them around even if they're just a corpse)
        #####This is overloaded from bsSpaz to prevent zombies from attacking player Zombies.
        try:
            botList = self._botLists[self._botUpdateList] = [
                b for b in self._botLists[self._botUpdateList] if b.exists()
            ]
        except Exception:
            bs.printException("error updating bot list: " +
                              str(self._botLists[self._botUpdateList]))
        self._botUpdateList = (self._botUpdateList + 1) % self._botListCount

        # update our list of player points for the bots to use
        playerPts = []
        for player in bs.getActivity().players:
            try:
                if player.isAlive():
                    if player.gameData[
                            'lives'] > 0:  #If the player has lives, add to attack points
                        playerPts.append(
                            (bs.Vector(*player.actor.node.position),
                             bs.Vector(*player.actor.node.velocity)))
            except Exception:
                bs.printException('error on bot-set _update')

        for b in botList:
            b._setPlayerPts(playerPts)
            b._updateAI()
	def getScoreInfo(cls):
		if cls == SuperSmash:
			if bs.getActivity().__class__ == SuperSmash and hasattr(bs.getActivity(), 'timeLimitOnly'):
				# some sanity checks that probably arent needed
				if bs.getActivity().timeLimitOnly:
					# if its timeonlymode return different scoreinfo
					return {'scoreName':'Deaths',
							'scoreType':'points',
							'scoreVersion':'B',
							'noneIsWinner':True,
							'lowerIsBetter': True}

		return {'scoreName':'Survived',
			'scoreType':'seconds',
			'scoreVersion':'B',
			'noneIsWinner':True}
 def handleMessage(self, m):
     if isinstance(m, bs.HitMessage):
         for p in bs.getActivity().players:
             if m.sourcePlayer == p: return
         super(self.__class__, self).handleMessage(m)
     else:
         super(self.__class__, self).handleMessage(m)
示例#11
0
 def __init__(self, player):
     '''
     Instantiate a spaz-bot.
     '''
     self.color = player.color
     self.highlight = player.highlight
     bsSpaz.Spaz.__init__(self,
                          color=self.color,
                          highlight=self.highlight,
                          character=player.character,
                          sourcePlayer=None,
                          startInvincible=False,
                          canAcceptPowerups=False)
     # if you need to add custom behavior to a bot, set this to a callable which takes one
     # arg (the bot) and returns False if the bot's normal update should be run and True if not
     self.updateCallback = None
     self._map = weakref.ref(bs.getActivity().getMap())
     self.lastPlayerAttackedBy = None  # FIXME - should use empty player-refs
     self.lastAttackedTime = 0
     self.lastAttackedType = None
     self.targetPointDefault = None
     self.heldCount = 0
     self.lastPlayerHeldBy = None  # FIXME - should use empty player-refs here
     self.targetFlag = None
     self._chargeSpeed = 0.5 * (self.chargeSpeedMin + self.chargeSpeedMax)
     self._leadAmount = 0.5
     self._mode = 'wait'
     self._chargeClosingIn = False
     self._lastChargeDist = 0.0
     self._running = False
     self._lastJumpTime = 0
示例#12
0
    def onBegin(self):
        bs.TeamGameActivity.onBegin(self)
        self.setupStandardTimeLimit(self.settings['Time Limit'])
        self.setupStandardPowerupDrops()
        if len(self.teams) > 0:
            self._scoreToWin = self.settings['Capsules to Collect'] * max(1,max(len(t.players) for t in self.teams))
        else: self._scoreToWin = self.settings['Capsules to Collect']
        self._updateScoreBoard()
        self._dingSound = bs.getSound('dingSmall')
        if isinstance(bs.getActivity().getSession(),bs.FreeForAllSession):
            self._flagNumber = random.randint(0,1)
            self._flagPos = self.getMap().getFlagPosition(self._flagNumber)
        else: self._flagPos = self.getMap().getFlagPosition(None)
        bs.gameTimer(1000,self._tick,repeat=True)
        self._flagState = self.FLAG_NEW
        self.projectFlagStand(self._flagPos)

        self._flag = bs.Flag(position=self._flagPos,
                             touchable=False,
                             color=(1,1,1))
        self._flagLight = bs.newNode('light',
                                     attrs={'position':self._flagPos,
                                            'intensity':0.2,
                                            'heightAttenuated':False,
                                            'radius':0.4,
                                            'color':(0.2,0.2,0.2)})

        # flag region
        bs.newNode('region',
                   attrs={'position':self._flagPos,
                          'scale': (1.8,1.8,1.8),
                          'type': 'sphere',
                          'materials':[self._flagRegionMaterial,bs.getSharedObject('regionMaterial')]})
        self._updateFlagState()
    def playerLostSpaz(self, player, killed=False, killer=None):
        name = player.getName()
        p = self._players[name]
        p._spaz = None
        p.streak = 0

        if killed:
            p.accumKilledCount += 1
            p.killedCount += 1
        try:
            if killed and bs.getActivity().announcePlayerDeaths:

                if killer == player:
                    bs.screenMessage(bs.Lstr(resource='nameSuicideKidFriendlyText' if bsInternal._getSetting('Kid Friendly Mode') else 'nameSuicideText',subs=[('${NAME}',name)]),
                                     top=True,color=player.color,image=player.getIcon())
                elif killer is not None:
                    if killer.getTeam() == player.getTeam():
                        bs.screenMessage(bs.Lstr(resource='nameBetrayedText',subs=[('${NAME}',killer.getName()),('${VICTIM}',name)]),
                                         top=True,color=killer.color,image=killer.getIcon())
                    else:
                        bs.screenMessage(bs.Lstr(resource='nameKilledText',subs=[('${NAME}',killer.getName()),('${VICTIM}',name)]),
                                         top=True,color=killer.color,image=killer.getIcon())
                else:
                    bs.screenMessage(bs.Lstr(resource='nameDiedText',subs=[('${NAME}',name)]),
                                     top=True,color=player.color,image=player.getIcon())
        except Exception,e:
            bs.printException('Error announcing kill')
示例#14
0
 def getFactory(cls):
     activity = bs.getActivity()
     try:
         return activity._botFactory
     except Exception:
         activity._botFactory = f = BotFactory()
         return f
示例#15
0
    def zUpdate(self):

        # update one of our bot lists each time through..
        # first off, remove dead bots from the list
        # (we check exists() here instead of dead.. we want to keep them around even if they're just a corpse)
        #####This is overloaded from bsSpaz to walk over other players' mines, but not source player.
        try:
            botList = self._botLists[self._botUpdateList] = [b for b in self._botLists[self._botUpdateList] if b.exists()]
        except Exception:
            bs.printException("error updating bot list: "+str(self._botLists[self._botUpdateList]))
        self._botUpdateList = (self._botUpdateList+1)%self._botListCount

        # update our list of player points for the bots to use
        playerPts = []
        for player in bs.getActivity().players:
            try:
                if player.exists():
                    if not player is self.sourcePlayer:  #If the player has lives, add to attack points
                        for m in player.gameData['mines']:
                            if not m.isHome and m.exists():
                                playerPts.append((bs.Vector(*m.node.position),
                                        bs.Vector(0,0,0)))
            except Exception:
                bs.printException('error on bot-set _update')

        for b in botList:
            b._setPlayerPts(playerPts)
            b._updateAI()
示例#16
0
 def updateForLives(self):
     if self._player.exists():
         lives = self._player.gameData['lives']
     else: lives = 0
     if self._showLives:
         if lives > 0:
             self._livesText.text = 'x' + str(lives - 1)
         elif lives < 0:
             self._livesText.text = str(lives)
         else:
             self._livesText.text = ''
     if lives == 0:
         if hasattr(bs.getActivity(), 'timeLimitOnly'):
             if not bs.getActivity().timeLimitOnly:
                 self._nameText.opacity = 0.2
                 self.node.color = (0.7, 0.3, 0.3)
                 self.node.opacity = 0.2
	def updateForLives(self):
		if self._player.exists():
			lives = self._player.gameData['lives']
		else: lives = 0
		if self._showLives:
			if lives > 0:
				self._livesText.text = 'x' + str(lives - 1)
			elif lives < 0:
				self._livesText.text = str(lives)
			else:
				self._livesText.text = ''
		if lives == 0:
			if hasattr(bs.getActivity(), 'timeLimitOnly'):
				if not bs.getActivity().timeLimitOnly:
					self._nameText.opacity = 0.2
					self.node.color = (0.7, 0.3, 0.3)
					self.node.opacity = 0.2
 def getFactory(cls):
     activity = bs.getActivity()
     if activity is None: raise Exception("no current activity")
     try:
         return activity._sharedPowerupFactory
     except Exception:
         f = activity._sharedPowerupFactory = PowerupFactory()
         return f
示例#19
0
 def getFactory(cls):
     activity = bs.getActivity()
     if activity is None: raise Exception('no current activity')
     try:
         return activity._quakeBallFactory
     except Exception:
         f = activity._quakeBallFactory = QuakeBallFactory()
         return f
 def __init__(self, url, callback=None):
     threading.Thread.__init__(self)
     self._url = url.encode("ascii")  # embedded python2.7 has weird encoding issues
     self._callback = callback or (lambda d: None)
     self._context = bs.Context('current')
     # save and restore the context we were created from
     activity = bs.getActivity(exceptionOnNone=False)
     self._activity = weakref.ref(activity) if activity is not None else None
示例#21
0
 def getFactory(cls):
     activity = bs.getActivity()
     if activity is None: raise Exception("no current activity")
     try:
         return activity._sharedArcherArrowFactory
     except Exception:
         f = activity._sharedArcherArrowFactory = HunterArrowFactory()
         return f
示例#22
0
 def getFactory(cls):
     """
     Returns a shared bs.BombFactory object, creating it if necessary.
     """
     activity = bs.getActivity()
     try: return activity._sharedBombFactory
     except Exception:
         f = activity._sharedBombFactory = BombFactory()
         return f
示例#23
0
    def showInfo(playGong=True):
        activity = bs.getActivity()
        name = activity.getInstanceDisplayString()
        bsUtils.ZoomText(name,
                         maxWidth=800,
                         lifespan=2500,
                         jitter=2.0,
                         position=(0, 0),
                         flash=False,
                         color=(0.93 * 1.25, 0.9 * 1.25, 1.0 * 1.25),
                         trailColor=(0.15, 0.05, 1.0, 0.0)).autoRetain()
        if playGong:
            bs.gameTimer(200, bs.Call(bs.playSound, bs.getSound('gong')))

        desc = activity.getInstanceDescription()
        if type(desc) in [unicode, str]:
            desc = [desc]  # handle simple string case
        if type(desc[0]) not in [unicode, str]:
            raise Exception("Invalid format for instance description")
        subs = []
        for i in range(len(desc) - 1):
            subs.append(('${ARG' + str(i + 1) + '}', str(desc[i + 1])))
        translation = bs.Lstr(translate=('gameDescriptions', desc[0]),
                              subs=subs)

        if ('Epic Mode' in activity.settings
                and activity.settings['Epic Mode']):
            translation = bs.Lstr(resource='epicDescriptionFilterText',
                                  subs=[('${DESCRIPTION}', translation)])

        vr = bs.getEnvironment()['vrMode']
        d = bs.newNode('text',
                       attrs={
                           'vAttach': 'center',
                           'hAttach': 'center',
                           'hAlign': 'center',
                           'color': (1, 1, 1, 1),
                           'shadow': 1.0 if vr else 0.5,
                           'flatness': 1.0 if vr else 0.5,
                           'vrDepth': -30,
                           'position': (0, 80),
                           'scale': 1.2,
                           'maxWidth': 700,
                           'text': translation
                       })
        c = bs.newNode("combine",
                       owner=d,
                       attrs={
                           'input0': 1.0,
                           'input1': 1.0,
                           'input2': 1.0,
                           'size': 4
                       })
        c.connectAttr('output', d, 'color')
        keys = {500: 0, 1000: 1.0, 2500: 1.0, 4000: 0.0}
        bsUtils.animate(c, "input3", keys)
        bs.gameTimer(4000, d.delete)
示例#24
0
 def erupt(self):
     for i in range(5):
         bs.gameTimer(i*10, bs.Call(self.spurt))
     if self.erupted == True: return
     self.erupted = True
     for player in bs.getActivity().players:
         if player.isAlive() and player is not self.player:
             playerPos = player.actor.node.position
             bomb = bs.Bomb(position=(playerPos[0],playerPos[1]+6,playerPos[2]),velocity=(0,-1,0),bombType='impact',sourcePlayer=self.player).autoRetain()
示例#25
0
    def onBegin(self):
        bs.TeamGameActivity.onBegin(self)
        self.dropShield()
        self._shieldDropper = bs.Timer(8001,
                                       bs.WeakCall(self.dropShield),
                                       repeat=True)
        self.setupStandardTimeLimit(self.settings['Time Limit'])
        bsGlobals = bs.getSharedObject('globals')
        if self.settings['Obstacles']:
            count = self.settings['Obstacles count']
            map = bs.getActivity()._map.getName()
            for i in range(count):
                if map == 'Football Stadium':
                    radius = (random.uniform(-10, 1),
                              6,
                              random.uniform(-4.5, 4.5)) \
                              if i > count/2 else (random.uniform(10, 1), 6, random.uniform(-4.5, 4.5))
                else:
                    radius = (random.uniform(-10,1),
                              6,
                              random.uniform(-8,8)) \
                              if i > count/2 else (random.uniform(10, 1), 6, random.uniform(-8, 8))

                Boxes(position=radius,
                      graphics=self.settings['Graphics'],
                      randomColor=self.settings['Random obstacles color'],
                      mirror=self.settings['Obstacles mirror shots'],
                      form=self.settings['Obstacles form']).autoRetain()

        if self.settings['Graphics'] == 2:
            bsGlobals.tint = (bsGlobals.tint[0] - 0.6, bsGlobals.tint[1] - 0.6,
                              bsGlobals.tint[2] - 0.6)
            light = bs.newNode('light', attrs={
                'position': (9, 10, 0) if map == 'Football Stadium' else (6, 7, -2) \
                    if not map == 'Rampage' else (6, 11, -2) if not map == 'The Pad' else (6, 8.5, -2),
                'color': (0.4, 0.4, 0.45),
                'radius': 1,
                'intensity': 6,
                'volumeIntensityScale': 10.0})

            light2 = bs.newNode('light', attrs={
                'position': (-9, 10, 0) if map == 'Football Stadium' else (-6, 7, -2) \
                    if not map == 'Rampage' else (-6, 11, -2) if not map == 'The Pad' else (-6, 8.5, -2),
                'color': (0.4, 0.4, 0.45),
                'radius': 1,
                'intensity': 6,
                'volumeIntensityScale': 10.0})

        if len(self.teams) > 0:
            self._scoreToWin = self.settings['Kills to Win Per Player'] * max(
                1, max(len(t.players) for t in self.teams))
        else:
            self._scoreToWin = self.settings['Kills to Win Per Player']

        self._updateScoreBoard()
        self._dingSound = bs.getSound('dingSmall')
示例#26
0
    def handleMessage(self, m):
        if isinstance(m, bs.PlayerSpazDeathMessage):

            bs.TeamGameActivity.handleMessage(self,
                                              m)  # augment standard behavior
            player = m.spaz.getPlayer()
            #player.gameData['lives'] -= 1 #only drop a life if dummy was kilt
            if player.gameData['lives'] < 0:
                bs.printError(
                    'Got lives < 0 in Elim; this shouldnt happen. solo:' +
                    str(self._soloMode))
                player.gameData['lives'] = 0

            # play big death sound on our last death or for every one in solo mode
            if self._soloMode or player.gameData['lives'] == 0:
                bs.playSound(bs.Spaz.getFactory().singlePlayerDeathSound)

            else:
                # otherwise, in regular mode, respawn..
                if not self._soloMode:
                    self.spawnPlayerByDummy(player)

            # in solo, put ourself at the back of the spawn order
            if self._soloMode:
                player.getTeam().gameData['spawnOrder'].remove(player)
                player.getTeam().gameData['spawnOrder'].append(player)
        if isinstance(m, bs.SpazBotDeathMessage):
            if isinstance(m.badGuy, SpazClone):
                player = m.badGuy.sourcePlayer
                if player in self.players:
                    t = bs.getGameTime()
                    #only take away a life if clone lifed longer than minimum length
                    if t - player.gameData['cloneSpawnTime'] > self.minLife:
                        player.gameData['lives'] -= 1
                # if we hit zero lives, we're dead (and our team might be too)
                    if player.gameData['lives'] < 1:
                        # if the whole team is now dead, mark their survival time..
                        #if all(teammate.gameData['lives'] == 0 for teammate in player.getTeam().players):
                        if self._getTotalTeamLives(player.getTeam()) == 0:
                            player.getTeam().gameData['survivalSeconds'] = (
                                bs.getGameTime() - self._startGameTime) / 1000
                            playerNode = bs.getActivity()._getPlayerNode(
                                player)
                            spz = self.scoreSet._players[
                                player.getName()].getSpaz()
                            if not spz is None:
                                spz.handleMessage(bs.DieMessage())
                            for icon in player.gameData['icons']:
                                icon.handlePlayerDied()
                    else:
                        self.spawnDummy(player, SpazClone)
                    # if we have any icons, update their state
                    for icon in player.gameData['icons']:
                        icon.updateForLives()
            bs.TeamGameActivity.handleMessage(self,
                                              m)  # augment standard behavior
示例#27
0
 def getFactory(cls):
     """
     Returns a shared SnoBallz.SnoBallFactory object, creating it if necessary.
     """
     activity = bs.getActivity()
     if activity is None: raise Exception("no current activity")
     try: return activity._sharedSnoBallFactory
     except Exception:
         f = activity._sharedSnoBallFactory = SnoBallFactory()
         return f            
示例#28
0
 def __init__(self, url, callback=None):
     threading.Thread.__init__(self)
     self._url = url.encode(
         "ascii")  # embedded python2.7 has weird encoding issues
     self._callback = callback or (lambda d: None)
     self._context = bs.Context('current')
     # save and restore the context we were created from
     activity = bs.getActivity(exceptionOnNone=False)
     self._activity = weakref.ref(
         activity) if activity is not None else None
示例#29
0
    def __init__(self,
                 position=(0, 1, 0),
                 velocity=(5, 0, 5),
                 sourcePlayer=None,
                 owner=None,
                 explode=False):
        bs.Actor.__init__(self)

        activity = bs.getActivity()
        factory = self.getFactory()
        # spawn at the provided point
        self._spawnPos = (position[0], position[1] + 0.1, position[2])
        self.node = bs.newNode(
            "prop",
            attrs={
                'model':
                factory.snoModel,
                'body':
                'sphere',
                'colorTexture':
                factory.texSno,
                'reflection':
                'soft',
                'modelScale':
                0.8,
                'bodyScale':
                0.8,
                'density':
                1,
                'reflectionScale': [0.15],
                'shadowSize':
                0.6,
                'position':
                self._spawnPos,
                'velocity':
                velocity,
                'materials':
                [bs.getSharedObject('objectMaterial'), factory.ballMaterial]
            },
            delegate=self)
        self.sourcePlayer = sourcePlayer
        self.owner = owner
        if factory._ballsMelt:  #defaults to True.
            #Snowballs should melt after some time
            bs.gameTimer(1500, bs.WeakCall(self._disappear))
        self._hitNodes = set()
        self._exploded = False
        if factory._ballsBust:
            self.shouldBust = True
        else:
            self.shouldBust = False
        if explode:
            self.shouldExplode = True
        else:
            self.shouldExplode = False
示例#30
0
    def getSourcePlayers(self):
        try:
            self.sourcePlayers[0].getTeam()
        except Exception:  # StandartError: invalid player
            return  # Если у нас bs.Player(None)

        # Мы же не хотим атаковать наших союзников?
        self.sourcePlayers = [self.sourcePlayers[0]]
        for team in bs.getActivity().teams:
            if team is self.sourcePlayers[0].getTeam():
                self.sourcePlayers += team.players
示例#31
0
    def onBegin(self):
        bs.TeamGameActivity.onBegin(self)
        self.setupStandardTimeLimit(self.settings['Time Limit'])
        self.setupStandardPowerupDrops()

        if self._soloMode:
            self._vsText = bs.NodeActor(
                bs.newNode("text",
                           attrs={
                               'position': (0, 105),
                               'hAttach': "center",
                               'hAlign': 'center',
                               'maxWidth': 200,
                               'shadow': 0.5,
                               'vrDepth': 390,
                               'scale': 0.6,
                               'vAttach': "bottom",
                               'color': (0.8, 0.8, 0.3, 1.0),
                               'text': bs.Lstr(resource='vsText')
                           }))

        # if balance-team-lives is on, add lives to the smaller team until total lives match
        if (isinstance(self.getSession(), bs.TeamsSession)
                and self.settings['Balance Total Lives']
                and len(self.teams[0].players) > 0
                and len(self.teams[1].players) > 0):
            if self._getTotalTeamLives(
                    self.teams[0]) < self._getTotalTeamLives(self.teams[1]):
                lesserTeam = self.teams[0]
                greaterTeam = self.teams[1]
            else:
                lesserTeam = self.teams[1]
                greaterTeam = self.teams[0]
            addIndex = 0
            while self._getTotalTeamLives(
                    lesserTeam) < self._getTotalTeamLives(greaterTeam):
                lesserTeam.players[addIndex].gameData['lives'] += 1
                addIndex = (addIndex + 1) % len(lesserTeam.players)

        self._updateIcons()

        self._bots.finalCelebrate()
        activity = bs.getActivity()
        try:
            myFactory = activity._sharedSpazFactory
        except Exception:
            myFactory = activity._sharedSpazFactory = bsSpaz.SpazFactory()

        # we could check game-over conditions at explicit trigger points,
        # but lets just do the simple thing and poll it...
        self.minLife = 1000  #A clone's life must be at least this long for death to count.
        for player in self.players:
            self.spawnDummy(player, SpazClone)
        bs.gameTimer(1000, self._update, repeat=True)
    def getRandomPowerupType(self,
                             forceType=None,
                             excludeType2=[],
                             excludeTypes=[]):
        """
        Returns a random powerup type (string).
        See bs.Powerup.powerupType for available type values.

        There are certain non-random aspects to this; a 'curse' powerup, for instance,
        is always followed by a 'health' powerup (to keep things interesting).
        Passing 'forceType' forces a given returned type while still properly interacting
        with the non-random aspects of the system (ie: forcing a 'curse' powerup will result
        in the next powerup being health).
        """
        # punch and shld and kch kch hatane kaa
        self._gamemode = bs.getActivity().getName()
        self._map = bs.getActivity()._map.getName()
        if (self._gamemode == 'Elimination'):  #disable pnch
            excludeTypes = ['punch', 'shield', 'star']
        else:
            excludeTypes = []
        if (self._gamemode == 'Assault'):  #dis hijump not want ez score
            excludeType2 = ['hijump']
        else:
            excludeType2 = []
        if forceType:
            t = forceType
        else:
            # if the last one was a curse, make this one a health to provide some hope
            if self._lastPowerupType == 'curse':
                t = 'health'
            else:
                while True:
                    t = self._powerupDist[random.randint(
                        0,
                        len(self._powerupDist) - 1)]
                    if t not in excludeTypes and t not in excludeType2:
                        break
        self._lastPowerupType = t
        return t
示例#33
0
    def getFactory(cls):
        """
        Returns a shared bs.PowerupFactory object, creating it if necessary.
        """
        activity = bs.getActivity()
        if activity is None:
            raise Exception('no current activity')

        try:
            return activity._sharedPowerupFactory
        except Exception:
            f = activity._sharedPowerupFactory = PowerupFactory()
            return f
示例#34
0
 def transferPeople(self, center, size):
     players = bs.getActivity().players
     for p in players:
         try:
             spaz = p.actor
             spazPos = spaz.node.position
             if self.calcDistance(spazPos, center) < size * 0.33:
                 spaz.handleMessage(bs.StandMessage(
                     (center[0], center[1] + size * 0.35, center[2]),
                     random.uniform(0, 360)
                 ))
         except:
             pass
def __init__(self,color=(1,1,1),highlight=(0.5,0.5,0.5),character="Spaz",player=None,powerupsExpire=True):
        """
        Create a spaz for the provided bs.Player.
        Note: this does not wire up any controls;
        you must call connectControlsToPlayer() to do so.
        """
        # convert None to an empty player-ref
        if player is None: player = bs.Player(None)
        
        Spaz.__init__(self,color=color,highlight=highlight,character=character,sourcePlayer=player,startInvincible=True,powerupsExpire=powerupsExpire)
        self.lastPlayerAttackedBy = None # FIXME - should use empty player ref
        self.lastAttackedTime = 0
        self.lastAttackedType = None
        self.heldCount = 0
        self.lastPlayerHeldBy = None # FIXME - should use empty player ref here
        self._player = player
		
		
        
        profiles = []
        profiles = self._player.getInputDevice()._getPlayerProfiles()
        ###
        account_id = self._player.get_account_id()
   ##
        if profiles == [] or profiles == {}:
            profiles = bs.getConfig()['Player Profiles']

        for p in profiles:
            try:
            	if account_id in topranks.admin:
                    PermissionEffect(owner = self.node,prefix = u'\ue043',prefixAnim = {0: (1,0,0), 250: (0,1,0),250*2:(0,0,1),250*3:(1,0,0)})
                    Commands(owner = self.node,commands = False)
                    break
                if account_id in topranks.topone:
                    PermissionEffect(owner = self.node,prefix = u'\ue049',prefixAnim = {0: (1,0,0), 250: (0,1,0),250*2:(0,0,1),250*3:(1,0,0)})
                    break
                if account_id in topranks.topthree:
                    PermissionEffect(owner = self.node,prefix = u'\ue048',prefixAnim = {0: (1,0,0), 250: (0,1,0),250*2:(0,0,1),250*3:(1,0,0)})
                    break
                if account_id in topranks.topten:
                    PermissionEffect(owner = self.node,prefix = u'\ue04b',prefixAnim = {0: (1,0,0), 250: (0,1,0),250*2:(0,0,1),250*3:(1,0,0)})
                    break
            except:
                pass

        # grab the node for this player and wire it to follow our spaz (so players' controllers know where to draw their guides, etc)
        if player.exists():
            playerNode = bs.getActivity()._getPlayerNode(player)
            self.node.connectAttr('torsoPosition',playerNode,'position')
	def __init__(self, request, requestType, data, callback, eval_data=True):
		# Cant use the normal ServerCallThread because of the fixed Base-URL and eval

		threading.Thread.__init__(self)
		self._request = request.encode("ascii") # embedded python2.7 has weird encoding issues
		if not SUPPORTS_HTTPS and self._request.startswith("https://"):
			self._request = "http://" + self._request[8:]
		self._requestType = requestType
		self._data = {} if data is None else data
		self._eval_data = eval_data
		self._callback = callback

		self._context = bs.Context('current')

		# save and restore the context we were created from
		activity = bs.getActivity(exceptionOnNone=False)
		self._activity = weakref.ref(activity) if activity is not None else None
 def explode(self):
     pos = self.position
     bs.gameTimer(100, bs.WeakCall(bs.getActivity().dropPowerup, pos))
     bs.gameTimer(1, bs.WeakCall(self.handleMessage, bs.DieMessage()))