所以我正在尝试制作一个战舰游戏。首先,我只想能够在特定位置放置船只,它们不需要超过 1 个空间。但是我无法理解如何检查我的船阵列中对象的位置。
我想要做的是能够放置在一个位置,例如 3,3 并检查那里是否有船。当然,我会在之后添加更多东西,比如更大的船只,与可以将船只放置在随机位置的 PC 对战。但就目前而言,我似乎无法弄清楚这一点。
我对编程还很陌生,所以如果您看到有关此脚本的任何问题,请随时指出。
我在其中初始化船阵列和板的主类。
static void Main()
{
Board board = new Board(10, 10);
try
{
Ship[] ships =
{
new Ship(new BoardLocation(1, 3, board)),
new Ship(new BoardLocation(3, 5, board)),
new Ship(new BoardLocation(5, 7, board))
};
Console.WriteLine("Enter the coordinate: ");
double cr1 = Convert.ToDouble(Console.ReadLine());
if (cr1 == ships.Contains<>)
{
}
我的板类:
namespace Battleship
{
class Board
{
public readonly int Width;
public readonly int Height;
public Board(int width, int height)
{
Width = width;
Height = height;
}
public bool OnBoard(Point point)
{
return point.X >= 0 && point.X < Width &&
point.Y >= 0 && point.Y < Height;
}
}
}
}
我的板位类:
namespace Battleship
{
class BoardLocation : Point
{
public BoardLocation(int x, int y, Board board) : base(x, y)
{
if (!board.OnBoard(this))
{
throw new OutOfBoundsException(x + "," + y + " is outside the
boundaries of the map.");
}
}
}
}
我的船级:
namespace Battleship
{
class Ship
{
public readonly int shipHealth = 1;
public readonly double shipLocation;
public BoardLocation _location;
public Ship(BoardLocation location)
{
_location = location;
}
}
}
我建议使用该FirstOrDefault
方法。null
如果条件不匹配,这将返回,如果匹配,它将返回该项目。所以在读取两个坐标后:
Console.WriteLine("Enter the X coordinate: ");
int X_input = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Y coordinate: ");
int Y_input = Convert.ToInt32(Console.ReadLine());
要检查坐标,您需要访问 的X
和Y
属性_location
。你可以使用 linq
Ship mayBeHit = ships.FirstOrDefault(
ship => ship._location.X==X_input &&
ship._location.Y == Y_input);
然后你可以检查你是否有命中
if(maybeHit != null)
{
// use the ship the you hit
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句