AWT09-弹球小游戏
阅读原文时间:2023年07月09日阅读:1

  为了让Java绘制动画,可以借助Swing的定时器,其构造为:

方法名

说明

Timer(int delay,ActionListener listener)

每间隔delay毫秒,自动触发ActionListener里的事件处理

1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4
5 public class ballGameDemo {
6 private final int TABLE_WIDTH = 300;
7 private final int TABLE_HEIGHT = 400;
8
9 private final int r_width = 60;
10 private final int r_height = 20;
11
12 private final int ball_size = 16;
13
14 private int ballx = 120;
15 private int bally = 20;
16
17 private int speedX = 5;
18 private int speedY = 5;
19
20 private int r_x = 120;
21 private final int r_y = 340;
22
23 private boolean isOver = false;
24
25 private Timer time;
26
27 private class MyCanvas extends Canvas {
28 @Override
29 public void paint(Graphics g){
30 if (isOver){
31 g.setColor(Color.RED);
32 g.setFont(new Font("Times",Font.BOLD,30));
33 g.drawString("Game Over",80,200);
34 }else{
35 g.setColor(Color.BLUE);
36 g.fillOval(ballx,bally,ball_size,ball_size);
37 g.drawOval(ballx,bally,ball_size,ball_size);
38
39 g.setColor(Color.PINK);
40 g.fillRect(r_x,r_y,r_width,r_height);
41 g.drawRect(r_x,r_y,r_width,r_height);
42 }
43 }
44 }
45
46 Frame frame = new Frame("弹弹球");
47
48 MyCanvas canvas = new MyCanvas();
49
50
51
52
53 public void init() {
54 KeyListener keyListener = new KeyAdapter() {
55 @Override
56 public void keyPressed(KeyEvent e) {
57 int keyCode = e.getKeyCode();
58
59 if (keyCode == KeyEvent.VK_A){
60 if (r_x > 0){
61 r_x -= 15;
62 }
63 }
64
65 if (keyCode == KeyEvent.VK_D){
66 if (r_x < (TABLE_WIDTH - r_width)){ 67 r_x +=15; 68 } 69 } 70 } 71 }; 72 73 frame.addKeyListener(keyListener); 74 canvas.addKeyListener(keyListener); 75 76 ActionListener actionListener = new ActionListener() { 77 @Override 78 public void actionPerformed(ActionEvent e) { 79 if (ballx <= 0 || ballx > (TABLE_WIDTH - ball_size)){
80 speedX = -speedX;
81 }
82
83 if (bally <= 0 ||(ballx > (r_y - ball_size) && ballx > r_x && ballx < (r_x+r_width))){ 84 speedY = -speedY; 85 } 86 87 if (bally > (r_y-ball_size) && (ballx < r_x || ballx >(r_x+r_width))){
88 time.stop();
89 isOver = true;
90 canvas.repaint();
91 }
92
93 ballx += speedX;
94 bally += speedY;
95
96 canvas.repaint();
97 }
98 };
99 time = new Timer(10, actionListener);
100 time.start();
101
102 canvas.setPreferredSize(new Dimension(TABLE_WIDTH,TABLE_HEIGHT));
103 frame.add(canvas);
104
105 frame.addWindowListener(new WindowAdapter() {
106 @Override
107 public void windowClosing(WindowEvent e) {
108 System.exit(0);
109 }
110 });
111 frame.pack();
112 frame.setVisible(true);
113 }
114
115 public static void main(String[] args) {
116 new ballGameDemo().init();
117 }
118 }