How would I be able to use a for loop to create a 5x10 set of a specified actor in the prepare() of myWorld? An example of code and explanation would be greatly appreciated.
private void prepare()
{
spaceship spaceship = new spaceship();
addObject(spaceship,300,550);
for(int i=4; i<=9; i++)
{
alien alien = new alien();
addObject(alien,30+40*i, 15);
}
for(int i=4; i<=9; i++)
{
alien alien = new alien();
addObject(alien,30+40*i, 45);
}
for(int i=4; i<=9; i++)
{
alien alien = new alien();
addObject(alien,30+40*i, 75);
}
for(int i=4; i<=9; i++)
{
alien alien = new alien();
addObject(alien,30+40*i, 105);
}
for(int i=4; i<=9; i++)
{
alien alien = new alien();
addObject(alien,30+40*i, 135);
}
}int apr = 10; aliens per row int gap = 40; // distance between aliens along a row int midX = getWorld()/2; // mid-world x-coordinate
int x0 = midX-(apr-1)*gap/2;
for (int row=0; row<5; row++) // for each row
{
for (int n=0; n<apr; n++) // for each alien in a row
{
addObject(new alien(), x0+gap*n, 15+30*row);
}
}public class alien extends Actor
{
public static int score = 0;
/**
* Act - do whatever the alien wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
alienShoot();
destroyAlien();
displayScore();
}
public boolean canSee(Class otherActor)//Actor detects other actors
{
Actor actor = getOneObjectAtOffset(0,0,otherActor);
if(actor != null)
{
return true;
}
else
{
return false;
}
}
public void destroy(Class otherActor)//Actor deletes the actor from the map
{
Actor actor = getOneObjectAtOffset(0,0,otherActor);
if(actor != null)
{
getWorld().removeObject(actor);
}
}
public void displayScore() //Score is shown
{
getWorld().showText("Aliens Destroyed: "+score, 125,30);
}
public void destroyAlien()
{
if(canSee(laser1.class))
{
removeTouching(laser1.class);
getWorld().removeObject(this);
score++;
}
}
private void alienShoot()
{
if (Greenfoot.getRandomNumber(1000)>=999) //1 in 1000 chance that an alien will generate and shoot a laser
{
laser2 laser2 = new laser2();
getWorld().addObject(laser2, getX(),getY());
}
}
}