程序来自《疯狂java讲义》,看着挺有意思,亲手敲了一遍。
package com;
import java.awt.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.Timer;;
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=8;//小球纵向的运行速度
//返回一个-0.5-0.5的比率,用以控制小球的运行方向
private double xyRate=rand.nextDouble()-0.5;
private int xSpeed=(int)(ySpeed*xyRate*2);//小球的横向速度
private int ballX=rand.nextInt(200)+20;//小球的坐标
private int ballY=rand.nextInt(10)+20;
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;
}
}
};
f.addKeyListener(keyProcessor);
tableArea.addKeyListener(keyProcessor);
ActionListener taskPerformer=new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
if(ballX<=0||ballX>=TABLE_WIDTH-BALL_SIZE)//如果小球碰到左边边框
{
xSpeed=-xSpeed;
}
//如果小球高度超出了球拍位置且横向不在球拍范围之内,游戏结束
if(ballY>=RACKET_Y-BALL_SIZE&&(ballX<racketX||ballX>racketX+RACKET_WIDTH))
{
timer.stop();
isLose=true;
tableArea.repaint();
}
//如果小球位于球拍之间,且达到球拍位置,小球反弹
else if(ballY<=0||(ballY>=RACKET_Y-BALL_SIZE&&ballX>racketX&&ballX<=racketX+RACKET_WIDTH))
{
ySpeed=-ySpeed;
}
ballY+=ySpeed;
ballX+=xSpeed;
tableArea.repaint();
}
};
// 创建一个 Timer 并将初始延迟和事件间延迟初始化为 100 毫秒
timer=new Timer(100,taskPerformer);
timer.start();
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new PinBall().init();
}
class MyCanvas extends Canvas
{
public void paint(Graphics g)
{
if(isLose)
{
g.setColor(new Color(255,0,0));
g.setFont(new Font("Times",Font.BOLD,30));
g.drawString("游戏已结束", 50, 200);
}
else
{
g.setColor(new Color(240,240,80));
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
g.setColor(new Color(80,80,200));
g.fillRect(racketX, RACKET_Y, RACKET_WIDTH, RACKET_HEIGHT);
}
}
}
}