GIDForums  

Go Back   GIDForums > Computer Programming Forums > Java Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 15-Nov-2006, 13:00
candykane69 candykane69 is offline
New Member
 
Join Date: May 2006
Posts: 3
candykane69 is an unknown quantity at this point
Post

Java bouncing blue ball


Write a program that bounces a blue ball inside an applet. The ball should begin moving with a mousePressed event. When the ball hits the edge of the applet, the ball should bounce off the edge and continue in the opposite direction.

Add a new ball each time the user clicks the mouse.
Provide for a minimum of 20 balls. Randomly choose the color for each new ball


help me add the additional color balls to this program please
JAVA Code:
// Ball.java
// Program bounces a ball around the applet
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Ball extends JApplet
          implements Runnable, MouseListener {
   private Thread blueBall;
   private boolean xUp, yUp, bouncing;
   private int x, y, xDx, yDy;

   public void init()
   {
      xUp = false;
      yUp = false;
      xDx = 1;
      yDy = 1;
      addMouseListener( this );
      bouncing = false;
   }

   public void mousePressed( MouseEvent e )
   {
      if ( blueBall == null ) {
         x = e.getX();
         y = e.getY();
         blueBall = new Thread( this );
         bouncing = true;
         blueBall.start();
      }
   }

   public void stop()
   {
      if ( blueBall != null ) {
         blueBall = null;
      }
   }

   public void paint( Graphics g )
   {
      if ( bouncing ) {
         g.setColor( Color.blue );
         g.fillOval( x, y, 10, 10 );
      }
   }

   public void run()
   {
      while ( true ) {

         try {
            blueBall.sleep( 100 );
         }
         catch ( Exception e ) {
            System.err.println( "Exception: " + e.toString() );
         }

         if ( xUp == true )
            x += xDx;
         else
            x -= xDx;

         if ( yUp == true )
            y += yDy;
         else
            y -= yDy;

         if ( y <= 0 ) {
            yUp = true;            
            yDy = ( int ) ( Math.random() * 5 + 2 );
         }
         else if ( y >= 190 ) {
            yDy = ( int ) ( Math.random() * 5 + 2 );
            yUp = false;
         }

         if ( x <= 0 ) {
            xUp = true;
            xDx = ( int ) ( Math.random() * 5 + 2 );
         }
         else if ( x >= 190 ) {
            xUp = false;
            xDx = ( int ) ( Math.random() * 5 + 2 );
         }

         repaint();
      }
   }

   public void mouseExited( MouseEvent e ) {}
   public void mouseClicked( MouseEvent e ) {}
   public void mouseReleased( MouseEvent e ) {}
   public void mouseEntered( MouseEvent e ) {}     
}
Last edited by LuciWiz : 15-Nov-2006 at 14:38. Reason: Please insert your Java code between [java] & [/java] tags
  #2  
Old 16-Nov-2006, 20:24
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,463
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Java bouncing blue ball


Are the colors repeatable? There are 13 colors in the Color class, one of which is white, which won't show on your background, and narrows that down to 12.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #3  
Old 17-Nov-2006, 04:11
candykane69 candykane69 is offline
New Member
 
Join Date: May 2006
Posts: 3
candykane69 is an unknown quantity at this point
Question

Re: Java bouncing blue ball


yes the colors can be repeated
  #4  
Old 18-Nov-2006, 19:22
TurboPT's Avatar
TurboPT TurboPT is offline
Senior Member
 
Join Date: Feb 2006
Location: Atlanta, GA
Posts: 1,463
TurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the roughTurboPT is a jewel in the rough

Re: Java bouncing blue ball


Since a new ball is added by a mouse click, instead of creating a bunch of them all at once makes this more involved -- but several things need to be added, but this should be a good start. Although I provide some code snippets, there are some parts you need to do/add.

Feel free to change the naming conventions...make sure to change the code where affected.

1. Rename the blueBall [thread] variable to something else. I use just the letter 't' in the snippets, below. This will make it easily reused from an inner class...

2. Add an inner class (inside your Ball class) to support the other balls. The good new is, you can extend the ball class itself (and avoids extra variables for the inner class).
JAVA Code:
private class MoreBalls extends Ball  { /* class code */ }
3. Add a two-argument constructor to the inner class, so that the mouse position can be passed with new creations from the mousePressed() function. The constructor needs to do similar things that init() does, plus more...
2.a. assign x and y to the values passed in from mousePressed().
2.b. no need to do anything with bouncing.
2.c. no need for another mouse listener.
2.d. assign 't' a new Thread (see step 6)
2.e. start 't'.
2.f. set a ballColor (see step 6 and step 10)
4. Clone your current run() into the inner class, but it does not need a repaint() call.

5. For a change required to paint(), add three more functions to the inner class to:
5.a. get the x value
5.b. get the y value
5.c. get the color value (see step 6)
==== That should do it for the inner class. Now back to the ball class...

6. Add four more variables (one is the step 1 rename):
JAVA Code:
	static final int N = 19; // for the other balls. [+ the applet's, makes 20]
	int ballCount = 0;	 // track the balls created.
	Thread t = null;         // change from 'blueBall'
	MoreBalls moreballs[] = null;  // array of the inner class.
	Color ballColor;          // general ball color use.
