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

2017/4/18

Help with spawning in an object a set location infinite times

1
2
Asiantree Asiantree

2017/4/18

#
Hello. I am to spawn in a bunch of colored balls that will fall from the top of the screen through a file dialog approach. The file contains this code with correlates the ball's color when it will be spawned in: 10 10 10 255 0 0 0 255 0 0 0 255 125 255 125 200 10 100 Where the first line is almost black, second is red, third is green, fourth is all blue, fifth is light-greenish, and the last is a reddish-purple. Now all of these elements will be stored into a class called BallInfo which is right here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
public class BallInfo extends Actor
{
    private Color ballColor;  // color of the balls being summarized
    private int totalCount;   // number of balls of this color ever seen in the world
    private int caughtCount;  // number of balls of this color ever "caught"
 
    /**
     * constructor for color and stats information about a ball type.
     * @param redValue the amount of red (0-255) in the RGB color to use
     * @param greenValue the amount of green (0-255) in the RGB color to use
     * @param blueValue the amount of blue (0-255) in the RGB color to use
     */
    public BallInfo(int redValue, int greenValue, int blueValue)
    {
        // initially, all counts will be zero.
        totalCount=0;
        caughtCount=0;
         
        // use specified color to create (redraw) image
        ballColor = new Color(redValue,greenValue,blueValue);
        redraw();
    }
     
    // private method to redraw the stats image.
    private void redraw(Color col)
    {
        // build a new image for this object
        GreenfootImage img = new GreenfootImage(150,12);
         
        // fill in the background color.
        img.setColor(new Color(200,200,200)); // could use Color.GRAY
        img.fill();
         
        // add an "icon" that shows the corresponding color
        GreenfootImage ball = new GreenfootImage(10,10);
        ball.setColor(col);
        ball.fillRect(0,0, ball.getWidth(), ball.getHeight());
        img.drawImage(ball, 1, 1);
         
        // add in the count statistics for this ball color
        img.setColor(new Color(0,0,0) ); // could use Color.BLACK
        String stats = String.format("#:%6d", totalCount);
        img.drawString(stats, 21, 11);
        stats = String.format("C:%6d", caughtCount);
        img.drawString(stats, 85, 11);
 
         
        setImage(img); // use the image we've built up.
    }
     
    // redraw the image with the current ball calor.
    private void redraw()
    {
        redraw(ballColor);
    }
     
    /**
     * returns the color for this ball type. Might be useful to help draw a ball in the game
     *   @return the color for this type
     */
    public Color getColor()
    {
        return ballColor;       
    }
     
    /**
     * returns the number of times a ball of this color has been added to the world
     *   @return the count of the number of balls of this color ever seen in the world
     */
    public int getTotal()
    {
        return totalCount;
    }
     
    /**
     * returns the number of times a ball of this color has been caught
     *   @return the count of the number of balls of this color ever been caught
     */
    public int getCaught()
    {
        return caughtCount;
    }
     
    /**
     * adds one to the total number of balls of this color seen in the world.
     */
    public void incTotal()
    {
        totalCount++;
        redraw();
    }
     
