话不多说,这是全部的代码。
package Draw;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PainBall {
Frame frame=new Frame("弹球小游戏");
//定义桌面宽度和高度
private final int TABLE_WIDTH=300;
private final int TABLE_HEIGHT=400;
//定义球拍的
private final int RAKET_WIDTH=20;
private final int REKET_HEIGHT=40;
//定义小球
private final int BALL_SIZE=16;
//定义变量,纪录小球坐标
private int ballX=102;
private int ballY=50;
//定义变量,纪录小球速度
private int speedX=10;
private int speedY=5;
//定义变量,纪录球拍坐标
private int raketX=120;
private int raketY=340;
//定义变量,标识游戏是否结束
private boolean isOver=false;
//定义定时器
private Timer timer;
//定义一个自定义类,继承Canvas,充当画布
private class MyCanvas extends Canvas{
public void paint(Graphics g){
if(isOver){
//游戏结束
g.setColor(Color.black);
g.setFont(new Font("Timer",Font.BOLD,30));
g.drawString("你已经死了",50,200);
}else {
//游戏中
//绘制小球
g.setColor(Color.red);
g.fillOval(ballX,ballY,BALL_SIZE,BALL_SIZE);
//绘制球拍
g.setColor(Color.PINK);
g.fillRect(raketX,raketY,RAKET_WIDTH,REKET_HEIGHT);
}
}
}
//创建一个绘画区域
MyCanvas drawArea=new MyCanvas();
public void init() {
//组装视图
KeyListener listener = new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
//左移
if (raketX>0){
raketX-=10;
}
}
if (keyCode==KeyEvent.VK_RIGHT){
if(raketX<(TABLE_WIDTH-RAKET_WIDTH)){
raketX+=10;
}
}
}
};
frame.addKeyListener(listener);
drawArea.addKeyListener(listener);
//小球坐标控制
ActionListener task=new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(ballX<=0||ballX>=(TABLE_WIDTH-BALL_SIZE)){
speedX=-speedX;
}
if (ballY<=0||(ballY>raketY-BALL_SIZE&&ballX<raketX+RAKET_WIDTH)){
speedY=-speedY;
}
if (ballY>raketY-BALL_SIZE&&(ballX<raketX||ballX>raketX+RAKET_WIDTH)){
timer.stop();
isOver=true;
drawArea.repaint();
}
ballX+=speedX;
ballY+=speedY;
drawArea.repaint();
}
};
timer=new Timer(100,task);
timer.start();
drawArea.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
frame.add(drawArea);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new PainBall().init();
}
}