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
def me(nick): if nick is None: return if isinstance(nick, bs.Player): n = nick.get_account_id() elif nick.startswith('pb'): n = nick else: return stats = db.getData(n) score = stats['s'] rank = db.getRank(n) points = stats['p'] message = bs.uni(stats['n']) message2 = u'\ue01f: ' + str(points) message3 = 'Total Score: ' + str(score) message4 = 'Rank: ' + str(rank) message5 = 'K: ' + str(stats['k']) message6 = 'D: ' + str(stats['d']) if n in joined: message7 = 'Time Spent: ' + str( datetime.timedelta(milliseconds=(bs.getRealTime() - joined[str(n)] + stats['tp']))).split('.', 2)[0] else: message7 = 'Time Spent: ' + \ str(datetime.timedelta(milliseconds=( stats['tp']))).split('.', 2)[0] bs.screenMessage(u' | '.join( [message, message2, message3, message4, message5, message6, message7])) clear(2500)
def join(accountid,clientID): if accountid is not None and clientID is not None: if db.isBanned(accountid): data = db.getBanData(accountid) bs.screenMessage( "You have been banned. Ban Expires on: {} IST".format( data['till'].strftime('%Y/%m/%d %H:%M:%S')), color=(1, 0, 0), clients=[clientID], transient=True) bsInternal._disconnectClient(clientID) return joined.update({accountid: bs.getRealTime()}) now_time = long(tim.strftime('%Y%m%d%H%M', tim.localtime(tim.time()))) stats = db.getData(accountid) if stats['i'] == []: stats['i'] = {} for name, exp in stats['i'].items(): if now_time > exp: bs.screenMessage( '%s Expired' % name, clients=[clientID], transient=True) stats['i'].pop(name) db.saveData(accountid, stats) daily(accountid,clientID) queue.remove(accountid)
def _cancelPress(self): if bs.getRealTime() - self._startTime < 1000: bs.playSound(bs.getSound('error')) return bsInternal._addTransaction({ 'type': 'DIALOG_RESPONSE', 'dialogID': self._dialogID, 'response': 0 }) bs.containerWidget(edit=self._rootWidget, transition='outScale')
def __init__(self, data): self._dialogID = data['dialogID'] txt = bs.Lstr(translate=('serverResponses', data['text']), subs=data.get('subs', [])).evaluate() txt = txt.strip() txtScale = 1.5 txtHeight = bsInternal._getStringHeight( txt, suppressWarning=True) * txtScale self._width = 500 self._height = 130 + min(200, txtHeight) self._rootWidget = bs.containerWidget( size=(self._width, self._height), transition='inScale', scale=1.8 if bsUI.gSmallUI else 1.35 if bsUI.gMedUI else 1.0) self._startTime = bs.getRealTime() bs.playSound(bs.getSound('swish')) t = bs.textWidget(parent=self._rootWidget, position=(self._width * 0.5, 70 + (self._height - 70) * 0.5), size=(0, 0), color=(1.0, 3.0, 1.0), scale=txtScale, hAlign="center", vAlign="center", text=txt, maxWidth=self._width * 0.85, maxHeight=(self._height - 110)) showCancel = data.get('showCancel', True) if showCancel: self._cancelButton = bs.buttonWidget( parent=self._rootWidget, position=(30, 30), size=(160, 60), autoSelect=True, label=bs.Lstr(resource='cancelText'), onActivateCall=self._cancelPress) else: self._cancelButton = None self._okButton = bs.buttonWidget( parent=self._rootWidget, position=((self._width - 182) if showCancel else (self._width * 0.5 - 80), 30), size=(160, 60), autoSelect=True, label=bs.Lstr(resource='okText'), onActivateCall=self._okPress) bs.containerWidget(edit=self._rootWidget, cancelButton=self._cancelButton, startButton=self._okButton, selectedChild=self._okButton)
def _handleFlagEnteredBase(self, team): flag = bs.getCollisionInfo("opposingNode").getDelegate() if flag.getTeam() is team: team.gameData['homeFlagAtBase'] = True # if the enemy flag is already here, score! if team.gameData['enemyFlagAtBase']: self._score(team) else: team.gameData['enemyFlagAtBase'] = True if team.gameData['homeFlagAtBase']: # award points to whoever was carrying the enemy flag try: player = flag._lastPlayerToHold except Exception: player = None if player is not None and player.exists( ) and player.getTeam() is team: self.scoreSet.playerScored(player, 50, bigMessage=True) # update score and reset flags self._score(team) # if the home-team flag isn't here, print a message to that effect else: if not hasattr(self, '_lastHomeFlagNoticePrintTime'): self._lastHomeFlagNoticePrintTime = 0 t = bs.getRealTime() if t - self._lastHomeFlagNoticePrintTime > 5000: self._lastHomeFlagNoticePrintTime = t p = team.gameData['basePos'] tNode = bs.newNode( 'text', attrs={ 'text': bs.Lstr(resource='ownFlagAtYourBaseWarning'), 'inWorld': True, 'scale': 0.013, 'color': (1, 1, 0, 1), 'hAlign': 'center', 'position': (p[0], p[1] + 3.2, p[2]) }) bs.gameTimer(5100, tNode.delete) bs.animate(tNode, 'scale', { 0: 0, 200: 0.013, 4800: 0.013, 5000: 0 })
def showCompletionBanner(self, sound=True): global gLastAchievementDisplayTime gLastAchievementDisplayTime = bs.getRealTime() # just piggy-back onto any current activity... # (should we use the session instead?..) activity = bs.getActivity(exceptionOnNone=False) # if this gets called while this achievement is occupying a slot already, ignore it.. # (probably should never happen in real life but whatevs..) if self._completionBannerSlot is not None: return if activity is None: print 'showCompletionBanner() called with no current activity!' return if sound: bs.playSound(bs.getSound('achievement'), hostOnly=True) else: bs.gameTimer( 500, bs.Call(bs.playSound, bs.getSound('ding'), hostOnly=True)) yOffs = 0 inTime = 300 outTime = 3500 baseVRDepth = 200 # find the first free slot i = 0 while True: if not i in gCompletionBannerSlots: #print 'ADDING SLOT',i,'FOR',self gCompletionBannerSlots.add(i) self._completionBannerSlot = i # remove us from that slot when we close.. # use a real-timer in the UI context so the removal runs even if our activity/session dies with bs.Context('UI'): bs.realTimer(inTime + outTime, self._removeBannerSlot) break i += 1 yOffs = 110 * self._completionBannerSlot objs = [] obj = bsUtils.Image(bs.getTexture('shadow'), position=(-30, 30 + yOffs), front=True, attach='bottomCenter', transition='inBottom', vrDepth=baseVRDepth - 100, transitionDelay=inTime, transitionOutDelay=outTime, color=(0.0, 0.1, 0, 1), scale=(1000, 300)).autoRetain() objs.append(obj) obj.node.hostOnly = True obj = bsUtils.Image(bs.getTexture('light'), position=(-180, 60 + yOffs), front=True, attach='bottomCenter', vrDepth=baseVRDepth, transition='inBottom', transitionDelay=inTime, transitionOutDelay=outTime, color=(1.8, 1.8, 1.0, 0.0), scale=(40, 300)).autoRetain() objs.append(obj) obj.node.hostOnly = True obj.node.premultiplied = True c = bs.newNode('combine', owner=obj.node, attrs={'size': 2}) bsUtils.animate( c, 'input0', { inTime: 0, inTime + 400: 30, inTime + 500: 40, inTime + 600: 30, inTime + 2000: 0 }) bsUtils.animate( c, 'input1', { inTime: 0, inTime + 400: 200, inTime + 500: 500, inTime + 600: 200, inTime + 2000: 0 }) c.connectAttr('output', obj.node, 'scale') bsUtils.animate(obj.node, 'rotate', {0: 0.0, 350: 360.0}, loop=True) obj = bsUtils.Image(self.getIconTexture(True), position=(-180, 60 + yOffs), attach='bottomCenter', front=True, vrDepth=baseVRDepth - 10, transition='inBottom', transitionDelay=inTime, transitionOutDelay=outTime, scale=(100, 100)).autoRetain() objs.append(obj) obj.node.hostOnly = True # flash color = self.getIconColor(True) c = bs.newNode('combine', owner=obj.node, attrs={'size': 3}) keys = { inTime: 1.0 * color[0], inTime + 400: 1.5 * color[0], inTime + 500: 6.0 * color[0], inTime + 600: 1.5 * color[0], inTime + 2000: 1.0 * color[0] } bsUtils.animate(c, 'input0', keys) keys = { inTime: 1.0 * color[1], inTime + 400: 1.5 * color[1], inTime + 500: 6.0 * color[1], inTime + 600: 1.5 * color[1], inTime + 2000: 1.0 * color[1] } bsUtils.animate(c, 'input1', keys) keys = { inTime: 1.0 * color[2], inTime + 400: 1.5 * color[2], inTime + 500: 6.0 * color[2], inTime + 600: 1.5 * color[2], inTime + 2000: 1.0 * color[2] } bsUtils.animate(c, 'input2', keys) c.connectAttr('output', obj.node, 'color') obj = bsUtils.Image(bs.getTexture('achievementOutline'), modelTransparent=bs.getModel('achievementOutline'), position=(-180, 60 + yOffs), front=True, attach='bottomCenter', vrDepth=baseVRDepth, transition='inBottom', transitionDelay=inTime, transitionOutDelay=outTime, scale=(100, 100)).autoRetain() obj.node.hostOnly = True # flash color = (2, 1.4, 0.4, 1) c = bs.newNode('combine', owner=obj.node, attrs={'size': 3}) keys = { inTime: 1.0 * color[0], inTime + 400: 1.5 * color[0], inTime + 500: 6.0 * color[0], inTime + 600: 1.5 * color[0], inTime + 2000: 1.0 * color[0] } bsUtils.animate(c, 'input0', keys) keys = { inTime: 1.0 * color[1], inTime + 400: 1.5 * color[1], inTime + 500: 6.0 * color[1], inTime + 600: 1.5 * color[1], inTime + 2000: 1.0 * color[1] } bsUtils.animate(c, 'input1', keys) keys = { inTime: 1.0 * color[2], inTime + 400: 1.5 * color[2], inTime + 500: 6.0 * color[2], inTime + 600: 1.5 * color[2], inTime + 2000: 1.0 * color[2] } bsUtils.animate(c, 'input2', keys) c.connectAttr('output', obj.node, 'color') objs.append(obj) obj = bsUtils.Text(bs.Lstr(value='${A}:', subs=[('${A}', bs.Lstr(resource='achievementText')) ]), position=(-120, 91 + yOffs), front=True, vAttach='bottom', vrDepth=baseVRDepth - 10, transition='inBottom', flatness=0.5, transitionDelay=inTime, transitionOutDelay=outTime, color=(1, 1, 1, 0.8), scale=0.65).autoRetain() objs.append(obj) obj.node.hostOnly = True obj = bsUtils.Text(self.getDisplayString(), position=(-120, 50 + yOffs), front=True, vAttach='bottom', transition='inBottom', vrDepth=baseVRDepth, flatness=0.5, transitionDelay=inTime, transitionOutDelay=outTime, flash=True, color=(1, 0.8, 0, 1.0), scale=1.5).autoRetain() objs.append(obj) obj.node.hostOnly = True obj = bsUtils.Text(bs.getSpecialChar('ticket'), position=(-120 - 170 + 5, 75 + yOffs - 20), front=True, vAttach='bottom', hAlign='center', vAlign='center', transition='inBottom', vrDepth=baseVRDepth, transitionDelay=inTime, transitionOutDelay=outTime, flash=True, color=(0.5, 0.5, 0.5, 1), scale=3.0).autoRetain() objs.append(obj) obj.node.hostOnly = True obj = bsUtils.Text('+' + str(self.getAwardTicketValue()), position=(-120 - 180 + 5, 80 + yOffs - 20), vAttach='bottom', front=True, hAlign='center', vAlign='center', transition='inBottom', vrDepth=baseVRDepth, flatness=0.5, shadow=1.0, transitionDelay=inTime, transitionOutDelay=outTime, flash=True, color=(0, 1, 0, 1), scale=1.5).autoRetain() objs.append(obj) obj.node.hostOnly = True # add the 'x 2' if we've got pro if bsUtils._havePro(): obj = bsUtils.Text('x 2', position=(-120 - 180 + 45, 80 + yOffs - 50), vAttach='bottom', front=True, hAlign='center', vAlign='center', transition='inBottom', vrDepth=baseVRDepth, flatness=0.5, shadow=1.0, transitionDelay=inTime, transitionOutDelay=outTime, flash=True, color=(0.4, 0, 1, 1), scale=0.9).autoRetain() objs.append(obj) obj.node.hostOnly = True obj = bsUtils.Text( self.getDescriptionComplete(), # self.getDescriptionCompleteLocalized(), position=(-120, 30 + yOffs), front=True, vAttach='bottom', transition='inBottom', vrDepth=baseVRDepth - 10, flatness=0.5, transitionDelay=inTime, transitionOutDelay=outTime, color=(1.0, 0.7, 0.5, 1.0), scale=0.8).autoRetain() objs.append(obj) obj.node.hostOnly = True for obj in objs: bs.gameTimer(outTime + 1000, bs.WeakCall(obj.handleMessage, bs.DieMessage()))
def run(self): score_set = self.score_set for p_entry in score_set.getValidPlayers().values(): try: account_id = p_entry.getPlayer().get_account_id() except: continue clid = p_entry.getPlayer().getInputDevice().getClientID() account_name = bs.uni( p_entry.getPlayer().getInputDevice()._getAccountName(True)) if account_id is None: continue stats = db.getData(account_id) for i, k in db.defaults.items(): stats.setdefault(i, k) import handle if account_id in handle.joined: stats['tp'] += bs.getRealTime() - \ handle.joined[account_id] handle.joined[account_id] = bs.getRealTime() stats['k'] += p_entry.accumKillCount stats['d'] += p_entry.accumKilledCount stats['s'] += min(p_entry.accumScore, 250) stats['b'] += p_entry.accumBetrayCount stats['n'] = p_entry.getPlayer().getName(full=True, icon=False) bonus = min( int(((p_entry.accumScore / 10) + (p_entry.accumKillCount * 5)) / 2), 70) stats['p'] += min( (int(p_entry.accumScore / 10) + p_entry.accumKillCount * 5) / 2, 70) stats['c'] = p_entry.getPlayer().character high = p_entry.getPlayer().highlight high = 65536 * (high[0] * 255) + 256 * (high[1] * 255) + (high[2] * 255) stats['ch'] = high high = p_entry.getPlayer().color high = 65536 * (high[0] * 255) + 256 * (high[1] * 255) + (high[2] * 255) stats['cc'] = high stats['ls'] = datetime.datetime.now().strftime( '%d/%m/%Y, %H:%M:%S') if not account_name in stats['a']: stats['a'].append(account_name) db.saveData(account_id, stats, final=True) if some.earned_msg: bs.screenMessage(u'You have earned {} \ue01f'.format( min((int(p_entry.accumScore / 10) + p_entry.accumKillCount * 5) / 2, 70)), color=(0.5, 1, 0.5), transient=True, clients=[clid]) try: import weakref act = weakref.proxy(bsInternal._getForegroundHostActivity()) teams = {} for p in act.players: teams[p.getTeam()] = teams.get(p.getTeam(), 0) + 1 diff = max(teams.values()) - min(teams.values()) if diff >= 2: v = list(teams.values()) k = list(teams.keys()) maxTeam = (k[v.index(max(v))]) minTeam = (k[v.index(min(v))]) for i in range(diff - 1): p = maxTeam.players[i] bs.screenMessage( u'Changing {}\'s Team To Balance The Game'.format( p.getName()), transient=True) p._setData(team=minTeam, character=p.character, color=minTeam.color, highlight=p.highlight) info = p._getIconInfo() p._setIconInfo(info['texture'], info['tintTexture'], minTeam.color, p.highlight) break except: pass db.updateRanks() import gc gc.collect()
def _chatFilter(msg, clientID): msg = bs.uni(msg.rstrip()) if clientID == -1: return msg if some.chatMuted and not msg == '/unmute': bs.screenMessage('Admin Has Muted The Chat For Some Time', color=(1, 0, 0), clients=[clientID], transient=True) return None m = msg.split(' ')[0] a = msg.split(' ')[1:] if m in ['/pvtmsg','/dm','/pm']: try: def getPlayerFromMention(mention): for i in bsInternal._getForegroundHostActivity().players: if i.getName().lower().find(mention.lower()) != -1: return i else: return None def getPlayerFromClientID(clientID): for i in bsInternal._getForegroundHostActivity().players: if i.getInputDevice().getClientID() == clientID: return i else: return None if a[0].isdigit(): for player in bsInternal._getForegroundHostActivity().players: if a[0] == str(bsInternal._getForegroundHostSession().players.index(player)): fr = getPlayerFromClientID(clientID) what = ' '.join(a[1:]).encode('utf-8') to = player bs.screenMessage('Private Message Has Been Sent To {}: {}'.format(to.getName(True).encode('utf-8'),what),transient=True,clients=[fr.getInputDevice().getClientID()],color=(0,2,2)) bs.screenMessage('Private Message From {}: {}'.format(fr.getName(True).encode('utf-8'),what),transient=True,clients=[to.getInputDevice().getClientID()],color=(0,2,2)) else: to = getPlayerFromMention(a[0]) fr = getPlayerFromClientID(clientID) what = ' '.join(a[1:]) bs.screenMessage('Private Message Has Been Sent To {}: {}'.format(to.getName(True).encode('utf-8'),what),transient=True,clients=[fr.getInputDevice().getClientID()],color=(0,2,2)) bs.screenMessage('Private Message From {}: {}'.format(fr.getName(True).encode('utf-8'),what),transient=True,clients=[to.getInputDevice().getClientID()],color=(0,2,2)) return None except Exception as e: bs.screenMessage('Format: /pvtmsg <name> <message>') print e if clientID in mutedIDs: bs.screenMessage( 'Admin has muted you for some time. Pro Tip: Stop Begging or Spamming', color=(1, 0, 0), clients=[clientID], transient=True) return None r = bsInternal._getGameRoster() split = msg.split(' ') if split[0] in timeouts: timeout = timeouts[split[0]] * 1000 if clientID in last: if (bs.getRealTime() - last[clientID][split[0]]) < timeout: bs.screenMessage( '{} Rate-Limited. Please wait for {} seconds.'.format( split[0], timeouts[split[0]] - (bs.getRealTime() - last[clientID][split[0]]) / 1000), color=(1, 0, 0), clients=[clientID], transient=True) return None else: last[clientID][split[0]] = bs.getRealTime() else: last[clientID] = {} for i in timeouts.keys(): last[clientID][i] = -99999 for a in r: if a['clientID'] == clientID: if len(a['players']) > 0: name = a['players'][0]['name'] player = handle.getPlayerFromNick(name) account_id = '-' if player is None else player.get_account_id() playerInGame = True else: name = (a['displayString']) account_id = '-' playerInGame = False break else: print r return None name = bs.uni(name) #if not '/!' in msg: start_new_thread(db.logChat,(msg, name, account_id)) #Chat Logs if not db.getAdmin(account_id): import re old_msg = msg clean_msg = re.sub('[^A-Za-z0-9 ]+', '', msg) for word in filter_words: if re.search(r'\b({})\b'.format(word), clean_msg, re.IGNORECASE): cen = ''.join( random.choice(list('@#$%!')) for a in range(len(word))) clean_msg = re.sub(r'\b({})\b'.format(word), cen, clean_msg, flags=re.IGNORECASE) msg = clean_msg if msg != old_msg: import kicker kicker.kick(name, reason='Abuse', warn=True) return msg if msg.startswith('/trans '): if _googletrans: start_new_thread( trans, (' '.join(msg.split(' ')[2:]), name, msg.split(' ')[1])) if msg.startswith('/'): if playerInGame: cmds.append([clientID, msg]) return None if msg.startswith( tuple(['/kick', '/warn', '/mute', '/unmute', '/!'])) else msg else: bs.screenMessage('Please Join The Game First', color=(1, 0.5, 0.5), transient=True, clients=[clientID]) if 'admin' in msg.lower() or 'mod' in msg.lower( ) or 'promote' in msg.lower(): for i in ['pls', 'please', 'give', 'want', 'can i']: if i in msg.lower(): bs.screenMessage( 'Stop Begging For Admin! This Server is Self-Sufficient!', color=(1, 0, 0), transient=True, clients=[clientID]) import kicker kicker.kick(name, reason='Begging', warn=True) return msg # if not msg in some.trans: # t = msg # d = 'en' # lang = translator.detect(t) # if (lang.lang in supported_langs): # tym = translator.translate('Translating Your Message...',lang.lang).text # bs.screenMessage(tym, # color=(0, 0.5, 0.5), transient=True, clients=[clientID]) # tn = translator.translate(t, d).pronunciation # if tn is None: # tn = bs.utf8(translator.translate(t, d).text) # tc = bs.utf8(profanity.censor(tn)) # if tc != tn: # import kicker # kicker.kick(n, reason='Abuse', warn=True) # if tc.lower() != t.lower(): # msg = '{} ({}) > {} (en)'.format(msg,lang.lang,tc) if not msg.lower() in some.trans and _googletrans: start_new_thread(trans, (msg, name)) return msg