为数组项目赋值,生命游戏

本文关键字:生命 游戏 赋值 数组 项目 | 更新日期: 2024-10-18 11:01:16

我是c#的新手,正在尝试编写Conways Game of Life,但我遇到了这个问题。我有一个类游戏板:

 public class GameBoard
{
    int height = 32;
    int width = 32;
    public void Create()
    {
        for (int x = 1; x < width; x++)
        {
            for (int y = 1; y < height; y++)
            {
                Tile[,] tile = new Tile[1024, 2];
                tile[x, y]= tile[,].value;   // not working
                Console.Write( "");
            }
            Console.WriteLine("");
        }
    }
}

瓷砖等级:

  public class Tile
{
    public int value = 0;
}

我希望能够在Create方法中为每个tile分配一个值,我需要该值来自tile类,我也有一些方法可以更改tile类中的值,所以我需要对它的引用。我的计划是将tile[x,y]的所有值设置为零,然后根据规则将其更改为1。如何将平铺值属性分配给平铺[x,y]数组项?

为数组项目赋值,生命游戏

需要注意的几件事:

  1. 按照现在的方式,每次迭代内部循环时都会初始化Tile数组(设置= new Tile[1024, 2];)。这将删除你存储在其中的任何值。你的Tile数组可能是Gameboard的一个字段,因为你很可能想在类外访问它。这意味着您需要将Tile数组的声明移动到高度和宽度值的下方。

  2. 你还需要检查你设置阵列的大小。看起来你的板子应该是由高度和宽度设置的尺寸。因此,在初始化数组时,需要使用宽度和高度。

  3. 您可能会考虑的另一个更改是创建一个构造函数并初始化其中的所有内容。构造函数的作用类似于方法,因为您有参数,并且可以在主体中执行代码。在大多数情况下,参数只是用于初始化类中的字段。在您的情况下,这将允许您轻松创建不同大小的游戏板。

  4. 我有点困惑你为什么在前臂上写字。调试?

  5. for循环(x和y)上的迭代器应该从0开始。如果您声明一个大小为32的数组,那么它将具有从0到31的索引。因此,如果您的数组命名为tiles并初始化为Tile[] tiles = new Tile[32];,则可以访问值tiles[0]tiles[31]

以下是我上面提到的变化。

    public class GameBoard
    {
        private int _height;
        private int _width;
        public Tile[,] Tiles; // Tile array is now a field
        public GameBoard(int height, int width)
        {
           _height = height;
           _width = width;
           Tiles = new Tile[width, height]; 
        }
    // I'm fairly certain the default value for c# of an integer is 0
    // so you may not need the following.
        public void SetGameBoardValues()
        {
            Random rand = new Random(); //only add if you want to randomly generate the board
            for (int x = 0; x < width; x++)//arrays start at 0
            {
                for (int y = 0; y < height; y++)//arrays start at 0
               {
                   Tiles[x, y] = 0;
                   // If you'd like to randomly assign the value you can do:
                   Tile[x,y] = rand.Next(0,2)
               }
            }
        }
    }

您现在可以通过以下方式从不同的类访问:

public class Main
{
   public static int main(string [] args) //if you're using the console
   {
      GameBoard gameBoard = new GameBoard(32, 32); // gameboard is size 32x32
      gameBoard.SetGameBoardValues();
      gameBoard.Tiles[0, 0] = 1; //You can access values this way.
   }
}