def avatarSideFollowAttack(suit, toon, duration, battle): windupDuration = duration * (0.10000000000000001 + whrandom.random() * 0.10000000000000001) projectDuration = duration * 0.75 impactDuration = duration - windupDuration - projectDuration suitHeight = suit.getHeight() toonHeight = toon.getHeight() suitCentralPoint = suit.getPos(battle) suitCentralPoint.setZ(suitCentralPoint.getZ() + suitHeight * 0.75) toonCentralPoint = toon.getPos(battle) toonCentralPoint.setZ(toonCentralPoint.getZ() + toonHeight * 0.75) initialX = whrandom.randint(12, 14) finalX = whrandom.randint(7, 8) initialY = whrandom.randint(-3, 0) finalY = whrandom.randint(-3, 0) initialZ = suitHeight * 0.5 + whrandom.random() * suitHeight finalZ = toonHeight * 0.5 + whrandom.random() * toonHeight if whrandom.random() > 0.5: initialX = -initialX finalX = -finalX return Track([ focusShot(initialX, initialY, initialZ, windupDuration, suitCentralPoint), focusMoveShot(finalX, finalY, finalZ, projectDuration, toonCentralPoint), WaitInterval(impactDuration) ])
def InitNewSDLVars(self): ageSDL = PtGetAgeSDL() ageSDL['UrwinLastUpdated'] = (PtGetDniTime(), ) beginningOfToday = (PtGetDniTime() - int( (PtGetAgeTimeOfDayPercent() * kDayLengthInSeconds))) endOfToday = (int((kDayLengthInSeconds / 2)) + beginningOfToday) randnum = float(whrandom.randint(0, kFirstMorningSpawn)) firstTime = (int( ((randnum / 1000.0) * kDayLengthInSeconds)) + beginningOfToday) print('nglnUrwinBrain: Generated a valid spawn time: %d' % firstTime) spawnTimes = [firstTime] while (type(spawnTimes[-1]) == type(long(1))): randnum = whrandom.randint(kMinimumTimeBetweenSpawns, kMaximumTimeBetweenSpawns) newTime = (spawnTimes[-1] + randnum) if (newTime < endOfToday): print('nglnUrwinBrain: Generated a valid spawn time: %d' % newTime) spawnTimes.append(newTime) else: print( 'nglnUrwinBrain: Generated a spawn time after dusk, exiting loop: %d' % newTime) break else: print "nglnUrwinBrain:ERROR---Tried to add a spawn time that's not a number: ", print spawnTimes spawnTimes = [0] while (len(spawnTimes) < 20): spawnTimes.append(0) ageSDL['UrwinSpawnTimes'] = tuple(spawnTimes)
def InitNewSDLVars(self): ageSDL = PtGetAgeSDL() ageSDL["UrwinLastUpdated"] = (PtGetDniTime(),) beginningOfToday = PtGetDniTime() - int(PtGetAgeTimeOfDayPercent() * kDayLengthInSeconds) endOfToday = int(kDayLengthInSeconds / 2) + beginningOfToday #print "Dawn: %d Dusk: %d" % (beginningOfToday, endOfToday) # We need a random times in the first 5 hours of the day # which is in the first 44.5 percent of the day. So we're # generating a number from 0 to 445 and dividing by 1000 to get # something roughly in that timeframe. randnum = float(whrandom.randint(0,kFirstMorningSpawn)) firstTime = int((randnum / 1000.0) * kDayLengthInSeconds) + beginningOfToday print "payiUrwinBrain: Generated a valid spawn time: %d" % (firstTime) spawnTimes = [firstTime] while type(spawnTimes[-1]) == type(long(1)): randnum = whrandom.randint(kMinimumTimeBetweenSpawns, kMaximumTimeBetweenSpawns) newTime = spawnTimes[-1] + randnum if newTime < endOfToday: print "payiUrwinBrain: Generated a valid spawn time: %d" % (newTime) spawnTimes.append(newTime) else: print "payiUrwinBrain: Generated a spawn time after dusk, exiting loop: %d" % (newTime) break else: print "payiUrwinBrain:ERROR---Tried to add a spawn time that's not a number: " , spawnTimes spawnTimes = [0] while len(spawnTimes) < 20: spawnTimes.append(0) ageSDL["UrwinSpawnTimes"] = tuple(spawnTimes)
def GetRandomName(self): "Build a random name from random numbers" fname = whrandom.randint(NAME_LOWER_BOUND, NAME_UPPER_BOUND) lname = whrandom.randint(NAME_LOWER_BOUND, NAME_UPPER_BOUND) name = ` fname ` + " " + ` lname ` + ` lname ` return name
def InitNewSDLVars(self): ageSDL = PtGetAgeSDL() ageSDL["UrwinLastUpdated"] = (PtGetDniTime(),) beginningOfToday = PtGetDniTime() - int(PtGetAgeTimeOfDayPercent() * kDayLengthInSeconds) endOfToday = int(kDayLengthInSeconds / 2) + beginningOfToday #print "Dawn: %d Dusk: %d" % (beginningOfToday, endOfToday) # We need a random times in the first 5 hours of the day # which is in the first 44.5 percent of the day. So we're # generating a number from 0 to 445 and dividing by 1000 to get # something roughly in that timeframe. randnum = float(whrandom.randint(0,kFirstMorningSpawn)) firstTime = int((randnum / 1000.0) * kDayLengthInSeconds) + beginningOfToday print "nglnUrwinBrain: Generated a valid spawn time: %d" % (firstTime) spawnTimes = [firstTime] while type(spawnTimes[-1]) == type(long(1)): randnum = whrandom.randint(kMinimumTimeBetweenSpawns, kMaximumTimeBetweenSpawns) newTime = spawnTimes[-1] + randnum if newTime < endOfToday: print "nglnUrwinBrain: Generated a valid spawn time: %d" % (newTime) spawnTimes.append(newTime) else: print "nglnUrwinBrain: Generated a spawn time after dusk, exiting loop: %d" % (newTime) break else: print "nglnUrwinBrain:ERROR---Tried to add a spawn time that's not a number: " , spawnTimes spawnTimes = [0] while len(spawnTimes) < 20: spawnTimes.append(0) ageSDL["UrwinSpawnTimes"] = tuple(spawnTimes)
def unregister(self): i = whrandom.randint(0, len(self.np)-1) r = whrandom.randint(0, (self.np[i].num_notices)-1) #while (not self.np[i].notice_names_flgs[r]): #search for a registered notice #i = whrandom.randint(0, len(self.np)-1) #r = whrandom.randint(0, (self.np[i].num_notices)-1) name_str = self.np[i].notice_names[r] lock1.acquire() print "REPORTER "+self.id+": unregister notice "+name_str timestamp = time.time() #self.notice_sess.unregister_notice(name_str) self.conn.unregister_notice(name_str) #check if we were currently registered for this notification if self.np_stats.notice_names_flgs[i][r] == 1: #flag notice as NOT registered for self.np_stats.notice_names_flgs[i][r] = 0 #record stop time self.np_stats.notice_names_intervals[i][r][1] = timestamp #write notice_name and start and stop times to log file self.file_ptr.write('"'+name_str+'", '+`self.np_stats.notice_names_intervals[i][r][0]`+', '+`timestamp`+'\n') lock1.release()
def fillscreen(im): (maxx,maxy)=im.size for y in xrange(maxy): print y for x in xrange(maxx): if pointwhite(im,x,y): color=(whrandom.randint(1,255),whrandom.randint(1,255),whrandom.randint(1,255)) floodfill(im,x,y,color)
def _codedate(date): if date is None: yyyy = whrandom.randint(3000,9999) mm = whrandom.randint(1,12) dd = whrandom.randint(1,31) else: yyyy, mm, dd = date return _codeint(yyyy, 3) + _codeint(mm, 1) + _codeint(dd, 1)
def ShroomieSurfaces(self,spawn): ageSDL = PtGetAgeSDL() respVisible.run(self.key) if spawn == 1: # it was the lever pull which attracted Shroomie tldnMainPowerOn = ageSDL["tldnMainPowerOn"][0] whichbehavior = whrandom.randint(1,4) if tldnMainPowerOn: print "tldnShroomieBrain: The Power Tower noise has scared Shroomie. He'll come, but not very close." NearOrFar = "Far" else: #Determine how far out Shroomie will be seen. Added 12/12/2004 print "tldnShroomieBrain: The Power Tower is down, so Shroomie isn't scared by the noise." howclose = whrandom.randint(1,100) if howclose == 1: NearOrFar = "Near" elif howclose > 1 and howclose < 50: NearOrFar = "Mid" elif howclose >= 50: NearOrFar = "Far" else: # it was entering a shoreside zone that attracted Shroomie whichbehavior = whrandom.randint(2,4) NearOrFar = "Far" print "tldnShroomieBrain: whichbehavior = ",whichbehavior," NearOrFar = ",NearOrFar whichspawnpoint = whrandom.randint(1,5) if NearOrFar == "Near": code = "target = SpawnNear0" + str(whichspawnpoint) + ".sceneobject.getKey()" elif NearOrFar == "Mid": code = "target = SpawnMid0" + str(whichspawnpoint) + ".sceneobject.getKey()" elif NearOrFar == "Far": code = "target = SpawnFar0" + str(whichspawnpoint) + ".sceneobject.getKey()" print "target code:", code exec code ShroomieMaster.sceneobject.physics.warpObj(target) code = "respTrick0" + str(whichbehavior) + ".run(self.key)" #~ print "code = ", code exec code CurrentTime = PtGetDniTime() ageSDL["ShroomieTimeLastSeen"] = (CurrentTime,) ShroomieTotalTimesSeen = ageSDL["ShroomieTotalTimesSeen"][0] ShroomieTotalTimesSeen = ShroomieTotalTimesSeen + 1 ageSDL["ShroomieTotalTimesSeen"] = (ShroomieTotalTimesSeen,) print "tldnShroomieBrain: Shroomie has been seen", ShroomieTotalTimesSeen,"times."
def request_notice(self): #probability factor p = whrandom.randint(0, 100) if p <= self.probibility: #pick a random notice r = whrandom.randint(0, self.num_notices-1) return self.notice_names[r] else: return None
def GenArtWord(self, Wordlength): """ GenArtWord(self, Wordlength) Builds an artifical word (with length Wordlength) out of Levelchars and Permitchars. Does it like: random(lchar) + random(pchar) + ..... """ ret = "" while len(ret) < Wordlength: ret = ret + self.llist[randint(0, len(self.llist) - 1)] + self.plist[randint(0, len(self.plist) - 1)] return ret
def __init__(self, one, two=None, retention=None): self.dir = whrandom.randint(0,1) self.dir = 1 if two==None: match = self.entry_re.match(one) retention = match.group('_3') if retention == None: retention = whrandom.randint(0,(SIZE/2)-1) else: retention = string.atoi(retention) self.ret, self.one, self.two = retention, match.group('_1'), match.group('_2') else: self.ret, self.one, self.two = string.atoi(retention), one, two
def getSalt(): salt = "" for j in range(2): i = whrandom.randint(0,9)%3 if i == 0 : i = (whrandom.randint(0,9)%11) elif i == 1: i = (whrandom.randint(0,9)%25) elif i == 2: i = (whrandom.randint(0,9)%25) salt = salt + str(i) return (salt)
def send_notice(self): i = whrandom.randint(0, len(self.np)-1) r = whrandom.randint(0, (self.np[i].num_notices)-1) name_str = self.np[i].notice_names[r] #msg_str = '' snd_time = `time.time()` msg_str = "('"+snd_time+"')" bounded_name_str = "{"+name_str+"}" print "DISPATCHER: send notice "+bounded_name_str+msg_str notice_string = "send notice "+bounded_name_str+msg_str tl(notice_string) self.file_ptr.write('"'+name_str+'", '+snd_time+'\n')
def ShroomieSurfaces(self, spawn): ageSDL = PtGetAgeSDL() respVisible.run(self.key) if (spawn == 1): tldnMainPowerOn = ageSDL['tldnMainPowerOn'][0] whichbehavior = whrandom.randint(1, 4) if tldnMainPowerOn: print 'tldnShroomieBrain: The Power Tower noise has scared Shroomie. He\'ll come, but not very close.' NearOrFar = 'Far' else: print 'tldnShroomieBrain: The Power Tower is down, so Shroomie isn\'t scared by the noise.' howclose = whrandom.randint(1, 100) if (howclose == 1): NearOrFar = 'Near' elif ((howclose > 1) and (howclose < 50)): NearOrFar = 'Mid' elif (howclose >= 50): NearOrFar = 'Far' else: whichbehavior = whrandom.randint(2, 4) NearOrFar = 'Far' print 'tldnShroomieBrain: whichbehavior = ', print whichbehavior, print ' NearOrFar = ', print NearOrFar whichspawnpoint = whrandom.randint(1, 5) if (NearOrFar == 'Near'): code = (('target = SpawnNear0' + str(whichspawnpoint)) + '.sceneobject.getKey()') elif (NearOrFar == 'Mid'): code = (('target = SpawnMid0' + str(whichspawnpoint)) + '.sceneobject.getKey()') elif (NearOrFar == 'Far'): code = (('target = SpawnFar0' + str(whichspawnpoint)) + '.sceneobject.getKey()') print 'target code:', print code exec code ShroomieMaster.sceneobject.physics.warpObj(target) code = (('respTrick0' + str(whichbehavior)) + '.run(self.key)') exec code CurrentTime = PtGetDniTime() ageSDL['ShroomieTimeLastSeen'] = (CurrentTime, ) ShroomieTotalTimesSeen = ageSDL['ShroomieTotalTimesSeen'][0] ShroomieTotalTimesSeen = (ShroomieTotalTimesSeen + 1) ageSDL['ShroomieTotalTimesSeen'] = (ShroomieTotalTimesSeen, ) print 'tldnShroomieBrain: Shroomie has been seen', print ShroomieTotalTimesSeen, print 'times.'
def cherrypick_best_from_list(lst, num): """ Returns a list of length min(len(lst), num) items that have been picked randomly from the list with an exponential distribution, preferring to pick ones from the head of the list over the tail. SIDE EFFECT: Removes picked items from lst. """ assert num >= 0 cherry_list = [] while lst and len(cherry_list) < num: idx = whrandom.randint(0, whrandom.randint(0, len(lst)-1)) cherry_list.append(lst[idx]) del lst[idx] return cherry_list
def shuffle(theList): if type(theList) == type([]): n = len(theList) nmo = n - 1 numIter = int(n * math.log(n)) for x in range(numIter): idx1 = whrandom.randint(0, nmo) idx2 = whrandom.randint(0, nmo) while idx1 == idx2: idx1 = whrandom.randint(0, nmo) idx2 = whrandom.randint(0, nmo) theList[idx1], theList[idx2] = theList[idx2], theList[idx1]
def StartToWalk(self): global StepsToTake ageSDL = PtGetAgeSDL() boolBatteryChargedAndOn = ageSDL['payiPodLights'][0] StepsToTake = whrandom.randint(minsteps, maxsteps) print('Urwin has decided to take %d steps.' % StepsToTake) if whrandom.randint(0, 1): self.SendNote('respUrwin_Walk_Loop01.run(self.key)') if boolBatteryChargedAndOn: respUrwinSfx.run(self.key, state='Walk01') else: self.SendNote('respUrwin_Walk_Loop02.run(self.key)') if boolBatteryChargedAndOn: respUrwinSfx.run(self.key, state='Walk02') UrwinMasterAnim.animation.resume()
def garble(self, toon, message): newMessage = '' animalType = toon.getStyle().getType() if ChatGarbler.animalSounds.has_key(animalType): wordlist = ChatGarbler.animalSounds[animalType] else: wordlist = ChatGarbler.animalSounds['default'] numWords = whrandom.randint(1, 7) for i in range(1, numWords + 1): wordIndex = whrandom.randint(0, len(wordlist) - 1) newMessage = newMessage + wordlist[wordIndex] if i < numWords: newMessage = newMessage + ' ' return newMessage
def scramble(obj, canvas): SCRAMBLE_MOVES = 256 board = canvas.get_data('board') pos = board.index(None) for i in range(SCRAMBLE_MOVES): while 1: dir = whrandom.randint(0,3) x = y = 0 if dir == 0 and pos > 3: y = -1 elif dir == 1 and pos < 12: y = 1 elif dir == 2 and pos%4: x = -1 elif dir == 3 and pos%4 != 3: x = 1 else: continue break oldpos = pos + y*4 + x board[pos] = board[oldpos] board[oldpos] = None board[pos].set_data('piece_pos', pos) board[pos].move (-x*PIECE_SIZE,-y*PIECE_SIZE) canvas.update_now() pos = oldpos
def __init__(self, items, randomize=0): """ items is a list or tuple of items to "cycle through". randomize, if false, means that as the cycler iterates over objects, it starts at the beginning of items, walks through the sequence in order, and returns to the start of sequence after it has reached the last item. If randomize is true, the cycler picks a random item in the sequence as the "start item". Each iteration then jumps to another, randomly chosen item in the sequence that is not the same item as before. Thus, no item will be used twice in a row. """ if type(items) not in (TupleType, ListType): raise TypeError, "items %s must be a list or tuple" % repr(items) if not items: raise ValueError, "items %s must not be empty" % repr(items) if len(items) < 2: raise ValueError, "items %s must have more than one item" % repr(items) self.items = items self.randlen = len(items) - 1 self.randomize = randomize if randomize: self.pointer = randint(0, self.randlen) else: self.pointer = 0
def randint(self, start, stop): newInt = whrandom.randint(start, stop) if type(_lastvalue) != type(None) and newInt == self._lastvalue: if self._series_length >= self._MAX_SERIES: while newInt == _lastvalue: newInt = whrandom.randint(start, stop) self._lastvalue = newInt self._series_length = 1 else: self._series_length = self._series_length + 1 else: self._lastvalue = newInt self._series_length = 1 return _lastvalue
def choose(prev2, prev1): count = 0 m = model[prev2][prev1] total = reduce(lambda a, b: a+b, m) n = whrandom.randint(1, m[26]) for i in range(27): if m[i] >= n: return i
def choose(self): """Pick a random symbol from the list of symbols with the correct probability.""" total = 0 n = whrandom.randint(1, self.count) for symbol, freq in self.freqs.items(): total = total + freq if n <= total: return symbol
def __init__(self,nick,passwd): self._nick = nick self._passwd = passwd self._agent = "PY-TOC" self._info = "I'm running the Python TOC Module by James Turner <*****@*****.**>" self._seq = whrandom.randint(0,65535) self.build_funcs()
def createToonDodgeMultitrack(tDodge, toon, leftToons, rightToons): toonTracks = [] if len(leftToons) > len(rightToons): PoLR = rightToons PoMR = leftToons else: PoLR = leftToons PoMR = rightToons upper = 1 + 4 * abs(len(leftToons) - len(rightToons)) if whrandom.randint(0, upper) > 0: toonDodgeList = PoLR else: toonDodgeList = PoMR if toonDodgeList is leftToons: sidestepAnim = 'sidestep-left' for t in toonDodgeList: toonTracks.append(Track([ (tDodge, ActorInterval(t, sidestepAnim)), FunctionInterval(t.loop, extraArgs = [ 'neutral'])])) else: sidestepAnim = 'sidestep-right' toonTracks.append(Track([ (tDodge, ActorInterval(toon, sidestepAnim)), FunctionInterval(toon.loop, extraArgs = [ 'neutral'])])) toonTracks.append(Track([ (tDodge, FunctionInterval(indicateMissed, extraArgs = [ toon]))])) return MultiTrack(toonTracks)
def __init__(self, items, randomize=0): """ items is a list or tuple of items to "cycle through". randomize, if false, means that as the cycler iterates over objects, it starts at the beginning of items, walks through the sequence in order, and returns to the start of sequence after it has reached the last item. If randomize is true, the cycler picks a random item in the sequence as the "start item". Each iteration then jumps to another, randomly chosen item in the sequence that is not the same item as before. Thus, no item will be used twice in a row. """ if type(items) not in (TupleType, ListType): raise TypeError, "items %s must be a list or tuple" % repr(items) if not items: raise ValueError, "items %s must not be empty" % repr(items) if len(items) < 2: raise ValueError, "items %s must have more than one item" % repr( items) self.items = items self.randlen = len(items) - 1 self.randomize = randomize if randomize: self.pointer = randint(0, self.randlen) else: self.pointer = 0
def Final(self): "Calculate MD5 check sums, and pack it ready for sending." import struct from whrandom import randint self.packlen=self.headlen + self.attrlen self.code=1 self.id=randint(0,255) # Do attributes fmt="BBH16s%ds" % self.attrlen if self.debug>0: print "Constructing Packet" args=[] args.append(fmt) args.append(int(self.code)) args.append(int(self.id)) args.append(int(self.packlen)) args.append(self.vector) args.append(self.attributes) self.packet=apply(struct.pack, tuple(args)) self.calledfinal=1
def pickSuitAttack(attacks, suitLevel): attackNum = None randNum = whrandom.randint(0, 99) notify.debug('pickSuitAttack: rolled %d' % randNum) count = 0 index = 0 total = 0 for c in attacks: total = total + c[3][suitLevel] for c in attacks: count = count + c[3][suitLevel] if randNum < count: attackNum = index notify.debug('picking attack %d' % attackNum) break index = index + 1 configAttackName = simbase.config.GetString('attack-type', 'random') if configAttackName == 'random': return attackNum else: i = 0 for attack in attacks: if attack[0] == configAttackName: return i i += 1 notify.warning('No such attack as %s:' % configAttackName) return attackNum
def __init__(self, file, rootdir, relthis): root, ext = os.path.splitext(file) html = root + '.html' p = self.__parser = HTParser(file, self.AUTHOR) f = self.__linkfixer = LinkFixer(html, rootdir, relthis) self.__body = None self.__cont = None # calculate the sidebar links, adding a few of our own self.__d = {'rootdir': rootdir} p.process_sidebar() p.sidebar.append(BLANKCELL) # it is important not to have newlines between the img tag and the end # end center tags, otherwise layout gets messed up p.sidebar.append(('%(rootdir)s', ''' <center> <img alt="" border="0" src="%(rootdir)s/pics/PythonPoweredSmall.gif"></center> ''' % self.__d)) self.__linkfixer.massage(p.sidebar, self.__d) Sidebar.__init__(self, p.sidebar) # # fix up our site links, no relthis because the site links are # relative to the root of our web pages # sitelink_fixer = LinkFixer(f.myurl(), rootdir) sitelink_fixer.massage(sitelinks, self.__d, aboves=1) Banner.__init__(self, sitelinks) # calculate the random corner # XXX Should really do a list of the pics directory... NBANNERS = 64 i = whrandom.randint(0, NBANNERS - 1) s = "PyBanner%03d.gif" % i self.__d['banner'] = s self.__whichbanner = i
def scramble(obj, canvas): SCRAMBLE_MOVES = BOARD_WIDTH**4 board = canvas.get_data('board') pos = board.index(None) for i in range(SCRAMBLE_MOVES): while 1: dir = whrandom.randint(0, 3) x = y = 0 if dir == 0 and pos > BOARD_WIDTH_MINUS_1: y = -1 elif dir == 1 and pos < (BOARD_WIDTH_MINUS_1 * BOARD_WIDTH): y = 1 elif dir == 2 and pos % BOARD_WIDTH: x = -1 elif dir == 3 and pos % BOARD_WIDTH != BOARD_WIDTH_MINUS_1: x = 1 else: continue break oldpos = pos + y * BOARD_WIDTH + x board[pos] = board[oldpos] board[oldpos] = None board[pos].set_data('piece_pos', pos) board[pos].move(-x * PIECE_SIZE, -y * PIECE_SIZE) canvas.update_now() pos = oldpos
def __init__(self, file, rootdir, relthis): root, ext = os.path.splitext(file) html = root + '.html' p = self.__parser = HTParser(file, self.AUTHOR) f = self.__linkfixer = LinkFixer(html, rootdir, relthis) self.__body = None self.__cont = None # calculate the sidebar links, adding a few of our own self.__d = {'rootdir': rootdir} p.process_sidebar() p.sidebar.append(BLANKCELL) # it is important not to have newlines between the img tag and the end # end center tags, otherwise layout gets messed up p.sidebar.append(('%(rootdir)s', ''' <center> <img alt="" border=0 src="%(rootdir)s/pics/PythonPoweredSmall.gif"></center> ''' % self.__d)) self.__linkfixer.massage(p.sidebar, self.__d) Sidebar.__init__(self, p.sidebar) # # fix up our site links, no relthis because the site links are # relative to the root of our web pages # sitelink_fixer = LinkFixer(f.myurl(), rootdir) sitelink_fixer.massage(sitelinks, self.__d, aboves=1) Banner.__init__(self, sitelinks) # calculate the random corner # XXX Should really do a list of the pics directory... NBANNERS = 64 i = whrandom.randint(0, NBANNERS-1) s = "PyBanner%03d.gif" % i self.__d['banner'] = s self.__whichbanner = i
def animate(self): self.load() for suit in self.actors: suit.pose('neutral', whrandom.randint(0, suit.getNumFrames('neutral') - 1)) suit.loop('neutral', 0)
def createToonDodgeMultitrack(tDodge, toon, leftToons, rightToons): toonTracks = [] if len(leftToons) > len(rightToons): PoLR = rightToons PoMR = leftToons else: PoLR = leftToons PoMR = rightToons upper = 1 + 4 * abs(len(leftToons) - len(rightToons)) if whrandom.randint(0, upper) > 0: toonDodgeList = PoLR else: toonDodgeList = PoMR if toonDodgeList is leftToons: sidestepAnim = 'sidestep-left' for t in toonDodgeList: toonTracks.append( Track([(tDodge, ActorInterval(t, sidestepAnim)), FunctionInterval(t.loop, extraArgs=['neutral'])])) else: sidestepAnim = 'sidestep-right' toonTracks.append( Track([(tDodge, ActorInterval(toon, sidestepAnim)), FunctionInterval(toon.loop, extraArgs=['neutral'])])) toonTracks.append( Track([(tDodge, FunctionInterval(indicateMissed, extraArgs=[toon]))])) return MultiTrack(toonTracks)
def dummy(n, results, lock): print n, "running" time.sleep(randint(1, 5)) lock.acquire() results.append(n) lock.release() print n, "finished"
def pickSuitAttack(attacks, suitLevel): attackNum = None randNum = whrandom.randint(0, 99) notify.debug("pickSuitAttack: rolled %d" % randNum) count = 0 index = 0 total = 0 for c in attacks: total = total + c[3][suitLevel] for c in attacks: count = count + c[3][suitLevel] if randNum < count: attackNum = index notify.debug("picking attack %d" % attackNum) break index = index + 1 configAttackName = simbase.config.GetString("attack-type", "random") if configAttackName == "random": return attackNum else: i = 0 for attack in attacks: if attack[0] == configAttackName: return i i += 1 notify.warning("No such attack as %s:" % configAttackName) return attackNum
def GetRandomOno(self): "Return a random ono but not one that has been reserved" done = FALSE while not done: x = whrandom.randint(1, NUM_ORDERS) if x not in self.ono_reserved: done = TRUE return x
def GetRandomCno(self): "Return a random cno but not one that has been reserved" done = FALSE while not done: x = whrandom.randint(1, NUM_CONTACTS) if x not in self.cno_reserved: done = TRUE return x
def warp_password(self): """Warps around the chars in the password.""" import string warps = {} # add the alphabet to the warplist for x in xrange(ord('a'), ord('z')+1): x = chr(x) warps[x] = [x, x.upper()] # add some specials specialchars = (("a", ["@", "4"]), ("e", ["3"]), ("g", ["6"]), ("i", ["1", "|", "!"]), ("l", ["1", "|", "!"]), ("o", ["0"]), ("s", ["5", "z", "Z"]), ("t", ["+", "7"]), ("z", ["s", "S", "2"])) for (a,b) in specialchars: warps[a] += b randoms = 0 warped_password = "" # warp the chars in the password for i in self.password: if i in warps.keys(): # 75% probability if randint(0, 3): warped_password += choice(warps[i]) else: warped_password += i else: warped_password += i # add a random character (max two) if randint(0, 5) == 0 and randoms < 2: warped_password += choice("\/_.,!;:'+-=") randoms += 1 # print "unwarped pass = "******"warped pass = ", warped_password return warped_password
def task(): global N import whrandom x = whrandom.randint(1, 3) a.acquire() N = N - 1 if N == 0: done.release() a.release()
def task(): global N import whrandom x = whrandom.randint(1,3) a.acquire() N = N - 1 if N == 0: done.release() a.release()
def getModi_simple(org): r = whrandom.randint(1,100) for i in range(len(ratio_sum)): if r <= ratio_sum[i]: res = org + change[i] break if debug: print org,'-->',res return res
def generateAuthenticator(self): """A 16 byte random string""" v = range(0,17) v[0] = '16B' for i in range(1,17): v[i] = whrandom.randint(1,255) return apply(struct.pack,v)
def WillShroomieBeSeen(self, probability): probability = probability * 3 # CHANGED randnum = whrandom.randint(0, 100) if (randnum < (probability * 100)): print '\t Shroomie WILL be seen.' return true else: print '\tShroomie WON\'T be seen.'
def makepage(numlinks): title='<title>' for u in range(whrandom.randint(3, 15)): pick=whrandom.randint(0, numchar-1) title=title+charset[pick] title=title+'</title>' url='\r\n' numlinks=whrandom.randint(2, numlinks) for i in range(numlinks): url=url+'<a href="/poison/' for u in range(whrandom.randint(3, 15)): pick=whrandom.randint(0, numchar-1) ch=charset[pick] if ch=='/' and url[-1]=='/': ch=charset[pick+1] url=url+ch url=url+'/">' for u in range(whrandom.randint(3, 15)): pick=whrandom.randint(0, numchar-1) url=url+charset[pick] url=url+'</a><br>\r\n' url=RESP_HEAD+title+RESP_MIDDLE+url+RESP_TAIL return url
def test(): print "Running Test Vectors" print "--------------------" # (plaintext, key, ciphertext) vectors = [("AAAAAAAAAAAAAAA", "", "EXKYIZSGEHUNTIQ"), ("AAAAAAAAAAAAAAA", "f", "XYIUQBMHKKJBEGY"), ("AAAAAAAAAAAAAAA", "foo", "ITHZUJIWGRFARMW"), ("AAAAAAAAAAAAAAA", "a", "XODALGSCULIQNSC"), ("AAAAAAAAAAAAAAA", "aa", "OHGWMXXCAIMCIQP"), ("AAAAAAAAAAAAAAA", "aaa", "DCSQYHBQZNGDRUT"), ("AAAAAAAAAAAAAAA", "b", "XQEEMOITLZVDSQS"), ("AAAAAAAAAAAAAAA", "bc", "QNGRKQIHCLGWSCE"), ("AAAAAAAAAAAAAAA", "bcd", "FMUBYBMAXHNQXCJ"), ("AAAAAAAAAAAAAAAAAAAAAAAAA", "cryptonomicon", "SUGSRSXSWQRMXOHIPBFPXARYQ"), ("SOLITAIRE", "cryptonomicon", "KIRAKSFJAN")] for i in vectors: s = SolitaireCipher() s.KeyDeck(i[1]) ciphertext = s.Encrypt(i[0]) if (ciphertext == i[2]): print "passed!" else: print "FAILED!" print "plaintext = " + i[0] print "key = " + i[1] print "expected ciphertext =", PrintInFives(i[2]) print "got ciphertext =", PrintInFives(ciphertext) print print "Test bijectivity (i.e. make sure that D(E(m)) == m" print "--------------------------------------------------" from whrandom import choice, randint from string import uppercase for i in range(0, 5): p = "" for i in range(0, randint(10, 25)): p = p + choice(uppercase) s = SolitaireCipher() s.KeyDeck("SECRETKEY") c = s.Encrypt(p) s = SolitaireCipher() s.KeyDeck("SECRETKEY") r = s.Decrypt(c) if (r[:len(p)] == p): print "passed!" else: print "FAILED!" print "Random plaintext =", PrintInFives(p) print "ciphertext =", PrintInFives(c) print "decrypt =", PrintInFives(r[:len(p)]) print
def select(data): if data != []: index = whrandom.randint(0, len(data) - 1) elem = data[index] data[index] = data[-1] del data[-1] return elem else: return data
def __swapTorso(self, offset): gender = self.toon.style.getGender() if not self.clothesPicked: length = len(AvatarDNA.toonTorsoTypes[6:]) torsoOffset = 6 else: if gender == 'm': length = len(AvatarDNA.toonTorsoTypes[:3]) torsoOffset = 0 if self.dna.armColor not in AvatarDNA.defaultBoyColorList: self.dna.armColor = AvatarDNA.defaultBoyColorList[0] if self.dna.legColor not in AvatarDNA.defaultBoyColorList: self.dna.legColor = AvatarDNA.defaultBoyColorList[0] if self.dna.headColor not in AvatarDNA.defaultBoyColorList: self.dna.headColor = AvatarDNA.defaultBoyColorList[0] if AvatarDNA.isValidBoyShirt(self.toon.style.topTex) == 0: pair = random.choice(AvatarDNA.BoyShirts) self.toon.style.topTex = pair[0] self.toon.style.sleeveTex = pair[1] clength = len(AvatarDNA.BoyShorts) if self.toon.style.botTex >= clength: self.toon.style.botTex = whrandom.randint(0, clength - 1) else: length = len(AvatarDNA.toonTorsoTypes[3:6]) if self.toon.style.torso[1] == 'd': torsoOffset = 3 else: torsoOffset = 0 if self.dna.armColor not in AvatarDNA.defaultGirlColorList: self.dna.armColor = AvatarDNA.defaultGirlColorList[0] if self.dna.legColor not in AvatarDNA.defaultGirlColorList: self.dna.legColor = AvatarDNA.defaultGirlColorList[0] if self.dna.headColor not in AvatarDNA.defaultGirlColorList: self.dna.headColor = AvatarDNA.defaultGirlColorList[0] if AvatarDNA.isValidBoyShirt(self.toon.style.topTex) == 0: pair = random.choice(AvatarDNA.GirlShirts) self.toon.style.topTex = pair[0] self.toon.style.sleeveTex = pair[1] clength = len(AvatarDNA.GirlBottoms) if self.toon.style.botTex >= clength: if self.toon.style.torso[1] == 'd': self.toon.style.botTex = AvatarDNA.getRandomGirlBottom( AvatarDNA.SKIRT) torsoOffset = 3 else: self.toon.style.botTex = AvatarDNA.getRandomGirlBottom( AvatarDNA.SHORTS) torsoOffset = 0 self.torsoChoice = (self.torsoChoice + offset) % length self.__updateScrollButtons(self.torsoChoice, length, self.torsoStart, self.torsoLButton, self.torsoRButton) torso = AvatarDNA.toonTorsoTypes[torsoOffset + self.torsoChoice] self.dna.torso = torso self.toon.swapToonTorso(torso) self.toon.loop('neutral', 0) self.toon.swapToonColor(self.dna)
def warp_password(self): """Warps around the chars in the password.""" import string warps = {} # add the alphabet to the warplist for x in xrange(ord('a'), ord('z') + 1): x = chr(x) warps[x] = [x, x.upper()] # add some specials specialchars = (("a", ["@", "4"]), ("e", ["3"]), ("g", ["6"]), ("i", ["1", "|", "!"]), ("l", ["1", "|", "!"]), ("o", ["0"]), ("s", ["5", "z", "Z"]), ("t", ["+", "7"]), ("z", ["s", "S", "2"])) for (a, b) in specialchars: warps[a] += b randoms = 0 warped_password = "" # warp the chars in the password for i in self.password: if i in warps.keys(): # 75% probability if randint(0, 3): warped_password += choice(warps[i]) else: warped_password += i else: warped_password += i # add a random character (max two) if randint(0, 5) == 0 and randoms < 2: warped_password += choice("\/_.,!;:'+-=") randoms += 1 # print "unwarped pass = "******"warped pass = ", warped_password return warped_password
def StartToWalk(self): global StepsToTake ageSDL = PtGetAgeSDL() boolBatteryChargedAndOn = ageSDL['nglnPodLights'][0] StepsToTake = whrandom.randint(minsteps, maxsteps) print('Urwin has decided to take %d steps.' % StepsToTake) self.SendNote('respUrwinWalkLoop.run(self.key)') UrwinMasterAnim.animation.resume() if boolBatteryChargedAndOn: respUrwinSfx.run(self.key, state='WalkLoop')
def WillShroomieBeSeen(self, probability): randnum = whrandom.randint(0, 100) #~ print "randnum = ",randnum,"probability = ", probability*100 if randnum < (probability * 100): print "\t Shroomie WILL be seen." return true else: print "\tShroomie WON'T be seen."
def randpass(passlen=5): """ This routine generates a random password. """ import whrandom # we'll only use easy to interpret symbols (no 1/l 0/o worries) ok = "abdefghijkmnopqrstuvwxyz" + "23456789" + "23456789" res = "" for i in range(passlen): res = res + ok[whrandom.randint(0, len(ok) - 1)] return res
def get(filename): "Select a random quotation, using a pregenerated .dat file" # First, we open the .dat file, and read the header information. # The C structure containing this info looks like: ## typedef struct { /* information table */ ## #define VERSION 1 ## unsigned long str_version; /* version number */ ## unsigned long str_numstr; /* # of strings in the file */ ## unsigned long str_longlen; /* length of longest string */ ## unsigned long str_shortlen; /* length of shortest string */ ## #define STR_RANDOM 0x1 /* randomized pointers */ ## #define STR_ORDERED 0x2 /* ordered pointers */ ## #define STR_ROTATED 0x4 /* rot-13'd text */ ## unsigned long str_flags; /* bit field for flags */ ## unsigned char stuff[4]; /* long aligned space */ ## #define str_delim stuff[0] /* delimiting character */ ## } STRFILE; datfile = open(filename + '.dat', 'r') data = datfile.read(5 * LONG_SIZE) if is_64_bit: v1, v2, n1, n2, l1, l2, s1, s2, f1, f2 = struct.unpack('!10L', data) version = v1 + (v2 << 32) numstr = n1 + (n2 << 32) longlen = l1 + (l2 << 32) shortlen = s1 + (s2 << 32) flags = f1 + (f2 << 32) else: version, numstr, longlen, shortlen, flags = struct.unpack('5l', data) delimiter = datfile.read(1) datfile.read(3) # Throw away padding bytes if is_64_bit: datfile.read(4) # 64-bit machines align to 8 bytes # Pick a random number r = whrandom.randint(0, numstr) datfile.seek(LONG_SIZE * r, 1) # Seek to the chosen pointer data = datfile.read(LONG_SIZE * 2) if is_64_bit: s1, s2, e1, e2 = struct.unpack('!4L', data) start, end = s1 + (s2 << 32), e1 + (e2 << 32) else: start, end = struct.unpack('!ll', data) datfile.close() file = open(filename, 'r') file.seek(start) quotation = file.read(end - start) L = string.split(quotation, '\n') while string.strip(L[-1]) == delimiter or string.strip(L[-1]) == "": L = L[:-1] return string.join(L, '\n')