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

2019/10/1

loops

Yichui Yichui

2019/10/1

#
Hi, I’m making a game and I want to implement some for-loops, and I was wondering if someone can give me some examples of for-loop scenarios (e.g. changing speed/image of an enemy once a certain score is achieved) or link me some thank you. Tried making some myself but feeling pretty lost ( ̄^ ̄)
danpost danpost

2019/10/1

#
Yichui wrote...
for-loop scenarios (e.g. changing speed/image of an enemy once a certain score is achieved)
I do not see how your examples could have anything to do with looping. You would not continuously change an enemy's speed or its image multiple times between consecutive frames in the running of the scenario. Loops are used to execute code multiple times during the same act step (at one moment in time as far as a human is concerned). Only the end result will be apparent to the user. One of the first uses you might have for a for loop is to add multiple objects into the world. This could be some number of the same type:
private void addEnemies(int count)
{
    for (int i=0; i<count; i++)
    {
        addObject(new Enemy(), randomX(), randomY()); // random methods not given here
    }
}
or of different types (no example given). Oftentimes, nested for loops are used to iterate over an 2d array (such as the cells in your world or pixels in an image). A different type of for loop can be used to iterate over a list of objects. For example, scrolling a world would involve changing the position of all the actors by some amount:
private void scrollActors(int dx, int dy)
{
    for (Object obj : getObjects(Actor.class))
    {
        Actor actor = (Actor)obj;
        actor.setLocation(actor.getX()+dx, actor.getY()+dy);
    }
}
You need to login to post a reply.