康威的生命游戏调试(Java)

时间:2015-05-13 21:04:00

标签: java debugging matrix conways-game-of-life

我正在努力让康威的生命游戏能够正确运行,但我的结果仍然不正确,我似乎无法弄清楚问题。这是我执行游戏生命世代的代码:

public void generate(int gen)
 {
   generations = gen;
   int count = 0;
   for (int x = 0; x < generations; x++)
   {
      //Copies array to temp
      for (int row = 0; row < 20; row++)
      {
         for (int col = 0; col < 20; col++)
         {
            temp[row][col] = mat[row][col];
         }
      }

      //Gets count of living organisms surrounding
      for (int row = 0; row < 20; row++)
      {
         for (int col = 0; col < 20; col++)
         {
            count = check(row, col);

            //determines life or death
            if (temp[row][col] == false)
            {
               if (count == 3)
               {
                  mat[row][col] = true;
               }
            }
            else
            {
               if (count > 3 || count < 2)
               {
                  mat[row][col] = false;
               }
            }
         }
      }
   }

   displayGrid();
 }

 //Checks the number of living organisms in adjacent cells
 public int check(int row, int col)
 {
   int count = 0;
   for (int r = -1; r < 2; r++)
   {
      for (int c = -1; c < 2; c++)
      {
         if (isLegal((row + r),(col + c)) && temp[row + r][col + c] == true)
         {
            count++;
         }
      }
   }
   return count;
 }

 //Checks whether an adjacent space is in the array 
 public boolean isLegal(int row, int col)
 {
   if (row > 19 || row < 0 || col > 19 || col < 0)
   {
      return false;
   }
   return true;
 }

我试图编写这个程序的方式是否存在根本性的错误?

1 个答案:

答案 0 :(得分:1)

check()方法中,您应该在row col中包含方格,而忽略它。