用C#写的扫雷程序源代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
初学C#一周,老师布置了个用C#编写仿Windows扫雷游戏的作业,我用了三天才弄出来,分享出来自我满足一下。程序是用vs 2008 控制台应用程序编的。界面有点粗糙,基本的功能倒是实现了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace saolei
{
class Program
{
//说明方向键控制方向,空格键显示,按R标记地雷
static int rl = 0; //rl横坐标
static int ud = 0; //ud纵坐标
static int level = 0; //游戏难度
static int Win = 0; //根据难度赋值,用来判断是否完成游戏
static string[,] LendMine = new string[9, 9];//二维数组表示游戏界面,横纵各9格
static string[,] LendMine2 = new string[16, 16];//横纵各16格
static Random rnd = new Random();
static bool b = true;
static void Main(string[] args)
{
Console.Write("请选择难度(1简单,2中级):");
level = int.Parse(Console.ReadLine());
switch (level)
{
case 1:
Level1();
Win = 71;
break;
case 2:
Level2();
Win = 216;
break;
default:
break;
}
#region绘制界面
switch (level)
{
case 1:
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
Console.Write("H");
}
Console.WriteLine();
}
break;
case 2:
for (int i = 0; i < 16; i++)
{
for (int j = 0; j < 16; j++)
{
Console.Write("H");
}
Console.WriteLine();
}
break;
default: break;
}
#endregion
#region进行游戏
Console.SetCursorPosition(0, 0);//光标初始位置
do
{
if (Console.KeyAvailable)
{
ConsoleKey ck = Console.ReadKey(true).Key;
if (ck == ConsoleKey.Spacebar)
{
Show(); //显示光标位置的数字
}
else
{
SetCursorPos(ck); //移动光标
}
}
} while (b);
#endregion
}
public static void Level1()
{
#region产生地雷
int[] a = new int[10];
int[] c = new int[10];
for (int i = 0; i <= 9; i++) //设置地雷位置,总共10个,用*表示
{
int H = rnd.Next(0, 9);
int S = rnd.Next(0, 9);
a[i] = H;
c[i] = S;
for (int j = 0; j < i; j++)
{
if (a[j] == H && c[j] == S)//判断第i个地雷位置是否与之前的有重复 {
i--; //i-1,下一个循环重新产生第i个地雷坐标
break;
}
}
LendMine[H, S] = "*";
}
#endregion
#region编辑数字分布
for (int i = 0; i < 9; i++) //横纵9*9=81格
{ //用LendMine[i,j]表示格子,存储的元素为数字或地雷("*") for (int j = 0; j < 9; j++)
{
int n = 0;
if(LendMine[i, j] != "*") //判断此格周围的地雷数,将数字存在此格LendMine[i,j]中
{
#region
if (i == 0)
{
if (j == 0) //位于左上顶点的格子
{
if (LendMine[i + 1, j] == "*")
{ n++; }
if (LendMine[i + 1, j + 1] == "*")
{ n++; }
if (LendMine[i, j + 1] == "*")
{ n++; }
LendMine[i, j] = string.Format("{0}", n);
}
if (j == 8) //右上顶点
{
if (LendMine[i + 1, j] == "*")
{ n++; }
if (LendMine[i + 1, j - 1] == "*")
{ n++; }
if (LendMine[i, j - 1] == "*")
{ n++; }
LendMine[i, j] = string.Format("{0}", n);
}
if (j > 0 && j < 8) //上边界
{
if (LendMine[i + 1, j] == "*")
{ n++; }
if (LendMine[i + 1, j + 1] == "*")
{ n++; }
if (LendMine[i + 1, j - 1] == "*")
{ n++; }
if (LendMine[i, j + 1] == "*")
{ n++; }
if (LendMine[i, j - 1] == "*")
{ n++; }
LendMine[i, j] = string.Format("{0}", n);
}
}
#endregion
#region
if (i == 8)
{
if (j == 0) //左下顶点
{
if (LendMine[i - 1, j] == "*")
{ n++; }