VB扫雷小游戏编程代码

合集下载

好玩的vbs代码

好玩的vbs代码

好玩的VBScript代码VBScript(Visual Basic Scripting Edition)是一种基于VB语言的脚本语言,它可以用来创建简单的Windows应用程序、网页脚本和系统管理脚本等。

VBScript 是一种通用的脚本语言,可以用来实现各种有趣的功能。

在本文中,我们将介绍一些好玩的VBScript代码,展示其强大的功能和娱乐价值。

1. 电脑妖怪第一个VBScript代码是创建一个电脑妖怪。

该代码将在电脑屏幕上创建一个随机移动的图形,并发出奇怪的声音。

Set wshShell = CreateObject("WScript.Shell")Set objShell = CreateObject("Shell.Application")Set objWMI = GetObject("winmgmts:\\.\root\cimv2")DowshShell.Run "mshta vbscript:CreateObject(""SAPI.SpVoice"").Speak(""Boo!"") (Close)"objShell.MinimizeAllobjShell.UndoMinimizeAllFor Each objDesktop in objWMI.InstancesOf("Win32_Desktop")objDesktop.SetWallpaper "C:\path\to\your\image.jpg"Nextwscript.sleep 100Loop通过运行该代码,将在桌面上创建一个随机移动的图形,并且屏幕上会突然发出吓人的声音。

这个代码可以用作恶作剧或者给你的朋友带来一些惊喜。

2. 无限弹窗第二个VBScript代码是创建一个无限弹窗的例子。

vb_扫雷程序源码

vb_扫雷程序源码
buttons(8, 6) = Button79
buttons(8, 7) = Button80
buttons(8, 8) = Button81
For i = 0 To 8
For j = 0 To 8
buttons(i, j).Enabled = True
buttons(7, 0) = Button64
buttons(7, 1) = Button65
buttons(7, 2) = Button66
buttons(7, 3) = Button67
buttons(7, 4) = Button68
End Sub
Private Sub Button82_Click() Handles Button82.Click
Me.Form1_Load()
End Sub
Private Sub Form1_Load() Handles MyBase.Load
buttons(0, 3) = Button4
buttons(0, 4) = Button5
buttons(0, 5) = Button6
buttons(0, 6) = Button7
buttons(0, 7) = Button8
buttons(1, 4) = Button14
buttons(1, 5) = Button15
buttons(1, 6) = Button16
buttons(1, 7) = Button17
buttons(1, 8) = Button18
clear_bomb += 1
End If
Next
Next

vb扫雷代码

vb扫雷代码
MinButton = 0 'False
ScaleHeight = 3060
ScaleWidth = 4620
StartUpPosition = 3 '窗口缺省
Begin monDialog CommonDialog1
End
Begin VB.Menu cls
Caption = "清空榜单"
End
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Dim lin As Integer '记录上一次游戏情况的容器
Dim zong As Integer '格子数量,从0开始计算
Dim lei As Integer '雷的数量
Dim shu As Integer '一行格子的数量
Dim heng As Integer '一列格子的数量
Left = 840
Picture = "扫雷.frx":0000
Style = 1 'Graphical
TabIndex = 1
TabStop = 0 'False
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
ForeColor = &H00FF0000&
Height = 375

winXP扫雷游戏vb

winXP扫雷游戏vb

winXP扫雷游戏内存查看代码左图是获取的图形结果,右图是扫雷结果。

黑色圆点对应地雷Public Class Form1Private Declare Auto Function FindWindow Lib "user32.dll" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtrPrivate Declare Auto Function GetWindowThreadProcessId Lib"user32.dll" (ByVal hwnd As IntPtr, ByRef lpdwProcessId As Integer) As IntPtrPrivate Declare Auto Function OpenProcess Lib "kernel32.dll" (ByVal dwDesiredAccess As Integer, ByVal bInheritHandle As Integer, ByVal dwProcessId As Integer) As IntPtrPublic Declare Function ReadProcessMemory Lib "kernel32" (ByVal hProcess As Integer, ByVal lpBaseAddress As Integer, ByVal lpBuffer() As Byte, ByVal nSize As Integer, ByRef lpNumberOfBytesWritten As Integer) As IntegerPublic Enum PROCESS_ACCESS As Integer' Specifies all possible access flags for the process object. PROCESS_ALL_ACCESS = &H1F0FFF' Enables using the process handle in the CreateRemoteThread function' to create a thread in the process.PROCESS_CREATE_THREAD = &H2' Enables using the process handle as either the source or' target process in the DuplicateHandle function to duplicate a handle.PROCESS_DUP_HANDLE = &H40' Enables using the process handle in the GetExitCodeProcess and ' GetPriorityClass functions to read information from the process object.PROCESS_QUERY_INFORMATION = &H400' Enables using the process handle in the SetPriorityClass function to' set the priority class of the process.PROCESS_SET_INFORMATION = &H200' Enables using the process handle in the TerminateProcess function to' terminate the process.PROCESS_TERMINATE = &H1' Enables using the process handle in the VirtualProtectEx and ' WriteProcessMemory functions to modify the virtual memory of the process.PROCESS_VM_OPERATION = &H8' Enables using the process handle in the ReadProcessMemory function to' read from the virtual memory of the process.PROCESS_VM_READ = &H10' Enables using the process handle in the WriteProcessMemory function to' write to the virtual memory of the process.PROCESS_VM_WRITE = &H20' Enables using the process handle in any of the wait functions to wait' for the process to terminate.SYNCHRONIZE = &H100000End EnumPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.ClickDim buf(0) As ByteDim hWnd As IntegerDim pid As IntegerDim bytesRead As IntegerDim ph As IntegerDim X(0) As ByteDim Y(0) As ByteDim curProcess As Process = Process.GetCurrentProcess()Me.TextBox2.Text = ""hWnd = FindWindow(vbNullString, "扫雷")GetWindowThreadProcessId(hWnd, pid)ph = OpenProcess(PROCESS_ACCESS.PROCESS_VM_READ, False, pid) ReadProcessMemory(ph, &H10056A8, X, 1, bytesRead)ReadProcessMemory(ph, &H10056A8, Y, 1, bytesRead)For k As Integer = 0 To (X(0) - 1) * 32 Step 32For j As Integer = 0 To Y(0) - 1ReadProcessMemory(ph, &H1005361 + k + j, buf, 1, bytesRead)If buf(0) = 143 ThenMe.TextBox2.Text += "●" + " "ElseMe.TextBox2.Text += "○" + " "End IfNextMe.TextBox2.Text += vbCrLfNextEnd SubEnd Class本文介绍了用Visual 开发聊天通信软件的实现过程。

VB课程设计报告——扫雷游戏

VB课程设计报告——扫雷游戏

VB课程设计报告-------扫雷游戏马学清1008260132 指导老师:张小兵一、题目介绍在计算机逐步渗入社会生活各个层面的今天,计算机已经成为人们日常生活的一分,越来越多的人使用计算机办公、娱乐等等。

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

我利用Turbo C编写了与它功能相仿的扫雷游戏,寓学于乐。

程序功能二、程序功能程序的功能是随机生成地雷数,通过鼠标操作玩游戏,不接受键盘,按任意键结束程序。

单击屏幕上的“开始”按钮可以重新开始游戏。

所有地雷标出后胜利,当鼠标左键单击到地雷时失败。

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

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

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

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

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

6.对掌握知识的深度、运用理论去处理问题的能力、实验能力、课程设计能力、书面及口头表达能力进行考核四、游戏规则设计10×10格区域,单击鼠标后,在此格中显示的数字,则表示它周围就有几个空格内含有的地雷数,周围没有地雷的显示空白,则不能再单击了。

如果是地雷,则游戏结束。

如果判断是地雷,可以单击鼠标右键标出,显示红色,要取消红旗标志则再单击鼠标右键,当所有地雷都标出,每个空格都处理过,那么游戏就胜利结束。

