我正在研究战舰,我正在使用 2D 数组,并用网格数组中的数字放置船只(表示),如下所示;
/// Places the ships in a sequence on the grid
/// </summary>
/// <param name="ship"></param>
public static void PlaceShips(Ship ship)
{
Random rnd1 = new Random();
Random rnd2 = new Random();
if (ship.Orientation == "h")
{
//int r = rnd1.Next(_grid.GetLength(0));
//int c = rnd2.Next(_grid.GetLength(1));
int r = 0;
int c = 2;
for (int i = 0; i < ship.Values.Length; i++)
{
_grid[r++, c] = ship.Values[i];
}
}
else if (ship.Orientation == "v")
{
//int r = rnd1.Next(_grid.GetLength(0));
//int c = rnd2.Next(_grid.GetLength(1));
int r = 3;
int c = 4;
for (int i = 0; i < ship.Values.Length; i++)
{
_grid[r, c++] = ship.Values[i];
}
}
我想使用随机方法来设置坐标,但是在检查数组边界并将船只保持在数组内时,我的数学是错误的。请问有人可以提供任何帮助吗?非常感激。我想我需要根据船的长度进行修改并检查剩余部分是否大于船的长度,但我正在努力将其放入代码中。