useful random generation

Random sensors suck. So use these puppies instead. I provided some useful examples of random generators so you guys can spend time on more important things :spin:. I think there was one snippet posted somewhere I saw for a random number generator but I figured I would re-post and elaborate for the newbies who hate python. Me being included in that category :eyebrowlift2:. Random’s are handy if you’re going to do any sort of unpredictable AI! enjoy.

#important, you need to import this or it does nothing
import random
import GameLogic

cont = GameLogic.getCurrentController()
own = cont.getOwner()

#random number from a set list of choices, pretty self explanitory,
#don't forget the [] inside the ()
rand_number = random.choice([1,2,3])

#random number from "whatever" to "whatever" 
rand_number = random.randint(1,50)

#incase for some reason you need a pile of random numbers.
#uses xrange for the population of the sample in this example
#good for a quick grab of numbers. or you could set up your own 
#population and place it in its place just as well. 
#random.sample(population,k) k is how many to pick out
rand_number = random.sample(xrange(100),5)

#say you need a random float for use in something but
#you want it to stay close to a given value. gauss is your
#friend. it's the good old normal distribution you get 
#shoved down your throat in college statistics classes.
#random.gauss(mean,sd) sd being the standard deviation
#basically how far from the mean (average) your float 
#output strays. actually, if the property you are assigning
#the resulting number to is set to int it will round up or down
rand_number = random.gauss(25,5)

#debugging text line for seeing wtf is going on in realtime in the game,
#needs a plane with a "Text" property and all the usual realtime type setup.
#setup a plane with the text and append it in your projects, they're more
#convenient than the console sometimes for debugging imo
own.Text = rand_number

#to use the random result just slap it on whatever property you need it for
#ex: own.peanuts = rand_number on whatever object is connected to the script
#and has a property "peanuts"
#random sample outputs a string enclosed in [] separated by ,'s fyi
#so keep that in mind. 
#make sure your property is in the right format: int, string, float, etc for what you need 

thanks for sharing the useful pycode :slight_smile:

Uh, great?!
A little .blend example, maybe, for us python illiterates?!
Thank you!

Like this one!??! :eek::eek:


random_demo.blend (244 KB)

For example!
Very nice…and impressive!
Thank you very much!

Heh, I just stared for quite some time at the cubes go and do their stuff. Very nice!

very nice examples, Thanks!