五、程序源代码'级别Private Sub Form_Load() '默认初级dengji = 1Call nandu(dengji)End SubPrivate Sub zidingyi_Click() '自定义类型Load Form2Form2.ShowEnd SubPrivate Sub again_Click() '重新开始Call nandu(dengji)End SubPrivate Sub chuji_Click() '1级dengji = 1Call nandu(dengji)End SubPrivate Sub zhongji_Click() '2级dengji = 2Call nandu(dengji)End SubPrivate Sub gaoji_Click() '3级dengji = 3Call nandu(dengji)End SubPrivate Sub tuichu_Click() '退出Unload MeEnd SubPrivate Sub bang_Click() '显示英雄榜Load Form3Form3.ShowEnd SubPrivate Sub about_Click() '显示关于扫雷Load Form4Form4.ShowEnd SubPrivate Sub Timer1_Timer() '处理计时器If time < 999 Thentime = time + 1stime1 = Format(time, "000")heng = Pic1.Width - (4 + 13) - 13 - 13 '时间处理For i = 1 To 3stime2 = Mid(stime1, i, 1)Pic1.PaintPicture Clip1.GraphicCell(11 - Val(stime2)), heng, 4heng = heng + 13Nextshijian(dengji) = timeEnd IfIf time = 999 Then '游戏失败MsgBox "你输了", 0, "失败"End IfEnd SubPublic Sub nandu(dengji)'调用主程序Dim s As IntegerOpen App.Path & "mingzi" For Random As 1For s = 1 To 3Get 1, s, yuanshijian(s)NextClose 1Pic1.Picture = LoadPicture() '清空计时器和记雷显示器Pic2.Picture = LoadPicture()Pic2.Enabled = TrueTimer1.Enabled = Falseq = 0mousedown = FalseIf dengji = 1 Then '判断等级hang = 9: lie = 9: chulei = 9ElseIf dengji = 2 Thenhang = 16: lie = 16: chulei = 39ElseIf dengji = 3 Thenhang = 30: lie = 30: chulie = 99ElseIf dengji = 4 Thenhang = dingh: lie = dingl: chulei = dingleiEnd IfReDim fankai(hang - 1, lie - 1) '重定义行列数ReDim lei(hang - 1, lie - 1)ReDim jilu(hang - 1, lie - 1)With Pic2.Height = 16 * hang + 3.Width = 16 * lie + 4.Left = 1 * 8.Top = 6 * 8End WithWith Pic1.Height = 8 * 4.Width = 16 * lie + 4.Left = 1 * 8.Top = 1 * 8End WithForm1.Width = 30 * Screen.TwipsPerPixelX + 16 * Screen.TwipsPerPixelX * lie '确定窗体高宽度Form1.Height = 100 * Screen.TwipsPerPixelY + 13 * Screen.TwipsPerPixelY + 16 * Screen.TwipsPerPixelY * hang + 100For i = 0 To lie - 1 '开始时雷区For j = 0 To hang - 1Pic2.PaintPicture Clip3.GraphicCell(0), i * 16, j * 16NextNextDo While k < chulei '布雷m = Int(Rnd * hang)n = Int(Rnd * lie)If lei(m, n) <> 1 Thenlei(m, n) = 1k = k + 1End IfLoopPic1.PaintPicture Clip1.GraphicCell(11 - k \ 100), 4, 4 '雷数Pic1.PaintPicture Clip1.GraphicCell(11 - (k Mod 100) \ 10), 4 + 13, 4Pic1.PaintPicture Clip1.GraphicCell(11 - (k Mod 10)), 4 + 26, 4Pic1.PaintPicture Clip1.GraphicCell(11), Pic1.Width - (4 + 13), 4 '时间Pic1.PaintPicture Clip1.GraphicCell(11), Pic1.Width - (4 + 26), 4Pic1.PaintPicture Clip1.GraphicCell(11), Pic1.Width - (4 + 13 * 3), 4Pic1.PaintPicture Clip1.GraphicCell(11), 4, 4Pic1.PaintPicture Clip2.GraphicCell(4), Pic1.Width / 2 - 12, 4 '显示笑脸End Sub'图片框1的MouseDown事件Private Sub Pic1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)If X >= Pic1.Width / 2 - 12 And X <= Pic1.Width / 2 + 12 And Y >= 4 And Y <= 24 + 4 Then Pic1.PaintPicture Clip2.GraphicCell(0), Pic1.Width / 2 - 12, 4End IfEnd Sub'图片框1的MouseUp事件Private Sub Pic1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)If X >= Pic1.Width / 2 - 12 And X <= Pic1.Width / 2 + 12 And Y >= 4 And Y <= 24 + 4 Then time = 0Call nandu(dengji)End IfEnd Sub'图片框的MouseDown事件Private Sub Pic2_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single) Static intq As Integerk = chuleimouseup = Falsei = X \ 16: j = Y \ 16If fankai(i, j) = False ThenIf Button = 1 Then '左键mousedown = TruePic1.PaintPicture Clip2.GraphicCell(3), Pic1.Width / 2 - 12, 4If jilu(i, j) <> 1 And jilu(i, j) <> -1 ThenPic2.PaintPicture Clip3.GraphicCell(15), i * 16, j * 16ElseIf b = -1 ThenPic2.PaintPicture Clip3.GraphicCell(6), i * 16, j * 16End IfElseIf Button = 2 Then '右键jilu(i, j) = jilu(i, j) + 1Pic2.PaintPicture Clip3.GraphicCell(jilu(i, j)), i * 16, j * 16If jilu(i, j) \ 2 = 1 Then jilu(i, j) = -1If jilu(i, j) = 1 Then intq = intq + 1If intq < 9 ThenPic1.PaintPicture Clip1.GraphicCell(11 - (k Mod 10) + intq), 4 + 26, 4 '画小旗ElseIf intq < 99 ThenFor intc = 0 To 9Pic1.PaintPicture Clip1.GraphicCell(11 - (k Mod 10) + intq), 4 + 26, 4 '雷数减少Next intcPic1.PaintPicture Clip1.GraphicCell(11 - (k Mod 100) \ 10 + intq), 4 + 13, 4 End IfIf jilu(i, j) = 1 And lei(i, j) = 1 Thenq = q + 1ElseIf jilu(i, j) = -1 Thenq = q - 1End IfIf q = chulei Then Call shengliEnd IfEnd IfEnd Sub'图片框2的MouseUp事件Private Sub Pic2_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single) mousedown = FalseIf Timer1.Enabled = False Then Timer1.Enabled = Truei = X \ 16: j = Y \ 16If Button = 1 ThenIf i >= 0 And i < hang And j >= 0 And j < lie ThenPic1.PaintPicture Clip2.GraphicCell(4), Pic1.Width / 2 - 12, 4If fankai(i, j) = False ThenIf jilu(i, j) <> 1 ThenIf lei(i, j) = 1 ThenCall jieshu(i, j)MsgBox "你输了", 0, "失败"ElseIf panduan(i, j) = 0 ThenCall fan(i, j)ElseIf panduan(i, j) <> 0 ThenPic2.PaintPicture Clip3.GraphicCell(15 - panduan(i, j)), i * 16, j * 16 '显示周围相邻雷的数量q = q + 1fankai(i, j) = TrueEnd IfEnd IfEnd IfEnd IfIf q = hang * lie - chulei Then Call shengliEnd IfEnd Sub'图片框2的MouseMove事件Private Sub Pic2_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)If mousedown = False ThenExit SubEnd Ifm = X \ 16: n = Y \ 16Call yidong(m, n)End Sub'通用过程:移动Private Sub yidong(m, n)If m >= 0 And m < hang And n >= 0 And n < lie ThenIf fankai(m, n) = False ThenIf jilu(m, n) = -1 ThenPic2.PaintPicture Clip3.GraphicCell(6), m * 16, n * 16ElseIf jilu(m, n) = 0 ThenPic2.PaintPicture Clip3.GraphicCell(15), m * 16, n * 16End IfEnd IfFor i = m - 1 To m + 1For j = n - 1 To n + 1If i >= 0 And i < hang And j >= 0 And j < lie ThenIf fankai(i, j) = False ThenIf i <> m Or j <> n ThenIf jilu(i, j) <> 1 ThenIf jilu(i, j) = 0 ThenPic2.PaintPicture Clip3.GraphicCell(0), i * 16, j * 16ElseIf jilu(i, j) = -1 ThenPic2.PaintPicture Clip3.GraphicCell(2), i * 16, j * 16End IfEnd IfEnd IfEnd IfEnd IfNextNextEnd IfEnd SubPrivate Sub jieshu(m, n)Pic2.PaintPicture Clip3.GraphicCell(3), m * 16, n * 16Pic1.PaintPicture Clip2.GraphicCell(2), Pic1.Width / 2 - 12, 4Pic2.Enabled = FalseTimer1.Enabled = FalseFor i = 0 To hang - 1For j = 0 To lie - 1If i <> m And j <> n ThenIf lei(i, j) = 1 And jilu(i, j) <> 1 ThenPic2.PaintPicture Clip3.GraphicCell(5), i * 16, j * 16ElseIf lei(i, j) <> 1 And jilu(i, j) = 1 ThenPic2.PaintPicture Clip3.GraphicCell(4), i * 16, j * 16End IfEnd IfNextNextEnd Sub'判断周围雷的数量Private Function panduan(m, n)Dim leishu As IntegerFor i = m - 1 To m + 1For j = n - 1 To n + 1If i >= 0 And i < hang And j >= 0 And j < lie ThenIf lei(i, j) = 1 Thenleishu = leishu + 1End IfEnd IfNextNextpanduan = leishuEnd Function'翻开递归Private Sub fan(m, n)Dim int1 As IntegerFor i = m - 1 To m + 1For j = n - 1 To n + 1If i >= 0 And i < hang And j >= 0 And j < lie ThenIf fankai(i, j) = False ThenIf lei(i, j) <> 1 ThenIf panduan(i, j) = 0 ThenPic2.PaintPicture Clip3.GraphicCell(15), i * 16, j * 16fankai(i, j) = Trueq = q + 1For int1 = 1 To 20 ',防止直接全部翻开Call fan(i, j) '递归:打开相邻无雷区域Next int1ElsePic2.PaintPicture Clip3.GraphicCell(15 - panduan(i, j)), i * 16, j * 16fankai(i, j) = Trueq = q + 1End IfEnd IfEnd IfEnd IfNextNextEnd Sub'成功Private Sub shengli()Pic1.PaintPicture Clip2.GraphicCell(1), Pic1.Width / 2 - 12, 4Pic2.Enabled = FalseTimer1.Enabled = FalseFor i = 0 To hang - 1For j = 0 To lie - 1If lei(i, j) = 1 And jilu(i, j) <> 1 ThenPic2.PaintPicture Clip3.GraphicCell(5), i * 16, j * 16End IfNextNextIf shijian(dengji) < yuanshijian(dengji) And dengji <> 4 Then mingzi(dengji) = InputBox("破纪录,输入姓名", "成功") Open App.Path & "mingzi" For Random As #1Put 1, dengji + 3, mingzi(dengji)Put 1, dengji, shijian(dengji)Close 1ElseMsgBox "你赢了", "0", "成功"End IfEnd SubPrivate Sub Command1_Click()dingh = Val(Text1.Text)dingl = Val(Text1.Text)dinglei = Val(Text3.Text)If Text1 <> "" And Text2 <> "" And Text3 <> "" ThenIf dinglei < dingh * dingl ThenCall Form1.nandu(4)Unload MeElseMsgBox "输入不合规范", 0, "请重新输入"End IfElseMsgBox "输入不合规范", 0, "请重新输入"End IfEnd SubPrivate Sub Command2_Click()Unload MeEnd SubPrivate Sub Command1_Click()Unload Form3End SubPrivate Sub Form_Load()Dim lab1(1 To 3) As IntegerDim lab2(1 To 3) As StringDim w As Integer, i As Integer, r As Integer, e As IntegerOpen App.Path & "mingzi" For Random As 1For i = 1 To 3Get 1, i, lab1(i)NextClose 1Open App.Path & "mingzi" For Random As 1For j = 4 To 6Get 1, j, lab2(j - 3)NextClose 1For e = 1 To 3bel4(e - 1).Caption = lab1(e)bel4(e + 2).Caption = lab2(e)NextFor r = 1 To 3yuanshijian(r) = lab1(r)NextEnd Sub六、心得体会课程设计是本科学习阶段一次非常难得的理论与实际相结合的机会,通过这次比较完整的一个程序的设计,我摆脱了单纯的理论知识学习状态,和实际设计的结合锻炼了我的综合运用所学的基础知识,解决实际问题的能力,同时也提高我查阅文献资料、对程序整体的把握等其他能力水平,而且通过对整体的掌控,对局部的取舍,以及对细节的斟酌处理,都使我的能力得到了锻炼,经验得到了丰富。

扫雷游戏设计代码(VB完善版)

扫雷游戏设计代码(VB完善版)

