【发布时间】: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<List<T>> 我可以做list[i][j] 来获得价值,这似乎工作到目前为止。但是list[i][j] = x 并没有像我预期的那样工作。
问题是:如何在不更改整个列的情况下将元素设置为 true?也许这很微不足道,但我对 C# 还很陌生,到目前为止,谷歌还没有回答我的问题。
抱歉写了一篇文章,我只是试图提供足够的细节。我希望我没有忘记一些重要的事情。如果重要的话,我会使用 Visual C# 2010 Express 和 Windows 7 (x64)。
【问题讨论】:
标签: c# arrays list multidimensional-array