JAVA小游戏—弹球乐
package Awt ;
import java. awt. * ;
import java. awt. event. * ;
import javax. swing. * ;
public class TanQiu {
private Frame f= new Frame ( "弹球小游戏" ) ;
private final int w1= 300 ;
private final int h1= 400 ;
private final int w2= 60 ;
private final int h2= 20 ;
private final int r= 16 ;
private int x1= 120 ;
private int y1= 20 ;
private int Vx = 5 ;
private int Vy = 10 ;
private int x2= 120 ;
private final int y2= 340 ;
private boolean isOver = false ;
private Timer timer;
private class MyCancas extends Canvas {
public void paint ( Graphics g) {
if ( isOver) {
g. setColor ( Color . BLUE) ;
g. setFont ( new Font ( "Timer" , Font . BOLD, 30 ) ) ;
g. drawString ( "游戏结束" , 50 , 200 ) ;
} else {
g. setColor ( Color . RED) ;
g. fillOval ( x1, y1, r, r) ;
g. setColor ( Color . PINK) ;
g. fillRect ( x2, y2, w2, h2) ;
}
}
}
MyCancas drawArea= new MyCancas ( ) ;
public void init ( ) {
KeyListener listener= new KeyAdapter ( ) {
@Override
public void keyPressed ( KeyEvent e) {
int keyCode= e. getKeyCode ( ) ;
if ( keyCode== KeyEvent . VK_LEFT) {
if ( x2> 0 ) {
x2-= 10 ;
}
}
if ( keyCode== KeyEvent . VK_RIGHT) {
if ( x2< 240 ) {
x2+= 10 ;
}
}
}
} ;
f. addKeyListener ( listener) ;
drawArea. addKeyListener ( listener) ;
ActionListener task= new ActionListener ( ) {
@Override
public void actionPerformed ( ActionEvent e) {
if ( x1<= 0 || x1>= 284 ) {
Vx = - Vx ;
}
if ( y1<= 0 || y1> y2- r&& x1> x2&& x1< x2+ w2) {
Vy = - Vy ;
}
if ( y1> y2- r&& ( x1< x2|| x1> x2+ w2) ) {
timer. stop ( ) ;
isOver= true ;
drawArea. repaint ( ) ;
}
x1+= Vx ;
y1+= Vy ;
drawArea. repaint ( ) ;
}
} ;
timer = new Timer ( 100 , task) ;
timer. start ( ) ;
f. addWindowListener ( new WindowAdapter ( ) {
@Override
public void windowClosing ( WindowEvent e) {
System . exit ( 0 ) ;
}
} ) ;
drawArea. setPreferredSize ( new Dimension ( w1, h1) ) ;
f. add ( drawArea) ;
f. pack ( ) ;
f. setVisible ( true ) ;
}
public static void main ( String [ ] args) {
new TanQiu ( ) . init ( ) ;
}
}