扫雷游戏VB设计实现最终界面如下:显然只需完成三个窗体的设计即可,具体设计界面和代码如下:一、主窗体(form10)设计界面:主窗体(form10)的代码:Dim d(11, 11) As IntegerDim k As IntegerDim v(100) As Integer '定义全局变量'Private Sub Command1_Click(Index As Integer)Timer1.Enabled = True '当点击任意一个命令按钮时(即开始游戏),则启动计时器' i = Index \ 10 + 1j = Index Mod 10 + 1 '将二维数组的元素与命令按钮一一对应'If d(i, j) = 1 Then '判断是否点到地雷'Timer1.Enabled = False '关闭计时器,游戏结束'For i = 1 To 10For j = 1 To 10n = 10 * (i - 1)m = j - 1If d(i, j) = 1 ThenCommand1.Item(m + n).Picture = LoadPicture(App.Path & "\2.jpg") '在按钮上显示地雷图片'End IfForm1.Show '弹出子窗体1(判断输赢)'Next jNext iElseIf v(Index) = Index + 1 Then '判断是否插上红旗或是问号图片'Command1.Item(Index).Picture = LoadPicture() '清除图片'Command1.Item(Index).Caption = f(i, j) '调用函数,显示周围地雷数'Command1.Item(Index).Enabled = False '将按钮设为不可用'Label7.Caption = Val(Label7.Caption) + 1v(Index) = 0End Ifh = s(i, j) '调用函数,显示周围的情况(边界)'For Y = 0 To 99If v(Y) = Y + 1 ThenCommand1.Item(Y).Enabled = True '如果是按钮插上了红旗则将按钮设置为可用'End IfNext YEnd IfFor k = 0 To 99If Command1.Item(k).Enabled = False Thenp = p + 1 '统计扫过的按钮个数'If p = 90 ThenFor Y = 0 To 100v(Y) = 0Next Y '将数组v的元素重新置0(此步目的为实现重玩而设)'Form2.Show '如果等于90个则结束游戏,弹出子窗体2(赢了)'End IfEnd IfNext kEnd SubPrivate Sub Command1_MouseUp(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = 2 Then '右击鼠标'If v(Index) <> Index + 1 Then '判断是否已插上红旗'Command1.Item(Index).Picture = LoadPicture(App.Path & "\1.jpg") '插上红旗'v(Index) = Index + 1 '给数组元素赋值,以此实现按钮图片的切换或显示状态'Label7.Caption = Val(Label7.Caption) - 1 '在标签7中显示插上的红旗个数'ElseCommand1.Item(Index).Picture = LoadPicture(App.Path & "\3.jpg") '将问号图片替换红旗'Label7.Caption = Val(Label7.Caption) + 1v(Index) = 0End IfEnd IfFor i = 1 To 10For j = 1 To 10If d(i, j) = 1 Thenn = 10 * (i - 1)m = j - 1If v(m + n) = m + n + 1 Then c = c + 1If c = 10 ThenFor Y = 0 To 100v(Y) = 0Next Y '将数组v的元素重新置0(此步目的为实现重玩而设)'Form2.Show '如果等于90个则结束游戏,弹出子窗体2(赢了)'End IfEnd IfNext jNext iEnd SubPrivate Sub Form_Load()k = 0For i = 1 To 10For j = 1 To 10d(i, j) = 0 '将数组元素置0'Next jNext iDo While n <> 10Randomizei = Int(10 * Rnd + 1)j = Int(10 * Rnd + 1)If d(i, j) = 0 Then d(i, j) = 1: n = n + d(i, j) '产生十个随机数,即相当于十个地雷'Loopbel7.Caption = 10bel2.Caption = 0bel3.Caption = 0End SubFunction f(i, j) '定义一个函数求一个区域周围地雷的个数'f = f + d(i - 1, j - 1) + d(i - 1, j) + d(i - 1, j + 1) + d(i, j - 1)f = f + d(i, j + 1) + d(i + 1, j - 1) + d(i + 1, j) + d(i + 1, j + 1)End FunctionFunction s(i, j) '定义一个函数显示点击区域周围的情况(即边界)' For Y = 0 To 100If v(Y) = Y + 1 ThenCommand1.Item(Y).Enabled = False '如插上了红旗,则将按钮先设为不可用'End IfNext YIf f(i, j) <> 0 Then '函数嵌套,调用函数判断周围是否无地雷'n = 10 * (i - 1)m = j - 1Command1.Item(m + n).Picture = LoadPicture()Command1.Item(n + m).Caption = f(i, j)Command1.Item(n + m).Enabled = False '清除图片,显示地雷数,设置按钮不可用'ElseFor a = i - 1 To i + 1For b = j - 1 To j + 1If a <> 0 And b <> 11 And a <> 11 And b <> 0 Thenn = 10 * (a - 1)m = b - 1If Command1.Item(n + m).Enabled = True ThenCommand1.Item(m + n).Picture = LoadPicture()Command1.Item(n + m).Caption = f(a, b)Command1.Item(n + m).Enabled = False '清除图片,显示地雷数,设置按钮不可用'h = s(a, b) '调用函数本身,即实现递归'End IfEnd IfNext bNext aEnd IfEnd FunctionPrivate Sub Timer1_Timer() '设计一个计时器'Label2.Caption = Val(Label2.Caption) + 1Label3.Caption = Val(Label2.Caption) \ 60 + Val(Label3.Caption)Label2.Caption = Val(Label2.Caption) Mod 60End Sub二、子窗体一(form1)界面如下:子窗体一(form1)的代码:Private Sub Command1_Click()Unload Form10Unload form1Form10.ShowEnd SubPrivate Sub Command2_Click()Unload Form10Unload form1End SubPrivate Sub Command3_Click()For i = 0 To 99mand1.Item(i).Picture = LoadPicture() mand1.Item(i).Caption = ""mand1.Item(i).Enabled = TrueNext ibel7.Caption = 10bel2.Caption = 0bel3.Caption = 0Unload form1End Sub三、子窗体(form2)界面如下:子窗体二(form2)的代码:Private Sub Command1_Click()Unload Form10Form10.ShowUnload form2End SubPrivate Sub Command2_Click()Unload Form10Unload form2End SubPrivate Sub Command3_Click()For i = 0 To 99mand1.Item(i).Picture = LoadPicture()mand1.Item(i).Caption = ""mand1.Item(i).Enabled = TrueNext iUnload form2bel7.Caption = 10bel2.Caption = 0bel3.Caption = 0End Sub注释:共三个窗体(这里是form10、form1、form2)、三个标签(这里是label2、label3、label7)设计时,根据具体的情况对应修改即可。

利用VB开发扫雷游戏

利用VB开发扫雷游戏


初 始 化
1 .在 本 程 序 中 ,设 置 程 序 界 面 为 6X 6共 3 6个 子 区 域 ,
Fr o i= 1T 6 o3
R no i ad mz e
初 始 化 雷 的个 数
I n (0 fIt 1
R d +1 n )>8T en h
每 一 个 区 域 i按 从 左 至 右 ,从 上 至 下 标 记 ) lbl() cn ( 有 aeli和 o —
徐 勇


本 文介 绍在 Wid w 环境 下利 用 V 6 0开发 一个 简单 的扫 雷 游戏 的方 法 。 no s B,
扫 雷 ,V 6 0 B . ,控件
关 键词
扫 雷 游 戏是 Widw 操 作 系 统 自带 的 一个 小 游 戏 ,过 去 的 no s
几 年 里 Widw 操 作 系 统 历 经 数 次换 代 , 变得 越 来 越 庞 大 、复 no s
b l qzs。
Fr o i= 2 T o 5
F r 1 L b l i . p in = ar i一 1 + a ri+ 1 o m . a e1() Ca t o r( ) r( ) + a ri+ 5 + a ri+ 6 + ar i+ 7) r( )~ r( ) r(
尝 试 着 开发 一 个 类 似 的 “ 雷 游 戏 ” ,下 面就 将 笔 者 在 教 学 过 扫
4 .用 一 个 cm a d控 件 表 示 游 戏 进 行 的 状 态 ( 始 化 按 omn 初 钮 ) 初 始 状 态 该 cm a d控 件 的 p tr 性 为 图 :平 静 的 , omn i ue属 c
路。

P i e ) 为 O表 示 什 么 也 没 有 , 示 红 旗 , ( d x值 n 1表 2是 问 号

VB扫雷小游戏编程代码

VB扫雷小游戏编程代码

VB扫雷小游戏一.编程目的二.编程思路1.新建command_up和label_down控件2.用load加载控件3.根据雷区的X、Y、以及难度进行随机布雷。

4.统计每一个label周围雷的数量并作为label的caption。

5.在单击command的时候显示label6.在右击command的时候进行标记7.在label上左右键同时按下的时候检查已标记雷的数量与label显示的数量是否一致。

三.界面设计四.代码设计Dim Start_Time, End_TimeDim Area_X%, Area_Y%, Area%, Area_List()Dim Current_Mine%Dim Difficulty#Dim Continue_Flag%, Success_Flag%, LeftAndRight_Flag%Dim Near_ListDim Mine_CountPrivate Sub Command_End_Click()EndEnd SubPrivate Sub Delete_Item(List(), Index As Integer)Dim i%For i = LBound(List) + Index - 1 To UBound(List) - 1List(i) = List(i + 1)Next i'防止100%的困难度If UBound(List) > LBound(List) Then ReDim Preserve List(LBound(List) To UBound(List) - 1) End SubPrivate Sub Command_retry_Click()'卸载For i = 1 To AreaUnload Label_Down(i)Unload Command_Up(i)Next iCommand_Start.Caption = "开始游戏"Call Command_Start_ClickEnd SubPrivate Sub Command_Up_Click(Index As Integer)Success_Flag = 1If Continue_Flag = 1 ThenIf Timer1.Enabled = False Then Call Command_Start_ClickIf Label_Down(Index).Caption = "X" ThenSuccess_Flag = 0Continue_Flag = 0For i = 1 To AreaIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbRed Then'标记雷正确Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_correct.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbGreen Then'标记雷错误Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_wrong.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseCommand_Up(i).Visible = FalseLabel_Down(i).Visible = TrueEnd IfNext iTimer1.Enabled = Falsetemp = MsgBox("Game Over !", vbOKOnly, "游戏结束")ElseIf Val(Label_Down(Index).Caption) > 0 ThenCommand_Up(Index).Visible = FalseLabel_Down(Index).Visible = TrueElse'如果等于0的话应该将周边的清零Command_Up(Index).Visible = FalseLabel_Down(Index).Visible = Truej = IndexFor i = 1 To 8'判断控件是否存在If j + Near_List(i) > 0 And j + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(j + Near_List(i)).Left -Label_Down(j).Left) <= Label_Down(j).Width And Abs(Label_Down(j + Near_List(i)).Top -Label_Down(j).Top) <= Label_Down(j).Height Then'判断是否有雷If Label_Down(j + Near_List(i)).BackColor = vbGreen And Command_Up(j + Near_List(i)).Visible = True ThenCall Command_Up_Click(j + Near_List(i)) '注意此处循环调用的时候一定要避免陷入死循环End IfEnd IfEnd IfNext iEnd If'检查是否游戏成功For i = 1 To AreaIf Command_Up(i).Visible = True And Label_Down(i).Caption <> "X" ThenSuccess_Flag = 0Exit ForEnd IfNext iIf Success_Flag = 1 ThenIf Continue_Flag = 1 ThenTimer1.Enabled = FalseFor i = 1 To AreaIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbRed Then'标记雷正确Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_correct.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbGreen Then'标记雷错误Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_wrong.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseCommand_Up(i).Visible = FalseLabel_Down(i).Visible = TrueEnd IfNext itemp = MsgBox("恭喜,扫雷成功!" & vbCrLf & "耗时:" & Mid(Label_Time.Caption, 4) & vbCrLf & "鸣谢:平方X O(∩_∩)O~", vbOKOnly, "成功") End IfContinue_Flag = 0 '提示一次后结束,防止在调用Command_Click事件中重复提示End IfEnd IfCommand_Start.SetFocusEnd SubPrivate Sub Command_Start_Click()If Command_Start.Caption = "开始游戏" ThenCommand_Start.Caption = "重新开始"Continue_Flag = 1Timer1.Enabled = TrueDifficulty = Val(Text_Difficulty.Text) / 100Area_X = Val(Text_X.Text)Area_Y = Val(Text_Y.Text)Area = Area_X * Area_Y'初始化这里进行二次初始化的原因是如果在之前的运行中对字体进行了改变,将有可能造成此处的控件大小发生变化With Picture_show.Left = 200.Top = 200.Width = 750 * 10.Height = 750 * 10.Visible = FalseEnd WithWith Command_Up(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = 200.Top = 200.Width = 750 * 10 / IIf(Area_X > Area_Y, Area_X, Area_Y).FontSize = 25 * (.Width / 750) '会自动缩放,必须先设置了.Height = 750 * 10 / IIf(Area_X > Area_Y, Area_X, Area_Y).Visible = FalseEnd WithWith Command_Up(0).Left = 200.Top = 200.Width = Label_Down(0).Width.Height = Label_Down(0).Height.Visible = FalseEnd WithReDim Near_List(1 To 8)Near_List(1) = 0 - 1 - Area_YNear_List(2) = 0 - 0 - Area_YNear_List(3) = 0 + 1 - Area_YNear_List(4) = 0 - 1Near_List(5) = 0 + 1Near_List(6) = 0 - 1 + Area_YNear_List(7) = 0 - 0 + Area_YNear_List(8) = 0 + 1 + Area_Y'如果在列表中有相等的元素将有可能造成统计雷的数目错误For i = 1 To 8For j = i + 1 To 8If Near_List(i) = Near_List(j) Then Near_List(i) = 0Next jNext iArea_temp = 0For Y = 1 To Area_Y'加载labelFor X = 1 To Area_XArea_temp = Area_temp + 1Load Label_Down(Area_temp)With Label_Down(Area_temp).Left = Label_Down(0).Left + Label_Down(0).Width * ((Area_temp -1) Mod Area_Y).Top = Label_Down(0).Top + Label_Down(0).Height * ((Area_temp -1) \ Area_Y).BackColor = vbGreen.Visible = False.Alignment = 2.Font = .FontBoldEnd With'加载commandLoad Command_Up(Area_temp)With Command_Up(Area_temp)'对列数求余的话就是在这一行第几个了.Left = Command_Up(0).Left + Command_Up(0).Width * ((Area_temp - 1) Mod Area_Y)'整除列数的话可以确定第几行.Top = Command_Up(0).Top + Command_Up(0).Height * ((Area_temp - 1) \ Area_Y).Visible = TrueEnd WithNext XNext YReDim Area_List(1 To Area)For i = 1 To AreaArea_List(i) = iNext i' 随即布雷RandomizeMine_Count = Val(Text_Mine_Count.Text)For i = 1 To Mine_CountCurrent_Mine = Int(Rnd * (UBound(Area_List) - LBound(Area_List) + 1) + 1) '在数组中随机一个,注意此处2个+1的必要性和准确性Label_Down(Area_List(Current_Mine)).BackColor = vbRed '将该位置标记为雷Call Delete_Item(Area_List, Current_Mine) '删除该位置,防止再次标记Next i'检查雷的数目For j = 1 To AreaIf Label_Down(j).BackColor = vbRed ThenLabel_Down(j).Caption = "X"ElseMine_Number = 0For i = 1 To 8'判断控件是否存在If j + Near_List(i) > 0 And j + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(j + Near_List(i)).Left -Label_Down(j).Left) <= Label_Down(j).Width And Abs(Label_Down(j + Near_List(i)).Top -Label_Down(j).Top) <= Label_Down(j).Height Then'判断是否有雷If Label_Down(j + Near_List(i)).BackColor = vbRed ThenMine_Number = Mine_Number + 1End IfEnd IfEnd IfNext iLabel_Down(j).Caption = Mine_NumberEnd IfNext jStart_Time = Now()ElseIf Command_Start.Caption = "重新开始" ThenCall Command_retry_ClickEnd IfEnd SubPrivate Sub Command_Up_MouseDown(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = 2 ThenIf Command_Up(Index).Caption = "" ThenCommand_Up(Index).Caption = "X"Command_Up(Index).Picture = LoadPicture(App.Path + "\pictures\mine.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)ElseIf Command_Up(Index).Caption = "X" ThenCommand_Up(Index).Caption = "?"Command_Up(Index).Picture = LoadPicture(App.Path + "\pictures\Unknown.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)ElseIf Command_Up(Index).Caption = "?" ThenCommand_Up(Index).Caption = ""Command_Up(Index).Picture = LoadPicture("") End IfEnd IfEnd SubPrivate Sub Form_Load()With Picture_show.Left = 200.Top = 200.Width = 750 * 10.Height = 750 * 10.Visible = FalseEnd WithWith Command_Up(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd With'加载计时器Timer1.Enabled = FalseTimer1.Interval = 100'加载滚动条With HScroll_Difficulty.LargeChange = 5.SmallChange = 1.Max = 100.Min = 0.Value = 10End WithWith HScroll_Area_X.LargeChange = 5.SmallChange = 1.Max = 100.Min = 1.Value = 10End WithWith HScroll_Area_Y.LargeChange = 5.SmallChange = 1.Max = 100.Min = 1.Value = 10End WithWith HScroll_Mine_Count.LargeChange = 5.SmallChange = 1.Max = 100.Min = 0.Value = 10End With'由于很多数据不方便处理,索性让其禁用了Text_Difficulty.Enabled = FalseText_Mine_Count.Enabled = FalseText_X.Enabled = FalseText_Y.Enabled = FalseEnd SubPrivate Sub HScroll_Area_X_Change()Text_X.Text = HScroll_Area_X.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_X_Scroll()Text_X.Text = HScroll_Area_X.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_Y_Change()Text_Y.Text = HScroll_Area_Y.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_Y_Scroll()Text_Y.Text = HScroll_Area_Y.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Difficulty_Change()Text_Difficulty.Text = HScroll_Difficulty.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Difficulty_Scroll()Text_Difficulty.Text = HScroll_Difficulty.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Mine_Count_Change()Text_Mine_Count.Text = HScroll_Mine_Count.ValueHScroll_Difficulty.Value = HScroll_Mine_Count.Value / (HScroll_Area_X.Value * HScroll_Area_Y.Value) * 100End SubPrivate Sub HScroll_Mine_Count_Scroll()Text_Mine_Count.Text = HScroll_Mine_Count.ValueHScroll_Difficulty.Value = HScroll_Mine_Count.Value / (HScroll_Area_X.Value * HScroll_Area_Y.Value) * 100End SubPrivate Sub Label_Down_MouseUp(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" And Command_Up(Index + Near_List(i)).Caption <> "?" ThenCommand_Up(Index + Near_List(i)).Picture = LoadPicture("")End IfEnd IfEnd IfNext iEnd SubPrivate Sub label_down_MouseDown(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)If LeftAndRight_Flag + Button = 3 Then '双击完成Mine_Number = Val(Label_Down(Index).Caption)Mark_mine_number = 0For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption = "X" ThenMark_mine_number = Mark_mine_number + 1End IfEnd IfEnd IfNext iIf Val(Label_Down(Index).Caption) - Mark_mine_number <= 0 Then '已全部标出,自动点开For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" ThenCall Command_Up_Click(Index + Near_List(i))End IfEnd IfEnd IfNext iElse '如果没有全部标注的话应该显示一下嘛For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" ThenCommand_Up(Index + Near_List(i)).Picture = LoadPicture(App.Path + "\pictures\xia.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)End IfEnd IfEnd IfNext iEnd IfElseLeftAndRight_Flag = Button'Print LeftAndRight_FlagEnd IfEnd SubPrivate Sub Timer1_Timer()LeftAndRight_Flag = 0End_Time = Now()spend_time = (End_Time - Start_Time) * 10 ^ 5Label_Time.Caption = "时间:" & Format(Int(spend_time) \ (60 * 60), "00") & ":" & Format((Int(spend_time) Mod (60 * 60)) \ 60, "00") & ":" & Format(Int(spend_time) Mod 60, "00") & "." & Format(Int((spend_time - Int(spend_time)) * 1000), "000")End Sub五.软件截图1 2 3。

扫雷程序设计思路_Visual Basic程序设计基础_[共4页]

扫雷程序设计思路_Visual Basic程序设计基础_[共4页]
以 9 个按钮为例设计一雷区。设命令按钮数组名为 Cmd,index 范围为 0~8。与之对应的 二维数组名为 A(0 to 2,0 to 2)。按钮各元素排列顺序如图 5-35(a)所示。与按钮对应的二维数组 的下标排列如图 5-35(b)所示,按钮对应的二维数组的元素值与按钮所标定的颜色如图 5-35(c) 所示。
133
ElseIf a = 1 Then Text1.Text = date_one - Val(Text1.Text)
ElseIf a = 2 Then Text1.Text = date_one * Val(Text1.Text)
ElseIf a = 3 Then If val(Text1.Text) = 0 Then MsgBox "除数不能为零", 50, "调试" Else Text1.Text = date_one / Val(Text1.Text) End If
第5章 数 组
Text1.Text = "" a = Index End Sub Private Sub Command3_Click() Text1.Text = -1 * Val(Text1.Text) End Sub Private Sub Command4_Click()
If a = 0 Then Text1.Text = date_one + Val(Text1.Text)
End If End Sub Private Sub Command5_Click()
If val(Text1.Text )= 0 Then MsgBox "除数不能为零", 50, "调试"
Else Text1.Text = 1 / Val(Text1.Text)

扫雷游戏的程序设计及代码示例

扫雷游戏的程序设计及代码示例

扫雷游戏的程序设计及代码示例前言:扫雷游戏是一款经典的单人益智游戏,玩家需要根据数字提示,揭开地图上隐藏的地雷,同时避免触雷。

本文将讨论扫雷游戏的程序设计思路以及提供一个简单的代码示例。

一、程序设计思路1. 游戏界面设计:扫雷游戏的界面通常包含一个方格矩阵和一些按键/菜单选项。

方格矩阵用于显示地图的状态,每个方格可以是隐藏的、揭开的、插上旗帜、标有数字或地雷等状态。

2. 游戏逻辑设计:扫雷游戏逻辑包括生成地雷布局、计算数字提示及判断游戏胜负等。

在游戏开始时,需要根据设定的难度级别随机生成地雷布局,将地雷随机分布在方格矩阵中的某些位置。

数字提示根据地雷周围的方格中地雷的数量计算得出。

游戏胜利的条件是所有非地雷方格都被揭开。

3. 用户交互设计:扫雷游戏需要与用户进行交互,比如根据用户的点击操作揭开方格、插上旗帜并标记地雷、显示计时等功能。

用户输入的坐标和操作将触发相应的逻辑判断和更新。

二、代码示例以下是一个用Python语言实现的简单扫雷游戏代码示例,供参考:```pythonimport randomdef generate_board(size, num_mines):# 生成地雷布局board = [[' ' for _ in range(size)] for _ in range(size)]mines = random.sample(range(size*size), num_mines)for mine in mines:row = mine // sizecol = mine % sizeboard[row][col] = '*'return boarddef calculate_hints(board):# 计算数字提示size = len(board)for row in range(size):for col in range(size):if board[row][col] == ' ':count = 0for i in range(max(0, row-1), min(row+2, size)): for j in range(max(0, col-1), min(col+2, size)): if board[i][j] == '*':count += 1if count > 0:board[row][col] = str(count)def reveal_square(board, row, col):# 揭开方格if board[row][col] == '*':return False # 触雷elif board[row][col] == ' ':size = len(board)queue = [(row, col)]while queue:r, c = queue.pop(0)if board[r][c] == ' ':board[r][c] = '-'for i in range(max(0, r-1), min(r+2, size)):for j in range(max(0, c-1), min(c+2, size)): if board[i][j] != '-':queue.append((i, j))elif board[r][c].isdigit():board[r][c] = board[r][c]return Truedef print_board(board, show_mines=False):# 打印游戏界面size = len(board)print('-'*(4*size+1))for row in range(size):for col in range(size):if board[row][col] == '*' and not show_mines: print(' #', end='')else:print(' ' + board[row][col], end='')print(' ')print('-'*(4*size+1))def play_game(size, num_mines):# 游戏主体逻辑board = generate_board(size, num_mines)calculate_hints(board)print_board(board)while True:row = int(input('请输入要翻开的方格行号:')) - 1 col = int(input('请输入要翻开的方格列号:')) - 1 if not (0 <= row < size and 0 <= col < size):print('输入无效,请重新输入!')continueif not reveal_square(board, row, col):print('触雷!游戏结束!')print_board(board, show_mines=True)breakprint_board(board)# 主函数if __name__ == '__main__':print('欢迎来到扫雷游戏!')size = int(input('请输入地图大小:'))num_mines = int(input('请输入地雷数量:'))play_game(size, num_mines)```三、总结以上是一个简单的扫雷游戏代码示例,通过实现游戏界面设计、游戏逻辑设计和用户交互设计,实现了基本的扫雷功能。

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 组件内必须存储大小相同的图片,所在这 款游戏设计中,显示的图片共分为三个部分:游戏状态图形、数字计数图形和地 雷区标示图形。

VB扫雷小游戏

VB扫雷小游戏

VB扫雷小游戏1.游戏功能分析扫雷小游戏需要做哪些功能呢?在开始游戏后,程序需要根据难度系数自动生成一片雷区,雷区包含少数地雷和多数空地,在规定时间内找出雷区中的所有地雷即可胜利。

左键点击地雷会导致游戏失败,并给出所有地雷的位置;右键点击地雷或者空地都会在上面标记一面小旗,但右键点击地雷时,剩余地雷数会-1,而点击空地时不会。

每次右键标记地雷后,都要判断剩余地雷数是否为0,是的话就胜利了。

2.控件分析通过以上的游戏功能分析可以得到我们需要用到的控件。

在游戏提示方面,我们需要1个标签lblbomb来显示雷数,1个标签lbltime来显示剩余时间,一个timer1来计时,1个按钮cmdstart作为开始游戏的按钮。

并且把以上控件全放如一个框架frame1中。

在雷区这里,我们需要1个按钮来表示空地,并设置index为0;1个按钮来表示地雷,并设置index为0;一个标签来显示周围地雷数,并设置index为0.在游戏开始后,需要根据游戏难度加载出空地按钮和地雷按钮以及显示周围地雷数得标签按钮下面给出主要控件的名称及主要参数【说明】【名称】【index】空地按钮Cmd0 0地雷按钮Cmd1 0标签按钮lblnum 0在调试过程中可以将空地按钮的caption设置为0,地雷按钮的caption 设置为1,便于调试。

3.变量参数分析主要游戏参数:Public level As Integer ' 游戏难度Public cmdnum As Integer ' 雷区所有按钮数目Public bombnum As Integer ' 地雷数目Public timerest As Integer ' 剩余时间Public matrix() As Integer ' 雷区矩阵,0代表空地,1代表地雷Public bombrest As Integer ' 剩余地雷数这里我们设置雷区为正方形,此正方形的一条边上有几个按钮,难度就是几,所以有cmdnum=level^2。

扫雷辅助代码

扫雷辅助代码

扫雷辅助代码// 扫雷.cpp : 此文件包含 "main" 函数。

程序执行将在此处开始并结束。

//#include "pch.h"#include#includeint main(){//获取扫雷句柄HWND hWinmine = FindWindow(NULL, L"扫雷");//线程变量DWORD dwPID = 0;//获得扫雷的线程GetWindowThreadProcessId(hWinmine, &dwPID);//获得线程句柄HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, dwPID);//左顶点的第一个雷地址DWORD dwFirstAddr = 0x01005361;//需要读取的内存数量DWORD dwNum = 0x57F - 0x361;//申请内存建立数组PBYTE pByte = new BYTE[dwNum];//读取内存ReadProcessMemory(hProcess, (LPVOID)dwFirstAddr, pByte,dwNum,NULL);//开始改地址BYTE bClear_flag = 0x8E;BYTE bClear_zero = 0x40;for (size_t i = 0; i <= dwNum; i++){if (pByte[i] == 0x8F){WriteProcessMemory(hProcess, (LPVOID)(dwFirstAddr + i), &bClear_flag, sizeof(BYTE), NULL);}elseif (pByte[i] == 0x0F){WriteProcessMemory(hProcess, (LPVOID)(dwFirstAddr + i), &bClear_zero, sizeof(BYTE), NULL);}}RECT rt = { 0 };//获取窗口客户区的大小GetClientRect(hWinmine, &rt);//指定的窗体更新区域添加一个矩形,然后窗口客户区域的这一部分将被重新绘制InvalidateRect(hWinmine, &rt, true);delete pByte;CloseHandle(hProcess);return 0;}。

简易vb扫雷代码

简易vb扫雷代码

简易vb扫雷代码Dim X As Integer, total%Private Sub Command1_Click()RandomizeDim k As Integer, m As Integerw = Form1.Widthh = Form1.Height * 0.9X = Val(InputBox("请输入行列数"))For i = 1 To XFor j = 1 To Xk = (i - 1) * X + jLoad Label1(k)Label1(k).Caption = ""Label1(k).Visible = TrueLabel1(k).Width = w \ XLabel1(k).Height = h \ XLabel1(k).Top = h / X * (i - 1)Label1(k).Left = w / X * (j - 1)If (i + j) Mod 2 = 0 ThenLabel1(k).BackColor = QBColor(12)ElseLabel1(k).BackColor = QBColor(15)End IfLabel1(k).FontSize = 260 \ XLabel1(k).Tag = IIf(Int(Rnd * 20 + 1) Mod 19 = 1, "○", " ") If Label1(k).Tag = "○" Then total = total + 1Label1(k).Alignment = 2Next jNext iLabel1(0).BackColor = QBColor(0)For i = 1 To XFor j = 1 To XIf j + 1 <= X And i > 1 ThenIf Label1((i - 2) * X + j + 1).Tag = "○" Then m = m + 1 End If If j + 1 <= X And i + 1 < X ThenIf Label1(i * X + j + 1).Tag = "○" Then m = m + 1End IfIf i + 1 <= X And j > 1 ThenIf Label1(i * X + j - 1).Tag = "○" Then m = m + 1End IfIf i > 1 And j > 1 ThenIf Label1((i - 2) * X + j - 1).Tag = "○" Then m = m + 1End IfIf j + 1 <= X ThenIf Label1((i - 1) * X + j + 1).Tag = "○" Then m = m + 1End IfIf i + 1 <= X ThenIf Label1(i * X + j).T ag = "○" Then m = m + 1End IfIf j > 1 ThenIf Label1((i - 1) * X + j - 1).Tag = "○" Then m = m + 1End IfIf i > 1 ThenIf Label1((i - 2) * X + j).Tag = "○" Then m = m + 1End IfLabel1((i - 1) * X + j).ToolTipText = mm = 0NextNextEnd SubPrivate Sub Form_Load()Label1(0).Visible = FalseMe.Width = 8000Me.Height = Me.WidthEnd SubPrivate Sub Label1_Mousedown(Index As Integer, Button As Integer, Shift As Integer, p As Single, q As Single)Static gross%If Button = 2 Then La bel1(Index).Caption = "※"If Button = 1 ThenIf Label1(Index).Tag = "○" ThenMsgBox "你挖到雷了"gross = 0For i = 1 To X * XLabel1(i).Caption = Label1(i).TagNext iFor i = 1 To X * X '延时Label1(i).BackColor = vbWhiteNextFor i = 1 To 1000000DoEventsNextFor i = 1 To X * XUnload Label1(i)NextElseLabel1(Index).BackColor = vbGreenLabel1(Index).Caption = Label1(Index).ToolTipTextIf Label1(Index).ToolTipText = "0" ThenIf Index Mod X = 0 Then i = Index / X Else i = Int(Index / X) + 1If Index Mod X = 0 Then j = X Else j = Index Mod XIf j + 1 <= X And i > 1 ThenLabel1((i - 2) * X + j + 1).Caption = Label1((i - 2) * X + j + 1).ToolTipText End IfIf j + 1 <= X And i + 1 < X ThenLabel1(i * X + j + 1).Caption = Label1(i * X + j + 1).ToolTipText End IfIf i + 1 <= X And j > 1 ThenLabel1(i * X + j - 1).Caption = Label1(i * X + j - 1).ToolTipText End IfIf i > 1 And j > 1 ThenLabel1((i - 2) * X + j - 1).Caption = Label1((i - 2) * X + j - 1).ToolTipText End IfIf j + 1 <= X ThenLabel1((i - 1) * X + j + 1).Caption = Label1((i - 1) * X + j + 1).ToolTipText End IfIf i + 1 <= X ThenLabel1(i * X + j).Caption = Label1(i * X + j).ToolTipT extEnd IfIf j > 1 ThenLabel1((i - 1) * X + j - 1).Caption = Label1((i - 1) * X + j - 1).ToolTipText End IfIf i > 1 ThenLabel1((i - 2) * X + j).Caption = Label1((i - 2) * X + j).ToolTipText End IfEnd IfEnd IfEnd Ifgross = 0If Label1.Count > 1 ThenFor i = 1 To X * XIf Label1(i).Caption = "※" Then gross = gross + 1Next iEnd Ifs = 0If Label1.Count > 1 ThenFor i = 1 To X * XIf Label1(i).BackColor = vbGreen Then s = s + 1Next iEnd IfDebug.Print "s的值是"; sDebug.Print "gross"; grossDebug.Print "total"; totalIf s + gross = X * X Then '确保探测完所有方块msg = MsgBox("恭喜你清完了所有雷,是否重新开始?", vbYesNo) If msg = vbYes ThenFor i = 1 To X * XUnload Label1(i)NextEnd Ifgross = 0End IfEnd Sub。

vb扫雷游戏代码

vb扫雷游戏代码

Public Class formDim chks(8, 8) As CheckBoxDim o As IntegerDim i, j As IntegerDim P, U As IntegerDim arr(9, 0) As ObjectPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Clicko = 0For i = 0 To 8For j = 0 To 8If chks(i, j) Is Nothing Thenchks(i, j) = New CheckBox()End IfAddHandler chks(i, j).MouseUp, AddressOf Chk_MouseUpchks(i, j).Appearance =Appearance.Buttonchks(i, j).height = 25chks(i, j).width = 25chks(i, j).Top = i * 25 + 50chks(i, j).left = j * 25chks(i, j).text = ""chks(i, j).tag = 0chks(i, j).BackColor = Me.BackColorchks(i, j).checked = Falsechks(i, j).Enabled = Truechks(i, j).Font = New Font("Arial", 14, FontStyle.Bold)Me.Controls.Add(chks(i, j))NextNextDim n As Integer = 0Dim h As Integer = 0Randomize()Do While h < 10P = Math.Floor(Rnd() * 9)U = Math.Floor(Rnd() * 9)If chks(P, U).Tag = 0 Thenarr(n, 0) = chks(P, U)chks(P, U).Tag = 1h = h + 1n += 1End IfLoopTimer1.Enabled = TrueEnd SubPrivate Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)End SubPrivate Sub Chk_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)Dim chk As CheckBox = CType(sender, CheckBox)Dim m As IntegerIf chk.Tag = 1 ThenFor m = 0 To 9arr(m, 0).BackColor = Color.BlueNextMsgBox("over ")EndEnd IfCall autoopen(chk)End SubSub autoopen(ByVal chk As CheckBox)Dim row As Integer = chk.Top / 25Dim col As Integer = chk.Left / 25Dim i, j As IntegerDim sum As Integer = 0For i = row - 1 To row + 1For j = col - 1 To col + 1If (i >= 0) And (i < 9) And (j >= 0) And (j < 9) Thensum += chks(i, j).TagEnd IfNextNextchk.Text = sumchk.Enabled = FalseIf sum = 0 ThenFor i = row - 1 To row + 1For j = row - 1 To row + 1If (i >= 1) And (i <= 8) And (j >= 1) And (j <= 8) ThenIf chks(i, j).Text = "" ThenCallautoopen(chks(i, j))End IfEnd IfNextNextEnd IfEnd SubPrivate Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadEnd SubPrivate Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Ticko = o + 1TextBox1.Text = oEnd SubPrivate Sub Button1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) HandlesButton1.MouseDoubleClickEnd SubPrivate Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChangedEnd SubEnd Class。

