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

2017/5/23

Change colors of an orb

alexaa alexaa

2017/5/23

#
Hello, i'm trying to have an orb change colors red, blue, yellow and green based on a random choice. I got this but for some reason the code isn't changing the orb or selecting a random color. Here's the code I came up with. I would love a direct fix if possible; I'm new to this program. The code commented out is another thing that I tried and didn't work...
 
    public void setColor() {
        GreenfootImage orbImg = new GreenfootImage("orb.png");
        colorChoice = Greenfoot.getRandomNumber(4);
        int x = 0;
        int y = 0;
        int z = 0;
        
        if (colorChoice == 0) {
            x = 255;
            y = 0;
            z = 0;
        } else if (colorChoice == 1) {
            x = 255;
            y = 255;
            z = 51;
        } else if (colorChoice == 2) {
            x = 51;
            y = 204;
            z = 255;
        } else { 
            x = 102;
            y = 204;
            z = 0;
        } 
        
        orbImg.setColor(new Color(x, y, z));
        orbImg.fillOval(0, 0, 0, 0);
        setImage(orbImg);
        
        // if (colorChoice == 0) {
            // orbImg.setColor(new Color(255, 0, 0)); // red
            // orbImg.fillOval(0, 0, 0, 0);
        // } else if (colorChoice == 1) {
            // orbImg.setColor(new Color(255, 255, 51)); // yellow
            // orbImg.fillOval(0, 0, 0, 0);
        // } else if (colorChoice == 2) {
            // orbImg.setColor(new Color(51, 204, 255)); // blue
            // orbImg.fillOval(0, 0, 0, 0);
        // } else { 
            // orbImg.setColor(new Color(102, 204, 0)); // green
            // orbImg.fillOval(0, 0, 0, 0);
        // } 
        
        // random speed: 1 to 4
        spd = Greenfoot.getRandomNumber(4) + 1;
    }
Super_Hippo Super_Hippo

2017/5/23

#
You have to change line 27. The first two 0 are the coordinates of the top left corner, the third and forth 0 represent the size of the oval. If it is 0, nothing can be filled. The random color thing could also be done like this:
Color color = null;
switch (Greenfoot.getRandomNumber(4))
{
    case 0: color = Color.RED; break;
    case 1: color = Color.YELLOW; break;
    case 2: color = Color.BLUE; break;
    case 3: color = Color.GREEN; break;
}
orbImage.setColor(color);
You need to login to post a reply.