21xrx.com
2025-03-21 08:27:24 Friday
文章检索 我的文章 写文章
Java小游戏开发——打地鼠游戏代码实现
2023-06-15 09:32:44 深夜i     25     0
Java 游戏开发 JFrame

打地鼠游戏是一种简单而又有趣的小游戏,适合初学者练习Java编程。在本文中,我们将会讲解如何使用Java语言编写一个打地鼠游戏。首先,我们需要明确一下这个游戏的规则和操作方法。

游戏规则:

1. 游戏场景为一个长方形的地图,地图上会不时出现地鼠。

2. 玩家需要在规定的时间内打中所有出现的地鼠。

3. 在规定时间内击中所有地鼠,游戏胜利。

4. 超时或者未能全部击中地鼠,游戏失败。

游戏操作:

1. 使用鼠标点击地图上的地鼠,即可打中地鼠。

2. 在规定时间内击中所有地鼠后,游戏结束。

在实现这个游戏时,我们需要用到Java的AWT和Swing两个工具包,用于实现游戏画面和游戏逻辑。下面是实现该游戏的关键代码:

public class Game extends JFrame {
  private JPanel contentPanel;
  private JButton button;
  private int count = 0;
  private int limit = 30;
  public Game() {
    initUI();
  }
  private void initUI() {
    setTitle("打地鼠游戏");
    contentPanel = new JPanel();
    contentPanel.setLayout(new GridLayout(4, 8, 5, 5));
    button = new JButton("开始游戏");
    button.addActionListener((ActionEvent event) -> {
      startGame();
    });
    for (int i = 0; i < 32; i++) {
      contentPanel.add(new JLabel());
    }
    add(contentPanel, BorderLayout.CENTER);
    add(button, BorderLayout.SOUTH);
    setSize(800, 600);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  private void startGame() {
    count = 0;
    button.setEnabled(false);
    Timer timer = new Timer(500, (ActionEvent event) -> {
      int index = (int) (Math.random() * 32);
      JLabel label = (JLabel) contentPanel.getComponent(index);
      label.setIcon(new ImageIcon("src/resources/mouse.png"));
      Timer secondTimer = new Timer(1000, (ActionEvent e) -> {
        label.setIcon(null);
      });
      secondTimer.setRepeats(false);
      secondTimer.start();
    });
    timer.setRepeats(true);
    timer.start();
    Timer endTimer = new Timer(limit * 1000, (ActionEvent event) -> {
      timer.stop();
      button.setEnabled(true);
      JOptionPane.showMessageDialog(this, "恭喜你,游戏胜利!");
    });
    endTimer.setRepeats(false);
    endTimer.start();
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
      Game game = new Game();
      game.setVisible(true);
    });
  }
}

在上述代码中,我们使用JFrame框架实现了游戏界面,其中contentPanel是用于存放32个JLabel的面板,这32个JLabel就是我们的“地鼠”。startGame()方法是开始游戏的函数,其中我们用到了Java的Timer类来实现地鼠随机出现的效果,并且这个Timer是可以重复的,因此地鼠就可以不停地跑出来。如果时间到了,我们用另一个Timer对象来停止游戏,弹出胜利的提示框。

  
  

评论区