VB.NET扫雷游戏

VB.NET扫雷游戏

目录问题描述 (1)需求分析 (1)程序规划 (3)程序流程图 (3)概要设计 (5)一、界面设计 (5)1、主界面MainForm (5)2、选项框Options (7)3、统计信息HighScore (8)4、帮助框体Help (9)5、关于AboutBox (9)详细设计 (10)1、函数设计 (10)MainForm窗体: (10)MainForm函数调用关系图: (17)Options窗体: (17)2、程序性能分析 (19)测试分析 (20)一、基本功能测试 (20)1、游戏功能 (20)2、设置功能 (24)3、帮助功能 (29)二、白盒测试 (31)输入错误测试 (31)三、测试结果 (34)问题描述编写一个扫雷程序,完成基本的扫雷游戏功能。

需求分析用户打开游戏界面。

游戏界面有两下拉菜单,一个是游戏菜单,另一个是帮助菜单。

界面中间是矩阵方格,下方是计时器和雷计数器,分别显示扫雷用时和未扫出雷的个数。

开始扫雷时,用户无论第一次点击哪个格子都不会是雷。

之后用户鼠标左键单击小格,是雷就扫雷失败,失败就显示所有雷的位置;不是雷且是数字就显示数字,没有数字就打开周围的空格直到周围(横向纵向的四个格子,不包括对角线)是数字。

