小白學習ing......
今天寫了一下控制臺的生命游戲:
百度了一下規則:
1. 如果一個細胞周圍有3個細胞為生(一個細胞周圍共有8個細胞),則該細胞為生(即該細胞若原先為死,則轉為生,若原先為生,則保持不變) ,
2. 如果一個細胞周圍有2個細胞為生,則該細胞的生死狀態保持不變;
3. 在其它情況下,該細胞為死(即該細胞若原先為生,則轉為死,若原先為死,則保持不變),
主要思路:
1.初始化地圖;
static void InitMapData(int[,] map, int[,] temp , int rowCount, int colCount){
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
{
Thread.Sleep(10);//每次進來讓主執行緒休息 停10毫秒 Random ran = new Random();
int val = ran.Next(0, 2);
map[row, col] = val;
temp[row, col] = val;
}
}
}
2.改變生命狀態;
static void ChangLifeState(int[,] map, int[,] temp, int rowCount, int colCount){
//跳過第0個,保證最外圈不會變,避免超過索引
for (int row = 1; row < rowCount-1; row++)
{
for (int col = 1; col < colCount-1; col++)
{
//周圍生命的個數
int count = 0; //找周圍的個數
for (int a = row - 1; a <= row + 1; a++)
{
for (int b = col - 1; b <= col + 1; b++)
{
if (row == a && col == b)
{ }
else if (map[a, b] == 1)
{
count++;
}
}
} if (count == 3)
{
//修改臨時的陣列的生命狀態
temp[row, col] = 1;
}
else if (count == 2)
{ }
else
{
temp[row, col] = 0;
} }
}
}
3.把臨時變化的陣列替換到地圖的陣列;
static void CopyTempToMap(int[,] map, int[,] temp, int rowCount, int colCount)
{
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
{
map[row, col] = temp[row, col];
}
}
}
4.畫地圖;
static void DrawWorld(int[,] map,int rowCount,int colCount)
{
Console.Clear();
for (int row = 0; row < rowCount; row++)
{
for (int col = 0; col < colCount; col++)
{
if (map[row, col] == 1)//活的生命
{
Console.ForegroundColor = ConsoleColor.Red;
}
else//死的生命
{
Console.ForegroundColor = ConsoleColor.White;
}
Console.Write("■");
}
Console.WriteLine();
}
}
5.主函式定義地圖的行和列、存盤地圖的二維陣列、臨時變化的二維陣列;執行上面的方法;
static void Main(string[] args){
//Console.WriteLine("輸入行數");
//int rowCount = int.Parse(Console.ReadLine());
//Console.WriteLine("輸入列數");
//int colCount = int.Parse(Console.ReadLine());
int rowCount = 25;
int colCount = 25; //定義世界地圖的二維陣列
int[,] map = new int[rowCount, colCount]; //臨時修改的二維陣列
int[,] tempMap = new int[rowCount, colCount]; //初始化地圖
InitMapData(map ,tempMap , rowCount, colCount); while (true)
{
ChangLifeState(map, tempMap, rowCount, colCount);
CopyTempToMap(map, tempMap, rowCount, colCount); //畫地圖
DrawWorld(map, rowCount, colCount);
//Console.ReadKey();
Thread.Sleep(100);
} }
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/240724.html
標籤:C#
