Description of a flower:
(1) a flower has:
- color (a string)
- position (two numbers)
- spin angle (a number)
(2) a flower can be created:
- by giving value for its color
the other properties set to
random values
(3) a flower can do:
//
// - tell us its color,
// position, etc.
// (omitted from example)
//
- private method to help the flower
pick random initial angle
illustrates the use of switch
emphasizes methods can be private
the rule for picking the color is made up:
* get a random value and assign:
- 30 degrees if value is 1, 2, or 3
- 60 degrees if value is 4
- 90 degrees if value is 5 or 6
- 0 degrees for any other value
- update its X, Y position
- rotate itself by a fixed
angle of 30 degrees
- draw itself based on
its location, color
and angle of spin
|
package cs1.ParkApp;
import cs1.app.*;
public class Flower
{
// data members: the "features/characteristics" of Flower
// typically private
private String color;
private double curX;
private double curY;
private int curAngle;
// constructor(s): same name as class, no return type
public Flower( String initColor )
{
color = initColor;
curX = canvas.getRandomInt( 0, canvas.getWidth() );
curY = canvas.getRandomInt( 4.0/5.0*canvas.getHeight(), canvas.getHeight() );
curAngle = pickAngle( );
}
// methods: the "actions/behaviors" of Flower
// typically public
//
// could put methods/behaviors
// getColor(), getX(), getY()
// omitted from this example
//
private int pickAngle( )
{
int randomNumber = canvas.getRandomInt( 1, 6 );
int angle = 0;
switch( randomNumber )
{
case 1: // if randomNumber is 1, 2, or 3
case 2:
case 3:
angle = 30; // we want the angle to be 30 degrees
break;
case 4: // if randomNumber is 4
angle = 60; // we want the angle to be 60 degrees
break;
case 5: // if randomNumber is 5 or 6
case 6:
angle = 90; // we want the angle to be 90 degrees
break;
default: // if randomNumber is anything else
angle = 0; // we want the angle to be 0 degrees
break;
}
return angle;
}
public void setX( double newX )
{
curX = newX; // change the X position
}
public void setY( double newY )
{
curY = newY; // change the Y position
}
public void spin( )
{
curAngle = ( curAngle + 30 ) % 360; // increase angle by 30 degrees
// (use % as alternative to if)
}
public void draw( )
{
String filename = "flower" + curAngle + ".png"
canvas.drawImage( curX, curY, fileName );
canvas.drawCircle( curX, curY, 5, color );
}
}
|