鼠标右键点击小格标注小红旗,如果不确定就点击两次右键标注问号,再点一次还原。

标注红旗则表示用户标注此处为雷(不管是否正确),问号用于给用户标注不确定的区域,对游戏进程无影响。

标注红旗的格子无法用左键打开,问号格子可以。

左右键同时点中一个数字且数字周围的红旗数等于数字则将其他的小格全部打开,若红旗数大于或小于数字则将其他的小格闪动提示用户无法打开。

如果旗子插错则导致打开含雷的区域,游戏失败。

若将所有雷标出则提示游戏通关,若超过该难度前十记录则提示用户保存记录。

游戏设有计时器,按秒计算,最高显示999秒。

游戏显示剩余雷数,此显示总雷数减去用户插的小旗数。

在游戏菜单中设有“新游戏”、“统计信息”、“选项”、“退出”,四个功能项。

Vb扫雷程序代码

Vb扫雷程序代码

Private objMine As New clsWinMinePrivate Sub Form_Load()Set objMine.frmDisplay = MeEnd SubPrivate Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, y As Single) ' 判断单击的是哪个区域objMine.BeginHitTest Button, x, yEnd SubPrivate Sub Form_MouseMove(Button As Integer, Shift As Integer, x As Single, y As Single) ' 判断当鼠标左键按下的时候鼠标指针在哪个区域objMine.TrackHitTest Button, x, yEnd SubPrivate Sub Form_MouseUp(Button As Integer, Shift As Integer, x As Single, y As Single) ' 判断释放鼠标左键的时候鼠标指针在哪个区域objMine.EndHitTest Button, x, yEnd SubPrivate Sub mnuBeginner_Click()mnuBeginner.Checked = TruemnuIntermediate.Checked = FalsemnuExpert.Checked = FalsemnuCustom.Checked = False' 初级模式objMine.SetMineFieldDimension 8, 8, 10, FalseobjMine.mblnNewGame = TrueEnd SubPrivate Sub mnuCustom_Click()mnuBeginner.Checked = FalsemnuIntermediate.Checked = FalsemnuExpert.Checked = FalsemnuCustom.Checked = True' 中级模式objMine.GetMineFieldDimensions frmCustomDlgfrmCustomDlg.Show 1' 如果按ESC键,则退出If frmCustomDlg.mblnEscape Then Exit SubobjMine.SetMineFieldDimension Val(frmCustomDlg.txtRows), Val(frmCustomDlg.txtColumns), Val(frmCustomDlg.txtMines), True' 卸载隐藏的对话框Unload frmCustomDlg' 做好准备开始新游戏objMine.mblnNewGame = TrueEnd SubPrivate Sub mnuExit_Click()' 调用terminate事件Set objMine = Nothing' 退出游戏EndEnd SubPrivate Sub mnuExpert_Click()mnuBeginner.Checked = FalsemnuIntermediate.Checked = FalsemnuExpert.Checked = TruemnuCustom.Checked = False' 高级模式objMine.SetMineFieldDimension 16, 30, 100, FalseobjMine.mblnNewGame = TrueEnd SubPrivate Sub mnuIntermediate_Click()mnuBeginner.Checked = FalsemnuIntermediate.Checked = TruemnuExpert.Checked = FalsemnuCustom.Checked = False' 自定义模式objMine.SetMineFieldDimension 16, 16, 40, FalseobjMine.mblnNewGame = TrueEnd SubPrivate Sub mnuNew_Click()' 开始新游戏objMine.NewGameEnd SubOption Explicit' 判断左键是否按下Private Const LEFT_BUTTON As Byte = 1' 标记没有地雷的区域Private Const NONE As Byte = 0' 标记是否触雷Private Const MINE As Byte = 243' 已经清除地雷的区域Private Const BEEN As Byte = 244' 标记确定已经有地雷的区域Private Const FLAGGED As Byte = 2' 标记可疑区域Private Const QUESTION As Byte = 1' 最大、最小行列数Private Const MIN_MINES As Byte = 10 Private Const MAX_MINES As Byte = 99 Private Const MIN_ROWS As Integer = 8 Private Const MAX_ROWS As Integer = 24 Private Const MIN_COLS As Integer = 8 Private Const MAX_COLS As Integer = 36' 宽Private Const mintButtonWidth As Byte = 16 ' 高Private Const mintButtonHeight As Byte = 16' 总地雷数Private mbytNumMines As Byte' 尚未标记的地雷数Private mbytCorrectHits As Byte' 已经标记出的雷数(包括错误的)Private mbytTotalHits As Byte' 不同等级游戏的总行列数Private mintRows As IntegerPrivate mintCols As IntegerPrivate mintRow As IntegerPrivate mintCol As Integer' 标记是否开始新游戏Public mblnNewGame As Boolean' 标记一个鼠标单击事件正在进行Private mblnHitTestBegun As BooleanPrivate mfrmDisplay As FormPrivate mbytMineStatus() As BytePrivate mbytMarked() As BytePrivate mbytMineLocations() As BytePrivate mcolWrongLocations As New CollectionPublic Sub BeginHitTest(intButton As Integer, intX As Single, intY As Single) ' 如果当前游戏结束则开始新的游戏If mblnNewGame ThenNewGameEnd IfmblnHitTestBegun = True' 根据位图计算栅格大小intX = Int(intX / mintButtonWidth)intY = Int(intY / mintButtonHeight)' 退出If intX >= mintCols _Or intY >= mintRows _Or intX < 0 _Or intY < 0 ThenExit SubEnd IfmintCol = intX * mintButtonWidthmintRow = intY * mintButtonHeightIf mbytMineStatus(intY, intX) >= BEEN Then Exit SubDim blnLeftDown As BooleanblnLeftDown = (intButton And LEFT_BUTTON) > 0' 如果左键单击If blnLeftDown Then' 如果该区域已经清除干净,则单击无效If mbytMarked(intY, intX) >= FLAGGED Then Exit SubIf mbytMarked(intY, intX) = QUESTION ThenmfrmDisplay.imgPressed.Visible = FalsemfrmDisplay.imgQsPressed.Visible = FalsemfrmDisplay.imgQsPressed.Left = mintColmfrmDisplay.imgQsPressed.Top = mintRowmfrmDisplay.imgQsPressed.Visible = TrueElsemfrmDisplay.imgQsPressed.Visible = FalsemfrmDisplay.imgPressed.Visible = FalsemfrmDisplay.imgPressed.Left = mintColmfrmDisplay.imgPressed.Top = mintRowmfrmDisplay.imgPressed.Visible = TrueEnd IfElse' 如果右键单击Dim Msg As StringDim CRLF As StringCRLF = Chr$(13) & Chr$(10)Select Case mbytMarked(intY, intX)Case NONE:If mbytTotalHits = mbytNumMines ThenMsg = "不能标记更多的雷!" & CRLFMsg = Msg & "一个或多个雷标记错误。

