?? ballworld7.java
字號:
// BallWorld - version 7
import java.awt.*;
public class BallWorld extends Frame
{
////////////////////////////////
////////// variables ///////////
////////////////////////////////
// application variables
// variables for width and height of frame
public static final int frameWidth = 600;
public static final int frameHeight = 400;
/// NEW NEW NEW - array of refernces to Ball objects
private Ball balls[];
// a counter - so we can paint the ball more than once
private int counter;
////////////////////////////////
///////////// methods //////////
////////////////////////////////
////////// method main ///////////
// sequence of instrucions for main program
static public void main (String [] args)
{
BallWorld world = new BallWorld ();
world.show ();
}
////////// method BallWorld ///////////
private BallWorld ()
{
// set size and title of our application window
setSize(frameWidth, frameHeight);
setTitle("Ball World");
// NEW NEW NEW - set up "balls" to hold 5 balls
balls = new Ball[5];
// NEW NEW NEW - set up each of the 5 balls
balls[0] = new Ball(100, 100, 50, 4, 5);
balls[1] = new Ball(200, 200, 25, -3, -2);
balls[2] = new Ball(50, 50, 5, 1, -1);
balls[3] = new Ball(200, 50, 10, -10, -15);
balls[4] = new Ball(75, 200, 75, -1, 1);
// NEW NEW NEW - make the balls different colours
balls[1].setColor( Color.green );
balls[2].setColor( Color.red );
balls[3].setColor( Color.yellow );
balls[4].setColor( Color.green );
// set out counter to zero
counter = 0;
}
private void bounce(Ball ball)
{
// check for left of frame collision (X value too small)
if ( ball.getX() < 0 )
ball.setMotion( -ball.getXMotion(), ball.getYMotion() );
// check for right of frame collision (X value too large)
if ( ball.getX() > frameWidth )
ball.setMotion(-ball.getXMotion(), ball.getYMotion());
// check for top of frame collision (Y value too small)
if ( ball.getY() < 0 )
ball.setMotion(ball.getXMotion(), -ball.getYMotion());
// check for bottom of frame collision (Y value too large)
if ( ball.getY() > frameHeight )
ball.setMotion(ball.getXMotion(), -ball.getYMotion());
}
////////// method paint ///////////
public void paint(Graphics g)
{
// NEW NEW NEW - display and move all 5 balls
for( int i = 0; i < balls.length; i++)
{
balls[i].paint( g );
balls[i].move();
}
pause( 20 );
// NEW NEW NEW - call method "bounce" for all 5 balls
for( int i = 0; i < balls.length; i++)
bounce( balls[i] );
counter = counter + 1;
if (counter < 500)
repaint();
else
System.exit(0);
}
////////// method pause ///////////
private void pause(int numMilliseconds)
{
// use a Java libary routine to pause a little
try{ Thread.sleep( numMilliseconds ); } catch (InterruptedException e){}
}
} // class BallWorld
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -