21xrx.com
2025-04-06 06:00:54 Sunday
文章检索 我的文章 写文章
关键词:Java编程、简单小游戏、代码例子
2023-06-10 17:00:26 深夜i     11     0

Java编程是现代软件开发中一门非常重要的语言,尤其在游戏开发领域中更是广泛应用。为了让学习者更好地理解Java编程,下面将介绍一个简单的小游戏,并附上代码例子。

游戏名称:打地鼠游戏

游戏规则:

游戏共有9个洞口,随机出现地鼠并在洞口上弹出,玩家需要用锤子打击地鼠使其消失。每次出现的地鼠只会停留一秒钟,如果玩家没及时打击地鼠或者打到洞口,玩家生命值减一,生命值为0时游戏结束。

代码例子如下:

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class HitMouse extends JFrame implements ActionListener {
  private static final long serialVersionUID = 1L;
  private static final int ROW = 3;
  private static final int COL = 3;
  private static final int HOLE_TOTAL = ROW * COL;
  private JLabel[] holes = new JLabel[HOLE_TOTAL];
  private JLabel scoreLabel;
  private JLabel lifeLabel;
  private Timer timer;
  private int score = 0;
  private int life = 3;
  private Random random = new Random();
  private HitMouse() {
    super("打地鼠");
    setSize(500, 400);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(ROW, COL));
    for (int i = 0; i < HOLE_TOTAL; i++) {
      JLabel hole = new JLabel();
      hole.setBorder(BorderFactory.createLineBorder(Color.gray, 2));
      hole.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
          JLabel hole = (JLabel) e.getSource();
          if ("1".equals(hole.getName())) {
            hole.setIcon(null);
            hole.setName("0");
            score++;
            scoreLabel.setText("得分:" + score);
          } else {
            life--;
            lifeLabel.setText("剩余生命值:" + life);
            if (life == 0) {
              JOptionPane.showMessageDialog(null, "游戏结束");
              timer.stop();
            }
          }
        }
      });
      holes[i] = hole;
      panel.add(hole);
    }
    add(panel, BorderLayout.CENTER);
    JPanel panel2 = new JPanel();
    scoreLabel = new JLabel("得分:" + score);
    panel2.add(scoreLabel);
    lifeLabel = new JLabel("剩余生命值:" + life);
    panel2.add(lifeLabel);
    add(panel2, BorderLayout.SOUTH);
    timer = new Timer(1000, this);
  }
  private void showMouse() {
    int index = random.nextInt(HOLE_TOTAL);
    JLabel hole = holes[index];
    if ("0".equals(hole.getName())) {
      hole.setIcon(new ImageIcon(getClass().getResource("mouse.png")));
      hole.setName("1");
    } else {
      showMouse();
    }
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    showMouse();
  }
  public static void main(String[] args) {
    HitMouse hitMouse = new HitMouse();
    hitMouse.setVisible(true);
    hitMouse.timer.start();
  }
}

通过本篇文章的小游戏例子,我们可以更好地理解Java编程语言的基础知识和代码实现,同时也可以通过自己编写的代码掌握如何用Java来进行游戏开发。

  
  

评论区

请求出错了