We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › using random for something other than int
Page Index Toggle Pages: 1
using random for something other than int (Read 608 times)
using random for something other than int
May 11th, 2009, 2:55am
 
Can you use random() for a string?

im wanting to display a shapes that i have loaded in so instead of having

PShape bot
PShape ant
etc
shape(bot,x,y)

is it possible to have it pick one at random and display the shape attached to the definition of PShape?

does that make sense




Re: using random for something other than int
Reply #1 - May 11th, 2009, 3:39am
 
dont know how much shapes you have to choose from. One way woult be to simple name your shapes 0,1,2,3 etc. but you can also store all the names in an array of strings, lets say.

String[] names = {  "ant", "bot", "xx", "yy",  };

and then randomly pick one string out of the array

String a = names[int(random(names.length))];
shape(a,x,y);

hope that helps
Re: using random for something other than int
Reply #2 - May 11th, 2009, 3:42am
 
You want to randomize a shape, not a string... Smiley
Anyway, that's the same technique (both are objects).
The simplest way, since I suppose you have a limited, known number of objects, is to put them in an array, then to generate an integer random number between 0 and the max index.

String[] shapeNames = { "bot.svg", "ant.svg", "foo.svg" };
PShape[] shapes = new PShape[shapeNames.length];
for (int s = 0; s < shapes.length; s++)
{
 shapes[s] = loadShape(shapeNames[s]);
}


then

PShape shapeToDraw = shapes[int(random(shapes.length))];

(untested)
Re: using random for something other than int
Reply #3 - May 11th, 2009, 9:03am
 
thats almost the same but you should go with PhiLhos example, its more detailed then mine
Page Index Toggle Pages: 1