This site requires JavaScript, please enable it in your browser!
Greenfoot back
m1chael
m1chael wrote ...

2012/1/7

Creating different objects randomly?

m1chael m1chael

2012/1/7

#
I want the program to create one of my four objects over and over again. The objects should be created randomly. So my question is: How can I make the variable i get a different random number after one object has been created? I also want to insert a delay after one object has been created. I hope you guys can understand my english and here is the code: int i = Greenfoot.getRandomNumber(4); public void act() { if(i == 1) { getWorld().addObject(new objekt1(), 150, 10); } if(i == 2) { getWorld().addObject(new objekt2(), 150, 10); } if(i == 3) { getWorld().addObject(new objekt3(), 250, 10); } if(i == 4) { getWorld().addObject(new objekt4(), 150, 10); } // Add your action code here. }
danpost danpost

2012/1/7

#
Add an instance variable to the class
int lastObjectNumber = 0;
then in act()
int i = Greenfoot.getRandomNumber(4) + 1;
while (i == lastObjectNumber) i = Greenfoot.getRandomNumber(4) + 1;
lastObjectNumber = i;
if (i == 1)
{
    // etc.
BTW, 'getRandomNumber(n)' returns a range (0 to n-1), hence I added one. The 'while' statement ensures that the last object added is not repeated.
danpost danpost

2012/1/7

#
As far as the delay, you can add another instance variable
int delay = 0;
and enclose the previous in act in
if (delay != 0) delay--;
else
{
    // insert previous code here
    delay = 1000; // reseting the delay, adjust the figure as needed
}
m1chael m1chael

2012/1/7

#
Ok that works fine :) thank you for helping me
Duta Duta

2012/1/9

#
By the way a replacement for:
if(i == 1)
{
    getWorld().addObject(new objekt1(), 150, 10);
}
if(i == 2)
{
    getWorld().addObject(new objekt2(), 150, 10);
}
if(i == 3)
{
    getWorld().addObject(new objekt3(), 250, 10);
}
if(i == 4)
{
    getWorld().addObject(new objekt4(), 150, 10);
}
is:
switch(i)
{
    case 1:
        getWorld().addObject(new objekt1(), 150, 10);
        break;
    case 2:
        getWorld().addObject(new objekt2(), 150, 10);
        break;
    case 3:
        getWorld().addObject(new objekt3(), 250, 10);
        break;
    case 4:
        getWorld().addObject(new objekt4(), 150, 10);
}
Also, if you were going to still use the multiple if statements, make the 2nd, 3rd and 4th "if"'s into "else if"'s, as this is more efficient for the processor. Although it makes barely any difference just for 4 if statements, its good habit to get into.
You need to login to post a reply.