本文給出一個 C# Mines(布雷)的 代碼,新手研究一下吧。
以下是引用片段:
using System.Collections;
using System.IO;
using System;
namespace com.Mines
{
class SearchingMines
{
public ArrayList list = new ArrayList();
public int[,] mines = new int[10, 10];
static void Main(string[] args)
{
SearchingMines sm = new SearchingMines();
sm.initMines();
sm.HidenMines();
sm.FillInOtherNumber();
sm.display();
// sm.SaveTxt();
}
public void initMines()
{
for (int i = 0; i < this.mines.GetLength(0); i++)
{
for (int j = 0; j < this.mines.GetLength(1); j++)
{
this.mines[i, j] = 0;
list.Add(this.mines[i, j]);
}
}
}
public void HidenMines()
{
Random r = new Random();
for (int i = 0; i < 9; i++)
{
int count = this.list.Count;
int number = r.Next(count);
int row = number / 10;
int column = number % 10;
this.mines[row, column] = 9;
this.list.RemoveAt(this.mines[row, column]);
}
}
public void FillInOtherNumber()
{
try
{
for (int i = 0; i < this.mines.GetLength(0); i++)
{
for (int j = 0; j < this.mines.GetLength(1); j++)
{
int left = j - 1;
int right = j + 1;
int top = i - 1;
int bottom = i + 1;
if (this.mines[i, j] != 9)
{
if(top>=0 && left>=0)//左邊和上邊
{
if (this.mines[top, left] == 9)//判斷左上方是否為9
{
mines[i,j] += 1;
}
}
if(top>=0 && right<10)//右邊和上邊
{
if (this.mines[top, right] == 9)//判斷該點的右上方是否
{
mines[i,j] += 1;
}
}
if(top>=0)//最上邊
{
if (this.mines[top, j] == 9)//上邊的那個是否為9
{
mines[i,j] += 1;
}
}
if(left>=0)//最左邊
{
if (this.mines[i, left] == 9)//看左邊那個是否為9
{
mines[i,j] += 1;
}
}
if(right<10)//最右邊
{
if (this.mines[i, right] == 9)//看右邊是否為9
{
mines[i,j] += 1;
}