扫雷游戏代码

扫雷游戏代码

/*block.h*/#ifndef BLOCK_H_#define BLOCK_H_#include<QLabel>class QWidget;class Block:public QLabel{Q_OBJECTpublic:explicit Block(bool mine_flag,QWidget* parent=0);void set_number(int number);void turn_over();bool is_mine()const;bool is_turn_over()const;signals:void turn_over(bool is_mine);protected:void mousePressEvent(QMouseEvent* event);private:bool mine_flag_;bool mark_flag_;bool turn_over_flag_;int number_;};#endif#include"block.h"#include<QLabel>#include<QMouseEvent>#include<QPixmap>#include<QWidget>Block::Block(bool mine_flag,QWidget* parent):QLabel(parent){mine_flag_=mine_flag;mark_flag_=false;turn_over_flag_=false;number_=-1;setPixmap(QPixmap(":/images/normal.png"));}void Block::set_number(int number){number_=number;}void Block::turn_over(){if(!turn_over_flag_){turn_over_flag_=true;if(mine_flag_)setPixmap(QPixmap(":/images/mine.png"));elsesetPixmap(QPixmap(":/images/mine_"+QString("%1").arg(number_) +".png"));update();}}bool Block::is_mine()const{return mine_flag_;}bool Block::is_turn_over()const{return turn_over_flag_;}/*鼠标事件的实现*/void Block::mousePressEvent(QMouseEvent* event){if(event->button()==Qt::LeftButton){if(!turn_over_flag_&&!mark_flag_){turn_over_flag_=true;if(mine_flag_==true){setPixmap(QPixmap(":/images/mine.png"));update();emit turn_over(true);}else{setPixmap(QPixmap(":/images/mine_"+QString("%1").arg(number_) +".png"));update();emit turn_over(false);}}}else if(event->button()==Qt::RightButton){if(!turn_over_flag_){if(!mark_flag_){mark_flag_=true;setPixmap(QPixmap(":/images/flag.png"));}else{mark_flag_=false;setPixmap(QPixmap(":/images/normal.png"));}update();}}QLabel::mousePressEvent(event);}#ifndef BLOCK_AREA_H_#define BLOCK_AREA_H_#include"block.h"#include<QWidget>class QEvent;class QGridLayout;class QObject;class BlockArea:public QWidget{Q_OBJECTpublic:BlockArea(int row,int column,int mine_number,QWidget* parent=0);void set_block_area(int row,int column,int mine_number,int init_flag=false);signals:void game_over(bool is_win);protected:bool eventFilter(QObject* watched, QEvent* event);private slots:void slot_turn_over(bool is_mine);private:int calculate_mines(int x,int y)const; //璁$畻浠,y涓轰腑蹇幂殑涔濆镙煎唴镄勯浄鏁voidtry_to_turn_over_more_blocks(int x,int y);private:QGridLayout* mainLayout;int row_;int column_;int total_block_number_;int total_mine_number_;int turn_over_block_number_;bool game_over_flag_;};#endif/*block_area.h*/#include"block_area.h"#include<algorithm>#include<QEvent>#include<QGridLayout>#include<QLayout>#include<QMouseEvent>#include<QObject>#include<QQueue>#include<QTime>#include<QWidget>/*雷的随机布置*/ptrdiff_t random(ptrdiff_t i){return qrand()%i;}ptrdiff_t (*p_random)(ptrdiff_t)=random;BlockArea::BlockArea(int row,int column,int mine_number,QWidget* parent):QWidget(parent){set_block_area(row,column,mine_number,true);}void BlockArea::set_block_area(int row,int column,int mine_number,int init_flag){if(!init_flag){for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)deletestatic_cast<Block*>(mainLayout->itemAtPosition(i,j)->widget());delete mainLayout;}row_=row;column_=column;total_block_number_=row_*column_;total_mine_number_=mine_number;turn_over_block_number_=0;game_over_flag_=false;bool mine_flag[total_block_number_];for(int i=0;i<total_mine_number_;i++)mine_flag[i]=true;for(int i=total_mine_number_;i<total_block_number_;i++)mine_flag[i]=false;QTime time;time=QTime::currentTime();qsrand(time.msec()+time.second()*1000);std::random_shuffle(mine_flag,mine_flag+total_block_number_,p _random);mainLayout=new QGridLayout(this);for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)mainLayout->addWidget(newBlock(mine_flag[i*column_+j]),i,j);for(int i=0;i<row_;i++){for(int j=0;j<column_;j++){Block*current_block=static_cast<Block*>(mainLayout->itemAtPosition(i,j)->wi dget());current_block->set_number(calculate_mines(i,j));connect(current_block,SIGNAL(turn_over(bool)),this,SLOT(slot_ turn_over(bool)));current_block->installEventFilter(this);}}}bool BlockArea::eventFilter(QObject* watched, QEvent* event){if(game_over_flag_)if(event->type()==QEvent::MouseButtonPress)return true;return QWidget::eventFilter(watched,event);}void BlockArea::slot_turn_over(bool is_mine){if(is_mine){game_over_flag_=true;emit game_over(false);}else{++turn_over_block_number_;if(turn_over_block_number_==total_block_number_-total_mine_nu mber_){game_over_flag_=true;emit game_over(true);}else{for(int i=0;i<row_;i++)for(int j=0;j<column_;j++)if(sender()==static_cast<Block*>(mainLayout->itemAtPosition(i ,j)->widget()))try_to_turn_over_more_blocks(i,j);}}}int BlockArea::calculate_mines(int x,int y)const{int number=0;for(int i=0;i<3;i++)for(int j=0;j<3;j++)if( (x-1+i>=0) && (x-1+i<row_) && (y-1+j>=0) && (y-1+j<column_) )if(static_cast<Block*>(mainLayout->itemAtPosition(x-1+i,y-1+j )->widget())->is_mine())++number;return number;}void BlockArea::try_to_turn_over_more_blocks(int x,int y){QQueue<QPair<int,int> > queue;QPair<int,int> pair;queue.enqueue(qMakePair(x,y));while(!queue.isEmpty()){pair=queue.head();queue.dequeue();if(calculate_mines(pair.first,pair.second)==0){for(int i=0;i<3;i++){for(int j=0;j<3;j++){if( (pair.first-1+i>=0) && (pair.first-1+i<row_) && (pair.second-1+j>=0) &&(pair.second-1+j<column_) ){if(!static_cast<Block*>(mainLayout->itemAtPosition(pair.first -1+i,pair.second-1+j)->widget())->is_turn_over()){static_cast<Block*>(mainLayout->itemAtPosition(pair.first-1+i ,pair.second-1+j)->widget())->turn_over();++turn_over_block_number_;queue.enqueue(qMakePair(pair.first-1+i,pair.second-1+j));}}}}}}if(turn_over_block_number_==total_block_number_-total_mine_nu mber_){game_over_flag_=true;emit game_over(true);}}#ifndef MAIN_WINDOW_H_#define MAIN_WINDOW_H_#include"block_area.h"#include<QMainWindow>#include<QTime>#include<QTimer>class QAction;class QActionGroup;class QCloseEvent;class QMenu;class QToolBar;class QWidget;class MainWindow:public QMainWindow{Q_OBJECTpublic:MainWindow(QWidget* parent=0);protected:void closeEvent(QCloseEvent* event);private slots:void slot_new_game();void slot_rank();void slot_show_game_toolBar(bool show);void slot_show_statusBar(bool show);void slot_standard(QAction* standard_action);void slot_about_game();void slot_game_over(bool is_win);void slot_timer();private:void read_settings();void write_settings();void create_actions();void create_menus();void create_game_toolBar();void create_statusBar();private:BlockArea* area_;int row_;int column_;int mine_number_;int easy_record_time_;int middle_record_time_;int hard_record_time_;QString easy_record_name_;QString middle_record_name_;QString hard_record_name_;int current_standard_;QMenu* game_menu;QMenu* setting_menu;QMenu* help_menu;QToolBar* game_toolBar;QAction* new_game_action;QAction* rank_action;QAction* exit_action;QAction* show_game_toolBar_action;QAction* show_statusBar_action;QAction* easy_standard_action;QAction* middle_standard_action;QAction* hard_standard_action;QAction* custom_standard_action;QActionGroup* standard_actionGroup;QAction* about_game_action;QAction* about_qt_action;QLabel* time_label;QTime time;QTimer timer;};#endif#include"main_window.h"#include<QAction>#include<QActionGroup>#include<QApplication>#include<QDialog>#include<QDialogButtonBox>#include<QHBoxLayout>#include<QIcon>#include<QInputDialog>#include<QLayout>#include<QMainWindow>#include<QMenu>#include<QMenuBar>#include<QMessageBox>#include<QPushButton>#include<QSettings>#include<QSpinBox>#include<QStatusBar>#include<QToolBar>#include<QVBoxLayout>#include<QWidget>/*关于游戏介绍的信息*/const QString g_software_name="Mine Sweeper";const QString g_software_version="1.2";const QString g_software_author="CHANGHUIZHEN";/*关于排行榜的信息*/const int g_no_record_time=9999;const QString g_no_record_name="";MainWindow::MainWindow(QWidget* parent):QMainWindow(parent){area_=new BlockArea(9,9,10);//一般设置connect(area_,SIGNAL(game_over(bool)),this,SLOT(slot_game_ove r(bool)));setCentralWidget(area_);create_actions();create_menus();create_game_toolBar();create_statusBar();QCoreApplication::setOrganizationName(g_software_author);QCoreApplication::setApplicationName(g_software_name);read_settings();layout()->setSizeConstraint(QLayout::SetFixedSize);setWindowTitle(g_software_name);setWindowIcon(QIcon(":/game.png"));/*等待最长时间,到时间就会提示游戏失败*/timer.start(1000);connect(&timer,SIGNAL(timeout()),this,SLOT(slot_timer()));slot_new_game();}void MainWindow::closeEvent(QCloseEvent*){write_settings();}void MainWindow::slot_new_game(){area_->set_block_area(row_,column_,mine_number_);time_label->setText("0");time.restart();timer.start();}void MainWindow::slot_rank(){QDialog dialog;dialog.setWindowTitle(tr("rank"));QGridLayout* up_layout=new QGridLayout;up_layout->addWidget(new QLabel(tr("Standard")),0,0);up_layout->addWidget(new QLabel(tr("Time")),0,1);up_layout->addWidget(new QLabel(tr("Name")),0,2);up_layout->addWidget(new QLabel(tr("Easy")),1,0);up_layout->addWidget(newQLabel(QString("%1").arg(easy_record_time_)),1,1);up_layout->addWidget(new QLabel(easy_record_name_),1,2);up_layout->addWidget(new QLabel(tr("Middle")),2,0);up_layout->addWidget(newQLabel(QString("%1").arg(middle_record_time_)),2,1);up_layout->addWidget(new QLabel(middle_record_name_),2,2);up_layout->addWidget(new QLabel(tr("Hard")),3,0);up_layout->addWidget(newQLabel(QString("%1").arg(hard_record_time_)),3,1);up_layout->addWidget(new QLabel(hard_record_name_),3,2);QPushButton* recount_button=new QPushButton(tr("recount"));QPushButton* close_button=new QPushButton(tr("close"));close_button->setDefault(true);connect(recount_button,SIGNAL(clicked()),&dialog,SLOT(accept( )));connect(close_button,SIGNAL(clicked()),&dialog,SLOT(reject()) );QHBoxLayout* bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(recount_button);bottom_layout->addWidget(close_button);QVBoxLayout* main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if(dialog.exec()==QDialog::Accepted){easy_record_time_=middle_record_time_=hard_record_time_=g_no_ record_time;easy_record_name_=middle_record_name_=hard_record_name_=g_no_ record_name;}}void MainWindow::slot_show_game_toolBar(bool show){if(show)game_toolBar->show();elsegame_toolBar->hide();}void MainWindow::slot_show_statusBar(bool show){if(show)statusBar()->show();elsestatusBar()->hide();}/*游戏的设置容易、中等、困难及自定义*/void MainWindow::slot_standard(QAction* standard_action) {if(standard_action==easy_standard_action){current_standard_=0;row_=9;column_=9;mine_number_=10;}else if(standard_action==middle_standard_action){current_standard_=1;row_=16;column_=16;mine_number_=40;}else if(standard_action==hard_standard_action){current_standard_=2;row_=16;column_=30;mine_number_=99;}else if(standard_action==custom_standard_action){QDialog dialog;dialog.setWindowTitle(tr("set standard"));QSpinBox* row_spinBox=new QSpinBox;row_spinBox->setRange(5,50);row_spinBox->setValue(row_);QSpinBox* column_spinBox=new QSpinBox;column_spinBox->setRange(5,50);column_spinBox->setValue(column_);QSpinBox* mine_spinBox=new QSpinBox;mine_spinBox->setValue(mine_number_);QHBoxLayout* up_layout=new QHBoxLayout;up_layout->addWidget(row_spinBox);up_layout->addWidget(column_spinBox);up_layout->addWidget(mine_spinBox);QDialogButtonBox* dialog_buttonBox=new QDialogButtonBox;dialog_buttonBox->addButton(QDialogButtonBox::Ok);dialog_buttonBox->addButton(QDialogButtonBox::Cancel);connect(dialog_buttonBox,SIGNAL(accepted()),&dialog,SLOT(acce pt()));connect(dialog_buttonBox,SIGNAL(rejected()),&dialog,SLOT(reje ct()));QHBoxLayout* bottom_layout=new QHBoxLayout;bottom_layout->addStretch();bottom_layout->addWidget(dialog_buttonBox);QVBoxLayout* main_layout=new QVBoxLayout(&dialog);main_layout->addLayout(up_layout);main_layout->addLayout(bottom_layout);if(dialog.exec()==QDialog::Accepted)if(row_spinBox->value()*column_spinBox->value()>mine_spinBox->value()){current_standard_=3;row_=row_spinBox->value();column_=column_spinBox->value();mine_number_=mine_spinBox->value();}}slot_new_game();}/*实现帮助菜单中的关于游戏,及功能*/void MainWindow::slot_about_game(){QString introduction("<h2>"+tr("About Mine Sweepr")+"</h2>"+"<p>"+tr("This game is played by revealing squares of the grid, typically by clicking them with a mouse. If a square containing a mine is revealed, the player loses the game. Otherwise, a digit is revealed in the square, indicating the number of adjacent squares (out of the possible eight) that contain mines.if this number is zero then the square appears blank, and the surrounding squares are automatically also revealed. By using logic, the player can in many instances use this information to deduce that certain other squares are mine-free, in which case they may be safely revealed, or mine-filled, in which they can be marked as such (which is effected by right-clicking the square and indicated by a flag graphic).")+"</p>"+"<p>"+tr("This program is free software; you can redistribute it and/or modify.it under the terms of the GNU General Public License as published by the Software Foundation; either version 3 of the License, or (at your option) any later version.")+"</p>"+"<p>"+tr("Please see ")+"<ahref=/licenses/gpl-3.0.html>/lice nses/gpl-3.0.html</a>"+tr(" for an overview of GPLv3 licensing")+"</p>"+"<br>"+tr("Version:")+g_software_version+"</br>"+"<br>"+tr("Author: ")+g_software_author+"</br>");QMessageBox messageBox(QMessageBox::Information,tr("About Mine Sweeper"),introduction,QMessageBox::Ok);messageBox.exec();}/*游戏的判断,及所给出的提示做出判断*/void MainWindow::slot_game_over(bool is_win){timer.stop();QString name;if(is_win){switch(current_standard_){case 0:if(time_label->text().toInt()<easy_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record. Please enter your name"));if(!name.isEmpty()){easy_record_time_=time_label->text().toInt();easy_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case 1:if(time_label->text().toInt()<middle_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record. Please enter your name"));if(!name.isEmpty()){middle_record_time_=time_label->text().toInt();middle_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;case 2:if(time_label->text().toInt()<hard_record_time_){name=QInputDialog::getText(this,tr("Please enter your name"),tr("You create a record. Please enter your name"));if(!name.isEmpty()){hard_record_time_=time_label->text().toInt();hard_record_name_=name;}}elseQMessageBox::information(this,tr("Result"),tr("You win"));break;default:QMessageBox::information(this,tr("Result"),tr("You win"));}}else{QMessageBox::information(this,tr("Result"),tr("You lose"));}}/*定时器的设置*/void MainWindow::slot_timer(){time_label->setText(QString("%1").arg(time.elapsed()/1000)); }/*关于菜单栏的设置是否显示游戏工具栏和状态栏*/void MainWindow::read_settings(){QSettings settings;settings.beginGroup("MainWindow");resize(settings.value("size").toSize());move(settings.value("pos").toPoint());boolshow_game_toolBar=settings.value("showGameToolBar").toBool();show_game_toolBar_action->setChecked(show_game_toolBar);slot_show_game_toolBar(show_game_toolBar);bool show_statusBar=settings.value("showStatusBar").toBool();show_statusBar_action->setChecked(show_statusBar);slot_show_statusBar(show_statusBar);settings.endGroup();settings.beginGroup("GameSetting");current_standard_=settings.value("current_standard").toInt();switch(current_standard_){case 0:easy_standard_action->setChecked(true);break;case 1:middle_standard_action->setChecked(true);break;case 2:hard_standard_action->setChecked(true);break;case 3:custom_standard_action->setChecked(true);break;default:;}row_=settings.value("row").toInt()==0?9:settings.value("row") .toInt();column_=settings.value("column").toInt()==0?9:settings.value( "column").toInt();mine_number_=settings.value("mine_number").toInt()==0?10:sett ings.value("mine_number").toInt();settings.endGroup();settings.beginGroup("Rank");easy_record_time_=settings.value("easy_record_time").toInt()= =0?g_no_record_time:settings.value("easy_record_time").toInt();middle_record_time_=settings.value("middle_record_time").toIn t()==0?g_no_record_time:settings.value("middle_record_time").toInt();hard_record_time_=settings.value("hard_record_time").toInt()= =0?g_no_record_time:settings.value("hard_record_time").toInt();easy_record_name_=settings.value("easy_record_name").toString ()==""?g_no_record_name:settings.value("easy_record_name").toString() ;middle_record_name_=settings.value("middle_record_name").toSt ring()==""?g_no_record_name:settings.value("middle_record_name").toSt ring();hard_record_name_=settings.value("hard_record_name").toString ()==""?g_no_record_name:settings.value("hard_record_name").toString() ;settings.endGroup();}void MainWindow::write_settings(){QSettings settings;settings.beginGroup("MainWindow");settings.setValue("size",size());settings.setValue("pos", pos());settings.setValue("showGameToolBar",show_game_toolBar_action->isChecked());settings.setValue("showStatusBar",show_statusBar_action->isCh ecked());settings.endGroup();settings.beginGroup("GameSetting");settings.setValue("current_standard",current_standard_);settings.setValue("row",row_);settings.setValue("column",column_);settings.setValue("mine_number",mine_number_);settings.endGroup();settings.beginGroup("Rank");settings.setValue("easy_record_time",easy_record_time_);settings.setValue("middle_record_time",middle_record_time_);settings.setValue("hard_record_time",hard_record_time_);settings.setValue("easy_record_name",easy_record_name_);settings.setValue("middle_record_name",middle_record_name_);settings.setValue("hard_record_name",hard_record_name_);settings.endGroup();}/*菜单栏里图片的显示*/void MainWindow::create_actions(){new_game_action=newQAction(QIcon(":/images/new_game.png"),tr("New Game"),this);new_game_action->setShortcut(QKeySequence::New);connect(new_game_action,SIGNAL(triggered()),this,SLOT(slot_ne w_game()));rank_action=newQAction(QIcon(":/images/rank.png"),tr("Rank"),this);connect(rank_action,SIGNAL(triggered()),this,SLOT(slot_rank() ));exit_action=newQAction(QIcon(":/images/exit.png"),tr("Exit"),this);exit_action->setShortcut(QKeySequence::Quit);connect(exit_action,SIGNAL(triggered()),this,SLOT(close()));show_game_toolBar_action=new QAction(tr("Show Game Tool Bar"),this);show_game_toolBar_action->setCheckable(true);connect(show_game_toolBar_action,SIGNAL(toggled(bool)),this,S LOT(slot_show_game_toolBar(bool)));show_statusBar_action=new QAction(tr("Show Status Bar"),this);show_statusBar_action->setCheckable(true);connect(show_statusBar_action,SIGNAL(toggled(bool)),this,SLOT (slot_show_statusBar(bool)));easy_standard_action=newQAction(QIcon(":/images/easy_standard.png"),tr("Easy"),this);easy_standard_action->setCheckable(true);middle_standard_action=newQAction(QIcon(":/images/middle_standard.png"),tr("Middle"),this);middle_standard_action->setCheckable(true);hard_standard_action=newQAction(QIcon(":/images/hard_standard.png"),tr("Hard"),this);hard_standard_action->setCheckable(true);custom_standard_action=newQAction(QIcon(":/images/custom_standard.png"),tr("Custom"),this);custom_standard_action->setCheckable(true);standard_actionGroup=new QActionGroup(this);standard_actionGroup->addAction(easy_standard_action);standard_actionGroup->addAction(middle_standard_action);standard_actionGroup->addAction(hard_standard_action);standard_actionGroup->addAction(custom_standard_action);connect(standard_actionGroup,SIGNAL(triggered(QAction*)),this ,SLOT(slot_standard(QAction*)));about_game_action=newQAction(QIcon(":/images/game.png"),tr("About Game"),this);connect(about_game_action,SIGNAL(triggered()),this,SLOT(slot_ about_game()));about_qt_action=new QAction(QIcon(":/images/qt.png"),tr("About Qt"),this);connect(about_qt_action,SIGNAL(triggered()),qApp,SLOT(aboutQt ()));}/*菜单栏的创建*/void MainWindow::create_menus(){game_menu=menuBar()->addMenu(tr("Game"));game_menu->addAction(new_game_action);game_menu->addSeparator();game_menu->addAction(rank_action);game_menu->addSeparator();game_menu->addAction(exit_action);setting_menu=menuBar()->addMenu(tr("Setting"));setting_menu->addAction(show_game_toolBar_action);setting_menu->addAction(show_statusBar_action);setting_menu->addSeparator();setting_menu->addAction(easy_standard_action);setting_menu->addAction(middle_standard_action);setting_menu->addAction(hard_standard_action);setting_menu->addAction(custom_standard_action);help_menu=menuBar()->addMenu(tr("Help"));help_menu->addAction(about_game_action);help_menu->addAction(about_qt_action);}void MainWindow::create_game_toolBar(){game_toolBar=addToolBar(tr("Game Tool Bar"));game_toolBar->setFloatable(false);game_toolBar->setMovable(false);game_toolBar->addAction(new_game_action);game_toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon );}void MainWindow::create_statusBar(){time_label=new QLabel;statusBar()->addPermanentWidget(time_label);statusBar()->addPermanentWidget(new QLabel(tr("second"))); }#include"main_window.h"#include<QApplication>#include<QTranslator>int main(int argc,char* argv[]){QApplication app(argc,argv);QTranslator translator;translator.load(":/mine_sweeper_zh.qm");app.installTranslator(&translator);MainWindow window;window.show();return app.exec();}。

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

