-
October 24th, 2013, 12:45 PM
#1
Need help, I need to randomly change the size of programs balls
I am starting to learn java at home and one of the tasks in the book is to create a program which randomly changes the size of balls which are bouncing off the screen, but all i seem to be able to do is get them to randomly start in different places not change size, can anyone help please?
here is my code:
Code:
import java.awt.*;
import java.awt.geom.*;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.ArrayList;
/**
* Class BallDemo - a short demonstration showing animation with the
* Canvas class.
*
* @author Michael Kölling and David J. Barnes
* @version 2011.07.31
*/
public class BallDemo
{
private Canvas myCanvas;
/**
* Create a BallDemo object. Creates a fresh canvas and makes it visible.
*/
public BallDemo()
{
myCanvas = new Canvas("Ball Demo", 600, 500);
}
public void drawFrame() {
int borderSize = 20;
Dimension size = myCanvas.getSize();
Rectangle r = new Rectangle(borderSize, borderSize, (int) size.getWidth() - 2*borderSize, (int) size.getHeight() - 2*borderSize);
myCanvas.draw(r);
}
/**
* Simulate two bouncing balls
*/
public void bounce(int numberOfBalls)
{
int ground = 400; // position of the ground line
myCanvas.setVisible(true);
// draw the ground
myCanvas.drawLine(50, ground, 550, ground);
// create and show the balls
Random random = new Random();
HashSet<BouncingBall> balls = new HashSet<BouncingBall>();
for(int i=0; i<numberOfBalls; i++) {
Dimension size = myCanvas.getSize();
int x = random.nextInt((int) size.getWidth());
int y = random.nextInt((int) size.getHeight());
BouncingBall ball = new BouncingBall(x, y, 16, Color.blue, ground, myCanvas);
balls.add(ball);
ball.draw();
}
// make them bounce
boolean finished = false;
while(!finished) {
myCanvas.wait(50); // small delay
for(BouncingBall ball : balls) {
ball.move();
// stop once ball has travelled a certain distance on x axis
if(ball.getXPosition() >= 550 + 32*numberOfBalls) {
finished = true;
}
}
}
for(BouncingBall ball : balls) {
ball.erase();
}
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|