我正在研究戰列艦,我正在使用二維數組並將數字放置在網格數組中的數字上(如圖所示);戰列艦數組界限檢查
/// 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];
}
}
我想用隨機方法來設置座標,但是我的數學是關閉的,當涉及到檢查數組邊界,並保持在陣列內的船隻。請任何人提供任何幫助?非常感激。我想我需要根據船的長度進行修改,然後檢查餘下部分是否大於船長,但我正在努力將其放入代碼中。
嗨,可以解釋downvote嗎?感謝:D – Patashu 2013-03-22 00:24:38