public bool ManualShot(Point target, IBattlefield battlefield) { if (!battlefield.IsPointInField(target)) { throw new IndexOutOfRangeException($"Point {target.X}, {target.Y} is not in field"); } var cell = battlefield[target]; if (cell.State.HasFlag(CellState.WasFired)) { throw new ArgumentException($"Can't shoot fired cell: {target.X}, {target.Y}"); } cell.State = battlefield[target].State | CellState.WasFired; if (!cell.State.HasFlag(CellState.Ship)) { return(false); } var ship = battlefield.Ships.Find(s => s.Cells.Contains(cell)); ship.State = ship.Cells.All(c => c.State.HasFlag(CellState.WasFired)) ? ShipState.Destroyed : ShipState.Damaged; if (ship.State == ShipState.Damaged) { AutoShotMethod = new RandomNearShot(this); } return(true); }
private void PlaceShipRandomly(int shipSize) { var random = RandomHelper.GetHelper(); var emptyCells = GetEmptyCells(); var randomCell = random.GetRandomCell(emptyCells); var isVertical = random.GetRandomBool(); List <Cell> range = new(); do { var pointRange = GetPointRange(randomCell.Coordinates, shipSize, isVertical); //if some points are outside of the field, //get new start point, new random direction and skip iteration if (pointRange.All(p => _battlefield.IsPointInField(p))) { range.Clear(); range.AddRange(pointRange.Select(point => _battlefield[point])); } randomCell = random.GetRandomCell(emptyCells); isVertical = random.GetRandomBool(); } while (!IsRangeOfCellSuitable(range, emptyCells)); foreach (var cell in range) { cell.State = CellState.Ship; } _battlefield.Ships.Add(new Ship(range)); EncircleShip(range); }