java swing实现的扫雷游戏及改进版完整示例

 更新时间:2017年12月13日 10:59:22   作者:Limbos  
这篇文章主要介绍了java swing实现的扫雷游戏及改进版,结合完整实例形式对比分析了java使用swing框架实现扫雷游戏功能与相关操作技巧,需要的朋友可以参考下

本文实例讲述了java swing实现的扫雷游戏及改进版。分享给大家供大家参考,具体如下:

版本1:

package awtDemo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
 * 这个是一个简单的扫雷例子,刚接触swing编写的,适合新手练习
 * 该程序使用setBounds(x,y,w,h)对控件布局
 * 做法参考win xp自带的扫雷,当然还写功能没做出来,
 * 另外做出来的功能有些还存在bug
 *
 * @author Ping_QC
 */
public class test extends JFrame implements ActionListener, Runnable,
    MouseListener {
  private static final long serialVersionUID = -2417758397965039613L;
  private final int EMPTY     = 0;
  private final int MINE     = 1;
  private final int CHECKED    = 2;
  private final int MINE_COUNT  = 10;  // 雷的个数
  private final int BUTTON_BORDER = 50;  // 每个点的尺寸
  private final int MINE_SIZE   = 10;  // 界面规格, 20x20
  private final int START_X    = 20;  // 起始位置x
  private final int START_Y    = 50;  // 起始位置y
  private boolean flag;
  private JButton[][] jb;
  private JLabel jl;
  private JLabel showTime;
  private int[][] map;
  /**
   * 检测某点周围是否有雷,周围点的坐标可由该数组计算得到
   */
  private int[][] mv = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 },
      { 1, -1 }, { 0, -1 }, { -1, -1 } };
  /**
   * 随机产生设定个数的雷
   */
  public void makeMine() {
    int i = 0, tx, ty;
    for (; i < MINE_COUNT;) {
      tx = (int) (Math.random() * MINE_SIZE);
      ty = (int) (Math.random() * MINE_SIZE);
      if (map[tx][ty] == EMPTY) {
        map[tx][ty] = MINE;
        i++; // 不记重复产生的雷
      }
    }
  }
  /**
   * 将button数组放到frame上,与map[][]数组对应
   */
  public void makeButton() {
    for (int i = 0; i < MINE_SIZE; i++) {
      for (int j = 0; j < MINE_SIZE; j++) {
        jb[i][j] = new JButton();
        // if (map[i][j] == MINE)
        // jb[i][j].setText(i+","+j);
        // listener add
        jb[i][j].addActionListener(this);
        jb[i][j].addMouseListener(this);
        jb[i][j].setName(i + "_" + j); // 方便点击是判断是点击了哪个按钮
        // Font font = new Font(Font.SERIF, Font.BOLD, 10);
        // jb[i][j].setFont(font);
        // jb[i][j].setText(i+","+j);
        jb[i][j].setBounds(j * BUTTON_BORDER + START_X, i
            * BUTTON_BORDER + START_Y, BUTTON_BORDER, BUTTON_BORDER);
        this.add(jb[i][j]);
      }
    }
  }
  public void init() {
    flag = false;
    jl.setText("欢迎测试,一共有" + MINE_COUNT + "个雷");
    jl.setVisible(true);
    jl.setBounds(20, 20, 500, 30);
    this.add(jl);
    showTime.setText("已用时:0 秒");
    showTime.setBounds(400, 20, 100, 30);
    this.add(showTime);
    makeMine();
    makeButton();
    this.setSize(550, 600);
    this.setLocation(700, 100);
    this.setResizable(false);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setVisible(true);
  }
  public test(String title) {
    super(title);
    this.setLayout(null);  //不使用布局管理器,每个控件的位置用setBounds设定
    jb = new JButton[MINE_SIZE][MINE_SIZE];
    jl = new JLabel();
    showTime = new JLabel();
    map = new int[MINE_SIZE][MINE_SIZE]; // 将按钮映射到数组中
  }
  public static void main(String[] args) {
    test test = new test("脚本之家 - 扫雷游戏测试1");
    test.init();
    test.run();
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    int x, y;
    if ((obj instanceof JButton) == false) {
      showMessage("错误", "内部错误");
      return;
    }
    String[] tmp_str = ((JButton) obj).getName().split("_");
    x = Integer.parseInt(tmp_str[0]);
    y = Integer.parseInt(tmp_str[1]);
    if (map[x][y] == MINE) {
      showMessage("死亡", "你踩到地雷啦~~~");
      flag = true;
      showMine();
      return;
    }
    dfs(x, y, 0);
    checkSuccess();
  }
  /**
   * 每次点击完后,判断有没有把全部雷都找到 通过计算状态为enable的按钮的个数来判断
   */
  private void checkSuccess() {
    int cnt = 0;
    for (int i = 0; i < MINE_SIZE; i++) {
      for (int j = 0; j < MINE_SIZE; j++) {
        if (jb[i][j].isEnabled()) {
          cnt++;
        }
      }
    }
    if (cnt == MINE_COUNT) {
      String tmp_str = showTime.getText();
      tmp_str = tmp_str.replaceAll("[^0-9]", "");
      showMessage("胜利", "本次扫雷共用时:" + tmp_str + "秒");
      flag = true;
      showMine();
    }
  }
  private int dfs(int x, int y, int d) {
    map[x][y] = CHECKED;
    int i, tx, ty, cnt = 0;
    for (i = 0; i < 8; i++) {
      tx = x + mv[i][0];
      ty = y + mv[i][1];
      if (tx >= 0 && tx < MINE_SIZE && ty >= 0 && ty < MINE_SIZE) {
        if (map[tx][ty] == MINE) {
          cnt++;// 该点附近雷数统计
        } else if (map[tx][ty] == EMPTY) {
          ;
        } else if (map[tx][ty] == CHECKED) {
          ;
        }
      }
    }
    if (cnt == 0) {
      for (i = 0; i < 8; i++) {
        tx = x + mv[i][0];
        ty = y + mv[i][1];
        if (tx >= 0 && tx < MINE_SIZE && ty >= 0 && ty < MINE_SIZE
            && map[tx][ty] != CHECKED) {
          dfs(tx, ty, d + 1);
        }
      }
    } else {
      jb[x][y].setText(cnt + "");
    }
    jb[x][y].setEnabled(false);
    return cnt;
  }
  /**
   * 在jl标签上显示一些信息
   *
   * @param title
   * @param info
   */
  private void showMessage(String title, String info) {
    jl.setText(info);
    System.out.println("in functino showMessage() : " + info);
  }
  public void run() {
    int t = 0;
    while (true) {
      if (flag) {
        break;
      }
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      t++;
      showTime.setText("已用时:" + t + " 秒");
    }
    // showMine();
  }
  private void showMine() {
//   Icon iconMine = new ImageIcon("e:/mine.jpg");
    for (int i = 0; i < MINE_SIZE; i++) {
      for (int j = 0; j < MINE_SIZE; j++) {
        if (map[i][j] == MINE) {
          jb[i][j].setText("#");
//         jb[i][j].setIcon(iconMine);
        }
      }
    }
  }
  @Override
  public void mouseClicked(MouseEvent e) {
    if (e.getButton() == 3) {
      Object obj = e.getSource();
      if ((obj instanceof JButton) == false) {
        showMessage("错误", "内部错误");
        return;
      }
      String[] tmp_str = ((JButton) obj).getName().split("_");
      int x = Integer.parseInt(tmp_str[0]);
      int y = Integer.parseInt(tmp_str[1]);
    if ("{1}".equals(jb[x][y].getText())) {
        jb[x][y].setText("");
      } else {
        jb[x][y].setText("{1}");
      }
  /*   if(jb[x][y].getIcon() == null){
        jb[x][y].setIcon(new ImageIcon("e:/flag.jpg"));
      }else{
        jb[x][y].setIcon(null);
      }*/
    }
  }
  @Override
  public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub
  }
  @Override
  public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub
  }
  @Override
  public void mouseEntered(MouseEvent e) {
    // TODO Auto-generated method stub
  }
  @Override
  public void mouseExited(MouseEvent e) {
    // TODO Auto-generated method stub
  }
}

运行效果:

版本2是对上面版本1程序的改进,在基础不变的基础上增加了右键标记功能以及自主选择难度功能。

package awtDemo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
@SuppressWarnings("serial")
public class saolei extends JFrame implements ActionListener, Runnable,
    MouseListener {
  private final int loEMPTY     = 0;
  private final int loMINE     = 1;
  private final int loCHECKED    = 2;
  private final int loMINE_COUNT  = 10;
  private final int loBUTTON_BORDER = 50;
  private final int loMINE_SIZE   = 10;
  private final int loSTART_X    = 20;
  private final int loSTART_Y    = 50;
  private boolean flag;
  private JButton[][] jb;
  private JLabel jl;
  private JLabel showTime;
  private int[][] map;
  private int[][] mv = { { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 },
      { 1, -1 }, { 0, -1 }, { -1, -1 } };
  public void makeloMINE() {
    int i = 0, tx, ty;
    for (; i < loMINE_COUNT;) {
      tx = (int) (Math.random() * loMINE_SIZE);
      ty = (int) (Math.random() * loMINE_SIZE);
      if (map[tx][ty] == loEMPTY) {
        map[tx][ty] = loMINE;
        i++;
      }
    }
  }
  public void makeButton() {
    for (int i = 0; i < loMINE_SIZE; i++) {
      for (int j = 0; j < loMINE_SIZE; j++) {
        jb[i][j] = new JButton();
        jb[i][j].addActionListener(this);
        jb[i][j].addMouseListener(this);
        jb[i][j].setName(i + "_" + j);
        jb[i][j].setBounds(j * loBUTTON_BORDER + loSTART_X, i
            * loBUTTON_BORDER + loSTART_Y, loBUTTON_BORDER, loBUTTON_BORDER);
        this.add(jb[i][j]);
      }
    }
  }
  public void init() {
    flag = false;
    jl.setText("欢迎测试,一共有" + loMINE_COUNT + "个雷");
    jl.setVisible(true);
    jl.setBounds(20, 20, 500, 30);
    this.add(jl);
    showTime.setText("已用时:0 秒");
    showTime.setBounds(400, 20, 100, 30);
    this.add(showTime);
    makeloMINE();
    makeButton();
    this.setSize(550, 600);
    this.setLocation(700, 100);
    this.setResizable(false);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setVisible(true);
  }
  public saolei(String title) {
    super(title);
    this.setLayout(null);  //不使用布局管理器,每个控件的位置用setBounds设定
    jb = new JButton[loMINE_SIZE][loMINE_SIZE];
    jl = new JLabel();
    showTime = new JLabel();
    map = new int[loMINE_SIZE][loMINE_SIZE]; // 将按钮映射到数组中
  }
  public static void main(String[] args) {
   saolei test = new saolei("脚本之家 - 扫雷游戏测试2");
    test.init();
    test.run();
  }
  @Override
  public void actionPerformed(ActionEvent e) {
    Object obj = e.getSource();
    int x, y;
    if ((obj instanceof JButton) == false) {
      showMessage("错误", "内部错误");
      return;
    }
    String[] tmp_str = ((JButton) obj).getName().split("_");
    x = Integer.parseInt(tmp_str[0]);
    y = Integer.parseInt(tmp_str[1]);
    if (map[x][y] == loMINE) {
      showMessage("死亡", "你踩到地雷啦~~~");
      flag = true;
      showloMINE();
      return;
    }
    dfs(x, y, 0);
    checkSuccess();
  }
  private void checkSuccess() {
    int cnt = 0;
    for (int i = 0; i < loMINE_SIZE; i++) {
      for (int j = 0; j < loMINE_SIZE; j++) {
        if (jb[i][j].isEnabled()) {
          cnt++;
        }
      }
    }
    if (cnt == loMINE_COUNT) {
      String tmp_str = showTime.getText();
      tmp_str = tmp_str.replaceAll("[^0-9]", "");
      showMessage("胜利", "本次扫雷共用时:" + tmp_str + "秒");
      flag = true;
      showloMINE();
    }
  }
  private int dfs(int x, int y, int d) {
    map[x][y] = loCHECKED;
    int i, tx, ty, cnt = 0;
    for (i = 0; i < 8; i++) {
      tx = x + mv[i][0];
      ty = y + mv[i][1];
      if (tx >= 0 && tx < loMINE_SIZE && ty >= 0 && ty < loMINE_SIZE) {
        if (map[tx][ty] == loMINE) {
          cnt++;
        } else if (map[tx][ty] == loEMPTY) {
          ;
        } else if (map[tx][ty] == loCHECKED) {
          ;
        }
      }
    }
    if (cnt == 0) {
      for (i = 0; i < 8; i++) {
        tx = x + mv[i][0];
        ty = y + mv[i][1];
        if (tx >= 0 && tx < loMINE_SIZE && ty >= 0 && ty < loMINE_SIZE
            && map[tx][ty] != loCHECKED) {
          dfs(tx, ty, d + 1);
        }
      }
    } else {
      jb[x][y].setText(cnt + "");
    }
    jb[x][y].setEnabled(false);
    return cnt;
  }
  private void showMessage(String title, String info) {
    jl.setText(info);
    System.out.println("in functino showMessage() : " + info);
  }
  public void run() {
    int t = 0;
    while (true) {
      if (flag) {
        break;
      }
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      t++;
      showTime.setText("已用时:" + t + " 秒");
    }
  }
  private void showloMINE() {
    for (int i = 0; i < loMINE_SIZE; i++) {
      for (int j = 0; j < loMINE_SIZE; j++) {
        if (map[i][j] == loMINE) {
          jb[i][j].setText("雷");
        }
      }
    }
  }
  public void mouseClicked(MouseEvent e) {
    if (e.getButton() == 3) {
      Object obj = e.getSource();
      if ((obj instanceof JButton) == false) {
        showMessage("错误", "内部错误");
        return;
      }
      String[] tmp_str = ((JButton) obj).getName().split("_");
      int x = Integer.parseInt(tmp_str[0]);
      int y = Integer.parseInt(tmp_str[1]);
    if ("{1}quot".equals(jb[x][y].getText())) {
        jb[x][y].setText("");
      } else {
        jb[x][y].setText("{1}quot");
      }
    }
  }
  public void mousePressed(MouseEvent e) {
  }
  @Override
  public void mouseReleased(MouseEvent e) {
  }
  public void mouseEntered(MouseEvent e) {
  }
  @Override
  public void mouseExited(MouseEvent e) {
  }
}

运行效果:

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。

相关文章

  • 解决Idea运行junit测试时报Error:[3,17] 程序包org.junit不存在的问题

    解决Idea运行junit测试时报Error:[3,17] 程序包org.junit不存在的问题

    这篇文章主要介绍了Idea运行junit测试时报Error:[3,17] 程序包org.junit不存在解决方法,本文给大家分享两种解决办法,需要的朋友可以参考下
    2023-03-03
  • Mybatis学习总结之mybatis使用建议

    Mybatis学习总结之mybatis使用建议

    这篇文章主要介绍了Mybatis学习总结之mybatis使用建议的相关资料,非常具有参考借鉴价值,需要的朋友可以参考下
    2016-05-05
  • Java基础教程之String深度分析

    Java基础教程之String深度分析

    这篇文章主要给大家介绍了关于Java基础教程之String的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2019-06-06
  • SpringBoot--- SpringSecurity进行注销权限控制的配置方法

    SpringBoot--- SpringSecurity进行注销权限控制的配置方法

    这篇文章主要介绍了SpringBoot--- SpringSecurity进行注销,权限控制,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • fastjson 使用方法详细介绍

    fastjson 使用方法详细介绍

    Fastjson是一个Java语言编写的JSON处理器,由阿里巴巴公司开发。接下来通过本文给大家分享fastjson 使用方法详细介绍,感兴趣的朋友一起看看吧
    2017-11-11
  • nacos配置中心持久化相关配置方式

    nacos配置中心持久化相关配置方式

    这篇文章主要介绍了nacos配置中心持久化相关配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • SpringMVC实现自定义类型转换器

    SpringMVC实现自定义类型转换器

    本篇文章主要介绍了SpringMVC实现自定义类型转换器 ,详细的介绍了自定义类型转换器的用法和好处,有兴趣的可以了解一下。
    2017-04-04
  • Java使用Iterator迭代器遍历集合数据的方法小结

    Java使用Iterator迭代器遍历集合数据的方法小结

    这篇文章主要介绍了Java使用Iterator迭代器遍历集合数据的方法,结合实例形式分析了java迭代器进行集合数据遍历的常见操作技巧,需要的朋友可以参考下
    2019-11-11
  • java数据结构-堆实现优先队列

    java数据结构-堆实现优先队列

    通常都把队列比喻成排队买东西,大家都很守秩序,先排队的人就先买东西。但是优先队列有所不同,它不遵循先进先出的规则,而是根据队列中元素的优先权,优先权最大的先被取出,这篇文章主要介绍了java数据结构-堆实现优先队列,感兴趣的朋友一起看看吧
    2021-08-08
  • 如何获取 Spring heapdump中的明文密码

    如何获取 Spring heapdump中的明文密码

    Actuator是Spring Boot提供的应用系统监控的开源框架,在攻防场景里经常会遇到Actuator配置不当的情况,攻击者可以直接下载heapdump堆转储文件,本文介绍如何获取 Spring heapdump中的密码明文,需要的朋友可以参考下
    2022-07-07

最新评论