没事自己简单做了一个扫雷,主要的点有两个,一个是地雷的随机放置;一个是八向查找地雷数;
随机地雷逻辑:
public int GenerateRandomNumber(int min, int max)
{
RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
byte[] randomNumber = new byte[4]; // 生成4字节的随机数,即32位整数
random.GetBytes(randomNumber);
int value = BitConverter.ToInt32(randomNumber, 0);
// 将生成的随机数限制在指定的范围内
return Math.Abs(value % (max - min + 1)) + min;
}
八向查找逻辑:
public void GetLandmineCount(int raw, int col)
{
HashSet<int> totalList = new HashSet<int>();
FindEmptyAndFlag(raw, col, totalList);
}
private void FindEmptyAndFlag(int raw, int col, HashSet<int> totalList)
{
HashSet<int> tempList = new HashSet<int>();
int index;
int count = 0;
for (int i = raw - 1; i <= raw + 1; i++)
{
for (int j = col - 1; j <= col + 1; j++)
{
if (i == raw && j == col) continue;
if (IsAllow(i, j))
{
index = i * this.col + j;
if (itemList[index].status != ClearanceItem.ItemStatus.landmine &&
itemList[index].curStatus == ClearanceItem.ItemStatus.normal &&
!(i == raw-1 && j == col-1 || i == raw-1 && j == col+1 ||
i== raw+1 && j == col-1 || i == raw+1 && j == col+1) &&
!totalList.Contains(index))
{
try
{
tempList.Add(index);
totalList.Add(index);
}
catch (Exception)
{
Debug.LogError("i = " + i + " j = " + j);
throw;
}
}
if (itemList[index].status == ClearanceItem.ItemStatus.landmine)
{
count++;
}
}
}
}
if(tempList.Count > 0)
{
foreach (var item in tempList)
{
int tempRaw = item / this.col;
int tempCol = item % this.col;
FindEmptyAndFlag(tempRaw, tempCol, totalList, setList);
}
}
index = raw * this.col + col;
totalList.Add(index);
itemList[index].SetCurStutas(count);
}