VB扫雷小游戏一.编程目的二.编程思路1.新建command_up和label_down控件2.用load加载控件3.根据雷区的X、Y、以及难度进行随机布雷。

4.统计每一个label周围雷的数量并作为label的caption。

5.在单击command的时候显示label6.在右击command的时候进行标记7.在label上左右键同时按下的时候检查已标记雷的数量与label显示的数量是否一致。

三.界面设计四.代码设计Dim Start_Time, End_TimeDim Area_X%, Area_Y%, Area%, Area_List()Dim Current_Mine%Dim Difficulty#Dim Continue_Flag%, Success_Flag%, LeftAndRight_Flag%Dim Near_ListDim Mine_CountPrivate Sub Command_End_Click()EndEnd SubPrivate Sub Delete_Item(List(), Index As Integer)Dim i%For i = LBound(List) + Index - 1 To UBound(List) - 1List(i) = List(i + 1)Next i'防止100%的困难度If UBound(List) > LBound(List) Then ReDim Preserve List(LBound(List) To UBound(List) - 1) End SubPrivate Sub Command_retry_Click()'卸载For i = 1 To AreaUnload Label_Down(i)Unload Command_Up(i)Next iCommand_Start.Caption = "开始游戏"Call Command_Start_ClickEnd SubPrivate Sub Command_Up_Click(Index As Integer)Success_Flag = 1If Continue_Flag = 1 ThenIf Timer1.Enabled = False Then Call Command_Start_ClickIf Label_Down(Index).Caption = "X" ThenSuccess_Flag = 0Continue_Flag = 0For i = 1 To AreaIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbRed Then'标记雷正确Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_correct.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbGreen Then'标记雷错误Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_wrong.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseCommand_Up(i).Visible = FalseLabel_Down(i).Visible = TrueEnd IfNext iTimer1.Enabled = Falsetemp = MsgBox("Game Over !", vbOKOnly, "游戏结束")ElseIf Val(Label_Down(Index).Caption) > 0 ThenCommand_Up(Index).Visible = FalseLabel_Down(Index).Visible = TrueElse'如果等于0的话应该将周边的清零Command_Up(Index).Visible = FalseLabel_Down(Index).Visible = Truej = IndexFor i = 1 To 8'判断控件是否存在If j + Near_List(i) > 0 And j + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(j + Near_List(i)).Left -Label_Down(j).Left) <= Label_Down(j).Width And Abs(Label_Down(j + Near_List(i)).Top -Label_Down(j).Top) <= Label_Down(j).Height Then'判断是否有雷If Label_Down(j + Near_List(i)).BackColor = vbGreen And Command_Up(j + Near_List(i)).Visible = True ThenCall Command_Up_Click(j + Near_List(i)) '注意此处循环调用的时候一定要避免陷入死循环End IfEnd IfEnd IfNext iEnd If'检查是否游戏成功For i = 1 To AreaIf Command_Up(i).Visible = True And Label_Down(i).Caption <> "X" ThenSuccess_Flag = 0Exit ForEnd IfNext iIf Success_Flag = 1 ThenIf Continue_Flag = 1 ThenTimer1.Enabled = FalseFor i = 1 To AreaIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbRed Then'标记雷正确Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_correct.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseIf Command_Up(i).Visible = True And Command_Up(i).Caption = "X" And Label_Down(i).BackColor = vbGreen Then'标记雷错误Command_Up(i).Picture = LoadPicture(App.Path + "\pictures\mine_wrong.gif", , , Command_Up(i).Width, Command_Up(i).Height)Command_Up(i).Visible = TrueLabel_Down(i).Visible = TrueElseCommand_Up(i).Visible = FalseLabel_Down(i).Visible = TrueEnd IfNext itemp = MsgBox("恭喜,扫雷成功!" & vbCrLf & "耗时:" & Mid(Label_Time.Caption, 4) & vbCrLf & "鸣谢:平方X O(∩_∩)O~", vbOKOnly, "成功") End IfContinue_Flag = 0 '提示一次后结束,防止在调用Command_Click事件中重复提示End IfEnd IfCommand_Start.SetFocusEnd SubPrivate Sub Command_Start_Click()If Command_Start.Caption = "开始游戏" ThenCommand_Start.Caption = "重新开始"Continue_Flag = 1Timer1.Enabled = TrueDifficulty = Val(Text_Difficulty.Text) / 100Area_X = Val(Text_X.Text)Area_Y = Val(Text_Y.Text)Area = Area_X * Area_Y'初始化这里进行二次初始化的原因是如果在之前的运行中对字体进行了改变,将有可能造成此处的控件大小发生变化With Picture_show.Left = 200.Top = 200.Width = 750 * 10.Height = 750 * 10.Visible = FalseEnd WithWith Command_Up(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = 200.Top = 200.Width = 750 * 10 / IIf(Area_X > Area_Y, Area_X, Area_Y).FontSize = 25 * (.Width / 750) '会自动缩放,必须先设置了.Height = 750 * 10 / IIf(Area_X > Area_Y, Area_X, Area_Y).Visible = FalseEnd WithWith Command_Up(0).Left = 200.Top = 200.Width = Label_Down(0).Width.Height = Label_Down(0).Height.Visible = FalseEnd WithReDim Near_List(1 To 8)Near_List(1) = 0 - 1 - Area_YNear_List(2) = 0 - 0 - Area_YNear_List(3) = 0 + 1 - Area_YNear_List(4) = 0 - 1Near_List(5) = 0 + 1Near_List(6) = 0 - 1 + Area_YNear_List(7) = 0 - 0 + Area_YNear_List(8) = 0 + 1 + Area_Y'如果在列表中有相等的元素将有可能造成统计雷的数目错误For i = 1 To 8For j = i + 1 To 8If Near_List(i) = Near_List(j) Then Near_List(i) = 0Next jNext iArea_temp = 0For Y = 1 To Area_Y'加载labelFor X = 1 To Area_XArea_temp = Area_temp + 1Load Label_Down(Area_temp)With Label_Down(Area_temp).Left = Label_Down(0).Left + Label_Down(0).Width * ((Area_temp -1) Mod Area_Y).Top = Label_Down(0).Top + Label_Down(0).Height * ((Area_temp -1) \ Area_Y).BackColor = vbGreen.Visible = False.Alignment = 2.Font = .FontBoldEnd With'加载commandLoad Command_Up(Area_temp)With Command_Up(Area_temp)'对列数求余的话就是在这一行第几个了.Left = Command_Up(0).Left + Command_Up(0).Width * ((Area_temp - 1) Mod Area_Y)'整除列数的话可以确定第几行.Top = Command_Up(0).Top + Command_Up(0).Height * ((Area_temp - 1) \ Area_Y).Visible = TrueEnd WithNext XNext YReDim Area_List(1 To Area)For i = 1 To AreaArea_List(i) = iNext i' 随即布雷RandomizeMine_Count = Val(Text_Mine_Count.Text)For i = 1 To Mine_CountCurrent_Mine = Int(Rnd * (UBound(Area_List) - LBound(Area_List) + 1) + 1) '在数组中随机一个,注意此处2个+1的必要性和准确性Label_Down(Area_List(Current_Mine)).BackColor = vbRed '将该位置标记为雷Call Delete_Item(Area_List, Current_Mine) '删除该位置,防止再次标记Next i'检查雷的数目For j = 1 To AreaIf Label_Down(j).BackColor = vbRed ThenLabel_Down(j).Caption = "X"ElseMine_Number = 0For i = 1 To 8'判断控件是否存在If j + Near_List(i) > 0 And j + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(j + Near_List(i)).Left -Label_Down(j).Left) <= Label_Down(j).Width And Abs(Label_Down(j + Near_List(i)).Top -Label_Down(j).Top) <= Label_Down(j).Height Then'判断是否有雷If Label_Down(j + Near_List(i)).BackColor = vbRed ThenMine_Number = Mine_Number + 1End IfEnd IfEnd IfNext iLabel_Down(j).Caption = Mine_NumberEnd IfNext jStart_Time = Now()ElseIf Command_Start.Caption = "重新开始" ThenCall Command_retry_ClickEnd IfEnd SubPrivate Sub Command_Up_MouseDown(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)If Button = 2 ThenIf Command_Up(Index).Caption = "" ThenCommand_Up(Index).Caption = "X"Command_Up(Index).Picture = LoadPicture(App.Path + "\pictures\mine.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)ElseIf Command_Up(Index).Caption = "X" ThenCommand_Up(Index).Caption = "?"Command_Up(Index).Picture = LoadPicture(App.Path + "\pictures\Unknown.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)ElseIf Command_Up(Index).Caption = "?" ThenCommand_Up(Index).Caption = ""Command_Up(Index).Picture = LoadPicture("") End IfEnd IfEnd SubPrivate Sub Form_Load()With Picture_show.Left = 200.Top = 200.Width = 750 * 10.Height = 750 * 10.Visible = FalseEnd WithWith Command_Up(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd WithWith Label_Down(0).Left = Picture_show.Left.Top = Picture_show.Top.Width = Picture_show.Width / 10.Height = Picture_show.Height / 10.FontSize = 1 '防止自动缩放.Visible = FalseEnd With'加载计时器Timer1.Enabled = FalseTimer1.Interval = 100'加载滚动条With HScroll_Difficulty.LargeChange = 5.SmallChange = 1.Max = 100.Min = 0.Value = 10End WithWith HScroll_Area_X.LargeChange = 5.SmallChange = 1.Max = 100.Min = 1.Value = 10End WithWith HScroll_Area_Y.LargeChange = 5.SmallChange = 1.Max = 100.Min = 1.Value = 10End WithWith HScroll_Mine_Count.LargeChange = 5.SmallChange = 1.Max = 100.Min = 0.Value = 10End With'由于很多数据不方便处理,索性让其禁用了Text_Difficulty.Enabled = FalseText_Mine_Count.Enabled = FalseText_X.Enabled = FalseText_Y.Enabled = FalseEnd SubPrivate Sub HScroll_Area_X_Change()Text_X.Text = HScroll_Area_X.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_X_Scroll()Text_X.Text = HScroll_Area_X.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_Y_Change()Text_Y.Text = HScroll_Area_Y.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Area_Y_Scroll()Text_Y.Text = HScroll_Area_Y.ValueHScroll_Mine_Count.Max = HScroll_Area_X.Value * HScroll_Area_Y.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Difficulty_Change()Text_Difficulty.Text = HScroll_Difficulty.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Difficulty_Scroll()Text_Difficulty.Text = HScroll_Difficulty.ValueHScroll_Mine_Count.Value = HScroll_Area_X.Value * HScroll_Area_Y.Value / 100 * HScroll_Difficulty.ValueEnd SubPrivate Sub HScroll_Mine_Count_Change()Text_Mine_Count.Text = HScroll_Mine_Count.ValueHScroll_Difficulty.Value = HScroll_Mine_Count.Value / (HScroll_Area_X.Value * HScroll_Area_Y.Value) * 100End SubPrivate Sub HScroll_Mine_Count_Scroll()Text_Mine_Count.Text = HScroll_Mine_Count.ValueHScroll_Difficulty.Value = HScroll_Mine_Count.Value / (HScroll_Area_X.Value * HScroll_Area_Y.Value) * 100End SubPrivate Sub Label_Down_MouseUp(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" And Command_Up(Index + Near_List(i)).Caption <> "?" ThenCommand_Up(Index + Near_List(i)).Picture = LoadPicture("")End IfEnd IfEnd IfNext iEnd SubPrivate Sub label_down_MouseDown(Index As Integer, Button As Integer, Shift As Integer, X As Single, Y As Single)If LeftAndRight_Flag + Button = 3 Then '双击完成Mine_Number = Val(Label_Down(Index).Caption)Mark_mine_number = 0For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption = "X" ThenMark_mine_number = Mark_mine_number + 1End IfEnd IfEnd IfNext iIf Val(Label_Down(Index).Caption) - Mark_mine_number <= 0 Then '已全部标出,自动点开For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" ThenCall Command_Up_Click(Index + Near_List(i))End IfEnd IfEnd IfNext iElse '如果没有全部标注的话应该显示一下嘛For i = 1 To 8'判断控件是否存在If Index + Near_List(i) > 0 And Index + Near_List(i) <= Area Then'判断是否相邻If Abs(Label_Down(Index + Near_List(i)).Left -Label_Down(Index).Left) <= Label_Down(Index).Width And Abs(Label_Down(Index + Near_List(i)).Top -Label_Down(Index).Top) <= Label_Down(Index).Height Then'判断是否有标记雷If Command_Up(Index + Near_List(i)).Caption <> "X" ThenCommand_Up(Index + Near_List(i)).Picture = LoadPicture(App.Path + "\pictures\xia.gif", , , Command_Up(Index).Width, Command_Up(Index).Height)End IfEnd IfEnd IfNext iEnd IfElseLeftAndRight_Flag = Button'Print LeftAndRight_FlagEnd IfEnd SubPrivate Sub Timer1_Timer()LeftAndRight_Flag = 0End_Time = Now()spend_time = (End_Time - Start_Time) * 10 ^ 5Label_Time.Caption = "时间:" & Format(Int(spend_time) \ (60 * 60), "00") & ":" & Format((Int(spend_time) Mod (60 * 60)) \ 60, "00") & ":" & Format(Int(spend_time) Mod 60, "00") & "." & Format(Int((spend_time - Int(spend_time)) * 1000), "000")End Sub五.软件截图1 2 3。

相关文档
最新文档