make sure to change blueBall anywhere else it appears too.

7. In init(), for your original color and the array, add these two statements:
JAVA Code:
   ballColor = Color.blue;   // your original color.
   moreballs = new MoreBalls[N];
8. In mousePressed(), add this code after the if block:
JAVA Code:
 else if ( ballCount < N )
 {
	moreballs[ballCount] = new MoreBalls( e.getX(), e.getY() );
	ballCount++;
 }
9. In paint(), add a loop after the if block to draw the other balls: [needs your function calls from step 5]
JAVA Code:
 for (int i = 0; i < ballCount; ++i)
 {
	 g.setColor(moreballs[i].<get the color>);   // add YOUR functions
	 g.fillOval(moreballs[i].<get x>, moreballs[i].<get y>, 10, 10);
 }
Also, change the 'Color.blue' to ballColor in the if.

finally...
10. Here's a function to add to the ball class to get a random ball color (the arguments are red, green, and blue values, respectively):
JAVA Code:
   public Color randomColor()
   {
	return new Color( (int)Math.round(Math.random() * 255),
		  	(int)Math.round(Math.random() * 255),
		  	(int)Math.round(Math.random() * 255) );
   }
Note that this can also be called from init() to possibly start with something other than blue.
__________________
Use the force...read the source!!
WYCIWYG -- what you code is what you get!
  #5  
Old 01-Dec-2006, 07:22
candykane69 candykane69 is offline
New Member
 
Join Date: May 2006
Posts: 3
candykane69 is an unknown quantity at this point

Re: Java bouncing blue ball


help with adding 20 balls


Add a new ball each time the user clicks the mouse.
Provide for a minimum of 20 balls. Randomly choose the color for each new ball

JAVA Code:
// Create a ball to bounce around a JPanel.
import javax.swing.JFrame;
import java.util.Random;

public class Ball implements Runnable
{
   private boolean xUp; // controls whether ball is moving up or down
   private boolean yUp; // controls whether ball is moving left or right
   private int x; // horizontal position of ball
   private int y; // vertical position of ball
   private int xDx; // change in horizontal position of ball
   private int yDy; // change in vertical position of ball
   private final int MAX_X = 200; // horizontal edge of JPanel
   private final int MAX_Y = 200; // vertical edge of JPanel
   private JFrame parent; // parent window of ball
   private Random generator = new Random();

   public Ball( JFrame window, int xPos, int yPos )
   {
      xUp = false; // set ball to moving to left
      yUp = false; // set ball to moving up
      xDx = 1; // set ball to move one pixel horizontally at a time
      yDy = 1; // set ball to move one pixel vertically at a time
      x = xPos; // set ball to horizontal position of mouse press
      y = yPos; // set ball to vertical position of mouse press
      parent = window; // set parent window of ball
   } // end Ball constructor

   // bounces ball perpetually until window is closed
   public void run()
   {
      while ( true ) // infinite loop
      {
         try 
         {
            Thread.sleep( 20 ); // sleep for 20 milliseconds
         } // end try
         // process InterruptedException during sleep
         catch ( InterruptedException exception ) 
         {
            exception.printStackTrace();
         } // end catch

         // determine new x position
         if ( xUp == true )
            x += xDx; // move ball right
         else
            x -= xDx; // move ball left

         // determine new y position
         if ( yUp == true )
            y += yDy; // move ball down
         else
            y -= yDy; // move ball up

         if ( y <= 0 ) // if bounce off top of JPanel
         {
            yUp = true; // ball is moving down
            yDy = generator.nextInt( 5 ) + 2; // change vertical move
         } // end if
         else if ( y >= MAX_Y - 10 ) // if bounce off bottom of JPanel
         {
            yUp = false; // ball is moving up
            yDy = generator.nextInt( 5 ) + 2; // change vertical move
         } // end else if

         if ( x <= 0 ) // if bounce off right of JPanel
         {
            xUp = true; // ball is moving right
            xDx = generator.nextInt( 5 ) + 2; // change horizontal move
         } // end if
         else if ( x >= MAX_X - 10 ) // if bounce off left of JPanel
         {
            xUp = false; // ball is moving left 
            xDx = generator.nextInt( 5 ) + 2; // change horizontal move
         } // end else if

         parent.repaint(); // repaint window
      }  // end while
   } // end method run

   // get horizontal position of ball
   public int getX()
   {
      return x; // return x value
   } // end method getX

   // get vertical position of ball
   public int getY()
   {
      return y; // return y value
   } // end method getY
}  // end class Ball
Last edited by LuciWiz : 01-Dec-2006 at 08:27. Reason: Please insert your Java code between [java] & [/java] tags
 


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Scalability in Java and C++ agx Miscellaneous Programming Forum 7 04-Feb-2006 15:35
cricket hostbreak Sports Forum 21 10-Dec-2005 07:28
[Java] Eclipse.org's Java IDE JdS Java Forum 5 04-Dec-2005 09:41
Checking source codes of image, audio and video files onauc C Programming Language 5 26-Feb-2005 21:47

Network Sites: GIDNetwork · GIDApp · GIDBlog · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 02:16.


vBulletin, Copyright © 2000 - 2014, Jelsoft Enterprises Ltd.