桌球游戏是一种室内运动,通常在一个正式的桌球台上进行。这种游戏也被称为台球或母球。桌球游戏的目标是使用一个击球杆将彩球击入桌面四个角落的袋子中,得分最高的一方获胜。桌球游戏需要一定的技巧和策略,因此是一项受欢迎的竞技运动和休闲娱乐活动。
以下是一个简单的桌球小游戏的Java代码实现示例:
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
-
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.Timer;
-
- public class DeskBallGame extends JPanel implements ActionListener {
- private static final long serialVersionUID = 1L;
- private int ballX = 200;
- private int ballY = 200;
- private int ballWidth = 30;
- private int ballHeight = 30;
- private int ballSpeedX = -2;
- private int ballSpeedY = -3;
- private int tableWidth = 400;
- private int tableHeight = 300;
- private int paddleX = 0;
- private int paddleY = 250;
- private int paddleWidth = 60;
- private int paddleHeight = 10;
- private Timer timer;
-
- public DeskBallGame() {
- timer = new Timer(5, this);
- timer.start();
- }
-
- public void paint(Graphics g) {
- super.paint(g);
- g.setColor(Color.BLUE);
- g.fillOval(ballX, ballY, ballWidth, ballHeight);
- g.setColor(Color.RED);
- g.fillRect(paddleX, paddleY, paddleWidth, paddleHeight);
- g.setColor(Color.BLACK);
- g.drawRect(0, 0, tableWidth, tableHeight);
- }
-
- public void actionPerformed(ActionEvent e) {
- ballX += ballSpeedX;
- ballY += ballSpeedY;
- if (ballX < 0 || ballX > tableWidth - ballWidth) {
- ballSpeedX = -ballSpeedX;
- }
- if (ballY < 0 || ballY > tableHeight - ballHeight) {
- ballSpeedY = -ballSpeedY;
- }
- if (ballY + ballHeight >= paddleY && ballX + ballWidth >= paddleX
- && ballX <= paddleX + paddleWidth) {
- ballSpeedY = -ballSpeedY;
- }
- repaint();
- }
-
- public static void main(String[] args) {
- JFrame frame = new JFrame("Desk Ball Game");
- DeskBallGame deskBallGame = new DeskBallGame();
- frame.add(deskBallGame);
- frame.setSize(deskBallGame.tableWidth, deskBallGame.tableHeight);
- frame.setVisible(true);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- }
这个代码实现了一个带有桌子、球和球拍的桌球小游戏。在窗口中,当球碰到桌子边界时,它将反弹。当球与球拍相撞时,它也将反弹。
要运行这个程序,只需将代码复制到Java开发环境中,并运行主方法。这将打开一个窗口,其中包含一个可移动的球和球拍,您可以使用箭头键移动球拍以避免让球落下。
效果如下: