Java扫雷游戏源代码
扫雷游戏部分代码
//设置状态#define freed 0 //初始状态#define click 1 //点击状态#define market 2 //标记为雷状态#define choose 3 //键盘选在状态#define nochoose 4 //为选在状态//设置地雷struct Mine{int x;int y;int status;//0为初始状态,1为被点击状态,2为标记为雷状态int value;//0为空,10为地雷,1-8为数字int ischoose;//是否被键盘选中int tag; //标记位};//一维数组存储地雷区域Mine mine[256];//初始化地雷区域void initpt(){i nt i=0;n owmine=0;f or(int y=0;y<16;y++)for(int x=0;x<16;x++){mine[i].x=x*2+dx+2;mine[i].y=y+dy+1;if(i==0)mine[i].ischoose=choose;//初始化为键盘所在位置elsemine[i].ischoose=nochoose;mine[i].status=freed;mine[i].value=0;mine[i].tag=0;i++;}}//设置地雷个数void setmine(int n){i nt num=0;s rand(time(NULL));w hile(num<n){int n=rand()%256;if(mine[n].value!=MINE_TAG) //如果没有重复的地雷{mine[n].value=MINE_TAG;num++;}}}//查询每个方块周围有几个地雷并标记为数字void setvalue(){f or(int i=0;i<256;i++){if(mine[i].value!=MINE_TAG){if((i+1)%16==0){if((i-16-1)>=0)if(mine[i-16-1].value==MINE_TAG)mine[i].value++;if((i-16)>=0)if(mine[i-16].value==MINE_TAG)mine[i].value++;if((i-1)>=0) //4if(mine[i-1].value==MINE_TAG)mine[i].value++;if((i+16-1)<=255) //6if(mine[i+16-1].value==MINE_TAG)mine[i].value++;if((i+16)<=255) //7if(mine[i+16].value==MINE_TAG)mine[i].value++;}else if(i%16==0){····}int movekey(){HANDLE handle;char buf[1];handle = initiate();WORD wColors[1];wColors[0]=FOREGROUND_RED| FOREGROUND_GREEN|FOREGROUND_INTENSITY; WORD wColors1[1];wColors1[0]=FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY; //设置颜色WORD wColors2[1]={FOREGROUND_RED|FOREGROUND_INTENSITY};while(1){if(_kbhit()){int key=_getch();int k;switch(key){case right:mine[nowmine].ischoose=nochoose;nowmine++;mine[nowmine].ischoose=choose;break;case left:mine[nowmine].ischoose=nochoose;nowmine--;mine[nowmine].ischoose=choose;break;…case space:if(mine[nowmine].status==market)mine[nowmine].status=freed;elsemine[nowmine].status=market;break;case enter:mine[nowmine].status=click;if(mine[nowmine].value==MINE_TAG){showmine();textout(handle,mine[nowmine].x,mine[nowmine].y,wColors2,1,"¤");textout(handle,dx+10,dy+6,wColors1,1,"你被炸得粉身碎骨!");textout(handle,dx+40,dy,wColors1,1,"重新开始按空格键!");textout(handle,dx+40,dy+1,wColors1,1,"退出按ESC键!");while(1){k=_getch();switch(k){case esc:return 0;break;case space:textout(handle,dx+10,dy+7,wColors1,1," ");return 1;break;}}}if(mine[nowmine].value==0)findnull(nowmine);break;}showtable();}}}//寻找空的小方块void findnull(int i){mine[i].tag=1;if(i%16==0) //如果在左边界,判断上,右,下三个方向有没有雷{if((i-16)>=0)//如果没有出界{if(mine[i-16].tag==0)//如果还没有判断,就判断有没有雷{if(mine[i-16].value==0){mine[i-16].status=click;findnull(i-16);}else if(mine[i-16].value!=MINE_TAG ){mine[i-16].status=click;mine[i-16].tag=1;//标记为已经被判断}}}if(mine[i+1].tag==0){if(mine[i+1].value==0){mine[i+1].status=click;findnull(i+1);}else if(mine[i+1].value!=MINE_TAG){mine[i+1].status=click;mine[i+1].tag=1;}}if((i+16)<=255){if(mine[i+16].tag==0){if(mine[i+16].value==0){mine[i+16].status=click;findnull(i+16);}else if(mine[i+16].value!=MINE_TAG){mine[i+16].status=click;mine[i+16].tag=1;}}}}else if((i+1)%16==0) //如果在右边界,判断左,上,下有没有雷{····}}。
(完整word版)JAVA课程设计--扫雷游戏
合肥学院计算机科学与技术系课程设计报告2009~2010学年第二学期课程Java语言与应用课程设计名称扫雷游戏学生姓名胡远远学号0604031005专业班级07网络工程一班指导教师许强张贯虹2010年09月1.设计内容及要求1.1 扫雷游戏的基本要求Windows 2000/XP系统提供的扫雷游戏是一个很有趣的游戏。
本章的课程设计使用Java语言编写一个与其类似的扫雷游戏。
具体要求如下:(1)选择级别后将出现相应级别的扫雷区域,这是用户使用鼠标左键单击雷区中任何一个方块便启动计时器。
(2)用户要揭开某个方块,可单击它。
若所揭方块下有雷,用户便输了这一局,若所揭方块下五雷,则显示一个数字,该数字代表方块的周围的8个方块中共有多少颗雷。
(3) 如果用户认为某个方块下埋着雷,单击右键可以在方块上标识一个用户认为是雷的图标,即给出一个扫雷标记。
用户每标记出一个扫雷标记(无论用户的标记是否正确),程序将显示的剩余雷数减少一个。
(4)扫雷胜利后,显示游戏胜利。
(5) 用户可以右击空格,可以选择标记为“旗帜”、“问号”或者返回成空格。
1.2 需实现的主要功能(1)用户点击笑脸实现复位操作。
调用repaint()和validate()函数对界面进行重置以及刷新操作(2)可以显示用户完全扫雷成功所花时间。
文本框TF记录扫雷成功所花的时间(3)在失败和胜利后跳出失败或胜利的文本框JoptionPane 该类用来调出对话框并提示胜利2.需求分析2.1 扫雷棋盘的布局设计系统的整体布局为:CardLayout布局, 采用了文本框、按钮、面板、框架…等组件,菜单主要有run按钮笑脸和哭脸,按钮的功能是重新开始新的游戏。
2.2 雷区的设计MineArea类是javax.swing包中Jpanel容器的子类,实现了ActionListener 和MouseListener接口,所创建的对象:mineArea是MineGame类中最重要的成员之一,作为一个容器添加到MineGame窗口的中心。
扫雷游戏代码
}
/*计算方块周围雷数 */
public void CountRoundBomb()
{
for (int i = 0; i < (int)Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int)Math.sqrt(BlockNum); j++) {
}
/*重新开始*/
public void replay()
{
nowBomb.setText("当前雷数"+" "+BombNum+"");
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)
for(int j = 0 ; j < (int)Math.sqrt(BlockNum) ; j++)
bombButton=new Bomb[ (int)Math.sqrt(BlockNum) ][];
for(int i = 0 ; i < (int)Math.sqrt(BlockNum) ; i++)
{
bombButton[ i ]=new Bomb[ (int)Math.sqrt(BlockNum) ];
int y =(int)(Math.random()*(int)(Math.sqrt(BlockNum)-1));
if(bombButton[ x ][ y ].isBomb==true)
i--;
else
bombButton[ x ][ y ].isBomb=true ;
扫雷项目源代码详解
主函数所在处package saolei.frame;import java.awt.BorderLayout;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JPanel;import saolei.tools.Tools;import saolei.menubar.Mymenubar;import saolei.panel.MybompPanel;import saolei.panel.MyfacePanel;public class MymineFrame extends JFrame{private Mymenubar mymenubar;//菜单栏private MyfacePanel myfacePanel;//笑脸lableprivate MybompPanel mybompPanel;//雷面板private JPanel jPanel;//主面板用来装笑脸面板和雷面板public Mymenubar getMymenubar() {return mymenubar;}public void setMymenubar(Mymenubar mymenubar) { this.mymenubar = mymenubar;}public MyfacePanel getMyfacePanel() {return myfacePanel;}public void setMyfacePanel(MyfacePanel myfacePanel) { this.myfacePanel = myfacePanel;}public MybompPanel getMybompPanel() {return mybompPanel;}public void setMybompPanel(MybompPanel mybompPanel) { this.mybompPanel = mybompPanel;}public MymineFrame(String s){super(s);init();this.add(jPanel);//将主面板装到这个Framethis.pack();//自动设置大小this.setVisible(true);//设置Frame可见}private void init() {mymenubar=new Mymenubar(this);myfacePanel=new MyfacePanel();mybompPanel=new MybompPanel(this);jPanel=new JPanel();jPanel.setLayout(new BorderLayout());//将主面板设置为边框布局Tools.faceLabel.addMouseListener(new MouseAdapter() {//对笑脸添加监听public void mousePressed(MouseEvent e) {Tools.faceLabel.setIcon(Tools.faceIcon[1]);//未释放时笑脸凹下去}public void mouseReleased(MouseEvent e) {Tools.faceLabel.setIcon(Tools.faceIcon[0]);//释放时重新开局rePlay();}});this.setIconImage(newImageIcon("./images/icon.gif").getImage());//设置扫雷图标this.setLocationRelativeTo(null);//设置窗口相对于指定组件的位置,因为参数为nul,所以此窗口将置于屏幕的中央this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置在关闭时退出this.setResizable(false);//设置不可变大小this.setJMenuBar(mymenubar);//放入菜单jPanel.add(myfacePanel,BorderLayout.NORTH);//放笑脸jPanel.add(mybompPanel,BorderLayout.CENTER);//放雷区}public void rePlay()//重新开局函数{Tools.timer.stop();//时间开始,因为只能有一个计时器所以将它写在静态区Tools.myTimerTask.time = 0;//设置开始时间为0Tools.timeLabelB.setIcon(Tools.numberIcon[0]);Tools.timeLabelS.setIcon(Tools.numberIcon[0]);Tools.timeLabelG.setIcon(Tools.numberIcon[0]);this.remove(jPanel);//移除主面板然后重新new一个jPanel = new JPanel();mymenubar = new Mymenubar(this);//重新定义里面元素myfacePanel = new MyfacePanel();Tools.setMineCount(Tools.mineCount);Tools.faceLabel.setIcon(Tools.faceIcon[0]);mybompPanel = new MybompPanel(this);jPanel.setLayout(new BorderLayout());jPanel.add(myfacePanel, BorderLayout.NORTH);jPanel.add(mybompPanel, BorderLayout.CENTER);//重新装载组件this.add(jPanel);this.pack();this.validate();//确保组件具有有效的布局}public static void main(String[] args) {MymineFrame mymineFrame=new MymineFrame("扫雷");//主函数 ,函数入口}}雷面板package saolei.panel;import java.awt.Color;import java.awt.GridLayout;import javax.swing.BorderFactory;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.border.BevelBorder;import javax.swing.border.Border;import saolei.frame.MymineFrame;import ble.MymineLable;import saolei.listener.MyListener;import saolei.tools.Tools;public class MybompPanel extends JPanel{public MymineFrame mymineFrame;private int leftClick;public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) {this.leftClick = leftClick;}private MymineLable[][]mymineLables;public MymineLable[][] getMymineLables() {return mymineLables;}public void setMymineLables(MymineLable[][] mymineLables) { this.mymineLables = mymineLables;}public MybompPanel(MymineFrame m){this.mymineFrame=m;init();}private void init() {this.setBackground(Color.LIGHT_GRAY);Border border1 = BorderFactory.createEmptyBorder(5, 5, 5, 5);Border border2 =BorderFactory.createBevelBorder(BevelBorder.LOWERED);this.setBorder(BorderFactory.createCompoundBorder(border1, border2));MyListener myListener=new MyListener(this);this.setLayout(new GridLayout(Tools.rowCount,Tools.colCount));mymineLables= new MymineLable[Tools.rowCount][Tools.colCount];for (int i = 0; i < Tools.rowCount; i++) {for (int j = 0; j < Tools.colCount; j++) {mymineLables[i][j] = new MymineLable(i, j);mymineLables[i][j].addMouseListener(myListener);this.add(mymineLables[i][j]);}}}public void setMine(int rowx,int coly){for(int i=0;i<Tools.mineCount;i++){int x=(int)(Math.random()*Tools.rowCount);int y=(int)(Math.random()*Tools.colCount);if(x==rowx&&y==coly){i--;}if(mymineLables[x][y].isIsmine()){i--;}else{mymineLables[x][y].setIsmine(true);mymineLables[x][y].setIcon(Tools.blank);}}for (int i = 0; i < Tools.rowCount; i++) {//算雷for (int j = 0; j < Tools.colCount; j++) {int count = 0;if (mymineLables[i][j].isIsmine() == false) {for (int x =i - 1; x <= i + 1; x++) {for (int y =j - 1; y <= j + 1; y++) {if (x>=0 && x<Tools.rowCount && y>=0 && y<Tools.colCount) {if (mymineLables[x][y].isIsmine()) {count++;}}}}}mymineLables[i][j].setCount(count);}}}笑脸面板package saolei.panel;import java.awt.BorderLayout;import java.awt.Color;import java.awt.Image;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.ImageIcon;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.BevelBorder;import javax.swing.border.Border;import saolei.tools.Tools;public class MyfacePanel extends JPanel{ private Box box;public MyfacePanel(){init();}public void init() {this.setLayout(new BorderLayout());box = Box.createHorizontalBox();box.add(Box.createHorizontalStrut(5));box.add(Tools.mineLabelB);box.add(Tools.mineLabelS);box.add(Tools.mineLabelG);box.add(Box.createHorizontalGlue());box.add(Tools.faceLabel);box.add(Box.createHorizontalGlue());box.add(Tools.timeLabelB);box.add(Tools.timeLabelS);box.add(Tools.timeLabelG);box.add(Box.createHorizontalStrut(5));this.add(box);this.setBackground(Color.LIGHT_GRAY);Border border1 = BorderFactory.createEmptyBorder(5,5,5,5);Border border2 =BorderFactory.createBevelBorder(BevelBorder.LOWERED);this.setBorder(BorderFactory.createCompoundBorder(border1,border2 ));}}关于扫雷对话框package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.BoxLayout;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.border.Border;import saolei.frame.MymineFrame;public class AboutSweeping extends JDialog {/****/private static final long serialVersionUID = 1L;private JLabel labelIcon;private JLabel labelOne;private JLabel labelTwo;private JLabel labelThree;private JLabel labelFour;private JLabel labelFive;private Box boxOne;private Box boxTwo;private Box boxThree;private Box boxFour;private Box boxFive;private JPanel panelT;AboutSweeping sweep = null;public AboutSweeping() {}public AboutSweeping(MymineFrame mainFrame) {super(mainFrame);sweep = this;this.setTitle("关于扫雷");init();this.setSize(new Dimension(300, 200));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);//this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {JPanel panel = new JPanel();labelIcon = new JLabel(new ImageIcon("./images/icon.gif"));labelOne = new JLabel("Java 扫雷智慧的挑战!");boxOne = Box.createHorizontalBox();boxOne.add(labelIcon);boxOne.add(Box.createHorizontalStrut(20));boxOne.add(labelOne);labelTwo = new JLabel("主要运用技术:swing和对象型数组");boxTwo = Box.createHorizontalBox();boxTwo.add(labelTwo);labelThree = new JLabel("主要知识:抽象类,继承,接口");boxThree = Box.createHorizontalBox();boxThree.add(labelThree);labelFour = new JLabel("版权所有:阿kiang");boxFour = Box.createHorizontalBox();boxFour.add(labelFour);labelFive = new JLabel("制作时间:2011.08.16");boxFive = Box.createHorizontalBox();boxFive.add(labelFive);panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));panel.add(boxOne);panel.add(boxTwo);panel.add(boxThree);panel.add(boxFour);panel.add(boxFive);JButton button = new JButton("确定");button.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {sweep.dispose();}});JPanel pl = new JPanel(new FlowLayout(FlowLayout.RIGHT));pl.add(button);panel.add(pl);Border border = BorderFactory.createEtchedBorder();panel.setBorder(border);panelT = new JPanel(new BorderLayout());Border b = BorderFactory.createEmptyBorder(10, 10, 10, 10);panelT.add(panel);panelT.setBorder(b);this.add(panel);}}扫雷英雄版package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import java.util.SortedSet;import java.util.TreeSet;import javax.swing.JDialog;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.table.DefaultTableModel;import saolei.frame.MymineFrame;import ble.HeroBean;import saolei.tools.Tools;public class HeroDialog extends JDialog {/****/private static final long serialVersionUID = 1L;private JPanel panel = null;private JTextArea area;private SortedSet<HeroBean> heroSet;DefaultTableModel dataModel;private int level = 0;public HeroDialog(int level, MymineFrame mainFrame) { /*** 设置拥有者*/super(mainFrame);this.level = level;init();this.setSize(new Dimension(220, 150));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {heroSet = new TreeSet();area = new JTextArea();if (level == 1) {heroSet = Tools.setB;this.setTitle("初级英雄榜");} else if (level == 2) {heroSet = Tools.setI;this.setTitle("中级英雄榜");} else if (level == 3) {heroSet = Tools.setE;this.setTitle("高级英雄榜");}for (HeroBean bean : heroSet) {area.append(bean.toString() + "\n");}area.setEditable(false);JScrollPane jsp = new JScrollPane(area);panel = new JPanel(new BorderLayout());panel.add(jsp,BorderLayout.CENTER);this.add(panel);}}扫雷英雄版积分版package saolei.dialog;import java.awt.Dimension;import javax.swing.BorderFactory;import javax.swing.Box;import javax.swing.BoxLayout;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.border.Border;import saolei.frame.MymineFrame;import saolei.listener.HeroInputListener;import saolei.tools.Tools;public class HeroInputDialog extends JDialog{/****/private static final long serialVersionUID = 1L;private JTextField jtfN;private JLabel jlL;private JButton buttonY;private JButton buttonN;private JPanel panel;private Box box1;private Box box2;private Box box3;private HeroInputListener listen;public HeroInputDialog(MymineFrame mainFrame) {/**固定拥有者*/super(mainFrame);listen = new HeroInputListener(this);init();this.setTitle("请输入英雄大名");this.setSize(new Dimension(200, 150));this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);this.setLocationRelativeTo(mainFrame);this.setResizable(false);this.setModal(true);this.setVisible(true);}private void init() {jlL = new JLabel();if(Tools.mineCount==10){jlL.setText("完成初级扫雷,请留下大名!");}if(Tools.mineCount==40){jlL.setText("完成中级扫雷,请留下大名!");}if(Tools.mineCount==99){jlL.setText("完成高级扫雷,请留下大名!");}panel = new JPanel();panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));jtfN = new JTextField("匿名");jtfN.setPreferredSize(new Dimension(20,10));buttonY = new JButton("确定");buttonY.addActionListener(listen);buttonN = new JButton("取消");buttonN.addActionListener(listen);box1 = Box.createHorizontalBox();box1.add(jlL);box2 = Box.createHorizontalBox();box2.add(Box.createHorizontalStrut(30));box2.add(jtfN);box2.add(Box.createHorizontalStrut(30));box3 = Box.createHorizontalBox();box3.add(buttonY);box3.add(Box.createHorizontalStrut(10));box3.add(buttonN);panel.add(box1);panel.add(Box.createVerticalStrut(13));panel.add(box2);panel.add(Box.createVerticalStrut(13));panel.add(box3);Border border = BorderFactory.createEmptyBorder(15, 5, 10, 5);panel.setBorder(border);this.add(panel);}public JButton getButtonN() {return buttonN;}public JButton getButtonY() {return buttonY;}public JTextField getJtfN() {return jtfN;}}扫雷英雄版自定义对话框package saolei.dialog;import java.awt.BorderLayout;import java.awt.Dimension;import javax.swing.Box;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;import saolei.frame.MymineFrame;import saolei.listener.SelfMineListener;import saolei.tools.Tools;public class Selfdefinedia extends JDialog{ private JPanel mianJPanel;private JPanel jPaneln;private JPanel jPanelc;private JPanel jPanels;private JLabel lx;private JLabel ly;private JLabel ll;private JTextField tx;private JTextField ty;private JTextField tl;private JButton sureButton;private JButton exitButton;public JPanel getMianJPanel() {return mianJPanel;}public void setMianJPanel(JPanel mianJPanel) {this.mianJPanel = mianJPanel;}public JPanel getjPaneln() {return jPaneln;}public void setjPaneln(JPanel jPaneln) { this.jPaneln = jPaneln;}public JPanel getjPanelc() {return jPanelc;}public void setjPanelc(JPanel jPanelc) { this.jPanelc = jPanelc;}public JPanel getjPanels() {return jPanels;}public void setjPanels(JPanel jPanels) { this.jPanels = jPanels;}public JLabel getLx() {return lx;}public void setLx(JLabel lx) {this.lx = lx;}public JLabel getLy() {return ly;}public void setLy(JLabel ly) {this.ly = ly;}public JLabel getLl() {return ll;}public void setLl(JLabel ll) {this.ll = ll;}public JTextField getTx() {return tx;}public void setTx(JTextField tx) { this.tx = tx;}public JTextField getTy() {return ty;}public void setTy(JTextField ty) {this.ty = ty;}public JTextField getTl() {return tl;}public void setTl(JTextField tl) {this.tl = tl;}public JButton getSureButton() {return sureButton;}public void setSureButton(JButton sureButton) { this.sureButton = sureButton;}public JButton getExitButton() {return exitButton;}public void setExitButton(JButton exitButton) { this.exitButton = exitButton;}public MymineFrame mymineFrame;public Selfdefinedia(MymineFrame mymineFrame){super(mymineFrame,"自定义扫雷",true);init();this.mymineFrame=mymineFrame;this.setLocationRelativeTo(mymineFrame);this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);this.setResizable(false);this.pack();this.setVisible(true);}private void init() {lx = new JLabel("行数:");ly = new JLabel("列数:");ll = new JLabel("雷数:");tx = new JTextField(Tools.rowCount+"");tx.setPreferredSize(new Dimension(40,20));ty = new JTextField(Tools.colCount+"");ty.setPreferredSize(new Dimension(40,20));tl = new JTextField(Tools.mineCount+"");tl.setPreferredSize(new Dimension(40,20));sureButton = new JButton("确定");sureButton.addActionListener(new SelfMineListener(this));exitButton = new JButton("取消");exitButton.addActionListener(new SelfMineListener(this));jPaneln = new JPanel();jPaneln.add(lx);jPaneln.add(tx);jPaneln.add(sureButton);jPanelc = new JPanel();jPanelc.add(ly);jPanelc.add(ty);jPanelc.add(Box.createHorizontalStrut(57));jPanels = new JPanel();jPanels.add(ll);jPanels.add(tl);jPanels.add(exitButton);mianJPanel = new JPanel();mianJPanel.setLayout(new BorderLayout());mianJPanel.add(jPaneln,BorderLayout.NORTH);mianJPanel.add(jPanelc,BorderLayout.CENTER);mianJPanel.add(jPanels,BorderLayout.SOUTH);this.add(mianJPanel);}}package ble;public class HeroBean implements Comparable{private String name = null;private String level = null;private int time = 0;public String getLevel() {return level;}public void setLevel(String level) {this.level = level;}public String getName() {return name;}public void setName(String name) { = name;}public int getTime() {return time;}public void setTime(int time) {this.time = time;}public int compareTo(Object o) {int i = -1;if(o instanceof HeroBean){HeroBean bean = (HeroBean)o;i = this.time-bean.time;if(i==0){i = .hashCode().hashCode();if(i==0){i=-1;}}}return i;}@Overridepublic String toString() {return + ":\t\t" + this.time+"秒";}}package ble;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MymineLable extends JLabel{ private int rowx;private int coly;private boolean ismine;private boolean isexpand;private int count;private int rightClick;private int leftClick;private boolean isFlag;private boolean isError;public boolean isError() {return isError;}public void setError(boolean isError) { this.isError = isError;}public boolean isFlag() {return isFlag;}public void setFlag(boolean isFlag) { this.isFlag = isFlag;}public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) { this.leftClick = leftClick;}public int getRowx() {return rowx;}public void setRowx(int rowx) {this.rowx = rowx;}public int getColy() {return coly;}public void setColy(int coly) {this.coly = coly;}public boolean isIsmine() {return ismine;}public void setIsmine(boolean ismine) { this.ismine = ismine;}public boolean isIsexpand() {return isexpand;}public void setIsexpand(boolean isexpand) { this.isexpand = isexpand;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public int getRightClick() {return rightClick;}public void setRightClick(int rightClick) { this.rightClick = rightClick;}public MymineLable(int rowx,int coly) {this.rowx = rowx;this.coly = coly;this.setIcon(Tools.blank);}public void openMine(MybompPanel panel){if(this.getCount()==0){for(int i=this.getRowx()-1;i<=this.getRowx()+1;i++){for(int j=this.getColy()-1;j<=this.getColy()+1;j++){if(i>=0&&i<9&&j>=0&&j<9&&!(panel.getMymineLables()[i][j].equals(t his))){panel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[panel. getMymineLables()[i][j].getCount()]);panel.getMymineLables()[i][j].setIsexpand(true);panel.getMymineLables()[i][j].openMine(panel);}}}}}}雷块package ble;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MymineLable extends JLabel{private int rowx;private int coly;private boolean ismine;private boolean isexpand;private int count;private int rightClick;private int leftClick;private boolean isFlag;private boolean isError;public boolean isError() {return isError;}public void setError(boolean isError) { this.isError = isError;}public boolean isFlag() {return isFlag;}public void setFlag(boolean isFlag) { this.isFlag = isFlag;}public int getLeftClick() {return leftClick;}public void setLeftClick(int leftClick) { this.leftClick = leftClick;}public int getRowx() {return rowx;}public void setRowx(int rowx) {this.rowx = rowx;}public int getColy() {return coly;}public void setColy(int coly) {this.coly = coly;}public boolean isIsmine() {return ismine;}public void setIsmine(boolean ismine) { this.ismine = ismine;}public boolean isIsexpand() {return isexpand;}public void setIsexpand(boolean isexpand) { this.isexpand = isexpand;}public int getCount() {return count;}public void setCount(int count) {this.count = count;}public int getRightClick() {return rightClick;}public void setRightClick(int rightClick) { this.rightClick = rightClick;}public MymineLable(int rowx,int coly) { this.rowx = rowx;this.coly = coly;this.setIcon(Tools.blank);}public void openMine(MybompPanel panel){if(this.getCount()==0){for(int i=this.getRowx()-1;i<=this.getRowx()+1;i++){for(int j=this.getColy()-1;j<=this.getColy()+1;j++){if(i>=0&&i<9&&j>=0&&j<9&&!(panel.getMymineLables()[i][j].equals(t his))){panel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[panel. getMymineLables()[i][j].getCount()]);panel.getMymineLables()[i][j].setIsexpand(true);panel.getMymineLables()[i][j].openMine(panel);}}}}}}英雄监听package saolei.listener;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import saolei.dialog.HeroInputDialog;import ble.HeroBean;import saolei.tools.Tools;public class HeroInputListener implements ActionListener{ private HeroInputDialog heroInputDialog;public HeroInputListener(HeroInputDialog heroInputDialog) { this.heroInputDialog = heroInputDialog;}@Overridepublic void actionPerformed(ActionEvent e) {if (e.getSource().equals(heroInputDialog.getButtonY())) { String text = heroInputDialog.getJtfN().getText();if (text != null && text.length() != 0) {text = text.trim();//去除左右空格if (text.length() > 10) {text = text.substring(0, 10);}} else {text = "匿名";}HeroBean heroBean = new HeroBean();heroBean.setName(text);heroBean.setTime(Tools.myTimerTask.time);if (Tools.mineCount == 10) {heroBean.setLevel("初级");Tools.setB.add(heroBean);}if (Tools.mineCount == 40) {heroBean.setLevel("中级");Tools.setI.add(heroBean);}if (Tools.mineCount == 99) {heroBean.setLevel("高级");Tools.setE.add(heroBean);}heroInputDialog.dispose();} else if(e.getSource().equals(heroInputDialog.getButtonN())) { heroInputDialog.dispose();}}}重写鼠标监听package saolei.listener;import java.awt.event.InputEvent;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.Timer;import javax.swing.ImageIcon;import javax.swing.JLabel;import saolei.dialog.HeroInputDialog;import saolei.frame.MymineFrame;import ble.MymineLable;import saolei.panel.MybompPanel;import saolei.tools.Tools;public class MyListener implements MouseListener{//写鼠标监听,该类监听有依据鼠标不同动作private MybompPanel mybompPanel;//用于获取布雷面板private MymineLable mymineLable;//用于获取事件源private int leftClick;//左键一共击了多少次private boolean isLeftPress;//是否为左键击private boolean isDoublePress;//是否为左右键private boolean isRightpress;//是否为右键击private int bompCount=Tools.mineCount;//布了几个雷public boolean isRightpress() {return isRightpress;}public void setRightpress(boolean isRightpress) {this.isRightpress = isRightpress;}public boolean isLeftPress() {return isLeftPress;}public void setLeftPress(boolean isLeftPress) {this.isLeftPress = isLeftPress;}public boolean isDoublePress() {return isDoublePress;}public void setDoublePress(boolean isDoublePress) {this.isDoublePress = isDoublePress;}public MyListener(MybompPanel m){this.mybompPanel=m;}public void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}public void mouseEntered(MouseEvent e) {// TODO Auto-generated method stub}public void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}/////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////public void mousePressed(MouseEvent e) {//鼠标点击未释放mymineLable=(MymineLable)(e.getSource());//左右击未释放if (e.getModifiersEx() == InputEvent.BUTTON1_DOWN_MASK+ InputEvent.BUTTON3_DOWN_MASK){setDoublePress(true);setLeftPress(false);setRightpress(false);Tools.faceLabel.setIcon(Tools.faceIcon[2]);//表情为惊讶if(!mymineLable.isIsexpand()){mymineLable.setIcon(new ImageIcon("./images/0.gif"));}for(inti=mymineLable.getRowx()-1;i<=mymineLable.getRowx()+1;i++){for(intj=mymineLable.getColy()-1;j<=mymineLable.getColy()+1;j++){if(i>=0&&i<Tools.rowCount&&j>=0&&j<Tools.colCount&&mybompPanel.ge tMymineLables()[i][j]!=mymineLable&&!(mybompPanel.getMymineLables()[i ][j].isIsexpand())&&(mybompPanel.getMymineLables()[i][j].getRightClick()!=1))//如果在区内且该雷不为被点的雷且被点的雷没有展开{if(mybompPanel.getMymineLables()[i][j].getRightClick()==2&&(mybom pPanel.getMymineLables()[i][j].getRightClick()!=1)){mybompPanel.getMymineLables()[i][j].setIcon(Tools.ask1);}if(mybompPanel.getMymineLables()[i][j].getRightClick()==0&&(mybom pPanel.getMymineLables()[i][j].getRightClick()!=1)){mybompPanel.getMymineLables()[i][j].setIcon(Tools.mineNumberIcon[ 0]);}}}}}///////////////////////////////////////////////////////////////// //////////////////////////////////////////if (e.getModifiers() == InputEvent.BUTTON1_MASK)//左键单击{setLeftPress(true);setRightpress(false);if(!mymineLable.isIsexpand()&&!isDoublePress()&&isLeftPress()) {for(int i=100000;i>0;i--){}if(!mymineLable.isIsexpand()&&!isDoublePress()&&isLeftPress()) {Tools.faceLabel.setIcon(Tools.faceIcon[2]);//表情为惊讶mymineLable.setIcon(newImageIcon("./images/0.gif"));//被击的凹下去}}}///////////////////////////////////////////////////////////////// ////////////////////////////if (e.getModifiers() == InputEvent.BUTTON3_MASK)//右击未释放{setLeftPress(false);setRightpress(true);if(!mymineLable.isIsexpand()&&!isDoublePress()&&isRightpress()){for(int i=100000;i>0;i--){}if(!mymineLable.isIsexpand()&&!isDoublePress()&&isRightpress()){mymineLable.setRightClick(mymineLable.getRightClick()+1);//该lable 右击次数加1。
python扫雷简易代码
python扫雷简易代码扫雷是一款经典的策略游戏,玩家需要在一个方格矩阵中找出所有没有地雷的格子。
在Python 中可以使用`pygame`库来实现扫雷游戏,`pygame`库是一个第三方库使用前请确保其已经安装,如下是一个代码示例:```pythonimport pygameimport sysimport random# 定义雷的数量和方格大小MINE_NUMBER = 10GRID_SIZE = 10# 定义颜色COLOR_BLACK = (0, 0, 0)COLOR_WHITE = (255, 255, 255)COLOR_RED = (255, 0, 0)COLOR_GREEN = (0, 255, 0)COLOR_GRAY = (192, 192, 192)# 初始化 pygamepygame.init()# 获取对显示系统的访问,并创建一个窗口 screenscreen = pygame.display.set_mode((GRID_SIZE * 20, GRID_SIZE * 20))# 设置画布的标题pygame.display.set_caption("扫雷游戏")# 定义游戏区域的坐标范围area_x = (0, GRID_SIZE * 20)area_y = (0, GRID_SIZE * 20)# 定义一个二维数组来表示游戏区域的状态grid = [[False for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]# 生成地雷的位置mines = []for i in range(GRID_SIZE):for j in range(GRID_SIZE):if random.randint(0, MINE_NUMBER) == 0:mines.append((i, j))# 在游戏区域中标记地雷的位置for mine in mines:grid[mine[0]][mine[1]] = True# 用 0 表示空白,1 表示地雷,2 表示已标记的地雷,3 表示周围有地雷的格子,4 表示已翻开的空白格子for i in range(GRID_SIZE):for j in range(GRID_SIZE):if grid[i][j]:grid[i][j] = 1else:grid[i][j] = 0# 游戏循环running = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.MOUSEBUTTONDOWN:x, y = pygame.mouse.get_pos()x = int((x - area_x[0]) / 20)y = int((y - area_y[0]) / 20)if x < 0 or x >= GRID_SIZE or y < 0 or y >= GRID_SIZE:continueif grid[x][y] == 1:running = Falseelif grid[x][y] == 0:grid[x][y] = 4elif grid[x][y] == 2:grid[x][y] = 3# 绘制游戏区域screen.fill(COLOR_WHITE)for i in range(GRID_SIZE):for j in range(GRID_SIZE):if grid[i][j] == 1:pygame.draw.rect(screen, COLOR_RED, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 2:pygame.draw.rect(screen, COLOR_GRAY, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 3:pygame.draw.rect(screen, COLOR_GREEN, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))elif grid[i][j] == 4:pygame.draw.rect(screen, COLOR_WHITE, (i * 20 + area_x[0], j * 20 + area_y[0], 20, 20))# 刷新显示pygame.display.flip()# 退出程序pygame.quit()sys.exit()```上述代码中定义了一个`扫雷`游戏,首先初始化`pygame`,并创建了一个游戏窗口,设置了游戏区域的大小和坐标范围。
JAVA实现经典扫雷游戏的示例代码
JAVA实现经典扫雷游戏的⽰例代码⽬录前⾔主要设计功能截图代码实现总结前⾔windows⾃带的游戏《扫雷》是陪伴了⽆数⼈的经典游戏,本程序参考《扫雷》的规则进⾏了简化,⽤java语⾔实现,采⽤了swing技术进⾏了界⾯化处理,设计思路⽤了⾯向对象思想。
主要需求1、要有难度等级,初级,中级,⾼级2、由玩家逐个翻开⽅块,以找出所有地雷为最终游戏⽬标。
如果玩家翻开的⽅块有地雷,则游戏结束3、游戏主区域由很多个⽅格组成。
使⽤⿏标左键随机点击⼀个⽅格,⽅格即被打开并显⽰出⽅格中的数字;⽅格中数字则表⽰其周围的8个⽅格隐藏了⼏颗雷。
4、⽤户右键可标记雷的位置5、雷都被标记出来则胜利主要设计1、格⼦格数固定为10*10格2、难度等级,初级:12,中级:24,⾼级:363、点击格⼦时,产⽣没有引爆的地图效果;4、点击格⼦时,此格⼦是雷,则显⽰所有雷的位置,并递归清空⾮雷格⼦,结束游戏5、实现检查所有的雷是否都被标记出来了,如果是,则胜利算法。
6、实现计时器算法,⽤来计时显⽰游戏开始多少秒7、实现难度等级,雷数的显⽰8、实现⿏标左键的实现逻辑9、实现⿏标右键的标记逻辑功能截图开始界⾯左键选中格⼦效果左键选中雷效果右键标记雷效果胜利效果代码实现程序启动类public class JMine extends JFrame implements MouseListener, ActionListener {private JMineArth mine;private JMineButton[][] mineButton;private GridBagConstraints constraints;private JPanel pane;private GridBagLayout gridbag;private boolean gameStarted;private static JCounter mineCounter;private static JCounter timeCounter;private Timer timer;private Timer winTimer = new Timer();public int numMine;public int numFlaged;private JMenuBar mb;private JMenu mGame;private JMenuItem miEasy;private JMenuItem miMiddle;private JMenuItem miHard;private JMenuItem miExit;private JMenu mHelp;private JMenuItem miAbout;private JPanel controlPane;private JButton bTest;private AboutFrame about;private WinFrame winFrame;private ImageIcon[] mineNumIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("1.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("2.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("3.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("4.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("5.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("6.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("7.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("8.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("0.gif"))};private ImageIcon[] mineStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("flag.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("question.gif")) }; private ImageIcon[] mineBombStatus = { new ImageIcon(JMine.class.getClassLoader().getResource("0.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("mine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("wrongmine.gif")), new ImageIcon(JMine.class.getClassLoader().getResource("bomb.gif")) };private ImageIcon[] faceIcon = { new ImageIcon(JMine.class.getClassLoader().getResource("smile.gif")),new ImageIcon(JMine.class.getClassLoader().getResource("Ooo.gif")) };// You loseprivate void bomb(int row, int col){try{//System.out.println("Bomb!");for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setIcon(mineBombStatus[0]);int toShow;toShow = mine.mine[i][j] != 9 ? 0 : 1;mineButton[i][j].setClickFlag(true);if (toShow == 1 && (i != row || j != col)) {mineButton[i][j].setIcon(mineBombStatus[toShow]);mineButton[i][j].setClickFlag(true);} else if (toShow == 1 && (i == row && j == col)) {mineButton[i][j].setIcon(mineBombStatus[3]);mineButton[i][j].setClickFlag(true);} else if (toShow == 0 && mineButton[i][j].getFlag() != 1) { mineButton[i][j].setEnabled(false);} else if (toShow == 0 && mineButton[i][j].getFlag() == 1) { mineButton[i][j].setIcon(mineBombStatus[2]);mineButton[i][j].setClickFlag(true);}}}timer.cancel();}catch (Exception e){}}// check if you win() {private boolean isWin() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {if (mine.mine[i][j] == 9 && mineButton[i][j].getFlag() != 1) { return (false);}if (mine.mine[i][j] != 9 && mineButton[i][j].getFlag() == 1) { return (false);}if (mine.mine[i][j] != 9&& mineButton[i][j].getClickFlag() == false) {return (false);}}}return (true);}// You Winprivate void win(){timer.cancel();winFrame.setVisible(true);winTimer.schedule(new TimerTask(){public void run() {while(!winFrame.getWinOk()){}numMine = winFrame.getMineNum();winFrame.setVisible(false);setNewGame(numMine);//System.out.println("Jerry Debug:"+numMine);this.cancel();winFrame.setWinOk(false);}},0L);}// Constructor of the gamepublic JMine() {super("JMine Game");setSize(250, 350);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);Insets space = new Insets(0, 0, 0, 0);// Game varsgameStarted = false;numMine = 12;numFlaged = 0;ImageIcon myIcon = new ImageIcon(JMine.class.getClassLoader().getResource("blank1.gif")); gridbag = new GridBagLayout();constraints = new GridBagConstraints();pane = new JPanel();pane.setLayout(gridbag);constraints.fill = GridBagConstraints.BOTH;constraints.anchor = GridBagConstraints.CENTER;// Begin Menu Setmb = new JMenuBar();mGame = new JMenu("Game");miEasy = new JMenuItem("Easy");miEasy.addActionListener(this);miMiddle = new JMenuItem("Middle");miMiddle.addActionListener(this);miHard = new JMenuItem("Hard");miHard.addActionListener(this);miExit = new JMenuItem("Exit");miExit.addActionListener(this);mGame.add(miEasy);mGame.add(miMiddle);mGame.add(miHard);mGame.addSeparator();mGame.add(miExit);mb.add(mGame);mHelp = new JMenu("Help");miAbout = new JMenuItem("About...");mHelp.add(miAbout);miAbout.addActionListener(this);mb.add(mHelp);this.setJMenuBar(mb);// end of Menu Set// Control PanelcontrolPane = new JPanel();bTest = new JButton(faceIcon[0]);bTest.setSize(26, 27);bTest.setMargin(space);bTest.addMouseListener(this);bTest.setPressedIcon(faceIcon[1]);mineCounter = new JCounter(numMine);timeCounter = new JCounter();controlPane.add(mineCounter);controlPane.add(bTest);controlPane.add(timeCounter);buildConstraints(constraints, 0, 0, 10, 2, 100, 100);gridbag.setConstraints(controlPane, constraints);pane.add(controlPane);// BottonsmineButton = new JMineButton[10][10];for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j] = new JMineButton(i, j, myIcon);mineButton[i][j].addMouseListener(this);mineButton[i][j].setMargin(space);buildConstraints(constraints, j, i + 3, 1, 1, 100, 100);gridbag.setConstraints(mineButton[i][j], constraints);pane.add(mineButton[i][j]);}}// Content PanesetContentPane(pane);setLocation(200, 150);setVisible(true);// About Frameabout = new AboutFrame("JMine About");winFrame = new WinFrame("You win!");}// Set the GUI objects positionsvoid buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {gbc.gridx = gx;gbc.gridy = gy;gbc.gridwidth = gw;gbc.gridheight = gh;gbc.weightx = wx;gbc.weighty = wy;}// the methods to check if there were mines, to be nestedvoid checkMine(int row, int col){int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;//System.out.println("Check Mine row:"+i + ",col:" +j);if (mine.mine[i][j] == 9) {bomb(i, j);} else if (mine.mine[i][j] == 0&& mineButton[i][j].getClickFlag() == false) {mineButton[i][j].setClickFlag(true);showLabel(i, j);for (int ii = i - 1; ii <= i + 1; ii++)for (int jj = j - 1; jj <= j + 1; jj++)checkMine(ii, jj);} else {showLabel(i, j);mineButton[i][j].setClickFlag(true);}if (isWin()) {win();}}private void clearAll(int row, int col){int top, bottom, left, right;top = row - 1 > 0 ? row - 1 : 0;bottom = row + 1 < 10 ? row + 1 : 9;left = col - 1 > 0 ? col - 1 : 0;right = col + 1 < 10 ? col + 1 : 9;for (int i = top; i <= bottom; i++) {for (int j = left; j <= right; j++) {if (mineButton[i][j].getFlag() != 1)checkMine(i, j);}}}private void resetAll() {for (int i = 0; i < 10; i++) {for (int j = 0; j < 10; j++) {mineButton[i][j].setFlag(0);mineButton[i][j].setClickFlag(false);mineButton[i][j].setIcon(mineStatus[0]);mineButton[i][j].setEnabled(true);mineButton[i][j].setVisible(true);}}}// to flag the mine you want to flag outvoid flagMine(int row, int col) {//System.out.println("Jerry Arrives here!");int i, j;i = row < 0 ? 0 : row;i = i > 9 ? 9 : i;j = col < 0 ? 0 : col;j = j > 9 ? 9 : j;if (mineButton[i][j].getFlag() == 0) {numFlaged++;} else if (mineButton[i][j].getFlag() == 1) {numFlaged--;}mineCounter.resetCounter(numMine - numFlaged >= 0 ? numMine - numFlaged: 0);mineButton[i][j].setFlag((mineButton[i][j].getFlag() + 1) % 3);showFlag(i, j);if (isWin()) {win();}}// show the numbers of the nearby minesvoid showLabel(int row, int col) {//System.out.println("ShowLabel row:" + row + ",col:" + col);int toShow;toShow = mine.mine[row][col];if (toShow != 0) {mineButton[row][col].setIcon(mineNumIcon[toShow]);mineButton[row][col].setClickFlag(true);//mineButton[row][col].setEnabled(false);} else {//mineButton[row][col].setIcon(mineNumIcon[0]);//mineButton[row][col].setClickFlag(true);mineButton[row][col].setEnabled(false);}}// circle the flag with blank, flaged, questionedvoid showFlag(int row, int col) {mineButton[row][col].setIcon(mineStatus[mineButton[row][col].getFlag()]);}// the mouse events listener methodspublic void mouseEntered(MouseEvent e) {//System.out.println("Jerry Test");}// method to start the new gameprivate void startNewGame(int num, int row, int col){mine = new JMineArth(num, row, col);//mine.printMine();gameStarted = true;timer = new Timer();timer.scheduleAtFixedRate(new TimerTask(){public void run() {timeCounter.counterAdd();//System.out.println(timeCounter.getCounterNum());}},1000,1000);}public void setNewGame(int num) {resetAll();numMine = num;numFlaged = 0;gameStarted = false;mineCounter.resetCounter(numMine);timeCounter.resetCounter(0);}// the event handle to deal with the mouse clickpublic void mouseClicked(MouseEvent e) {if (e.getSource() == bTest) {setNewGame(numMine);return;}int row, col;row = ((JMineButton) e.getSource()).getRow();col = ((JMineButton) e.getSource()).getCol();if (!gameStarted) {startNewGame(numMine, row, col);}if (e.getModifiers() == (InputEvent.BUTTON1_MASK + InputEvent.BUTTON3_MASK)) { //System.out.println("HA");clearAll(row, col);}if (!mineButton[row][col].getClickFlag()) {if (e.getModifiers() == InputEvent.BUTTON1_MASK) {//System.out.println("LeftButton");if (mineButton[row][col].getFlag() == 1) {return;} else {checkMine(row, col);}} else if (e.getModifiers() == InputEvent.BUTTON3_MASK) { //System.out.println("RightButton");flagMine(row, col);} else {//System.out.println("MiddleButton");}}}public void mousePressed(MouseEvent e) {//System.out.println("Jerry Press");}public void mouseReleased(MouseEvent e) {//System.out.println("Jerry Release");}public void mouseExited(MouseEvent e) {//System.out.println("Jerry Exited");}public void actionPerformed(ActionEvent e) {try {if (e.getSource() == miEasy) {setNewGame(12);return;}if (e.getSource() == miMiddle) {setNewGame(24);return;}if (e.getSource() == miHard) {setNewGame(36);return;}if (e.getSource() == miExit) {System.exit(0);}if (e.getSource() == miAbout) {about.setVisible(true);}} catch (Exception ie) {}}public static void main(String [] args) {JMine jmine = new JMine();jmine.setVisible(true);}}地雷分布图算法类public class JMineArth {public int [][] mine;private boolean fMineSet;JMineArth(int mineNum, int row, int col) {mine = new int[10][10];setMine(mineNum, row, col);setMineNum();}private void setMine(int mineNum, int Outrow, int Outcol) {int col=0, row = 0, i=0;//Math.srand(now);while (i < mineNum) {col = (int)(Math.random()*100)%10;row = (int)(Math.random()*100)%10;if (mine[col][row]==0 && (row!=Outrow || col!=Outcol || Outrow==10 )) {mine[row][col]=9;i++;}}}private void setMineNum() {for ( int i=0 ; i <10; i++) {for (int j=0; j < 10; j++) {mine[i][j]=mine[i][j]==9?9:checkMineNum(i,j);}}fMineSet = true;}private int checkMineNum(int ii,int jj) {int top,bottom, left, right, count=0;top=ii-1>0?ii-1:0;bottom=ii+1<10?ii+1:9;left=jj-1>0?jj-1:0;right=jj+1<10?jj+1:9;for (int i=top; i<=bottom; i++) {for(int j=left; j<= right; j++) {if (mine[i][j]==9) count++;}}return(count);}public void printMine() {for (int i = 0; i < 10; i++) {for (int j=0; j < 10; j++) {System.out.print(this.mine[i][j] + " ");}System.out.println();}}public static void main(String[] args) {JMineArth mine = new JMineArth(Integer.parseInt(args[0]),Integer.parseInt(args[1]),Integer.parseInt(args[2]));mine.printMine();}}总结通过此次的《扫雷》游戏实现,让我对swing的相关知识有了进⼀步的了解,对java这门语⾔也有了⽐以前更深刻的认识。
扫雷游戏模板,扫雷游戏文档下载(二)2024
扫雷游戏模板,扫雷游戏文档下载(二)引言概述:本文档提供了扫雷游戏模板的详细说明,包括游戏规则、功能特点、游戏界面和操作说明等内容。
本文还提供了扫雷游戏的源代码下载,方便用户自行进行二次开发和定制。
正文:一、游戏规则1. 扫雷游戏的目标是根据已经点击的方块和数字提示,找出并标记所有的地雷位置。
2. 点击一个方块后,该方块会显示数字,表示该方块周围八个方向上的地雷数量。
3. 如果点击的方块没有地雷,会自动揭示周围的方块,直到遇到数字方块或边界。
4. 如果点击的方块是一个地雷,则游戏结束,玩家失败。
5. 玩家可以通过标记方块来记录自己认为是地雷的位置,以便辅助游戏过程。
二、功能特点1. 游戏模板具有灵活性,可以根据实际需求进行扩展和修改。
2. 支持自定义游戏难度,包括地雷数量、游戏面板大小等参数的调整。
3. 提供多种游戏模式选择,包括经典模式、计时模式和竞速模式等。
4. 支持排行榜功能,记录玩家的最佳成绩和游戏时长等信息。
5. 提供可视化的游戏界面和操作,简单易懂,适合不同年龄段的玩家。
三、游戏界面1. 游戏界面分为游戏区域和操作区域两个主要部分。
2. 游戏区域展示了地雷方块的位置和数字提示。
3. 操作区域包括开始游戏按钮、计时器、标记方块按钮和重新开始按钮等。
4. 游戏区域和操作区域之间进行合理的布局设计,方便玩家进行游戏操作。
四、操作说明1. 点击游戏区域的方块进行翻开和揭示操作。
2. 长按方块可以进行地雷标记。
3. 点击操作区域的开始游戏按钮,开始游戏。
4. 点击操作区域的重新开始按钮,重新开始当前游戏。
5. 游戏结束后,可以点击排行榜按钮查看玩家的成绩和排名等信息。
五、总结本文档详细介绍了扫雷游戏模板的规则、功能特点、游戏界面和操作说明等内容。
通过下载文档中提供的扫雷游戏源代码,开发者可以自行进行二次开发和定制,以满足不同的需求。
希望这个扫雷游戏模板能够给玩家带来快乐和挑战。
如有任何问题或建议,请随时联系我们。
扫雷游戏代码
扫雷游戏代码Document serial number【UU89WT-UU98YT-UU8CB-UUUT-UUT108】/**/#ifndef BLOCK_H_#define BLOCK_H_#include<QLabel>class QWidget;class Block:public QLabel{Q_OBJECTpublic:explicit Block(bool mine_flag,QWidget*parent=0);void set_number(int number);void turn_over();bool is_mine()const;bool is_turn_over()const;signals:void turn_over(bool is_mine);protected:void mousePressEvent(QMouseEvent*event); private:bool mine_flag_;bool mark_flag_;bool turn_over_flag_;int number_;};#endif#include""#include<QLabel>#include<QMouseEvent>#include<QPixmap>#include<QWidget>Block::Block(bool mine_flag,QWidget*parent) :QLabel(parent){mine_flag_=mine_flag;mark_flag_=false;turn_over_flag_=false;number_=-1;setPixmap(QPixmap(":/images/"));}void Block::set_number(int number){number_=number;}void Block::turn_over(){if(!turn_over_flag_){turn_over_flag_=true;if(mine_flag_)setPixmap(QPixmap(":/images/"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();}}bool Block::is_mine()const{return mine_flag_;}bool Block::is_turn_over()const{return turn_over_flag_;}/*鼠标事件的实现*/void Block::mousePressEvent(QMouseEvent*event){if(event->button()==Qt::LeftButton){if(!turn_over_flag_&&!mark_flag_){turn_over_flag_=true;if(mine_flag_==true){setPixmap(QPixmap(":/images/"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(num ber_)+".png"));update();emit turn_over(false);}}}else if(event->button()==Qt::RightButton){if(!turn_over_flag_){if(!mark_flag_){mark_flag_=true;setPixmap(QPixmap(":/images/"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include""#include<QWidget>class QEvent;class QGridLayout;class QObject;class BlockArea:public QWidget{Q_OBJECTpublic:BlockArea(int row,int column,int mine_number,QWidget* parent=0);void set_block_area(int row,int column,intmine_number,int init_flag=false);signals:void game_over(bool is_win);protected:bool eventFilter(QObject*watched,QEvent*event); private slots:void slot_turn_over(bool is_mine);private:int calculate_mines(int x,int y)const;rg(easy_record_time_)),1,1);up_layout->addWidget(new QLabel(easy_record_name_),1,2);up_layout->addWidget(new QLabel(tr("Middle")),2,0);up_layout->addWidget(newQLabel(QString("%1").arg(middle_record_time_)),2,1);up_layout->addWidget(newQLabel(middle_record_name_),2,2);up_layout->addWidget(new QLabel(tr("Hard")),3,0);up_layout->addWidget(newQLabel(QString("%1").arg(hard_record_time_)),3,1);up_layout->addWidget(new QLabel(hard_record_name_),3,2);QPushButton*recount_button=newQPushButton(tr("recount"));QPushButton*close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(ac cept()));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reje ct()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(recount_button);bottom_layout->addWidget(close_button);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted){easy_record_time_=middle_record_time_=hard_record_time_= g_no_record_time;easy_record_name_=middle_record_name_=hard_record_name_= g_no_record_name;}}void MainWindow::slot_show_game_toolBar(bool show){if(show)game_toolBar->show();elsegame_toolBar->hide();}void MainWindow::slot_show_statusBar(bool show){if(show)statusBar()->show();elsestatusBar()->hide();}/*游戏的设置容易、中等、困难及自定义*/void MainWindow::slot_standard(QAction*standard_action) {if(standard_action==easy_standard_action){current_standard_=0;row_=9;column_=9;mine_number_=10;}else if(standard_action==middle_standard_action){ current_standard_=1;row_=16;column_=16;mine_number_=40;}else if(standard_action==hard_standard_action){current_standard_=2;row_=16;column_=30;mine_number_=99;}else if(standard_action==custom_standard_action){ QDialog dialog;(tr("set standard"));QSpinBox*row_spinBox=new QSpinBox;row_spinBox->setRange(5,50);row_spinBox->setValue(row_);QSpinBox*column_spinBox=new QSpinBox;column_spinBox->setRange(5,50);column_spinBox->setValue(column_);QSpinBox*mine_spinBox=new QSpinBox;mine_spinBox->setValue(mine_number_);QHBoxLayout*up_layout=new QHBoxLayout;up_layout->addWidget(row_spinBox);up_layout->addWidget(column_spinBox);up_layout->addWidget(mine_spinBox);QDialogButtonBox*dialog_buttonBox=new QDialogButtonBox;dialog_buttonBox->addButton(QDialogButtonBox::Ok);dialog_buttonBox->addButton(QDialogButtonBox::Cancel);connect(dialog_buttonBox,SIGNAL(accepted()),&dialog,SLOT (accept()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT (reject()));QHBoxLayout*bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout*main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBox->value()){current_standard_=3;row_=row_spinBox->value();column_=column_spinBox->value();mine_number_=mine_spinBox->value();}}slot_new_game();}/*实现帮助菜单中的关于游戏,及功能*/void MainWindow::slot_about_game(){QString introduction("<h2>"+tr("About Mine Sweepr")+"</h2>"+"<p>"+tr("This game is played by revealing squares of the grid,typically by clicking them with a mouse.If a square containing a mine is revealed,the player loses the game.Otherwise,a digit is revealed in the square,indicating the number of adjacent squares(out of the possible eight)that contain this number is zero then the square appears blank,and the surrounding squares are automatically also revealed.By using logic,the player can in many instances use this information to deduce that certain other squares are mine-free, in which case they may be safely revealed,or mine-filled,in which they can be marked as such(which is effected by right-clicking the square and indicated by a flag graphic).")+"</p>"+"<p>"+tr("This program is free software;you can redistribute it and/or under the terms of the GNU General Public License as published by the Software Foundation;either version3of the License,or(at your option)any later version.")+"</p>"+"<p>"+tr("Please see")+"<a href="+tr("for an overview of GPLv3licensing")+"</p>"+"<br>"+tr("Version:")+g_software_version+"</br>"+"<br>"+tr("Author:")+g_software_author+"</br>");QMessageBoxmessageBox(QMessageBox::Information,tr("About Mine Sweeper"),introduction,QMessageBox::Ok);();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){();QString name;if(is_win){switch(current_standard_){case0:if(time_label->text().toInt()<easy_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){easy_record_time_=time_label->text().toInt();easy_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case1:if(time_label->text().toInt()<middle_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){middle_record_time_=time_label->text().toInt();middle_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case2:if(time_label->text().toInt()<hard_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record.Please enter your name"));if(!()){hard_record_time_=time_label->text().toInt();hard_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;default:QMessageBox::information(this,tr("Result"),tr("Y ou win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg()/1000));}/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;("MainWindow");resize("size").toSize());move("pos").toPoint());bool show_game_toolBar=("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);();("GameSetting");current_standard_=("current_standard").toInt();switch(current_standard_){case0:easy_standard_action->setChecked(true);break;case1:middle_standard_action->setChecked(true);break;case2:hard_standard_action->setChecked(true);break;case3:custom_standard_action->setChecked(true);break;default:;}row_=("row").toInt()==09:("row").toInt();column_=("column").toInt()==09:("column").toInt();mine_number_=("mine_number").toInt()==010:("mine_number" ).toInt();();("Rank");easy_record_time_=("easy_record_time").toInt()==0g_no_re cord_time:("easy_record_time").toInt();middle_record_time_=("middle_record_time").toInt()==0g_n o_record_time:("middle_record_time").toInt();hard_record_time_=("hard_record_time").toInt()==0g_no_re cord_time:("hard_record_time").toInt();easy_record_name_=("easy_record_name").toString()==""g_n o_record_name:("easy_record_name").toString();middle_record_name_=("middle_record_name").toString()==" "g_no_record_name:("middle_record_name").toString();hard_record_name_=("hard_record_name").toString()==""g_n o_record_name:("hard_record_name").toString();();}void MainWindow::write_settings(){QSettings settings;("MainWindow");("size",size());("pos",pos());("showGameToolBar",show_game_toolBar_action->isChecked());("showStatusBar",show_statusBar_action->isChecked());();("GameSetting");("current_standard",current_standard_);("row",row_);("column",column_);("mine_number",mine_number_);();("Rank");("easy_record_time",easy_record_time_);("middle_record_time",middle_record_time_);("hard_record_time",hard_record_time_);("easy_record_name",easy_record_name_);("middle_record_name",middle_record_name_);("hard_record_name",hard_record_name_);();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=new QAction(QIcon(":/images/"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(sl ot_new_game()));rank_action=newQAction(QIcon(":/images/"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_r ank()));exit_action=newQAction(QIcon(":/images/"),tr("Exit"),this);exit_action->setShortcut(QKeySequence::Quit);connect(exit_action,SIGNAL(triggered()),this,SLOT(close( )));show_game_toolBar_action=new QAction(tr("Show Game Tool Bar"),this);show_game_toolBar_action->setCheckable(true);connect(show_game_toolBar_action,SIGNAL(toggled(bool)),t his,SLOT(slot_show_game_toolBar(bool)));show_statusBar_action=new QAction(tr("Show Status Bar"),this);show_statusBar_action->setCheckable(true);connect(show_statusBar_action,SIGNAL(toggled(bool)),this ,SLOT(slot_show_statusBar(bool)));easy_standard_action=newQAction(QIcon(":/images/"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/"),tr("Custom"),this);custom_standard_action->setCheckable(true);standard_actionGroup=new QActionGroup(this);standard_actionGroup->addAction(easy_standard_action);standard_actionGroup->addAction(middle_standard_action);standard_actionGroup->addAction(hard_standard_action);standard_actionGroup->addAction(custom_standard_action);connect(standard_actionGroup,SIGNAL(triggered(QAction*)) ,this,SLOT(slot_standard(QAction*)));about_game_action=newQAction(QIcon(":/images/"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT( slot_about_game()));about_qt_action=new QAction(QIcon(":/images/"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(ab outQt()));}/*菜单栏的创建*/void MainWindow::create_menus(){game_menu=menuBar()->addMenu(tr("Game"));game_menu->addAction(new_game_action);game_menu->addSeparator();game_menu->addAction(rank_action);game_menu->addSeparator();game_menu->addAction(exit_action);setting_menu=menuBar()->addMenu(tr("Setting"));setting_menu->addAction(show_game_toolBar_action);setting_menu->addAction(show_statusBar_action);setting_menu->addSeparator();setting_menu->addAction(easy_standard_action);setting_menu->addAction(middle_standard_action);setting_menu->addAction(hard_standard_action);setting_menu->addAction(custom_standard_action);help_menu=menuBar()->addMenu(tr("Help"));help_menu->addAction(about_game_action);help_menu->addAction(about_qt_action);}void MainWindow::create_game_toolBar(){game_toolBar=addToolBar(tr("Game Tool Bar"));game_toolBar->setFloatable(false);game_toolBar->setMovable(false);game_toolBar->addAction(new_game_action);game_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); }void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(newQLabel(tr("second")));}#include""#include<QApplication>#include<QTranslator>int main(int argc,char*argv[]){QApplication app(argc,argv);QTranslator translator;(":/");(&translator);MainWindow window;();return();}。
Java简单雷电游戏代码
完整代码!!!import java.awt.*;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.ImageIcon;import javax.swing.JPanel;public class Mhh {public static void main(String args[]){Frame w=new Frame();w.setSize(430,500);MyPanel9 mp=new MyPanel9();w.add(mp);w.addKeyListener(mp);mp.addKeyListener(mp);Thread t=new Thread(mp);t.start();w.show();}}class MyPanel9 extends JPanel implements Runnable,KeyListener { int count=1000;//发射子弹的数目int flag1=0;//标志flag为1时发射子弹int m=0;//记录已发射子弹的数目int max=2000;//记录得分int x=280;//下面飞机的坐标int y=420;int x1[]=new int[15];//上面飞机的坐标int[] y1=new int[15];int x2[]=new int[count];//发射子弹的坐标int[] y2=new int[count];public MyPanel9(){//上面飞机随即分布for(int i=0;i<15;i++){x1[i]=(int)(Math.random()*400);y1[i]=(int)(Math.random()*500);}}public void paint(Graphics g){super.paint(g);Image img2=new ImageIcon("1.jpg").getImage();g.drawImage(img2,0,0,430,500,null);Image img1=new ImageIcon("2.jpg").getImage();//画下面的飞机g.drawImage(img1,x,y,30,40,null);if(max>0){Font f=new Font("",Font.BOLD,16);g.setFont(f);g.setColor(Color.RED);g.drawString("成绩是:"+max,20,20);for(int i=0;i<10;i++){Image img3=new ImageIcon("4.jpg").getImage();//画上面的飞机g.drawImage(img3,x1[i],y1[i],30,40,null);}if(m==count) m=0;if(flag1==1){//画新子弹的位置x2[m]=x;y2[m]=y;m++;flag1=0;}for(int i=0;i<m;i++){g.setColor(Color.RED);g.fillOval(x2[i]+5,y2[i],15,15);}}else{Font ff=new Font("",Font.BOLD,36);g.setFont(ff);g.setColor(Color.RED);g.drawString("GAME OVER",100,200);}}public void run(){while(true){for(int i=0;i<10;i++){//飞机随机下落y1[i]++;if(y1[i]>500){y1[i]=0;x1[i]=(int)(Math.random()*400);max-=50;}}for(int j=0;j<m;j++){//子弹移动的过程y2[j]-=10;}for(int i=0;i<m;i++){ //子弹击中飞机的过程if(y2[i]>0){for(int j=0;j<10;j++){if(0<=(y2[i]-y1[j])&&(y2[i]-y1[j])<=10){if(-15<=(x2[i]-x1[j])&&(x2[i]-x1[j])<=10){max+=10;y2[i]=-1;x1[j]=(int)(Math.random()*400);y1[j]=0;}}}}}if(max<0){return;}try{Thread.sleep(35);}catch(Exception e){}repaint();}}public void keyTyped(KeyEvent e) {// TODO Auto-generated method stub}public void keyPressed(KeyEvent e) {//控制下面飞机移动if(e.getKeyCode()==KeyEvent.VK_LEFT){ x-=10;if(x<0){x=0;}}if(e.getKeyCode()==KeyEvent.VK_UP){y-=10;if(y<0){y=0;}}if(e.getKeyCode()==KeyEvent.VK_RIGHT){ x+=10;if(x>400){x=400;}}if(e.getKeyCode()==KeyEvent.VK_DOWN){ y+=10;if(y>420){y=420;}}repaint();if(e.getKeyCode()==KeyEvent.VK_SPACE){ flag1=1;}}public void keyReleased(KeyEvent e) {// TODO Auto-generated method stub}}。
java课程设计——扫雷
java课程设计——扫雷⼀、团队课程设计博客链接:⼆、个⼈负责模块或任务说明:模块:⽂件操作 Minefield类实现三、⾃⼰的代码提交记录截图四、⾃⼰负责模块或任务详细说明1.Minefield类实现Minefield是我们主要的算法实现模块。
在正式开始扫雷游戏时,看见的是如下界⾯:⼀格⼀格的蓝⾊格⼦表⽰可点击区域。
点击后,分三个情况:1)标记该区域为雷(右击)2)该区域是点击到雷,游戏结束 3)该区域⽆雷,显⽰区域九宫格范围内的雷的个数。
(此处有9种情况)4)游戏提前结束,显⽰所有未被点击的雷。
下图囊括四种情况:选项区域:这⾥涉及到的保存进度,下条中讲解。
对于以上游戏功能,我们是这样实现的。
先根据所选等级,初始化⼀个map数组,数组的⾏数和列数取决于等级。
然后⽤Math.random()数结合循环语句和判断语句⽣成,将类的区域置9。
其余位置元素值属于0~8,分别表⽰以当前位置为中⼼的九宫格中雷的数⽬。
⾄此,map数组⽣成完毕。
由于游戏界⾯中,真正显⽰出来的状态有13种(0~8九个数字九种,标记该位置为雷、该位置是被点击的雷、游戏成功后未被点击的雷、当前可点击区域各⼀种),⽤map数组来控制游戏界⾯的显⽰会有冲突,所以此处引⼊hiddenmap数组,元素数值范围为0~12,分别表⽰上述13种情况。
对于游戏界⾯,其实是⼀个JButton数组,由于界⾯的美观性,⽤hiddenmap数组值为每个按钮分配图⽚,根据hiddenmap数组值分配对应的功能图⽚。
⽣成雷:⽣成map数组其他位置的数字:for (int i = 0; i < getWidth(); i++)for (int j = 0; j < getLength(); j++) {if (map[i][j] != 9) // 只对不为雷的区域进⾏雷数判断{int number = 0;if (i == 0) {if (j == 0) {if (map[i][j + 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j + 1] == 9)number++;} else if (j == getLength() - 1) {if (map[i][j - 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j - 1] == 9)number++;} else {if (map[i][j - 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i + 1][j - 1] == 9)number++;if (map[i + 1][j] == 9)number++;if (map[i + 1][j + 1] == 9)number++;}}if (i == getWidth() - 1) {if (j == 0) {if (map[i][j + 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j + 1] == 9)number++;} else if (j == getLength() - 1) {if (map[i][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j - 1] == 9)number++;} else {if (map[i][j - 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i - 1][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i - 1][j + 1] == 9)number++;}}if (i != 0 && i != (getWidth() - 1)) {if (j == 0) {if (map[i - 1][j + 1] == 9)number++;if (map[i][j + 1] == 9)number++;if (map[i + 1][j + 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i + 1][j] == 9)number++;}if (j == getLength() - 1) {if (map[i - 1][j - 1] == 9)number++;if (map[i][j - 1] == 9)number++;if (map[i + 1][j - 1] == 9)number++;if (map[i - 1][j] == 9)number++;if (map[i + 1][j] == 9)number++;}}if ((i != 0) && (j != 0) && (i != getWidth() - 1) && (j != getLength() - 1)) { // 不在边缘的情况// 单位九宫格内的雷数for (int n = i - 1; n <= i + 1; n++)for (int m = j - 1; m <= j + 1; m++)if (map[n][m] == 9)number++;}map[i][j] = number;}}}所有过程中我们的操作都是对我们的hiddenmap做修改,我们的map是我们的真实雷区不做改动,接下来讲讲核⼼的具体实现。
JAVA作业_Java课程设计实验报告_扫雷_哈工大选修课作业
H a r b i n I n s t i t u t e o f T e c h n o l o g y课程设计报告课程名称: JAVA网络设计设计题目:扫雷游戏院系:电子班级:08设计者:学号:指导教师:辛明影设计时间: 2010,11,29一,题目分析扫雷游戏分析:●扫雷的基本原理九宫格中(3*3共九个格子),中间的数字代表其周围的地雷个数,即以中间数为中心所在地九格中共有中间那个数的地雷。
比如中间为1,那么以这个1为中心,其周围共八个空格中只有一个是地雷。
●扫雷的基本功能1) 开局:首先选择游戏等级,然后生成不同等级的雷区界面。
游戏等级分为三级:各等级方块数为——初级:9×9、中级:16×16、高级:24×24;自定义:X,各级地雷数分别为10,40,99;雷区每个方块下面或埋藏有1个地雷,或者没有地雷;2) 挖雷:鼠标点击方块,可挖开它;若所揭方块下有雷,则踩雷,此时所有含地雷的块都标记,该局游戏失败;如果方块上出现数字,它代表在它周围的8个方块中共有多少颗地雷;3) 标记地雷:在某个光标上点击鼠标右键,则标记此块下埋着地雷(实际上可能是误标),显示为F。
每标记一个地雷,地雷数减少1;4) 自动挖开:如果某个数字方块周围的地雷全都标记完,则自动将其剩下的方块挖开;5) 扩散:扫雷程序还会自动展开已确定没有雷的雷区。
如果a[3,4]周围雷数为1,a[2,3]已被标示为地雷,那么a[24],a[25],a[33],a[35],a[43],a[44],a[45]将被展开,一直波及到不可确定的雷区。
6) 游戏数据的记录:对于得分较高的玩家进行统计,保存在“mine.log”文件中。
7)用于记录游戏时间的独立线程,并在界面实时显示游戏时间。
7)总体设计开发环境:Windows Xp sp3+NetBeans IDE1.项目包的UML视图:图1-项目包视图项目由三个包组成:●saolei.game.mine 功能:这个包是游戏的核心,其中实现了主界面,核心算法,图片管理,等级记录等功能●saolei.awt 功能:实现LedNumber类,把数字格式化为液晶显示图片●saolei.swing 功能:实现 AboutDialog类,响应about事件。
扫雷源代码(精)
#include <Windows.h>#include <stdio.h>#include <stdlib.h>#include <conio.h>#include <time.h>#define RECT 10#define MY_BUFSIZE 1024 // 宽字符缓冲// 棋盘的最大x,y#define MAXX 21#define MAXY 21// 按键大小写皆可以输入#define LEFT 75#define RIGHT 77#define UP 72#define DOWN 80#define ENTER 13#define ESC 27#define UPA 'A'#define LOWA 'a'#define UPW 'W'#define LOWW 'w'#define UPQ 'Q'#define LOWQ 'q'#define UPD 'D'#define LOWD 'd'void init();//初始化雷曲函数void draw_board(void); //画布函数void draw_face(int type);//游戏状态函数void draw_rect(int type);//按键后响应函数void operate_mine(void);//随机生成雷函数void move(void);//移动函数void hide(void);//隐藏函数void show(void);//高亮当前坐标void open_mine(void);//挖雷函数int is_win(void);//判断输赢函数void change_rectColor(int x, int y, int col);//改变周围颜色函数void test(char a[]);LPCWSTR StrToLPWSTR(char *szStr); // c风格字符串转宽字符串void goto_xy(int x, int y); // 定位光标void set_fontColor(int color); // 设置字符显示的背景前景色int get_keys(void); // 获取按键// 全局变量int x = 0, y = 0; // 初始化坐标值int num = 0; // 统计当前总共雷数量CONSOLE_CURSOR_INFO cur_info = { 1, 0 }; // 光标信息结构HANDLE hOut = NULL; // 控制台句柄结构指针COORD pos = { 0, 0 }; // 定位控制台坐标结构struct Seave //定义结构体储存每个方格的状态{int flag; //是否翻开bool mark; //雷是否标记int num; //周围雷的个数如果为9表示为雷};struct Seave mine[10][10];void init() //初始化雷区,全部设置为未翻开,未标记{int i, j;for (i = 0; i<10; i++)for (j = 0; j<10; j++){mine[i][j].flag = 0;mine[i][j].mark = true;//表示没有雷mine[i][j].num= 0;}}void DONG(int *b, int i) //计算雷周围的函数{int x = 0;if (*(b + i) == 0){if (i == 0){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;}else if (i == 9){if (*(b + i - 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;}else if (i != 0 && i % 10 == 0){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 + 1) == 9)x += 1;}else if ((i - 9) != 0 && (i - 9) % 10 == 0) {if (*(b + i - 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}else if (i == 90){if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;}else if (i == 99){if (*(b + i - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}else{if (*(b + i - 1) == 9)x += 1;if (*(b + i + 1) == 9)x += 1;if (*(b + i + 10) == 9)x += 1;if (*(b + i + 10 + 1) == 9)x += 1;if (*(b + i + 10 - 1) == 9)x += 1;if (*(b + i - 10) == 9)x += 1;if (*(b + i - 10 + 1) == 9)x += 1;if (*(b + i - 10 - 1) == 9)x += 1;}*(b + i) = x;}}void operate_mine(void) //随机产生雷{int z, i, j;int a[10][10] = { 0 };srand((unsigned)time(NULL));for (z = 0; z <= 12; z++){i = rand() % 11;j = rand() % 11;if (a[i][j] == 0){a[i][j] = 9;mine[i][j].mark = false; //雷区标记}else z--;}for (i = 0; i <= 99; i++)DONG(&a[0][0], i);for (i = 0; i<10; i++)for (j = 0; j<10; j++){mine[i][j].num = a[i][j];}}void set_fontColor(int color)//设置前景颜色{hOut == NULL ? (hOut = GetStdHandle(STD_OUTPUT_HANDLE)) : hOut;SetConsoleTextAttribute(hOut, color);}void draw_rect(int type){switch (type){case 0: // 未挖开方格set_fontColor(0x87); goto_xy(2 * x + 1, 2 * y + 1); printf("█"); break;case 1: // 表示挖开,并显示数字,如果有set_fontColor(0x88); goto_xy(2 * x + 1, 2 * y + 1); printf("█");if (mine[x][y].num == 0) break;set_fontColor(0x8a); goto_xy(2 * x + 1, 2 * y + 1); printf("%2d", mine[x][y].num); break;case 2: // 排除地雷set_fontColor(0x74); goto_xy(2 * x + 1, 2 * y + 1); printf(" X"); break;case 3: // 标记问号,表示不确定set_fontColor(0x74); goto_xy(2 * x + 1, 2 * y + 1); printf(" ?"); break;case 4: // 挖出地雷了set_fontColor(0xc0); goto_xy(2 * x + 1, 2 * y + 1); printf("●"); break;default: break;}}/*****************************测试之后才知道方向键两个字节第一个字节ASCII 0x00e0 224第二个字节分别是:上:0x0048 72下:0x0050 80左:0x012b 75右:0x012d 77*****************************/int get_keys(void){char ch;if (_kbhit()){ // 有按键按下if ((ch = _getch()) == 224 || ch == -32) // 方向键产生2个char,后一个用于判断ch = _getch();while (_kbhit())_getch(); // 清空剩余按键return ch;}elsereturn -1; // 没有按键按下}void show(void){//高亮显示当前方块所在的方格线change_rectColor(x, y, 0x8c);}void change_rectColor(int x, int y, int col){// 棋子周围棋盘线变色set_fontColor(col);goto_xy(2 * x, 2 * y + 1);printf("|");goto_xy(2 * x + 2, 2 * y + 1);printf("|");goto_xy(2 * x, 2 * y);printf(" --- ");goto_xy(2 * x, 2 * y + 2);printf(" --- ");}LPCWSTR StrToLPWSTR(char *szStr){WCHAR wszClassName[MY_BUFSIZE]; // 宽字符缓冲区WCHAR *retWchar = wszClassName;memset(wszClassName, 0, sizeof(wszClassName)); // 缓冲区清零MultiByteToWideChar(CP_ACP, 0, szStr, strlen(szStr) + 1, wszClassName,sizeof(wszClassName) / sizeof(wszClassName[0]));return retWchar;}void goto_xy(int x, int y){pos.X = x * 2; pos.Y = y;hOut == NULL ? (hOut = GetStdHandle(STD_OUTPUT_HANDLE)) : hOut;SetConsoleCursorPosition(hOut, pos);}void hide(void){change_rectColor(x, y, 0x87);// 恢复方块所在方格线颜色switch (mine[x][y].flag){case 0:; // 表示此方格未挖开draw_rect(0);break;case 1: // 挖开并且显示数字draw_rect(1);break;case 2: // 方格上有标记,表明此方格有雷draw_rect(2);break;case 3:draw_rect(3);break;default:break;}}void test(char a[], int x, int y){set_fontColor(0x8a);goto_xy(0, MAXY + 2);printf("%10s%d%d", a, x, y);}void draw_board(void){int i, j;SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&cur_info);// 隐藏光标system("mode con cols=46 lines=28");// 改变控制台窗体宽高SetConsoleTitle(StrToLPWSTR("扫雷 by 达夫东文&钓钓的猫")); // 改变窗口标题system("COLOR 87");// 控制台背景前景色// 打印棋盘到屏幕printf("-----------------------------------------\n");printf("| | | | | | | | | | | 1\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 2\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 3\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 4\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 5\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 6\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 7\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 8\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 9\n");printf("-----------------------------------------\n");printf("| | | | | | | | | | | 10\n");printf("-----------------------------------------\n");printf(" 1 2 3 4 5 6 7 8 9 10\n");// 画灰白色的方格set_fontColor(0x87);for (i = 0; i < RECT; i++)for (j = 0; j < RECT; j++){goto_xy(2 * i + 1, 2 * j + 1);printf("█");}set_fontColor(0x8a);goto_xy(0, MAXY + 2);printf("%16s", "剩余:00");draw_face(0);//操作说明set_fontColor(0x87);goto_xy(0, MAXY + 4);printf(" \"方向键移动\",\"ESC退出游戏\",\"a扫雷\"\n"" \"q标记问号\",\"w标记地雷\",\"d结束当前游戏\""); }void main(){for (;1;){int key;draw_board();init();operate_mine();while (1){key = get_keys();switch (key){case LEFT:hide();x--;x = x >= 0 ? x : 0;show();break;case RIGHT:hide();x++;x = x > 9 ? 9 : x;show();break;case UP:hide();y--;y = y >= 0 ? y : 0;show();break;case DOWN:hide();y++;y = y > 9 ? 9 : y;show();break;case UPA:case LOWA:if (mine[x][y].flag != 0) // 已经挖过,退出break;if (mine[x][y].mark == false){ // 挖到地雷了for (x = 0; x < 10; x++) // 显示出所有地雷for (y = 0; y < 10; y++)if (mine[x][y].mark == false)draw_rect(4);set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%12s", "sorry你输了");draw_face(2); // 显示出悲伤的表情_getch();return ;}open_mine(); // 没挖过且没有地雷,则挖开周围方格show();if (is_win()){set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%8s", "赢了");draw_face(1);_getch();return ;}break;case UPW: // 标记“X”,说明方格有雷case LOWW:if (mine[x][y].flag == 2) // 如果在已经标记为X的方格上再按一次w键,则取消标记X{num++;mine[x][y].flag = 0;draw_rect(0);break;}if (mine[x][y].flag != 0)break;mine[x][y].flag = 2;draw_rect(2); // 显示标记Xshow(); // 显示当前选择的方块if (is_win()){set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%8s", "赢了");draw_face(1);_getch();return ;}break;case UPQ: // 标记?,不确定是否有地雷case LOWQ:if (mine[x][y].flag == 3) // 如果在已经标记为?的方格上再按一次?键,则取消标记?{mine[x][y].flag = 0;draw_rect(0);break;}if (mine[x][y].flag != 0)break;mine[x][y].flag = 3;draw_rect(3); // 显示标记?show(); // 显示当前选择的方块break;case UPD:case LOWD:for (x = 0; x < 10; x++) // 显示出所有地雷for (y = 0; y < 10; y++)if (mine[x][y].mark == false)draw_rect(4);set_fontColor(0x8c);goto_xy(16, MAXY + 2);printf("%12s", "sorry你输了");draw_face(2); // 显示出悲伤的表情_getch();break;case ESC:exit(1);break;default:break;}}}getchar();return ;}void draw_face(int type){set_fontColor(0x8a);goto_xy(8, MAXY + 2);switch (type){case 0: printf("%16s", "状态:@_@"); break; // 游戏进行中case 1: printf("%16s", "状态:^_^"); break; // 胜利case 2: printf("%16s", "状态:>_<"); break; // 失败default: break;}}void open_mine(void)// 扫雷,此函数调用者已经判断了是否踩雷,不需重复判断{int temp_x, temp_y;int m, n;temp_x = x;temp_y = y;if (mine[x][y].num == 0 && mine[x][y].flag == 0) // 没有被挖开且方格上没有数字{mine[x][y].flag = 1;draw_rect(1); // 挖开此处方格for (m = -1; m<2; m++) // 挖开此方格周围的方格for (n = -1; n<2; n++){x = temp_x + m;y = temp_y + n;if (x == temp_x && y == temp_y) // 如果不加此条件,则无限递归continue;if (x >= 0 && x<10 && y >= 0 && y<10)// 限制边界并递归open_mine();}}else // 如果数字非0挖开方格,如果标记非0挖开方格,但不会挖开地雷,地雷周围有非0数字方格包围{ // 而挖到数字方格时是递归函数返回的时候,所以挖到数字方格停止翻开方格mine[x][y].flag = 1;draw_rect(1);}x = temp_x;y = temp_y;}int is_win(void){int i, j;for (i = 0; i<10; i++)for (j = 0; j<10; j++){if (mine[i][j].flag == 0) // 方格没有挖完return 0;if (mine[i][j].flag == 2&&mine[i][j].mark !=true)return 0;}return 1; // 游戏胜利结束,正确的扫完了所有的雷}。
python扫雷简易代码
python扫雷简易代码Python是一种简单易学、功能强大的编程语言,广泛应用于各个领域。
在本文中,我们将介绍如何使用Python编写一个简易的扫雷程序。
1. 游戏规则扫雷是一种经典的益智游戏,玩家需要根据已翻开的方块上的数字判断周围是否有雷,并标记雷的位置。
游戏的目标是翻开所有非雷方块,而不触雷。
2. 扫雷算法为了实现扫雷游戏,我们需要设计一个算法来生成雷区并计算每个方块周围的雷数。
以下是一个简单的扫雷算法:(1)初始化一个二维列表,表示雷区。
列表中的每个元素为一个字典,包含is_mine(是否是雷)、is_open(是否已翻开)和mine_count(周围的雷数)三个属性。
(2)随机生成一定数量的雷,将雷的is_mine属性设置为True。
(3)遍历雷区的每个方块,计算它周围的雷数并将结果存储在mine_count属性中。
3. Python代码实现下面是一个简易的Python扫雷程序代码:```pythonimport randomdef generate_minesweeper_board(rows, cols, mine_count):board = []for r in range(rows):row = []for c in range(cols):cell = {'is_mine': False, 'is_open': False, 'mine_count': 0} row.append(cell)board.append(row)mines = random.sample(range(rows * cols), mine_count)for index in mines:row = index // colscol = index % colsboard[row][col]['is_mine'] = Truefor r in range(rows):for c in range(cols):if not board[r][c]['is_mine']:count = 0for dx in [-1, 0, 1]:for dy in [-1, 0, 1]:if 0 <= r + dx < rows and 0 <= c + dy < cols and board[r + dx][c + dy]['is_mine']:count += 1board[r][c]['mine_count'] = countreturn boardrows = 10cols = 10mine_count = 10board = generate_minesweeper_board(rows, cols, mine_count)for r in range(rows):for c in range(cols):if board[r][c]['is_mine']:print('X', end=' ')else:print(board[r][c]['mine_count'], end=' ')print()```4. 代码解析(1)首先,我们通过调用`generate_minesweeper_board`函数生成一个扫雷的雷区,指定雷区的行数、列数和雷的数量。
java课程设计 SWT 扫雷(功能图,类图,类详细说明,测试)
《面向对象程序设计》课程设计报告题目:扫雷游戏院(系):计算机与电子系专业班级:计算机科学与技术0901班学生姓名:***学号:***********指导教师:**20 12 年 6 月 4 日至20 12 年 6 月 15 日华中科技大学武昌分校制面向对象程序设计课程设计任务书目录1需求与总体设计 (1)1.1需求分析 (1)1.2功能图样 (1)1.3总体设计 (2)1.4类图设计 (2)2详细设计 (4)2.1总体阐述 (4)2.2 ImageSource类 (4)2.3 MouseLeftListener类 (5)2.4 MouseRightListener类 (5)2.5 CountT类 (6)2.6 fuzhumianbanComposite类 (7)2.7 hero类 (8)2.8 mainshell类 (9)2.9 MenuShell类 (10)2.10 mineborder类 (11)3编码实现 (13)3.1minesweeper.action包 (13)3.2minesweeper.images包 (22)3.3minesweeper.swt包 (22)4系统测试 (44)4.1程序主界面 (44)4.2游戏难度测试 (44)4.3英雄榜测试 (46)4.4游戏失败测试 (47)4.4游戏获胜测试 (47)总结 (50)1需求与总体设计1.1需求分析1.1.1课程设计目的本次课程设计的主要目的是为了通过具体的程序加深对java语言的掌握,提高自己的编程水平。
选择的题目为扫雷游戏,这是一个综合性的题目,可以对java中的各项功能有更好的理解和使用,同时也为以后的工作打下一定基础。
1.1.2应用平台系统平台:Windows XP/VISTA/7编程语言:JAVA开发平台:Eclipse图形化界面:SWT1.1.3 程序描述和功能需求分析扫雷游戏分为初级,中级和高级三个级别,扫雷英雄榜存储每个级别的最好成绩,即挖出全部的地雷且用时最少者。
扫雷小游戏课程设计
西安科技大学软件工程课程设计报告题目:扫雷游戏开发班级:计科0901班学号:xxxxxxxxxxxx姓名:xxxxxxx电话:xxxxxxxxxxxxx2012年7月目录1 绪论 (3)选题目的及意义 (3)系统概述 (3)2 可行性研究报告 (4)3 需求规格说明书 (5)4 总体设计说明书 (6)5详细设计说明书 (7)6 系统实现 (16)开发环境 (16)关键技术 (16)运行结果 (16)7测试分析报告 (17)8心得体会 (19)参考文献1.绪论选题目的及意义随着现在生活节奏的加快,人们在工作学习之余需要一个轻松娱乐的放松环境。
因此我编写此软件的目的,一方面作为初学者来了解java环境下的小程序开发,另一方面使用户能在娱乐休闲的同时拓展思维能力。
扫雷是单人计算机游戏。
游戏的用户界面由小方格组成的战场构成。
当游戏开始时,计算机将固定的地雷数随机的放到战场的方格。
此游戏还允许玩家指定战场中的地雷数。
参考Windows 操作系统提供的扫雷游戏,改进扫雷游戏程序,增加以下功能:在主界面中添加一个菜单栏,菜单栏中包括游戏和帮助两个菜单,其中游戏菜单中设置初级、中级、高级、自定义、声音、扫雷英雄榜这几个菜单项,帮助菜单中设置游戏规则和制作人员两个菜单项。
背景说明:a.软件名称:扫雷b.用户:所有扫雷游戏爱好者系统概述扫雷游戏的基本要求Windows 2000/XP系统提供的扫雷游戏是一个很有趣的游戏。
本章的课程设计使用Java语言编写一个与其类似的扫雷游戏。
具体要求如下:(1) 扫雷游戏分为初级、中级和高级三个级别。
单击游戏菜单可以选择“初级”、“中级”和“高级”。
(2) 选择级别后将出现相应级别的扫雷区域,这时用户使用鼠标左键单击‘“开始”便启动计时器。
(3) 用户要揭开某个方块,可左键单击它。
若所揭方块下有雷,用户便输了这一局,若所揭方块下无雷,则显示一个数字,该数字代表方块的周围的8个方块中共有多少颗雷。
c语言扫雷源代码
c语言扫雷源代码扫雷游戏是一种非常经典的单人益智游戏,玩家需要根据数字提示找出地雷的位置。
下面给出一个简单的C语言扫雷游戏的源代码示例:```c#include <stdio.h>#include <stdlib.h>#include <time.h>#define SIZE 10 // 扫雷游戏的大小#define MINE_COUNT 10 // 地雷的数量typedef struct {int x;int y;} Position;typedef struct {int isMine; // 是否是地雷int isFlagged; // 是否被标记为地雷int isRevealed; // 是否已被翻开int adjacentMines; // 相邻地雷的数量} Cell;Cell board[SIZE][SIZE];void initializeBoard() {int i, j;// 初始化游戏面板for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {board[i][j].isMine = 0;board[i][j].isFlagged = 0;board[i][j].isRevealed = 0;board[i][j].adjacentMines = 0;}}}void generateMines() {int i, j;int count = 0;srand(time(NULL)); // 以当前时间作为随机数种子 while (count < MINE_COUNT) {i = rand() % SIZE;j = rand() % SIZE;// 如果该格子已经是地雷,则重新生成随机位置 if (!board[i][j].isMine) {board[i][j].isMine = 1;count++;}}}void calculateAdjacentMines() {int i, j, k, l;int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};for (i = 0; i < SIZE; i++) {for (j = 0; j < SIZE; j++) {if (!board[i][j].isMine) {for (k = 0; k < 8; k++) {int ni = i + dx[k];int nj = j + dy[k];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && board[ni][nj].isMine) {board[i][j].adjacentMines++;}}}}}}void displayBoard() {int i, j;printf(" ");for (i = 0; i < SIZE; i++) {printf("%d ", i);}printf("\n");for (i = 0; i < SIZE; i++) {printf("%d ", i);for (j = 0; j < SIZE; j++) {if (board[i][j].isRevealed) {if (board[i][j].isMine) {printf("M ");} else {printf("%d ", board[i][j].adjacentMines);}} else if (board[i][j].isFlagged) {printf("F ");} else {printf(". ");}}printf("\n");}}void revealAdjacentEmptyCells(Position pos) {int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1};int dy[] = {-1, 0, 1, -1, 1, -1, 0, 1};int i;for (i = 0; i < 8; i++) {int ni = pos.x + dx[i];int nj = pos.y + dy[i];if (ni >= 0 && ni < SIZE && nj >= 0 && nj < SIZE && !board[ni][nj].isRevealed && !board[ni][nj].isMine) { board[ni][nj].isRevealed = 1;if (board[ni][nj].adjacentMines == 0) {Position newPos;newPos.x = ni;newPos.y = nj;revealAdjacentEmptyCells(newPos);}}}}int main() {Position pos;char cmd;int isSuccess = 0;initializeBoard();generateMines();calculateAdjacentMines();displayBoard();while (!isSuccess) {printf("Enter command (R: reveal, F: flag): ");fflush(stdout);scanf(" %c", &cmd);printf("Enter position (x, y): ");fflush(stdout);scanf("%d %d", &(pos.x), &(pos.y));if (cmd == 'R') {board[pos.x][pos.y].isRevealed = 1;if (board[pos.x][pos.y].isMine) {printf("Game Over!\n");isSuccess = 1;} else if (board[pos.x][pos.y].adjacentMines == 0) {revealAdjacentEmptyCells(pos);}} else if (cmd == 'F') {board[pos.x][pos.y].isFlagged = 1;}displayBoard();}return 0;}```上述代码实现了一个简单的C语言扫雷游戏。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.awt.BorderLayout;import java.awt.Container;import java.awt.Font;import java.awt.GridLayout;import java.awt.Insets;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.Timer;public class ScanLei1 extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L;private Container contentPane;private JButton btn;private JButton[] btns;private JLabel b1;private JLabel b2;private JLabel b3;private Timer timer;private int row=9;private int col=9;private int bon=10;private int[][] a;private int b;private int[] a1;private JPanel p,p1,p2,p3;public ScanLei1(String title){super(title);contentPane=getContentPane();setSize(297,377);this.setBounds(400, 100, 400, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timer =new Timer(1000,(ActionListener) this);a = new int[row+2][col+2];initGUI();}public void initGUI(){p3=new JPanel();b=bon;JMenuBar menuBar=new JMenuBar();JMenu menu1=new JMenu("游戏");JMenu menu2=new JMenu("帮助");JMenuItem mi1=new JMenuItem("初级");JMenuItem mi2 = new JMenuItem("中级");JMenuItem mi3 =new JMenuItem("高级");mi1.addActionListener(this);menu1.add(mi1);mi2.addActionListener(this);menu1.add(mi2);mi3.addActionListener(this);menu1.add(mi3);menuBar.add(menu1);menuBar.add(menu2);p3.add(menuBar);b1=new JLabel(bon+"");a1=new int[bon];btn =new JButton("开始");btn.addActionListener(this);b2=new JLabel("0");b3=new JLabel("");btns=new JButton[row*col];p=new JPanel();p.setLayout(new BorderLayout());contentPane.add(p);p.add(p3,BorderLayout.NORTH);//combo=new JComboBox(new Object[]{"初级","中级","高级"} );//加监听/*combo.addItemListener(new ItemListener(){}});*/p1=new JPanel();//在那个位置//(( FlowLayout)p1.getLayout()).setAlignment( FlowLayout.RIGHT);p1.add(b1);p1.add(btn);p1.add(b2);p1.add(b3);p.add(p3,BorderLayout.NORTH);p.add(p1,BorderLayout.CENTER);p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton("");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p,BorderLayout.NORTH);contentPane.add(p2,BorderLayout.CENTER);}public void go(){setVisible(true);}public static void main(String[] args){new ScanLei1("扫雷").go();}public void out(int[][] a,JButton[] btns,ActionEvent e,int i,int x,int y){int p=1;if(a[x][y]==0){a[x][y]=10;btns[i].setEnabled(false); //33for(int l=y-1;l<=y+1;l++){int m=x-1-1;int n=l-1;p=1;System.out.println(a[1][2]);if(n>-1&&n<col&&m>-1&&m<row){for(int q=0;q<row&&p==1;q++){//col-->row;if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x-1][l]!=0&&a[x-1][l]!=10){btns[n+col*q].setText(a[x-1][l]+"");a[x-1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x-1][l]==0){//a[x-1][l]=10;btns[n+col*q].setEnabled(false);out(a,btns,e,n+col*q,x-1,l);////55////a[x-1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x+1][l]!=0&&a[x+1][l]!=10){btns[n+col*q].setText(a[x+1][l]+"");a[x+1][l]=10;btns[n+col*q].setEnabled(false);}else if(a[x+1][l]==0){out(a,btns,e,n+col*q,x+1,l);///55////a[x+1][l]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}int m=x-1;int n=y-1-1;p=1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y-1]!=0&&a[x][y-1]!=10){btns[n+col*q].setText(a[x][y-1]+"");a[x][y-1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y-1]==0){out(a,btns,e,n+col*q,x,y-1);a[x][y-1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}p=1;m=x-1;n=y+1-1;if(n>-1&&n<col&&m>-1&&m<col){for(int q=0;q<row&&p==1;q++){if(((n+col*q)>=(m*col))&&((n+col*q)<(m+1)*col)){if(a[x][y+1]!=0&&a[x][y+1]!=10){btns[n+col*q].setText(a[x][y+1]+"");a[x][y+1]=10;btns[n+col*q].setEnabled(false);}else if(a[x][y+1]==0){out(a,btns,e,n+col*q,x,y+1);a[x][y+1]=10;btns[n+col*q].setEnabled(false);}p=0;}}}}}public void actionPerformed(ActionEvent e) {if(e.getActionCommand()=="初级"){row=9;col=9;bon=10;a1=new int[bon];b=bon;//setSize(297,377);a = new int[row+2][col+2];this.remove(p2);timer.stop();b1.setText("10");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(297,377);this.pack();for(int i=0;i<row*col;i++){btns[i].setText(" ");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="中级"){row=16;col=16;bon=40;//setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("40");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);this.pack();//setSize(33*col,33*row+80);for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}else if(e.getActionCommand()=="高级"){row=16;col=32;bon=99;setSize(33*col,33*row+80);a1=new int[bon];a = new int[row+2][col+2];b=bon;this.remove(p2);timer.stop();b1.setText("99");b2.setText("0");b3.setText("");btns=new JButton[row*col];p2=new JPanel();p2.setLayout(new GridLayout(row,col,0,0));for(int i=0;i<row*col;i++){btns[i]=new JButton(" ");btns[i].setMargin(new Insets(0,0,0,0));btns[i].setFont(new Font(null,Font.BOLD,25));btns[i].addActionListener(this);btns[i].addMouseListener(new NormoreMouseEvent());p2.add(btns[i]);}contentPane.add(p2,BorderLayout.CENTER);//setSize(33*col,33*row+80);this.pack();for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}}if(e.getSource()==btn){timer.start();b=bon;b3.setText("");//System.out.println(bon);//清空for(int i=0;i<row*col;i++){btns[i].setText("");btns[i].setEnabled(true);}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){a[i][j]=0;}}//产生随机数for(int i=0;i<bon;i++){ int p=1;int m=(int)(Math.random()*row*col);while(p==1){int l=1;int j;for( j=0;j<i&&l==1;j++){if(a1[j]==m){m=(int)(Math.random()*row*col);l=0;}}if(j==i){a1[i]=m;p=0;}}}b1.setText(bon+"");b2.setText("0");//布雷for(int i=0;i<bon;i++){int x=(a1[i]/col+1);int y=(a1[i]%col+1);a[x][y]=100;}for(int i=0;i<row+2;i++){for(int j=0;j<col+2;j++){if(i==0||j==0||i==row+1||j==col+1){a[i][j]=0;}}}for(int i=1;i<=row;i++){for(int j=1;j<=col;j++){if(a[i][j]!=100){for(int l=j-1;l<=j+1;l++){if(a[i-1][l]==100){a[i][j]++;}if(a[i+1][l]==100){a[i][j]++;}}if(a[i][j-1]==100){a[i][j]++;}if(a[i][j+1]==100){a[i][j]++;}}}}}if(e.getSource()==timer){String time=b2.getText().trim();int t=Integer.parseInt(time);//System.out.println(t);if(t>=600){timer.stop();}else{t++;b2.setText(t+"");}}for(int i=0;i<col*row;i++){if(btns[i].getText()!="★"){int x=i/col+1;int y=i%col+1;if(e.getSource()==btns[i]&&a[x][y]==100){btns[i].setText("★");btns[i].setEnabled(false);a[x][y]=10;for(int k=0;k<col*row;k++){int m1=k/col+1;int n1=k%col+1;if(a[m1][n1]!=10&&btns[k].getText()=="★"){btns[k].setText("*o*");}}for(int j=0;j<col*row;j++){int m=j/col+1;int n=j%col+1;if(a[m][n]==100){btns[j].setText("★");btns[j].setEnabled(false);b3.setText("你输了!!");}btns[j].setEnabled(false);a[m][n]=10;}timer.stop();}else if(e.getSource()==btns[i]){if(a[x][y]==0){out(a,btns,e,i,x,y);a[x][y]=10;btns[i].setEnabled(false);}if(a[x][y]!=0&&a[x][y]!=10){btns[i].setText(a[x][y]+"");btns[i].setEnabled(false);a[x][y]=10;}}}else if(btns[i].getText()=="★"){}}}class NormoreMouseEvent extends MouseAdapter{public void mouseClicked(MouseEvent e) {System.out.println(b);for(int i=0;i<col*row;i++){int x1=i/col+1;int y1=i%col+1;if(e.getSource()==btns[i]&&btns[i].getText()!="★"&&a[x1][y1]!=10) {if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("★");b--;if(b==0){int flag=0;for(int j=0;j<col*row;j++){int x=j/col+1;int y=j%col+1;if(a[x][y]==100&&btns[j].getText()=="★"){flag++;}}if(flag==bon){timer.stop();b3.setText("你赢了!");}}b1.setText(b+"");}}elseif(e.getSource()==btns[i]&&btns[i].getText()=="★"&&a[x1][y1]!=-1){if(e.getButton()==MouseEvent.BUTTON3){btns[i].setText("");b++;if(b>bon){b1.setText(bon+"");}else{b1.setText(b+"");}btns[i].setEnabled(true);}}}}}}。