【问题标题】:Retrieving and changing value in a multidimensional List在多维列表中检索和更改值
【发布时间】:2014-01-06 00:57:05
【问题描述】:

我正在尝试用 C# 制作鱼雷游戏来完成家庭作业。在这个游戏中,我需要一个二维数组。它的大小在运行时应该是可变的,所以据我所知我不能使用简单的数组。这就是我尝试使用List<List<bool>> 的原因。

我尝试将与地图相关的所有内容归类。这是我到目前为止所做的课程:

class Map {
    // Map properties
    public int Width;
    public int Height;
    public int Ships;

    // A clear map
    public List<List<bool>> ShipPos = new List<List<bool>>();

    // Constructor (width, height, num. of ships)
    public Map(int w, int h, int num) {
        Width = w; Height = h; Ships = num;
        List<bool> row = new List<bool>();
        for (int i = 0; i < w; i++) row.Add(false);
        for (int i = 0; i < h; i++) ShipPos.Add(row);
    }

    // Method for generating ships for the computer
    public void ComputerShips(ref Random r) {
        for (int i = 0; i < Ships; i++) {
            int x, y; bool reserved;
            do {
                x = r.Next(0, Width);
                y = r.Next(0, Height);
                reserved = ShipPos[x][y];
            } while (reserved);
            ShipPos[x][y] = true;
        }
    }
}

问题似乎出在方法ComputerShips(ref Random r) 中,行ShipPos[x][y] = true。预期的行为是在二维数组中设置例如 6 个随机位置为真。但相反,我从设置为 true 的行中得到 6 个随机值,并且所有行都变得相同。

示例输出: 我希望在有 5 艘船的 8x8 地图中出现这样的情况(0 = 假,1 = 真):

0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0
0 0 1 0 0 1 0 0
0 0 0 0 0 0 0 0

但是会发生这样的事情:

0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0
0 1 1 0 1 1 1 0

也许我花了太多时间寻找答案,但到目前为止没有成功。我知道(我想我知道)如何获取和设置普通数组中的值。我会做类似array[i,j] 来获取,array[i,j] = x 来设置二维数组元素的值。在List&lt;List&lt;T&gt;&gt; 我可以做list[i][j] 来获得价值,这似乎工作到目前为止。但是list[i][j] = x 并没有像我预期的那样工作。

问题是:如何在不更改整个列的情况下将元素设置为 true?也许这很微不足道,但我对 C# 还很陌生,到目前为止,谷歌还没有回答我的问题。

抱歉写了一篇文章,我只是试图提供足够的细节。我希望我没有忘记一些重要的事情。如果重要的话,我会使用 Visual C# 2010 Express 和 Windows 7 (x64)。

【问题讨论】:

    标签: c# arrays list multidimensional-array


    【解决方案1】:

    问题出在你的构造函数中。

    您正在创建一行,然后多次添加该行。这意味着所有行实际上都是同一行。

    您需要为每一行创建一个新列表:

    public Map(int w, int h, int num) {
      Width = w; Height = h; Ships = num;
      for (int i = 0; i < h; i++) {
        List<bool> row = new List<bool>();
        for (int i = 0; i < w; i++) row.Add(false);
        ShipPos.Add(row);
      }
    }
    

    旁注:ComputerShips 方法的参数上不需要 ref。您可能会使用它来尝试使代码更快,但实际上它会使代码变慢一些,因为每次访问参数都会有另一个重定向。

    请勿使用refout 参数,除非您确实需要更改方法内作为参数发送的变量。

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      • 2014-03-26
      • 2018-03-05
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多