public class PinBall {
//桌面的宽度
private final int TABLE_WIDTH=300;
//桌面高度
private final int TABLE_HEIGHT=400;
//球拍的垂直位置
private final int RACKET_Y=340;
//球拍的高度和宽度
private final int RACKET_HEIGHT=20;
private final int RACKET_WIDTH=60;
//小球的大小
private final int BALL_SIZE=16;
private Frame f=new Frame("弹球游戏");
Random rand=new Random();
//小球的纵向运行速度
private int ySpeed=10;
//返回一个-0.5-0.5的比率,用于控制小球的运动方向
private double xyRate=rand.nextDouble()-0.5;
//小球横向的运行速度
private int xSpeed=(int)(ySpeed*xyRate*2);
//ballX和ballY代表小球的坐标
private int ballX=rand.nextInt(200)+20;
private int ballY=rand.nextInt(10)+20;
//racketX代表球拍的水平位置
private int racketX=rand.nextInt(200);
private MyCanvas tableArea=new MyCanvas();
Timer timer;
//游戏是否结束的旗标
private boolean isLose=false;
public void init(){
tableArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
f.add(tableArea);
KeyAdapter keyProcessor=new KeyAdapter(){
public void keyPressed(KeyEvent ke){
//按下向左、向右键时,球拍水平坐标分别减少、增加
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
if(racketX>0)
{
racketX-=10;
}
if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
if(racketX<TABLE_WIDTH-RACKET_WIDTH){
racketX+=10;
}
}
}