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

2019/10/30

About random populating

Ethan_net Ethan_net

2019/10/30

#
Now I'm working on a project, which needs to plant marbles inside a 12*12 world with random of x and increasing y as the coordinance, but I don't know how to properly states this in greenfoot. Here is my existed code for this:
/**
     * Creates a new Ground object, with or without marbles.
     * This constructor is useful for writing software tests.
     * @param createBalls If true, the floor will be populated
     *                    with Marbles.
     */
    public Ground(boolean createMarbles)
    {
        super(12, 12, 60);
        
        for (int i = 0; i < 12; i++)
        {
            this.addMarbles();
        }
        //if (createMarbles)
        //{
        //    populate();
        //}
    }
    
    /**
     * This use random generator to plant a marble
     * at a random x-ordinance.
     */
    public void addMarbles()
    {
        Marble marbles = new Marble();
        add(marbles, Random.generator().
                nextInt(getWidth()));
    }
Ethan_net Ethan_net

2019/10/30

#
I'm mainly confussing about how to states the increasing y.
Ethan_net Ethan_net

2019/10/30

#
Oh, and also only one marble exist for one y value.
danpost danpost

2019/10/30

#
Ethan_net wrote...
Oh, and also only one marble exist for one y value.
Have the method, addMarbles, and add all the marbles in one calling. That is, move the loop from the constructor to the method. That way, the loop counter value can aid in controlling the y-coordinate value where the marbles are placed.
You need to login to post a reply.