扫雷游戏源代码

合集下载

扫雷游戏部分代码

扫雷游戏部分代码

//设置状态#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) //如果在右边界,判断左,上,下有没有雷{····}}。

C语言扫雷(自带外挂)

C语言扫雷(自带外挂)
//---------------------外挂启动方法:输入11 11-------------------------//
void setmine(char n[9][9])
{
int a,b;
srand(time(NULL));
for(int k=0;k<=9;)
{
a=(rand())%9;
printf("You are %d steps away from Success!!!GO on!!!\n",left-10);
if(w-1==10&&e-1==10)
goto read1;//外挂部分,直接跳到胜利条件中间
//-----------------------布雷-----------------------------------------//
if(n[w-1][e-1]=='*')
{
printf("You stepped on a BOMB! GAME OVER!!!!!!!!!\n");//点到地雷,游戏失败
break;
}
else
{
void spread(int r,int c,char n[9][9],int mask[9][9]);
}
goto read;
}
}
}
//----------------------------------------------------------------//
void spread(int r,int c,char n[9][9],int mask[9][9])

Android的扫雷游戏源代码

Android的扫雷游戏源代码
(blockDimension + 2 * blockPadding)* numberOfColumnsInMineField,blockDimension + 2 * blockPadding));
}
}
私人无效endExistingGame()
{
stopTimer(); / /停止,如果计时器正在运行
{
/ /我们为每方一列额外的行
/ /整体两个额外的两个额外的行和列
/ /第一个和最后一个行/列用于计算仅
/ / x |的xxxxxxxxxxxxxx | x
/ / ------------------
/ / X的| | x
/ / X的| | x
/ / ------------------
块[行] [列] setPadding(blockPadding,blockPadding,blockPadding,blockPadding)。
tableRow.addView(块[行] [列]);
}
mineField.addView(TableRow的,新的youtParams(
txtTimer.setText(“000”); / /恢复所有文本
txtMineCount.setText(“000”); / /恢复矿山数量
btnSmile.setBackgroundResource(R.drawable.smile);
/ /删除所有行雷区TableL是处理LongClick
/ /如果块没有再发现标记附近区
/ /直到我们得到编号地雷
如果(!块[currentRow] [currentColumn]。isFlagged())

C#带你玩扫雷(附源码)

C#带你玩扫雷(附源码)

C#带你玩扫雷(附源码)扫雷游戏,⼤家都应该玩过吧!其实规则也很简单,可是我们想⾃⼰实现⼀个扫雷,我们应该怎么做呢?Step1: 知晓游戏原理扫雷就是要把所有⾮地雷的格⼦揭开即胜利;踩到地雷格⼦就算失败。

游戏主区域由很多个⽅格组成。

使⽤⿏标左键随机点击⼀个⽅格,⽅格即被打开并显⽰出⽅格中的数字;⽅格中数字则表⽰其周围的8个⽅格隐藏了⼏颗雷;如果点开的格⼦为空⽩格,即其周围有0颗雷,则其周围格⼦⾃动打开;如果其周围还有空⽩格,则会引发连锁反应;在你认为有雷的格⼦上,点击右键即可标记雷;如果⼀个已打开格⼦周围所有的雷已经正确标出,则可以在此格上同时点击⿏标左右键以打开其周围剩余的⽆雷格。

1代表1的上下左右及斜⾓合计有⼀颗雷,依次轮推,2则有2颗,3则有3颗..在确实是炸弹的⽅格上点了旗⼦,就安全了,不是炸弹的被点了旗⼦,后⾯会被炸死的..问号就先不确定这⾥有没有炸弹,不会存在点错了被炸死的状况..Step2: 由step1可知,游戏由格⼦组成,翻译成代码语⾔就叫做数组,也就是游戏地图就是⼀个⼆维数组。

格⼦对象,格⼦的值即当前雷的数量,那么此时我们暂定雷的数字标识为-1。

除此之外,格⼦对象还有是否被显⽰,显⽰当前雷数量等属性,那么我们⼤概可以定义这样⼀个类:public class CellBlockRole{/// <summary>/// 位于游戏地图中的坐标点X/// </summary>public int X { get; set; }/// <summary>/// 位于游戏地图中的坐标点Y/// </summary>public int Y { get; set; }/// <summary>/// 是否展⽰最后格⼦所代表的结果/// </summary>public bool IsShowResult { get; set; } = false;/// <summary>/// 是否计算数字结果/// </summary>public bool IsComputeResult { get; set; } = false;/// <summary>/// 是否已经展⽰过计算结果了/// </summary>public bool IsHasShowComputed { get; set; } = false;/// <summary>/// 当前的格⼦的⾓⾊数字, -1:地雷,其他当前雷的数量/// </summary>public int Number { set; get; } = 0;/// <summary>/// 是否被Flag标识/// </summary>public bool IsFlag { get; set; } = false;/// <summary>/// 是否是雷/// </summary>public bool IsBoom => Number == -1;}绘制游戏UI画⾯,见代码:using System;using System.Collections.Generic;using ponentModel;using System.Drawing;using System.Data;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;using SweeperLibrary.Properties;using Timer = System.Threading.Timer;namespace SweeperLibrary{public delegate void OnGameOverDelegate();public delegate void OnShowANumberDelegate();public delegate void OnPublishGameTimeDelegate(string timeDescription);public partial class GameView : UserControl{/// <summary>/// 游戏结束事件/// </summary>public event OnGameOverDelegate OnGameOverEvent;/// <summary>/// 当⼀个格⼦被点击时,显⽰当前数字的事件/// </summary>public event OnShowANumberDelegate OnShowANumberEvent;/// <summary>/// 发布当前游戏的时间/// </summary>public event OnPublishGameTimeDelegate OnPublishGameTimeEvent;/// <summary>/// 游戏绘制地图的每个格⼦的⼤⼩/// </summary>public static readonly int CellSize = 40;/// <summary>/// 游戏规模N*N/// </summary>public static readonly int GameCellCount = 10;/// <summary>/// 移动⽅向坐标点改变的数组/// </summary>public static readonly int[][] MoveDirectionPoints = {new[]{-1, -1},new[] {0, -1},new[] {1, -1},new[] {1, 0},new[] {1, 1},new[] {0, 1},new[] {-1, 1},new[] {-1, 0}};/// <summary>/// 随机数雷⽣成对象/// </summary>private static readonly Random random = new Random(Guid.NewGuid().GetHashCode()); /// <summary>/// 游戏地图标识数组/// </summary>private CellBlockRole[][] gameMap = new CellBlockRole[GameCellCount][];/// <summary>/// 雷的数量,默认为10/// </summary>public int BoomCount { get; set; } = 10;/// <summary>/// 游戏开始时间/// </summary>private DateTime gameStartTime;/// <summary>/// 计时定时器/// </summary>private System.Windows.Forms.Timer gameTimer = new System.Windows.Forms.Timer();public GameView(){InitializeComponent();SetStyle(ControlStyles.OptimizedDoubleBuffer, true);SetStyle(ControlStyles.AllPaintingInWmPaint, true);InitGame(); //默认游戏已经开始SetGameTimer(); //设置游戏定时器}private void GameView_Paint(object sender, PaintEventArgs e){Width = GameCellCount + 1 + GameCellCount * CellSize;Height = GameCellCount + 1 + GameCellCount * CellSize;//绘制游戏界⾯Graphics graphics = e.Graphics;graphics.Clear(Color.WhiteSmoke);if (gameMap != null && gameMap.Length > 0 && gameMap[0] != null && gameMap[0].Length > 0){for (int y = 0; y < GameCellCount; y++){for (int x = 0; x < GameCellCount; x++){int dx = x + 1 + x * CellSize,dy = y + 1 + y * CellSize;CellBlockRole cellBlockRole = gameMap[y][x];graphics.FillRectangle(new SolidBrush(cellBlockRole.IsShowResult ? Color.LightSlateGray : Color.WhiteSmoke),dx, dy, CellSize, CellSize);graphics.DrawRectangle(new Pen(Color.LightGray), dx, dy, CellSize, CellSize);if (cellBlockRole.IsShowResult && cellBlockRole.Number != 0){switch (cellBlockRole.Number){case -1: //雷graphics.DrawImage(Image.FromHbitmap(Resources.boom.GetHbitmap()), new RectangleF(dx, dy, CellSize, CellSize)); break;default: //数字string drawText = cellBlockRole.Number.ToString();Font textFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);SizeF textSize = graphics.MeasureString(drawText, textFont);graphics.DrawString(drawText, textFont, new SolidBrush(Color.White),dx + (CellSize - textSize.Width) / 2, dy + (CellSize - textSize.Height) / 2);break;}}}}}}private void GameView_MouseDown(object sender, MouseEventArgs e){int px = (e.X - 1) / (CellSize + 1),py = (e.Y - 1) / (CellSize + 1);switch (e.Button){case MouseButtons.Left: //⿏标左键if (!gameMap[py][px].IsShowResult){if (gameMap[py][px].IsBoom){new Thread(() =>{ShowAllCellBlockRoleNumber();if (this.InvokeRequired){MethodInvoker del = Invalidate;this.Invoke(del);} else{Invalidate();}}).Start();gameTimer.Stop();OnGameOverEvent?.Invoke();} else{new Thread(() =>{ShowNeiborhoodCellRolesByPosi(px, py);if (this.InvokeRequired){MethodInvoker del = Invalidate;this.Invoke(del);} else{Invalidate();}}).Start();OnShowANumberEvent?.Invoke();}}break;case MouseButtons.Right: //⿏标右键break;}}/// <summary>/// 初始化游戏/// </summary>private void InitGame(){new Thread(() =>{InitGameMap();GenerateBooms();if (this.InvokeRequired){MethodInvoker del = Invalidate;this.Invoke(del);} else{Invalidate();}}).Start();}/// <summary>/// 设置游戏定时器/// </summary>private void SetGameTimer(){gameTimer.Interval = 1000;gameTimer.Enabled = true;gameTimer.Tick += (sender, args) =>{long dMillisecond = lisecond - lisecond;long hour = dMillisecond / 60 / 60 / 1000;long minute = (dMillisecond - hour * (60 * 60 * 1000)) / (60 * 1000);long second = ((dMillisecond - hour * (60 * 60 * 1000)) % (60 * 1000)) / 1000;OnPublishGameTimeEvent?.Invoke((hour > 0 ? (hour > 9 ? hour.ToString() : "0" + hour) + ":" : "")+ (minute > 9 ? minute.ToString() : "0" + minute) + ":" + (second > 9 ? second.ToString() : "0" + second)); };}/// <summary>/// 初始化游戏地图/// </summary>private void InitGameMap(){for (int i = 0; i < GameCellCount; i++){gameMap[i] = new CellBlockRole[GameCellCount];for (int j = 0; j < GameCellCount; j++)gameMap[i][j] = new CellBlockRole{X = j,Y = i};}}gameStartTime = DateTime.Now;gameTimer.Start();}/// <summary>/// 重置游戏地图/// </summary>public void ResetGameMap(){new Thread(() =>{for (int i = 0; i < GameCellCount; i++){for (int j = 0; j < GameCellCount; j++){gameMap[i][j].X = j;gameMap[i][j].Y = i;gameMap[i][j].Number = 0;gameMap[i][j].IsShowResult = false;gameMap[i][j].IsComputeResult = false;gameMap[i][j].IsHasShowComputed = false;}}GenerateBooms(); //⽣成⼀些雷if (this.InvokeRequired){MethodInvoker del = Invalidate;this.Invoke(del);} else{Invalidate();}}).Start();gameStartTime = DateTime.Now;gameTimer.Start();}/// <summary>/// 随机⽣成⼀些地雷/// </summary>public void GenerateBooms(){for (int i = 0; i < BoomCount; i++){int boomNumberIndex = random.Next(0, GameCellCount * GameCellCount - 1); //⽣成随机数的范围 int boomX = boomNumberIndex % GameCellCount,boomY = boomNumberIndex / GameCellCount;if (gameMap[boomY][boomX].Number == 0)gameMap[boomY][boomX].Number = -1; //-1表⽰雷else // 已经存在雷了,所以要重新处理i--;}MakeAllNumberComputeInCellRole(0, 0); //默认从坐标(0,0)开始}/// <summary>/// 显⽰所有的格⼦的信息/// </summary>private void ShowAllCellBlockRoleNumber(){for (int i = 0; i < GameCellCount; i++){for (int j = 0; j < GameCellCount; j++){gameMap[i][j].IsShowResult = true;}}/// <summary>/// 显⽰某点周边所有格⼦的数字/// </summary>/// <param name="posiX">X轴坐标</param>/// <param name="posiY">Y轴坐标</param>private void ShowNeiborhoodCellRolesByPosi(int posiX, int posiY){gameMap[posiY][posiX].IsShowResult = true;gameMap[posiY][posiX].IsHasShowComputed = true;int boomCount = GetBoomCountInNeiborhood(posiX, posiY);if (boomCount == 0) //如果周围没有雷,则翻开所有8个⽅向的相关数字{for (int i = 0; i < MoveDirectionPoints.Length; i++){int[] itemPosi = MoveDirectionPoints[i];int rx = posiX + itemPosi[0],ry = posiY + itemPosi[1];bool isNotOutIndexRange = rx >= 0 && rx < GameCellCount && ry >= 0 && ry < GameCellCount; if (isNotOutIndexRange) //防⽌坐标溢出{gameMap[ry][rx].IsShowResult = true;if (!gameMap[ry][rx].IsHasShowComputed && gameMap[ry][rx].Number == 0)ShowNeiborhoodCellRolesByPosi(rx, ry);}}}}/// <summary>/// 获取某点附近的雷数量/// </summary>/// <param name="posiX">X轴坐标点</param>/// <param name="posiY">Y轴坐标点</param>/// <returns></returns>private int GetBoomCountInNeiborhood(int posiX, int posiY){int boomCount = 0;for (int i = 0; i < MoveDirectionPoints.Length; i++){int[] itemPosi = MoveDirectionPoints[i];int rx = posiX + itemPosi[0],ry = posiY + itemPosi[1];bool isNotOutIndexRange = rx >= 0 && rx < GameCellCount && ry >= 0 && ry < GameCellCount; if (isNotOutIndexRange && gameMap[ry][rx].IsBoom) //防⽌坐标溢出{boomCount++;}}return boomCount;}/// <summary>/// 计算每个格⼦的数字标识/// </summary>/// <param name="posiX">X轴坐标</param>/// <param name="posiY">Y轴坐标</param>private void MakeAllNumberComputeInCellRole(int posiX, int posiY){int boomCount = GetBoomCountInNeiborhood(posiX, posiY);if (boomCount != 0) //如果周围没有雷,则计算周围的8个⽅向的格⼦{gameMap[posiY][posiX].Number = boomCount;} else{if (!gameMap[posiY][posiX].IsBoom)gameMap[posiY][posiX].Number = 0;}gameMap[posiY][posiX].IsComputeResult = true;for (int i = 0; i < MoveDirectionPoints.Length; i++){int[] itemPosi = MoveDirectionPoints[i];int rx = posiX + itemPosi[0],ry = posiY + itemPosi[1];bool isNotOutIndexRange = rx >= 0 && rx < GameCellCount && ry >= 0 && ry < GameCellCount;if (isNotOutIndexRange && !gameMap[ry][rx].IsComputeResult && !gameMap[ry][rx].IsBoom) //防⽌坐标溢出{MakeAllNumberComputeInCellRole(rx, ry);}}}}}主要代码已经实现,现已知现有代码的定时器由问题,暂时不⽀持Flag(旗⼦标识)。

c语言扫雷程序代码

c语言扫雷程序代码
for(j=0;j<2;j++) if(b[x+i][y+j]==11) n++;
if(n==0) {
for(i=0;i<2;i++) for(j=0;j<2;j++) { if(b[x+i][x+j]==10) { b[x+i][y+j]=0; printf_0(b,x+i,y+j); } }
} else b[x][y]=n; } else if(x==0&&y<Map_list-1&&y>0) { n=0; for(i=0;i<2;i++)
for(j=-1;j<2;j++) if(b[x+i][y+j]==11) n++;
if(n!=0) b[x][y]=n;
else for(i=0;i<2;i++)
for(j=-1;j<2;j++) {
if(b[x+i][y+j]==10) {
b[x+i][y+j]=0; printf_0(b,x+i,y+j); } } } else if(x==0&&y==Map_list-1) { n=0; for(i=0;i<2;i++) for(j=-1;j<1;j++) if(b[x+i][y+j]==11) n++; if(n!=0) b[x][y]=n; else for(i=0;i<2;i++) for(j=-1;j<1;j++) { if(b[x+i][y+j]==10) { b[x+i][y+j]=0; printf_0(b,x+i,y+j); } } } else if(y==Map_list-1&&x!=0&x!=Map_line-1) { n=0; for(i=-1;i<2;i++) for(j=-1;j<1;j++) if(b[x+i][y+j]==11) n++; if(n!=0) b[x][y]=n; else for(i=-1;i<2;i++) for(j=-1;j<1;j++) { if(b[x+i][y+j]==10) {

题目二扫雷游戏

题目二扫雷游戏
5、扫雷胜利后(用时最少者),程序弹出保存成绩的对话框。
2.3 总体设计
通常包括功能模块划分、功能模块层次、相关类文件及类的调用关系等。
在设计扫雷游戏时,需要编写7个Java源文件:MineGame.java、MineArea.java、Block.java、BlockView.java、LayMines.java、Record.java和ShowRecord.java。
}
else if(num<10)
{
JOptionPane.showMessageDialog(null,"您设置的地雷数太少了,请重设!","错误",
JOptionPane.ERROR_MESSAGE);//错误提示
num=10;
BombNum=num;
}
else
{
JOptionPane.showMessageDialog(null,"您设置的地雷数太多了,请重设!","错误",
扫雷只有一个类,这个类包含多个函数,每个函数具有不同的功能,在主函数里调用,从而生成扫雷。
2.4.2类成员变量及方法设计
介绍各个类的成员变量及方法的设计细节,详细阐述主要方法的算法逻辑。
2.4.3类图及关键算法流程图
2.4.4源代码分析
详细阐述主要功能实现涉及的类及方法,要求对关键代码段进行分析,简述其设计思路。
{
for(int j=0;j<(int)Math.sqrt(BlockNum);j++)
{
bombButton[i][j].isBomb=false;
bombButton[i][j].isClicked=false;

扫雷项目源代码详解

扫雷项目源代码详解

主函数所在处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。

扫雷游戏Java源代码

扫雷游戏Java源代码

扫雷游戏Java源代码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;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);}}}}}}。

VB 扫雷游戏程序

VB 扫雷游戏程序

5.2.3 关于窗体设计.......................................................................................... 11 5.4 运行界面.......................................................................................................... 11 6 系统测试................................................................................................................... 13 结束语.......................................................................................................................... 14 参考文献...................................................................................................................... 16 附录.............................................................................................................................. 17
3
唐山学院课程设计 及右键,则 Button 值为 1+2=3. 在本游戏中,利用右键的 MouseDown 事件标示“已标示”方块,利用左键的 MouseDown 事件,标示使用者准备按下的方块,利用左键的 MouseUp 事件确定翻 开的方块。 4. ImageList 组件 利用 Imagelist 可以存储显示方块的图形[2]。将组件布置于窗体上后编辑组 件属性,通过【插入图片】按钮和【删除图片】按钮即可编辑组件内所存放的图 片。如图 1 所示。因为一个 Imagelist 组件内必须存储大小相同的图片,所在这 款游戏设计中,显示的图片共分为三个部分:游戏状态图形、数字计数图形和地 雷区标示图形。

java课程设计——扫雷

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是我们的真实雷区不做改动,接下来讲讲核⼼的具体实现。

扫雷小游戏代码c++版

扫雷小游戏代码c++版

#include<iostream>#include<ctime>#include<cstdlib>using namespace std;int lei;int line,arrange,thunder1,thunder2,space;void saolei(char **&a,char **&c,int **&b,int **&d,int **&e,int **&g,int &line,int &arrange,int &thunder1,int &thunder2,int &space){int all=1;while(all){int i,j;a=new char*[line],c=new char*[line],b=new int*[line],d=new int*[line],e=new int*[line],g=new int*[line];for(i=0;i<=line-1;i++)a[i]=new char[arrange],c[i]=new char[arrange],b[i]=new int[arrange],d[i]=newint[arrange],e[i]=new int[arrange],g[i]=new int[arrange];for(i=0;i<line;i++)for(j=0;j<arrange;j++)a[i][j]='.',b[i][j]=0,c[i][j]='.',e[i][j]=0,g[i][j]=0;int k;srand(int(time(0)));int z=1;while(z){k=rand()%(thunder2+1);if(k>=thunder1)z=0;}srand(int(time(0)));for(i=1;i<=k;i++){int s,t;L:{s=rand()%line;t=rand()%arrange;}if(!(s>=0&&s<line&&t>=0&&t<arrange&&a[s][t]!='#'))goto L;for(int m=0;m<line;m++)for(int n=0;n<arrange;n++){if(m==s&&n==t&&a[m][n]!='#')a[m][n]='#';}}for(i=0;i<line;i++)for(j=0;j<arrange;j++){if(j-1>=0&&a[i][j-1]=='#')if(j+1<arrange&&a[i][j+1]=='#')b[i][j]++;if(i-1>=0&&a[i-1][j]=='#')b[i][j]++;if(i+1<line&&a[i+1][j]=='#')b[i][j]++;if(i-1>=0&&j+1<arrange&&a[i-1][j+1]=='#')b[i][j]++;if(i-1>=0&&j-1>=0&&a[i-1][j-1]=='#')b[i][j]++;if(i+1<line&&j+1<arrange&&a[i+1][j+1]=='#')b[i][j]++;if(j-1>=0&&i+1<line&&a[i+1][j-1]=='#')b[i][j]++;}int f=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++){if(a[i][j]=='#')d[i][j]=2;else {if(j-1>=0&&a[i][j-1]=='.')f++;if(j+1<arrange&&a[i][j+1]=='.')f++;if(i-1>=0&&a[i-1][j]=='.')f++;if(i+1<line&&a[i+1][j]=='.')f++;if(i-1>=0&&j+1<arrange&&a[i-1][j+1]=='.')f++;if(i-1>=0&&j-1>=0&&a[i-1][j-1]=='.')f++;if(i+1<line&&j+1<arrange&&a[i+1][j+1]=='.')f++;if(j-1>=0&&i+1<line&&a[i+1][j-1]=='.')f++;if(i-1>=0&&i+1<line&&j-1>=0&&j+1<arrange){if(f==8)d[i][j]=1;else d[i][j]=0;}else if(i==0&&j==0||i==0&&j==arrange-1||i==line-1&&j==0||i==line-1&&j==arrange-1) {if(f==3)else d[i][j]=0;}else{if(i==0&&j!=0&&j!=arrange-1||i==line-1&&j!=arrange-1&&j!=0||i!=line-1&&i!=0&&j==0||i!=line-1&&i!=0&&j==arrange-1){if(f==5)d[i][j]=1;else d[i][j]=0;}}f=0;}}int x,y,left=0,right=0,hang,shu,duan=0,jishu=0;z=1;for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";}cout<<i+1<<" ";for(j=0;j<arrange;j++)cout<<c[i][j]<<" ";cout<<endl;}while(z){cout<<"请输入你要翻开的位置(如:6 0 或5 6 1 ):";cin>>x>>y>>lei;x--,y--;if(a[x][y]=='#')e[x][y]=1;if(a[x][y]=='.'){if(b[x][y]!=0)e[x][y]=1;if(b[x][y]==0){for(i=0;i<line&&duan==0;i++)for(j=0;j<arrange&&duan==0;j++)if(d[i][j]==1){d[i][j]=3;int dir=3,fu=0,pan=1,ci=0;int m=i,n=j;do{ switch(dir){ case 1 : //向左走{if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置右边else if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置前方else if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置左边else if(n+1<arrange&&d[m][n+1]==1){d[m][n+1]=3;n++;dir=3;} //检测所在位置后方else if(m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置右边else if (n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置前方else if (m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置左边else {if(n+1<arrange&&d[m][n+1]==3){n++;dir=3;}} //检测所在位置后方}break;case 2 : //向上走{if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置右边else if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置前方else if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置左边else if(m+1<line&&d[m+1][n]==1){d[m+1][n]=3;m++;dir=4;} //检测所在位置后方else if(n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置右边else if (m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置前方else if (n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置左边else {if(m+1<line&&d[m+1][n]==3){m++;dir=4;}} //检测所在位置后方}break;case 3 : //向右走{ if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置右边else if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置前方else if (m-1>=0&&d[m-1][n]==1) {d[m-1][n]=3;m--;dir=2;} //检测所在位置左边else if(n-1>=0&&d[m][n-1]==1){d[m][n-1]=3;n--;dir=1;} //检测所在位置后方else if(m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置右边else if (n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置前方else if (m-1>=0&&d[m-1][n]==3) {m--;dir=2;} //检测所在位置左边else {if(n-1>=0&&d[m][n-1]==3){n--;dir=1;}} //检测所在位置后方}break;case 4 : //向下走{if (n-1>=0&&d[m][n-1]==1) {d[m][n-1]=3;n--;dir=1;} //检测所在位置右边else if (m+1<line&&d[m+1][n]==1) {d[m+1][n]=3;m++;dir=4;} //检测所在位置前方else if (n+1<arrange&&d[m][n+1]==1) {d[m][n+1]=3;n++;dir=3;} //检测所在位置左边else if(m-1>=0&&d[m-1][n]==1){d[m-1][n]=3;m--;dir=2;} //检测所在位置后方else if(n-1>=0&&d[m][n-1]==3) {n--;dir=1;} //检测所在位置右边else if (m+1<line&&d[m+1][n]==3) {m++;dir=4;} //检测所在位置前方else if (n+1<arrange&&d[m][n+1]==3) {n++;dir=3;} //检测所在位置左边else {if(m-1>=0&&d[m-1][n]==3){m--;dir=2;}} //检测所在位置后方}break;}if(d[m][n]==3)ci++;if(ci>=line*arrange)pan=0;if(m==i&&n==j){fu++;if(fu==4)pan=0;}if(m==x&&n==y)left=i+1,right=j+1,duan=1;}while(pan);if(left==0&&right==0)for(hang=0;hang<line;hang++)for(shu=0;shu<arrange;shu++)if(d[hang][shu]==3)d[hang][shu]=1;}left=0,right=0,duan=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3)e[i][j]=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3){if(j-1>=0)e[i][j-1]=1;if(j+1<arrange)e[i][j+1]=1;if(i-1>=0)e[i-1][j]=1;if(i+1<line)e[i+1][j]=1;if(i-1>=0&&j+1<arrange)e[i-1][j+1]=1;if(i-1>=0&&j-1>=0)e[i-1][j-1]=1;if(i+1<line&&j+1<arrange)e[i+1][j+1]=1;if(j-1>=0&&i+1<line)e[i+1][j-1]=1;}}}//当b[x][y]==0时system("cls");//清屏for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(d[i][j]==3)d[i][j]=1;if(a[x][y]=='.'&&b[x][y]!=0&&lei!=2) {for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(i==x&&y==j)cout<<b[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}if(lei==1){jishu++;if(jishu<=3)cout<<"提示:判断错误"<<jishu<<"次,若判断错误超过三次,你将输掉游戏,注意哦o(︶︿︶)o"<<endl; }}//第一种情况if(a[x][y]=='.'&&b[x][y]==0&&lei!=2){for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<b[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}if(lei==1){jishu++;if(jishu<=3)cout<<"提示:判断错误"<<jishu<<"次,若判断错误超过三次,你将输掉游戏,注意哦o(︶︿︶)o"<<endl; }}//第二种情况if(a[x][y]=='#'&&lei==0)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9){for(k=1;k<=space;k++)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<a[i][j]<<" ";else if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}cout<<"oh my god 你输了!所有雷的位置已显示出,请再接再厉哦(*^__^*) 嘻嘻……"<<endl; z=0;}//第三种情况if(a[x][y]=='#'&&lei==1){for(i=1;i<=space;i++)cout<<" ";for(i=0;i<=line;i++)if(i<=9)cout<<i<<" ";else cout<<i;cout<<endl;for(i=0;i<line;i++){if(i<9)cout<<" ";cout<<i+1<<" ";}if(i>=9){for(k=1;k<=space-1;k++)cout<<" ";cout<<i+1<<" ";}for(j=0;j<arrange;j++)if(g[i][j]==1){if(a[i][j]=='#')cout<<a[i][j]<<" ";else cout<<b[i][j]<<" ";}else if(e[i][j]==1)cout<<a[i][j]<<" ";else cout<<c[i][j]<<" ";cout<<endl;}}//第四种情况if(lei==2||lei==3||lei==4)z=0,all=0;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(e[i][j]==1)g[i][j]=e[i][j];for(i=0;i<line;i++)for(j=0;j<arrange;j++)e[i][j]=0;int sum=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)sum*=g[i][j];if(sum!=0){cout<<"oh good 你赢了耶!( ^_^ )不错嘛"<<endl; z=0;}int total=1;for(i=0;i<line;i++)for(j=0;j<arrange;j++)if(a[i][j]=='#'){if(g[i][j]==1)total*=1;if(g[i][j]!=1)total*=0;}if(total!=0&&sum==0){cout<<"oh good 你赢了耶!( ^_^ )不错嘛"<<endl;z=0;}if(jishu>3){cout<<"how pitty! 错误判断超过三次,你输了,下次注意哦(*^__^*)"<<endl;z=0;}}//循环并判断是否继续循环}}int main(){L:{cout<<"游戏名称:扫雷"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"说明:.代表未翻开的地方;#表示雷;翻开地方显示的数字表示:该地方四周的八个相邻的地方含有雷的总数"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"规则:根据翻开地方显示的数字判断雷所在的地方"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"操作:根据判断,请输入位置(如:6 0/1/2/3/4)"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"解释:输入的三个数字中,前两个数字表示位置,如:表示行数,表示列数;第三个表示判断与选择,--无雷,--有雷,--再来一局,--结束游戏,--重启整个游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<'\n' <<"例如:5 6 0 表示游戏者认为该处无雷,6 1表示游戏者认为该处有雷,6 2表示再来一局,6 3表示结束游戏,6 4表示重启游戏系统"<<'\n'<<"--------------------------------------------------------------------------------"<<endl; int choice,i;char **a=NULL,**c=NULL;int **b=NULL,**d=NULL,**e=NULL,**g=NULL;cout<<"游戏等级有五:"<<'\n'<<"1--茅塞未开(方格x7, 雷数-->5)"<<'\n'<<"2--七窍通六(方格x10,雷数-->10)"<<'\n'<<"3--闲庭信步(方格x13,雷数-->15)"<<'\n'<<"4--炉火纯青(方格x15,雷数-->30)"<<'\n'<<"5--偶滴神呀(方格x25,雷数-->100)"<<'\n'<<"6--自定义难易程度"<<endl;cout<<"请选择:";cin>>choice;if(choice==1)line=7,arrange=7,thunder1=3,thunder2=5,space=33;if(choice==2)line=10,arrange=10,thunder1=7,thunder2=10,space=30;if(choice==3)line=13,arrange=13,thunder1=10,thunder2=15,space=27;if(choice==4)line=15,arrange=15,thunder1=15,thunder2=30,space=25;if(choice==5)line=25,arrange=25,thunder1=50,thunder2=100,space=15;if(choice==6){cout<<"请输入方格的行(行<=39):";cin>>line;cout<<"请输入方格的列(列<=39):";cin>>arrange;cout<<"希望出现雷的个数的范围(如:5):";cin>>thunder1>>thunder2;space=40-arrange;}if(choice<=0||choice>6||line<=0||arrange<=0||thunder2<thunder1||thunder2>line*arrange) {lei=3;goto M;}saolei(a,c,b,d,e,g,line,arrange,thunder1,thunder2,space);if(lei==2)saolei(a,c,b,d,e,g,line,arrange,thunder1,thunder2,space);M:{if(lei==3)cout<<"*******游戏结束,欢迎下次使用********"<<endl;}if(lei==4){system("cls");goto L;}for(i=0;i<=line-1;i++)delete []a[i],delete []b[i],delete []c[i],delete []d[i],delete []e[i],delete []g[i]; delete []a,delete []b,delete []c,delete []d,delete []e,delete []g;a=NULL,b=NULL,c=NULL,d=NULL,e=NULL,g=NULL;}}。

C语言代码实现简单扫雷小游戏

C语言代码实现简单扫雷小游戏

C语⾔代码实现简单扫雷⼩游戏⽤C语⾔写⼀个简单的扫雷,供⼤家参考,具体内容如下1.所需要的知识c语⾔的基本语法,简单的⼆维数组,⼀点简单的递归知识。

2.总体思路扫雷游戏主要由3个部分组成,埋雷⼦,扫雷,判断输赢。

扫雷游戏的主体是两个个字符类型的⼆维数组。

⼀个是mine[][]它的构成是'0'和‘1',其中'0'表⽰⽆雷,'1'表⽰有雷。

⼀个是show[][]它的构成是'*'和'数字'。

星号表⽰未开启的地⽅,数字表⽰周围的雷数。

这⾥要注意的是:mine和show的实际⼤⼩是11x11,但是展⽰的效果是 9x9。

这样做的优点将在Find()中体现。

蓝⾊部分是可见的9x9,实际的类似红⾊ 11x11。

下⾯是我⽤到的⼀些函数。

//game.h#pragma once#ifndef __GAME_H__#define __GAME_H__#include<stdio.h>#include<stdlib.h>#include<process.h>#include<string.h>#include<time.h>#define ROW 9 // 9⾏#define COL 9 // 9列#define ROWS ROW+2 //实际⾏#define COLS COL+2 //实际列#define MineNum 10 //雷⼦数量//菜单信息void menu();//执⾏菜单void test(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//游戏主体void game(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//打印雷阵void InitBoard(char arr[ROWS][COLS], int row, int col);//埋雷⼦void SetMine(char mine[ROWS][COLS], int row, int col);//找雷⼦int FindMine(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2);//空⽩算法void Find(char mine[ROWS][COLS], int row1, int col1, char show[ROWS][COLS], int row2, int col2,int x, int y,int exam[ROWS][COLS]);#endif//__GAME_H__下⾯是主函数内容#include"game.h"int main(){char mine[ROWS][COLS];char show[ROWS][COLS];srand ((unsigned int)time(NULL)); //⽣成随机数,⽤于随机埋雷int i = 0, j = 0;test(mine, ROWS, COLS, show, ROWS, COLS); //测试函数system("pause");return 0;}3.详细实现菜单函数void menu(){printf("******************\n");printf("******1.play *****\n");printf("******0.exit *****\n");printf("******************\n");}这个函数是⽤来打印信息的,打印⼀个简单的菜单。

扫雷源代码(精)

扫雷源代码(精)

#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; // 游戏胜利结束,正确的扫完了所有的雷}。

C语言程序设计扫雷游戏

C语言程序设计扫雷游戏

C语言程序设计报告题目: 扫雷小游戏设计电子通信与物理学院日期: 2018 年 7 月 12 日指导教师评语目录1. 课程设计容 (1)2. 课程设计目的 (1)3. 背景知识 (1)4. 工具/准备工作 (3)5. 设计步骤、方法 (3)5.1 (3)5.2定义全局变量 (4)5.3挖雷部分函数的分析 (5)6. 设计结果及分析 (11)7. 设计结论 (16)8. 参考文献 (17)附录 (17)1. 课程设计容在计算机逐步渗入社会生活各个层面的今天,计算机已经成为人们日常生活的一分,越来越多的人使用计算机办公、娱乐等等。

扫雷游戏是Windows操作系统自带的一款小游戏,在过去的几年里,Windows操作系统历经数次换代更新,变得越来越庞大、复杂,功能也越来越强大,但是这款小游戏依然保持原来的容貌,可见这款小游戏受到越来越多人的喜爱。

我利用C-free编写了与它功能相仿的挖地雷游戏,寓学于乐。

即:设计一个功能与Windows中的挖雷游戏相同的小游戏。

2. 课程设计目的1.培养学生综合运用所学知识独立完成课题的能力。

2.试学生更深入地理解和掌握该课程中的有关基本概念,程序设计思想和方法。

3.提高对工作认真负责、一丝不苟,对同学团结友爱,协作攻关的基本素质。

4.培养勇于探索、严谨推理、实事、有错必改,用实践来检验理论,全方位考虑问题等科学技术人员应具有的素质。

5.培养从资料文献、科学实验中获得知识的能力,提高从别人经验中找到解决问题的新途径的悟性,初步培养工程意识和创新能力。

6.对掌握知识的深度、运用理论去处理问题的能力、实验能力、课程设计能力、书面及口头表达能力进行考核3. 背景知识游戏区包括雷区、地雷计数器(位于左上角,记录剩余地雷数)和计时器(位于右上角,记录游戏时间),确定大小的矩形雷区中随机布置一定数量的地雷(初级为9*9个方块10个雷,中级为16*16个方块40个雷,高级为16*30个方块99个雷,自定义级别可以自己设定雷区大小和雷数,但是雷区大小不能超过24*30),玩家需要尽快找出雷区中的所有不是地雷的方块,而不许踩到地雷。

c语言编写扫雷代码

c语言编写扫雷代码

c语言编写扫雷代码示例编写扫雷游戏的代码涉及到图形界面、事件处理等,因此需要使用相应的库来简化这些操作。

下面是一个使用C语言和Simple DirectMedia Layer (SDL)库编写的简单扫雷游戏的代码示例。

请注意,这只是一个基本的示例,实际的扫雷游戏可能需要更多功能和复杂性。

首先,确保你已经安装了SDL库。

接下来,你可以使用以下代码作为一个简单的扫雷游戏的起点。

```c#include <SDL.h>#include <stdio.h>#include <stdlib.h>#include <time.h>// 游戏常量#define SCREEN_WIDTH 640#define SCREEN_HEIGHT 480#define CELL_SIZE 20#define ROWS 15#define COLS 20#define MINES 40// 游戏状态typedef struct {int revealed; // 是否被揭示int mine; // 是否是地雷int adjacent; // 相邻地雷数量} Cell;// 游戏数据Cell board[ROWS][COLS];// SDL 相关变量SDL_Window* window = NULL;SDL_Renderer* renderer = NULL;// 初始化游戏板void initializeBoard() {// 初始化每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {board[i][j].revealed = 0;board[i][j].mine = 0;board[i][j].adjacent = 0;}}// 随机生成地雷位置srand(time(NULL));for (int k = 0; k < MINES; ++k) {int i = rand() % ROWS;int j = rand() % COLS;if (!board[i][j].mine) {board[i][j].mine = 1;// 增加相邻地雷数量for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {board[ni][nj].adjacent++;}}}} else {// 如果已经有地雷,重新生成k--;}}}// 渲染游戏板void renderBoard() {// 清空屏幕SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);SDL_RenderClear(renderer);// 绘制每个单元格for (int i = 0; i < ROWS; ++i) {for (int j = 0; j < COLS; ++j) {if (board[i][j].revealed) {// 已揭示的单元格if (board[i][j].mine) {SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // 地雷} else {SDL_SetRenderDrawColor(renderer, 192, 192, 192, 255); // 其他}} else {// 未揭示的单元格SDL_SetRenderDrawColor(renderer, 128, 128, 128, 255);}// 绘制单元格SDL_Rect cellRect = {j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE};SDL_RenderFillRect(renderer, &cellRect);// 绘制地雷数量(已揭示的单元格)if (board[i][j].revealed && !board[i][j].mine && board[i][j].adjacent > 0) {char text[2];snprintf(text, sizeof(text), "%d", board[i][j].adjacent);SDL_Color textColor = {0, 0, 0, 255};SDL_Surface* surface = TTF_RenderText_Solid(font, text, textColor);SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);SDL_Rect textRect = {j * CELL_SIZE + CELL_SIZE / 3, i * CELL_SIZE + CELL_SIZE / 3, CELL_SIZE / 2, CELL_SIZE / 2};SDL_RenderCopy(renderer, texture, NULL, &textRect);SDL_DestroyTexture(texture);SDL_FreeSurface(surface);}}}// 刷新屏幕SDL_RenderPresent(renderer);}// 处理鼠标点击事件void handleMouseClick(int x, int y) {int i = y / CELL_SIZE;int j = x / CELL_SIZE;if (!board[i][j].revealed) {board[i][j].revealed = 1;if (board[i][j].mine) {// 点击到地雷,游戏结束printf("Game Over!\n");SDL_Quit();exit(1);} else {// 递归揭示相邻单元格if (board[i][j].adjacent == 0) {for (int ni = i - 1; ni <= i + 1; ++ni) {for (int nj = j - 1; nj <= j + 1; ++nj) {if (ni >= 0 && ni < ROWS && nj >= 0 && nj < COLS && !(ni == i && nj == j)) {handleMouseClick(nj * CELL_SIZE, ni * CELL_SIZE);}}}}}}}int main() {// 初始化SDLSDL_Init(SDL_INIT_VIDEO);// 创建窗口和渲染器window = SDL_CreateWindow("Minesweeper", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);// 初始化游戏板initializeBoard();// 游戏循环int quit = 0;SDL_Event e;while (!quit) {// 处理事件while (SDL_PollEvent(&e) != 0) {if (e.type == SDL_QUIT) {quit = 1;} else if (e.type == SDL_MOUSEBUTTONDOWN) {if (e.button.button == SDL_BUTTON_LEFT) {handleMouseClick(e.button.x, e.button.y);}}}//渲染游戏板renderBoard();}// 清理资源SDL_DestroyWindow(window);SDL_DestroyRenderer(renderer);SDL_Quit();return 0;}```这是一个简单的扫雷游戏的C语言代码,使用SDL库来创建窗口、处理事件和渲染图形。

扫雷程序源代码

扫雷程序源代码

frmMainOption ExplicitDim picFace(0 To 4) As StdPicture '存放笑脸图片Dim picNum(0 To 9) As StdPicture '存放雷区数字图片Dim picArea(0 To 6) As StdPicture '存放雷区非数字图片Dim picTime(0 To 11) As StdPicture '存放时间数字图片Dim Bomb() As Integer '存放地雷位置周围雷数Dim Status() As Integer '记录所在位置状态,0为原状,1为红旗,2为问号,3为点开Dim LeftbombNum As Integer '剩余雷数Dim iTime As Integer '时间Private Sub Form_Load()Dim i As IntegerFor i = 0 To 4 '加载表情图片Set picFace(i) = LoadResPicture(140 + i, 0)NextFor i = 0 To 8Set picNum(i) = LoadResPicture(115 - i, 0) '加载雷区数字图片NextFor i = 0 To 6Set picArea(i) = LoadResPicture(100 + i, 0) '加载雷区非数字图片NextFor i = 0 To 11Set picTime(i) = LoadResPicture(120 + i, 0) '加载时间数字图片NextCall mnuBegin_ClickEnd SubPublic Sub Start() '开始LeftbombNum = Num '初始剩余雷数Text1.Text = NumpicboxArea.Enabled = TruepicboxFace.PaintPicture picFace(4), 0, 0 '显示笑脸图片Dim i As Integer, j As IntegerpicboxArea.Width = 260 * X '布置窗体和控件picboxArea.Height = 260 * YpicboxArea.ScaleWidth = picboxArea.WidthpicboxArea.ScaleHeight = picboxArea.HeightpicboxShow.Width = picboxArea.WidthpicboxShow.ScaleHeight = picboxShow.HeightpicboxShow.ScaleWidth = picboxShow.WidthfrmMain.Width = picboxArea.Width + 180frmMain.Height = picboxArea.Height + picboxShow.Height + 950picboxShow.Left = 50picboxArea.Left = 50picboxShow.Top = 50picboxArea.Top = picboxShow.Height + 140picboxFace.Height = 420picboxFace.Width = 420picboxFace.Left = picboxShow.Width / 2 - 210picboxFace.Top = picboxShow.Height / 2 - 210PicboxNum(5).Left = picboxArea.ScaleWidth - 670PicboxNum(6).Left = picboxArea.ScaleWidth - 415PicboxNum(4).Left = picboxArea.ScaleWidth - 925Call Drawbomb(Val(Text1.Text))PicboxNum(3).PaintPicture picTime(0), 0, 0, 13, 26 '加载时间图像(初始为0)PicboxNum(2).PaintPicture picTime(0), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(0), 0, 0, 13, 26Timer1.Enabled = FalseiTime = 0Call ArrangeFor j = 1 To Y '绘制雷区For i = 1 To XpicboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260NextNextEnd SubPublic Sub Arrange() '程随机放置地雷Dim i As Integer, j As Integer, k As Integer, l As IntegerReDim Bomb(0 To X + 1, 0 To Y + 1)ReDim Status(0 To X + 1, 0 To Y + 1)RandomizeFor i = 1 To Numxx = Int(Rnd * X + 1): yy = Int(Rnd * Y + 1)If Bomb(xx, yy) <> 10 Then '值为10表示此格有雷Bomb(xx, yy) = 10Else '若此格已有雷,则重新随机选格i = i - 1End IfNextFor j = 1 To YFor i = 1 To XIf Bomb(i, j) <> 10 ThenFor k = -1 To 1For l = -1 To 1If Bomb(i + k, j + l) = 10 Then Bomb(i, j) = Bomb(i, j) + 1 '数周围雷数NextNextEnd IfNextNextFor i = 0 To X + 1 Step X + 1 '设定边界,防止出现无定义For j = 0 To Y + 1Bomb(i, j) = 9NextNextFor j = 0 To Y + 1 Step Y + 1For i = 0 To X + 1Bomb(i, j) = 9NextNextEnd SubPrivate Sub mnuStart_Click() '开局Call mnuBegin_ClickEnd SubPrivate Sub mnuBegin_Click() '初级mnuBegin.Checked = TruemnuMiddle.Checked = FalsemnuExpert.Checked = FalsemnuCust.Checked = FalseX = 9: Y = 9: Num = 10Call StartEnd SubPrivate Sub mnuMiddle_Click() '中级X = 16: Y = 16: Num = 40mnuBegin.Checked = FalsemnuMiddle.Checked = TruemnuCust.Checked = FalsemnuExpert.Checked = FalseCall StartEnd SubPrivate Sub mnuExpert_Click() '高级X = 16: Y = 30: Num = 99mnuBegin.Checked = FalsemnuMiddle.Checked = FalsemnuExpert.Checked = TruemnuCust.Checked = FalseCall StartEnd SubPrivate Sub mnuCust_Click() '自定义mnuCust.Checked = TruefrmCustom.Show 1, Me '显示子顶替对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub mnuAbout_Click()frmAbout.Show 1, Me '显示关于扫雷对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub mnuExit_Click() '退出游戏Unload MeEnd SubPrivate Sub mnuRecord_Click()frmRecord.Show 1, Me '显示扫雷英雄榜对话框,模态窗口,暂停执行位于Show后面的语句End SubPrivate Sub picboxFace_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)picboxFace.Picture = picFace(0)End SubPrivate Sub picboxFace_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) picboxFace.Picture = picFace(4)Call StartEnd SubPrivate Sub picboxArea_MouseDown(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)picboxFace.Picture = picFace(3)Dim x2 As Integer, y2 As IntegerPosition x1, y1, x2, y2 '定位If Status(x2, y2) = 0 Then '若鼠标点击的方格为初始状态If Button = 1 Then '左击picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(1), (x2 - 1) * 260, (y2 - 1) * 260End IfElseIf Status(x2, y2) = 1 Then '若鼠标点击的方格为红旗状态If Button = 2 Then '右击picboxArea.PaintPicture picArea(2), (x2 - 1) * 260, (y2 - 1) * 260End IfElseIf Status(x2, y2) = 2 Then '若鼠标点击的方格为问号状态If Button = 1 Then '左击picboxArea.PaintPicture picArea(6), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(0), (x2 - 1) * 260, (y2 - 1) * 260End IfEnd IfTimer1.Enabled = True '计时器开始计时Text1.Text = LeftbombNum - 1 '剩余雷数减少一个End SubPrivate Sub picboxArea_MouseMove(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)If Button = 0 Then Exit SubDim i As Integer, j As IntegerFor i = 1 To XFor j = 1 To YIf Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260 '当鼠标离开后按下去的按键恢复原状End IfNextNextDim x2 As Integer, y2 As IntegerPosition x1, y1, x2, y2If x2 > 0 And y2 > 0 And x2 < X + 1 And y2 < Y + 1 ThenIf Status(x2, y2) = 0 Then picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) *260 '鼠标所在处按键显示按下End IfEnd SubPrivate Sub picboxArea_MouseUp(Button As Integer, Shift As Integer, x1 As Single, y1 As Single)Dim x2 As Integer, y2 As Integer, i As Integer, j As IntegerPosition x1, y1, x2, y2 '定位If x2 > 0 And y2 > 0 And x2 < X + 1 And y2 < Y + 1 ThenIf Status(x2, y2) = 0 Then '若鼠标点击的方格为初始状态If Button = 1 Then '左击If Bomb(x2, y2) <> 0 And Bomb(x2, y2) <> 10 ThenStatus(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(Bomb(x2, y2)), (x2 - 1) * 260, (y2 - 1) * 260 '显示周围雷的个数ElseIf Bomb(x2, y2) = 0 Then '若周围没有雷Status(x2, y2) = 3picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260For i = -2 To 0For j = -2 To 0picboxArea_MouseUp 1, 0, 260 * (x2 + i), 260 * (y2 + j) '检查周围八个格子NextNextElseIf Bomb(x2, y2) = 10 Then '若有雷For i = 1 To XFor j = 1 To YIf Bomb(i, j) = 10 And Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '未被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 1 ThenpicboxArea.PaintPicture picArea(4), (i - 1) * 260, (j - 1) * 260 '被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 2 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '疑似的雷显示End IfNextNextpicboxArea.PaintPicture picArea(3), (x2 - 1) * 260, (y2 - 1) * 260 '被点开的雷显示picboxArea.Enabled = False '雷区不响应任何事件End IfElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(1), (x2 - 1) * 260, (y2 - 1) * 260 '方格被标记红旗Status(x2, y2) = 1LeftbombNum = LeftbombNum - 1 '剩余雷数减少一个End IfElseIf Status(x2, y2) = 1 Then '若鼠标点击的方格为红旗If Button = 2 Then '右击picboxArea.PaintPicture picArea(2), (i - 1) * 260, (j - 1) * 260 '方格状态变为问号Status(x2, y2) = 2LeftbombNum = LeftbombNum + 1 '剩余雷数增加一End IfElseIf Status(x2, y2) = 2 Then '若鼠标点击的方格为问号If Button = 1 Then '左击If Bomb(x2, y2) <> 0 And Bomb(x2, y2) <> 10 ThenStatus(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(Bomb(x2, y2)), (x2 - 1) * 260, (y2 - 1) * 260ElseIf Bomb(x2, y2) = 0 Then '若周围无雷Status(x2, y2) = 3 '方格被点开picboxArea.PaintPicture picNum(0), (x2 - 1) * 260, (y2 - 1) * 260For i = -2 To 0 '检查周围八个格子For j = -2 To 0picboxArea_MouseUp 1, 0, 260 * (x2 + i), 260 * (y2 + j)NextNextElseIf Bomb(x2, y2) = 10 Then '若有雷For i = 1 To XFor j = 1 To YIf Bomb(i, j) = 10 And Status(i, j) = 0 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '未被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 1 ThenpicboxArea.PaintPicture picArea(4), (i - 1) * 260, (j - 1) * 260 '被标记的雷显示ElseIf Bomb(i, j) = 10 And Status(i, j) = 2 ThenpicboxArea.PaintPicture picArea(5), (i - 1) * 260, (j - 1) * 260 '疑似的雷显示End IfNextNextpicboxArea.PaintPicture picArea(3), (x2 - 1) * 260, (y2 - 1) * 260 '被点开的雷显示picboxArea.Enabled = False '雷区不响应任何事件End IfElseIf Button = 2 Then '右击picboxArea.PaintPicture picArea(0), (i - 1) * 260, (j - 1) * 260Status(x2, y2) = 0End IfEnd IfElseIf Status(x2, y2) = 3 Then '若方格被点开Dim n As IntegerFor i = -1 To 1For j = -1 To 1If Status(x2 + i, y2 + j) = 1 Then n = n + 1NextNextIf n = Bomb(x2, y2) ThenFor i = -2 To 0 '检查周围八个格子For j = -2 To 0picboxArea_MouseUp 1, 0, (x2) * 260, (y2) * 260NextNextEnd IfEnd IfIf picboxArea.Enabled ThenpicboxFace.Picture = picFace(4)ElsepicboxFace.Picture = picFace(2)Timer1.Enabled = False '计时器停止iTime = 0 '时间清零frmCheer.Show 1, Me '显示加油窗体End IfText1.Text = LeftbombNum '文本框中显示剩余雷数Dim time1 As Integer, time2 As Integer, time3 As Integer '把含有时间信息的字符串转换为数值time1 = Val(frmRecord.lblTime1.Caption)time2 = Val(frmRecord.lblTime2.Caption)time3 = Val(frmRecord.lblTime3.Caption)If Text1.Text = 0 ThenIf Bomb(xx, yy) = 10 ThenIf Status(xx, yy) = 1 Then '若所有地雷全部标记出来了Timer1.Enabled = False '计时器停止计时If Y = 9 And iTime >= time1 Then '若为初级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 9 And iTime < time1 Then '若为初级,破了纪录frmMessage1.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfIf Y = 16 And iTime >= time2 Then '若为中级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 16 And iTime < time2 Then '若为中级,破了纪录frmMessage2.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfIf Y = 40 And iTime >= time3 Then '若为高级,未破纪录frmWin.Show 1, Me '显示胜利对话框picboxFace.PaintPicture picFace(1), 0, 0ElseIf Y = 30 And iTime < time3 Then '若为高级,破了纪录frmMessage3.Show 1, Me '显示扫雷英雄榜信息提示对话框End IfEnd IfEnd IfEnd IfEnd SubPrivate Sub Position(x1 As Single, y1 As Single, x2 As Integer, y2 As Integer)x2 = x1 \ 260 + 1: y2 = y1 \ 260 + 1 '显示鼠标所在格子坐标End SubSub DrawNum(inum As Integer)If iTime >= "0" And iTime <= "9" Then '绘制数字0-9PicboxNum(3).PaintPicture picTime(Val(iTime)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElseIf iTime >= "10" And iTime <= "99" ThenPicboxNum(3).PaintPicture picTime(Val(iTime Mod 10)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(iTime \ 10)), 0, 0, 13, 26PicboxNum(1).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElseIf iTime >= "100" And iTime <= "999" ThenPicboxNum(1).PaintPicture picTime(Val(iTime \ 100)), 0, 0, 13, 26PicboxNum(2).PaintPicture picTime(Val(iTime \ 10 - 10 * (iTime \ 100))), 0, 0, 13, 26PicboxNum(3).PaintPicture picTime(Val(iTime Mod 10)), 0, 0, 13, 26 '绘制时间显示图像End IfCall Drawbomb(Val(LeftbombNum))End SubPrivate Sub Timer1_Timer() '显示游戏时间If iTime < 999 TheniTime = iTime + 1DrawNum iTimeTimer1.Interval = 1000End IfCall DrawNum(Val(Text1.Text))End SubSub Drawbomb(LeftbombNum As Integer) '绘制剩余雷数图像LeftbombNum = Val(Text1.Text)If LeftbombNum >= "0" ThenIf LeftbombNum >= "0" And LeftbombNum <= "9" ThenPicboxNum(6).PaintPicture picTime(Val(LeftbombNum)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(0)), 0, 0, 13, 26ElsePicboxNum(6).PaintPicture picTime(Val(LeftbombNum Mod 10)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(LeftbombNum \ 10)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(0)), 0, 0, 13, 26End IfElseIf LeftbombNum >= "-9" And LeftbombNum <= "-1" ThenPicboxNum(6).PaintPicture picTime(-Val(Text1.Text)), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(Val(0)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(11)), 0, 0, 13, 26ElseIf LeftbombNum >= "-99" And LeftbombNum <= "-10" ThenPicboxNum(6).PaintPicture picTime(-Val(Text1.Text) Mod 10), 0, 0, 13, 26PicboxNum(5).PaintPicture picTime(-Val(Text1.Text \ 10)), 0, 0, 13, 26PicboxNum(4).PaintPicture picTime(Val(11)), 0, 0, 13, 26End IfEnd SubfrmCustomOption ExplicitPrivate Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmMain.mnuBegin.Checked = False '属性为True时,菜单标题前显示复选标记,False则不显示frmMain.mnuMiddle.Checked = FalsefrmMain.mnuExpert.Checked = FalsefrmMain.mnuCust.Checked = TrueX = Val(txtCol.Text) '把含有数值信息的字符串转换为数值Y = Val(txtRow.Text)Num = Val(txtNum.Text)Call frmMain.Start ‘开始游戏Unload MeEnd SubPrivate Sub Form_Load()txtRow.Text = 20 ‘自动加载初始值txtCol.Text = 20txtNum.Text = 20End SubfrmAboutPrivate Sub cmdOK_Click()Unload MeEnd SubfrmRecordPrivate Sub cmdClose_Click()Unload MeEnd SubfrmCheerPrivate Sub Command1_Click()Unload MeEnd SubfrmWinPrivate Sub cmdOK_Click()Unload MeCall frmMain.StartEnd SubfrmMessage1Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName1.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime1.Caption = iTimeUnload MeEnd SubfrmMessage2Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName2.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime2.Caption = iTimeUnload MeEnd SubfrmMessage3Private Sub cmdCancle_Click()Unload MeEnd SubPrivate Sub cmdOK_Click()frmRecord.lblName3.Caption = Text1.Text ‘保存英雄榜信息frmRecord.lblTime3.Caption = iTimeUnload MeEnd Sub标准模块Public X As Integer, Y As Integer, Num As Integer 'x为横宽,y为竖长,num为雷数Public xx As Integer, yy As Integer 'x1,y1为布雷的位置坐标。

C++实现简单扫雷游戏

C++实现简单扫雷游戏

C++实现简单扫雷游戏扫雷是⼀个经典的电脑⼩游戏,⽤C++来编⼀下,效果⾃⼰试⼀下#include<stdio.h>#include<Windows.h>#define YELLOW FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define CYAN FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define ORANGE FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY#define PURPLE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITYusing namespace std;const int STARTX = 30;const int STARTY = 6;const int MAXX = 9;//雷区的宽const int MAXY = 9;//雷区的⾼const int BOMBNUMBER = 10;//地雷数量class Cube{private:bool ifHaveBomb;//该⽅块是否含有炸弹bool ifOpen;//该⽅块有⽆被玩家翻开int nearBombNumber;//该区块周围8格的含有炸弹的⽅块的数量public:void setOpen() {//将Open的值改为trueifOpen = true;}bool getOpen() {//获取ifOpen的值return ifOpen;}void setNearBombNumber(int number) {//给nearBombNumber赋值nearBombNumber = number;}void haveBomb() {//给⽅块放置地雷ifHaveBomb = true;}bool getIfHaveBomb() {//获取ifHaveBomb的值return ifHaveBomb;}int getNearBombNumber() {//获取nearBombNumber的值return nearBombNumber;}void resetCube(bool ifhavebomb = false, bool ifopen = false, int nearbombnumber = 0){//初始化成员数据ifHaveBomb = ifhavebomb;ifOpen = ifopen;nearBombNumber = nearbombnumber;}};Cube cube[MAXX][MAXY];void GoTo(int x, int y);//定位光标void setBomb(int bombNumber);//⽣成bombNumber个炸弹并且放进随机的⽅块中void show();//显⽰地雷阵int checkAndSetNearBombNumber(int x, int y);//检查当前⽅块周围的雷数量void gameStart();//初始化游戏void showXY();//显⽰雷区坐标bool player(bool &life);//玩家输⼊坐标翻开⽅块void message(bool life);//玩家游戏结束后输出的信息void autoOpen(int x,int y);//玩家翻开的⽅块为不含雷且周围⽆雷的⽅块时,⾃动翻开周围⽆雷的⽅块bool ifWin();//判断玩家是否扫雷成功void showBomb();//游戏结束后显⽰地雷位置int main() {system("title 李柏衡");gameStart();show();bool life = true, win = true;while (player(life) && !ifWin()) {}message(life && ifWin());return 0;}void GoTo(int x, int y) {//定位光标COORD coord = { x,y };SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void setBomb(int bombNumber = BOMBNUMBER) {//⽣成bombNumber个炸弹并且放进随机的⽅块中srand((unsigned)GetCurrentTime());while (bombNumber--) {int x = MAXX + 1, y = MAXY + 1;while ((x >= MAXX || y >= MAXY) || cube[x][y].getIfHaveBomb() == true) {x = rand() % MAXX;y = rand() % MAXY;}cube[x][y].haveBomb();}}void show() {//显⽰地雷阵system("cls");showXY();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);for (int i = 0;i < MAXY;i++) {GoTo(STARTX, STARTY + i);for (int j = 0;j < MAXX;j++) {if (cube[j][i].getOpen() == true) {if (cube[j][i].getIfHaveBomb() == false) {if (cube[j][i].getNearBombNumber() == 0) { //挖开⽆雷的⽅块显⽰该⽅块周围多少个⽅块含雷,若为0则显⽰空格 printf(" ");} else {printf(" %d", cube[j][i].getNearBombNumber());}} else {printf("×");//有雷的⽅块被挖开后显⽰×}} else {printf("■");//未翻开的⽅块⽤■显⽰}}}}void showXY() {//显⽰坐标轴SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), CYAN);GoTo(STARTX - 3, STARTY + MAXY / 2);printf("Y");GoTo(STARTX + MAXX, STARTY - 2);printf("X");SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);for (int i = 0;i < MAXY;i++) {GoTo(STARTX - 1, STARTY + i);printf("%d ", i);}for (int i = 0;i < 2 * MAXX;i += 2) {GoTo(STARTX + i + 1, STARTY - 1);printf("%d ", i / 2);}}int checkAndSetNearBombNumber(int x, int y) {//检查当前⽅块周围的雷数量int num = 0;if (cube[x][y].getIfHaveBomb() == true) {//若该⽅块有地雷,则不⽤判断它周围有⼏个雷return 0;} else {//⽤两个循环当前⽅块周围8格扫⼀遍for (int i = -1; i <= 1; i++) {for (int j = -1; j <= 1; j++) {int nx = x + i;int ny = y + j;if (!(ny == y && nx == x) && (nx >= 0 && nx <= MAXX - 1) &&(ny >= 0 && ny <= MAXY - 1)) {if (cube[nx][ny].getIfHaveBomb()) {num++;}}}}cube[x][y].setNearBombNumber(num);//设置该⽅块附近的地雷的数量 return 0;}}void gameStart() {//初始化游戏for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {cube[j][i].resetCube();}}setBomb();for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {checkAndSetNearBombNumber(j, i);}}}bool player(bool &life) {//玩家输⼊坐标翻开⽅块int x, y;GoTo(STARTX - 3, STARTY + MAXY + 1);printf("请输⼊坐标(x,y),x和y⽤空格隔开");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);scanf("%d%d", &x, &y);if ((x < 0) || (x > MAXX - 1) || (y < 0) || (y > MAXY - 1)) {//当玩家输⼊的坐标超出范围时show();GoTo(STARTX - 3, STARTY + MAXY + 3);printf("该坐标不存在,请重新输⼊坐标");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);} else if (cube[x][y].getIfHaveBomb() == true) {//当玩家翻开的⽅块有地雷时cube[x][y].setOpen();show();life = false;return false;} else if (cube[x][y].getOpen() == false) {//当玩家翻开的⽅块⽆雷时if (cube[x][y].getNearBombNumber() == 0) {autoOpen(x, y);cube[x][y].setOpen();show();} else {cube[x][y].setOpen();show();}} else if (cube[x][y].getOpen() == true) {//当玩家输⼊已翻开⽅块的坐标时show();GoTo(STARTX, STARTY + MAXY + 3);printf("该⽅块已被挖开,请再次输⼊坐标");GoTo(STARTX + MAXX / 2, STARTY + MAXY + 2);}ifWin();return true;}void message(bool result) {if (result == true) {//玩家胜利时输出的信息showBomb();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), YELLOW);GoTo(STARTX - 1, STARTY + MAXY + 1);printf("祝贺你,你胜利了!");GoTo(STARTX, STARTY + MAXY + 2);} else {//玩家失败时输出的信息showBomb();SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), PURPLE);GoTo(STARTX - 1, STARTY + MAXY + 1);printf("××你踩中地雷了××");GoTo(STARTX, STARTY + MAXY + 2);}}void autoOpen(int x, int y) {//玩家翻开的⽅块为不含雷且周围⽆雷的⽅块时,⾃动翻开周围⽆雷的⽅块for (int i = -1; i <= 1; i++) {for (int j = -1; j <= 1; j++) {int nx = x + i;int ny = y + j;if (!(ny == y && nx == x) && (nx >= 0 && nx <= MAXX - 1) &&(ny >= 0 && ny <= MAXY - 1) && cube[nx][ny].getOpen() == false) {if (cube[nx][ny].getNearBombNumber() == 0) {cube[nx][ny].setOpen();autoOpen(nx, ny);} else {cube[nx][ny].setOpen();}}}}}bool ifWin() {//判断玩家是否扫雷成功达到游戏结束条件int num = 0;for (int i = 0;i < MAXX;i++) {for (int j = 0;j < MAXY;j++) {if (cube[j][i].getOpen() == false) {num++;}}}if (num == BOMBNUMBER) {return true;} else {return false;}}void showBomb() {//游戏结束后显⽰地雷位置for (int i = 0;i < MAXY;i++) {for (int j = 0;j < MAXX;j++) {if (cube[j][i].getIfHaveBomb() == true) {cube[j][i].setOpen();}}}show();}更多精彩游戏⼩代码,请点击阅读以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

c语言扫雷源代码

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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

import javax.swing.ImageIcon;public class Block {String name; //名字,比如"雷"或数字int aroundMineNumber; //周围雷的数目 ImageIcon mineIcon; //雷的图标boolean isMine=false; //是否是雷boolean isMark=false; //是否被标记boolean isOpen=false; //是否被挖开public void setName(String name) {=name;}public void setAroundMineNumber(int n) { aroundMineNumber=n;}public int getAroundMineNumber() {return aroundMineNumber;}public String getName() {return name;}public boolean isMine() {return isMine;}public void setIsMine(boolean b) {isMine=b;}public void setMineIcon(ImageIcon icon){ mineIcon=icon;}public ImageIcon getMineicon(){return mineIcon;}public boolean getIsOpen() {return isOpen;}public void setIsOpen(boolean p) {isOpen=p;}public boolean getIsMark() {return isMark;}public void setIsMark(boolean m) {isMark=m;}}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+"");}}else if(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);}}}}}}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+"");}}else if(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);}}}}}}。

相关文档
最新文档