java AWT弹球游戏
java AWT弹球游戏
1 package io.guanghe;
2
3 import javax.swing.*;
4 import java.awt.*;
5 import java.awt.event.*;
6
7 public class BallGame {
8 private Frame frame = new Frame("光何弹球");
9 private final int TABLE_WIDTH = 300;
10 private final int TABLE_HEIGHT = 400;
11 private final int RACKET_WIDTH = 60;
12 private final int RACKET_HEIGHT = 20;
13 private final int BALL_SIZE = 16;
14 private int ballX = 120;
15 private int ballY = 20;
16 private int speedX = 10;
17 private int speedY = 5;
18 private int racketX = 120;
19 private int racketY = 340;
20 private boolean isOver = false;
21 private Timer timer;
22 private class BallCanvas extends Canvas {
23 @Override
24 public void paint(Graphics g) {
25 super.paint(g);
26 if(isOver) {
27 g.setColor(Color.BLUE);
28 g.setFont(new Font("Times", Font.BOLD, 30));
29 g.drawString("游戏结束", 50, 200);
30 } else {
31 g.setColor(Color.RED);
32 g.fillOval(ballX, ballY, BALL_SIZE, BALL_SIZE);
33 g.setColor(Color.PINK);
34 g.fillRect(racketX, racketY, RACKET_WIDTH, RACKET_HEIGHT);
35 }
36 }
37 }
38 BallCanvas ballCanvas = new BallCanvas();
39 public void init() {
40 frame.addWindowListener(new WindowAdapter() {
41 @Override
42 public void windowClosing(WindowEvent e) {
43 System.exit(0);
44 }
45 });
46 KeyListener listener = new KeyAdapter() {
47 @Override
48 public void keyPressed(KeyEvent e) {
49 super.keyPressed(e);
50 int keyCode = e.getKeyCode();
51 if(keyCode == KeyEvent.VK_LEFT) {
52 if(racketX > 0) {
53 racketX -= 10;
54 }
55 } else if(keyCode == KeyEvent.VK_RIGHT) {
56 if(racketX < (TABLE_WIDTH - RACKET_WIDTH)) {
57 racketX += 10;
58 }
59 }
60 }
61 };
62 frame.addKeyListener(listener);
63 ballCanvas.addKeyListener(listener);
64 ActionListener task = e -> {
65 if(ballX <= 0 || ballX >= (TABLE_WIDTH - BALL_SIZE)) {
66 speedX = -speedX;
67 }
68 if(ballY <= 0 || (ballY > racketY - BALL_SIZE && ballX > racketX && ballX < racketX + RACKET_WIDTH)) {
69 speedY = -speedY;
70 }
71 if(ballY > racketY - BALL_SIZE && (ballX < racketX || ballX > racketX + RACKET_WIDTH)) {
72 timer.stop();
73 isOver = true;
74 }
75 ballX += speedX;
76 ballY += speedY;
77 ballCanvas.repaint();
78 };
79 timer = new Timer(100, task);
80 timer.start();
81 ballCanvas.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HEIGHT));
82 frame.add(ballCanvas);
83 frame.pack();
84 frame.setVisible(true);
85 }
86
87 public static void main(String[] args) {
88 new BallGame().init();
89 }
90 }