21xrx.com
2024-09-20 01:09:59 Friday
登录
文章检索 我的文章 写文章
《Java经典游戏》教你制作扫雷小游戏
2023-06-16 15:25:24 深夜i     --     --
Java语言 扫雷小游戏 游戏制作

扫雷是一款经典的小游戏,在电脑上也有相应的版本。今天,我们来学习如何用Java语言制作一个属于自己的扫雷游戏吧!

首先,我们需要知道扫雷游戏的规则:在一个方格棋盘上,有长度和宽度确定的格子,里面隐藏着雷或者数字(代表周围的地雷数量)。玩家需要根据数字来猜测哪些方格里面有地雷,哪些是安全的。如果玩家猜错了地雷位置,游戏就会结束。如果玩家成功猜出所有的地雷位置,则游戏获胜。

接下来就是Java代码时间啦!我们可以用swing包来制作一个界面,包括开始游戏、查看排行榜和结束游戏等功能。我们还需要定义雷区类和游戏区类,其中雷区类要生成并记录雷的位置,游戏区类要实现鼠标点击事件。

下面是雷区类的代码:


import java.util.Random;

public class MineField {

  private int[][] mines;

  public MineField(int row, int col, int mineCount) {

    mines = new int[row][col];

    Random rand = new Random();

    int count = 0;

    while (count < mineCount) {

      int i = rand.nextInt(row);

      int j = rand.nextInt(col);

      if (mines[i][j] == 0) {

        mines[i][j] = -1;

        count++;

      }

    }

  }

  

  public int[][] getMines()

    return mines;

  

}

这个类包括了生成地雷位置的方法。我们用一个二维数组来保存地雷的位置,其中-1表示该位置有地雷。在构造方法中,我们会不停地随机生成一个位置,直到生成了足够数量的地雷。

下面是游戏区类的代码:


import javax.swing.*;

import java.awt.*;

import java.awt.event.MouseAdapter;

import java.awt.event.MouseEvent;

public class GameArea extends JPanel {

  private int[][] mines;

  private int[][] board;

  private int rows, cols, minesCount;

  public GameArea(int rows, int cols, int minesCount) {

    this.rows = rows;

    this.cols = cols;

    this.minesCount = minesCount;

    setPreferredSize(new Dimension(rows * 20, cols * 20));

    setVisible(true);

    initGame();

    addMouseListener(new MouseAdapter() {

      @Override

      public void mouseClicked(MouseEvent e) {

        int row = e.getY() / 20;

        int col = e.getX() / 20;

        if (SwingUtilities.isRightMouseButton(e)) {

          if (board[row][col] == 9) {

            board[row][col] = 11;

          } else if (board[row][col] == 11) {

            board[row][col] = 9;

          }

        } else {

          if (mines[row][col] == -1) {

            JOptionPane.showMessageDialog(null,"GameOver");

            initGame();

          } else if (board[row][col] == 9) {

            board[row][col] = mines[row][col] + 1;

            if (board[row][col] == 10) {

              if (checkWin()) {

                JOptionPane.showMessageDialog(null,"You Win!");

                initGame();

              }

            }

            repaint();

          }

        }

      }

    });

  }

  private boolean checkWin() {

    int count = 0;

    for (int i = 0; i < rows; i++) {

      for (int j = 0; j < cols; j++) {

        if (board[i][j] == 10) {

          count++;

        }

      }

    }

    return count == minesCount;

  }

  private void initGame() {

    MineField mineField = new MineField(rows, cols, minesCount);

    mines = mineField.getMines();

    board = new int[rows][cols];

    for (int i = 0; i < rows; i++) {

      for (int j = 0; j < cols; j++) {

        board[i][j] = 9;

      }

    }

    repaint();

  }

  @Override

  protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    for (int i = 0; i < rows; i++) {

      for (int j = 0; j < cols; j++) {

        if (board[i][j] == 9 || board[i][j] == 11) {

          g.setColor(Color.gray);

          g.fillRect(i * 20, j * 20, 20, 20);

        } else if (board[i][j] == 10) {

          g.setColor(Color.green);

          g.fillRect(i * 20, j * 20, 20, 20);

        } else {

          g.setColor(Color.white);

          g.fillRect(i * 20, j * 20, 20, 20);

          g.setColor(Color.black);

          if (mines[i][j] != 0) {

            g.drawString("" + (mines[i][j]), i * 20 + 5, j * 20 + 15);

          }

        }

      }

    }

  }

}

这个类包括了鼠标点击事件和游戏初始化的方法。我们用一个二维数组来记录游戏区每个位置的状态,初始状态为9,表示未翻开。右键点击表示标记有地雷的位置,左键点击会翻开该位置,如果该位置有地雷,则游戏结束,否则会显示周围地雷的数量。如果所有地雷位置都被标记,游戏获胜。

最后,我们只需要将两个类组装起来就可以了:


import javax.swing.*;

import java.awt.*;

public class MineSweeper extends JFrame {

  public MineSweeper() {

    setTitle("MineSweeper");

    setSize(300, 300);

    setLocationRelativeTo(null);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(new BorderLayout());

    JPanel buttonPanel = new JPanel();

    JButton start = new JButton("Start");

    start.addActionListener(e -> showGame());

    buttonPanel.add(start);

    add(buttonPanel, BorderLayout.NORTH);

    setVisible(true);

  }

  private void showGame() {

    JFrame gameFrame = new JFrame();

    gameFrame.setTitle("MineSweeper");

    gameFrame.setSize(400,400);

    gameFrame.setLocationRelativeTo(null);

    gameFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    GameArea gameArea = new GameArea(10,10,10);

    gameFrame.setContentPane(gameArea);

    gameFrame.setVisible(true);

  }

  public static void main(String[] args) {

    new MineSweeper();

  }

}

这个类包括了主界面和开始按钮的功能,点击开始按钮会弹出游戏界面并开始游戏。

好了,代码已经介绍完毕。现在您可以试试自己动手编写一个Java版扫雷游戏了!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章