    /**
     * adds one to the total number of ballos of this color that have been caught
     */
    public void incCaught()
    {
        caughtCount++;
        redraw();
    }
I need to be able to spawn these balls in at the top of the screen and have them fall until they hit the bottom of the screen or a player-controlled slider that will make them disappear. When a ball hits the slider, it should be updated in the BallInfo class aforementioned. How would I go about spawning the balls in continuously and then updating the scoreboard when a ball hits the slider at the bottom of the screen?
danpost danpost

2017/4/18

#
The code you gave was for displaying the info on the balls. But, you also mentioned spawning balls, which requires your world class code, and ball behavior (hitting slider or edge and updating info), which requires your Ball class code. Also, you gave "file" data that you said would be stored in the BallInfo class. Why is it given outside the class with no actual place to put the data within the class?
Asiantree Asiantree

2017/4/18

#
I will display the World and Ball classes now: World
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class MyWorld extends World
{
     
    /**
     * Constructor for objects of class MyWorld.
     *
     */
    public MyWorld()
    {   
        // Create a new world with 800x600 cells with a cell size of 1x1 pixels.
        super(800, 600, 1);
    }
     
    public void act()
    {
        //spawnBalls();
    }
     
    public void spawnBalls()
    {
        if (Greenfoot.isKeyDown("l"))
        {
            FileDialog fd = null;
            fd = new FileDialog(fd, "Pick a file" , FileDialog.LOAD);
            fd.setVisible(true);
         
            String fname = fd.getDirectory() + fd.getFile();
         
            File file = new File(fname);
         
            Scanner fReader = null;
        try
        {
            fReader = new Scanner(file);
        }
        catch(FileNotFoundException fne)
        {
            System.out.println(fne);
            return;
        }
       }
    }
}
Ball public class Ball extends Actor { // constants that you may find usefull while coding. public static final int DIAMETER = 50; // diameter of a Ball public static final int RADIUS = DIAMETER/2; // radius of a Ball private double ySpeed; //the ySpeed of a Ball private double exactX; //determines the current X location private double exactY; //determines the current Y location private BallInfo ballData; // How can I use this reference to spawn in Balls into the World? /** * builds a ball with the color specified by the parameter * * @param bi the BallInfo associated with this object. */ public Ball(BallInfo bi) { ballData = bi; // store (reference to) this ball's info. You may find this useful later // build an image for this ball. GreenfootImage img = new GreenfootImage(DIAMETER, DIAMETER); // draw an appropriately colored circle in the image img.setColor(bi.getColor()); img.fillOval(0,0,DIAMETER,DIAMETER); // use the image just drawn as this ball's image setImage(img); this.ySpeed = 0.05; } /** * Protects a Ball everytime it is spawned into the world */ protected void addedToWorld (World myWorld) { exactX = getX(); exactY = getY(); } /** * Act - do whatever the Ball wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { exactY += ySpeed + 0.05; setLocation ( (int) exactX, (int) exactY ); } } I am to load in the integers that represent the colors with a file dialog option. I need help with understanding the reference to the BallInfo that was given to me (I have commented it in the code above for the Ball class) to help me continuously spawn in Balls going through the integers that are in the file. In other words, I need to load in a file and use the integers in sets of three continuously until I hit the stop button.
danpost danpost

2017/4/18

#
Okay, so you have the user selecting a file and set a Scanner to it. My question now are: * how are you verifying that the selected file is a valid one? -- what checks should be performed for this? * where is the code that reads in the data from the file? * how will you get the data to the BallInfo class? or, is the data actually going to be stored in the world, with the objects receiving their respective colors?
danpost danpost

2017/4/18

#
Asiantree wrote...
I need to load in a file and use the integers in sets of three continuously until I hit the stop button.
You need to do this continuously? or can you read all the data in at once and then continuously run through the data that was read in?
Asiantree Asiantree

2017/4/19

#
Here is the information given to me for the project I am to work on. The classes I have listed above are the classes that were given to me to work on. But I am confused on how I am to work on the code given to me, so here is the instructions: "On the left side of the world, a (vertical) collection of all possible ball colors should be visible. This collection will have one element for each possible ball color that could be dropped. Each element will display the ball color it represents, the number of such balls that have ever appeared in the world, and the number of such balls that have been caught. Don’t panic - you are being given a BallInfo class that contains code to build, display, and update such an element. Just above the collection of Ball Information, you should place a toggle button that controls how the Ball Information elements will be sorted. By default, they should be sorted in order from highest total appearance count to lowest total appearance count, top to bottom; the button should contain text like "Sorting by Total (DESC)" when this is the case. Once clicked, the button’s text should change to something like "Sorting by Caught(ASC)" and the Ball Information elements should be arranged from lowest caught count to highest caught count, top to bottom. Whenever clicked, the button text should “toggle” between the two options. Don’t panic - you are being given a ToggleButton class to aid with this! The collection of BallInfo elements should be populated (i.e. filled in) as the result of the following user interactions: • if the user presses the "L" or "l" key (for ”load”), then all of the current BallInfo elements should be removed (and so should all of the falling Balls). A FileDialog box should then appear, prompting the user to select an input file that contains a sequence of colors, each of which should become a new BallInfo element in the collection. Each color in the input file is specified as three integers corresponding to the color’s red, green, and blue components (each ranging from 0 to 255). Thus, an example input file might be: 10 10 10 255 0 0 0 255 0 0 0 255 125 255 125 200 10 100 The first line is almost black, the second is all red, the third is all green, the fourth is all blue, the fifth is a less bright shade of green, and the last is a reddish-purple (mostly red and blue). Thus, the result should be that the collection of BallInfo colors now has 6 elements in it, containing the colors listed above with total and caught counts of 0. • if the user presses the "M" (or "m") key (for ”merge”), a FileDialog should pop up asking the user to select an input file (matching the same specifications as for loading above). The corresponding colors should have BallInfo elements added to the collection without removing any of the existing elements. You are guaranteed that no more than 42 color values will be specified. Conveniently, there is enough vertical space to place 42 BallInfo objects from y location 50 to the bottom of the world, with a single blank “row” of pixels between each BallInfo element. Provided at least one BallInfo element is present, a new Ball should be added to the world every five calls to the world’s act method. The new ball should have a random color, chosen randomly from the colors found in the BallInfo collection. A new Ball should appear at y location 0 and have a random x location, but no ball should ever be “intersecting” with any BallInfo images (i.e. Balls should only appear to the right of the BallInfo collection). A Ball also has a speed in the y direction (called speedy below), which is initially 0 but increases with each call to act. A ball moves vertically in the y direction (but not at all in the x direction) as follows: 1. add 0.05 to speedy. Note that this has an implication as to what the type of speedy should be. 2. add speedy to the current y location. Note that this has a (rather serious) implication as to what the type of y should be. 3. you should probably tell Greenfoot to update where it thinks the location (wording is a hint!) of this Ball is."
danpost danpost

2017/4/19

#
I think your world is going to need a List object to track all the possible BallInfo objects, so you can easily clear and load or merge a new group of objects to it. Maybe you can also add a second Lit object for the specific colors as well, keeping both lists coordinated with each other so that the colors match element for element. It might also come in handy to have a list of the files whose colors are currently in use so that you can prevent a file from being merged into a list whose colors have already been added to the list. When a file is called upon for use, read each set of colors values, create the Color object and add it to a temporary List object. After creating all the colors, close the file and create another temporary List object of new BallInfo objects by iterating through the temporary list of Color objects. Then you can either append or replace the current color and ball info lists with the temporary ones, as well as remove, add and/or relocate the BallInfo objects from the current list in the world. The current color list can be used to randomly generate balls of the current colors from the world act method using an int timer field to regulate the speed at which they spawn.
Asiantree Asiantree

2017/4/20

#
I may need some help getting this started. I am able to get a BallInfo object to spawn in just by me placing it somewhere, but I need a BallInfo object to spawn in whenever there is a ball present in the world. In other words, how can I get both to spawn in using the file I have displayed, while using a List or Array method?
danpost danpost

2017/4/20

#
Asiantree wrote...
I may need some help getting this started. I am able to get a BallInfo object to spawn in just by me placing it somewhere, but I need a BallInfo object to spawn in whenever there is a ball present in the world.
Actually -- no. You want to spawn the BallIfnfo objects based on the current colors being used. In other words, they should be in the world before any balls of that color are spawned. The order of execution for "loading" follows: * remove all Ball objects from world * remove all BallInfo objects from world * clear list of BallInfo objects * clear list of Color objects * read in data * iterate through data to create and add Color object to Color list * iterate through Color list to create and add BallInfo objects to the BallInfo list * call a method to iterate through the BallInfo list and add them into the world This, of course, would be in your world class code.
1
2
3
4
5
// with a BallInfo list declared as
private List<BallInfo> infos = new ArrayList<BallInfo>();
 
// create a ball with
Ball ball = new Ball(infos.get(Greenfoot.getRandomNumber(infos.size()));
then add 'ball' into the world.
Asiantree Asiantree

2017/4/20

#
I get a "bound must be positive" error for this code:
1
Ball ball = new Ball(infos.get(Greenfoot.getRandomNumber(infos.size())));
danpost danpost

2017/4/20

#
You need to have a BallInfo object to spawn a ball. Put the following condition on the line:
1
if (!infos.size().isEmpty())
Asiantree Asiantree

2017/4/20

#
I am unsure where to put the three lines of code you have given me. I know in the world class, but under the act method?
danpost danpost

2017/4/20

#
Asiantree wrote...
I am unsure where to put the three lines of code you have given me. I know in the world class, but under the act method?
The one beginning with private goes outside any method, the other two in the act method. BTW, the condition is to be placed not only on creating the ball but adding it into the world:
1
2
3
4
5
if (!infos.size().isEmpty())
{
    Ball ball = ...
    addObject(ball ...
}
Your 'spawnBalls' method is really inaccurately named. No balls are even spawned within the method. Change its name to something like 'loading' and create another method for 'merging'. Code similar to both can be refactored into separate methods. If coded properly, the only different between the two would be the first few steps that I listed above; but, I do not expect you to be able to code it that efficiently.
Asiantree Asiantree

2017/4/20

#
Now I am getting an error for "cannot dereference an int" for this line of code:
1
if (!infos.size().isEmpty())
danpost danpost

2017/4/20

#
Asiantree wrote...
Now I am getting an error for "cannot dereference an int" for this line of code:
1
if (!infos.size().isEmpty())
That is funny! Sorry. Try this:
1
if (!infos.isEmpty())
There are more replies on the next page.
1
2