弹球小游戏
建议Copy到IDEA中玩一玩
为了实现间隔一定的时间就重新调用组件的repaint()方法,可以借助于Swing中提供的Timer类,Timer类是一个定时器:
Timer(int delay,ActionLister listener):每个delay毫秒,系统自动触发ActionLister监听器里的事件处理器方法,在方法内部我们就可以调用组件的repaint()方法,完成组件重绘。
AWT抽象窗口工具集&Timer定时器的应用:
package com.awt.xm.graphics.pinball;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 弹球游戏,可直接运行!
*/
public class PinBallGame {
/**
* 窗口对象
*/
private jFrame frame = new jFrame("弹球游戏");
/**
* 窗口的宽度
*/
private final int WINDOW_WIDTH = 300;
/**
* 窗口的高读
*/
private final int WINDOW_HEIGHT = 400;
/**
* 球拍的宽度
*/
private final int BEAT_WIDTH = 60;
/**
* 球拍的高度
*/
private final int BEAT_HEIGHT = 20;
/**
* 小球大小
*/
private final int BALL_SIZE = 16;
/**
* 定义变量,记录小球的位置
*/
private int ballX = 100;
private int ballY = 20;
/**
* 定义变量,记录小球在X和Y方向上移动的速度
*/
private int speedX = 5;
private int speedY = 5;
/**
* 定义变量记录球拍的坐标
*/
private int beatX = 120;
private final int beatY = 340;
/**
* 定义变量,标识游戏是否已经结束
*/
private boolean isOver = false;
/**
* 声明一个定时器
*/
private Timer timer;
/**
* 自定义一个类继承Canvas充当画布。
*/
private class MyCanvas extends JPanel {
@Override
public void paint(Graphics g) {
super.paint(g);
if (isOver) {
g.setColor(Color.BLUE);
g.setFont(new Font("Times", Font.BOLD, 30));
g.drawString("游戏结束", 80, 200);
}
else {
g.setColor(Color.RED);
g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
g.setColor(Color.ORANGE);
g.fillRect(beatX, beatY, BEAT_WIDTH, BEAT_HEIGHT);
}
}
}
/**
* 绘画区域
*/
MyCanvas myCanvas = new MyCanvas();
private void init() {
//球拍的控制
KeyListener keyListener = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
if (beatX > 0)
beatX -= 10;
}
if (keyCode == KeyEvent.VK_RIGHT) {
if (beatX < (WINDOW_WIDTH - BEAT_WIDTH))
beatX += 10;
}
}
};
frame.addKeyListener(keyListener);
myCanvas.addKeyListener(keyListener);
//小球坐标的控制
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (ballX <= 0 || ballX >= (WINDOW_WIDTH - BALL_SIZE))
speedX = -speedX;
if (ballY <= 0 || ballY >= beatY - BALL_SIZE && ballX >= beatX && ballX <= beatX + BEAT_WIDTH)
speedY = -speedY;
if (ballY > beatY - BALL_SIZE && (ballX < beatX || ballX > beatX + BEAT_WIDTH)) {
timer.stop();
isOver = true;
myCanvas.repaint();
}
ballX += speedX;
ballY += speedY;
myCanvas.repaint();
}
};
timer = new Timer(100, listener);
timer.start();
//放入frame
myCanvas.setPreferredSize(new Dimension(WINDOW_WIDTH, WINDOW_HEIGHT));
frame.add(myCanvas);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
/**
* 启动
* @param args 命令行参数
*/
public static void main(String[] args) {
new PinBallGame().init();
}
}