Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Brock Haun
- // HELP! Nothing is working for part 3. I did everything, but no actual balls are produced on the applet.
- package balls;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Rectangle;
- import java.util.Random;
- import javax.swing.JApplet;
- public class BallsApplet extends JApplet {
- private int numBalls = 20; //just for private usage. makes code more readable.
- private Ball balls[] = new Ball[numBalls];
- private boolean stop = false; //private usage
- private Physics physics = new Physics(this,this,10);
- @Override
- public void init() {
- setSize(400, 500);
- //ball = new Ball(30, 30, 10, Color.GREEN);
- for (int i=0;i<numBalls;i++) {
- balls[i]= makeRandomBall();
- physics.addBall(balls[i]);
- } //for
- //physics.addBall(ball);
- } //init()
- @Override
- public void paint(Graphics g) {
- Rectangle bounds = getBounds();
- g.setColor(Color.lightGray);
- g.fillRect(0, 0, bounds.width, bounds.height);
- int redBalls = 0;
- int greenBalls = 0;
- for (int i=0;i<numBalls;i++) {
- balls[i].draw(g);
- if (balls[i].getColor().equals(Color.red))
- redBalls++;
- else greenBalls++;
- } //for
- //string output
- g.setColor(Color.blue);
- String greenCount = "Green balls: " + greenBalls;
- String redCount = "Red balls: " + redBalls;
- g.drawString(greenCount, 20, 20);
- g.drawString(redCount, 20, 30);
- g.drawString("Brock Haun" , 300, 10);
- if (greenBalls == 0)
- physics.stopIt();
- } //paint()
- private int randomRange(int low, int high) {
- Random r = new Random();
- int randomInt = r.nextInt(high)+ low;
- return randomInt;
- } //randomRange()
- private Ball makeRandomBall() {
- Random r = new Random();
- int randX = r.nextInt(180)+21; //instructions say between 20 and 200, not inclusive so ceiling=179,floor=21. rand starts at 0.
- int randY = r.nextInt(180)+21;
- int randRad = r.nextInt(7)+3; //same as before, but BETWEEN 2 and 10, so 3-9
- //making random values for x and y is a 2 step process since we can't declare a negative range.
- //first we make a random int (0 or 1); then we take -1 and square it by the random int (0 or 1). if it is 0,
- //the sign won't change (stay positive). if it is 1, the sign will become negative.
- int sign = r.nextInt(2);
- double randVelX = (Math.pow(-1, sign)*(r.nextInt(41)));
- double randVelY = (Math.pow(-1, sign)*(r.nextInt(41)));
- Ball randomBall = new Ball(randX,randY,randRad,Color.green, randVelX, randVelY);
- return randomBall;
- } //makeRandomBall()
- } //BallsApplet class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement