public bool IsHit(Position position) { var x = OriginPosition.X; var y = OriginPosition.Y; for (var j = 0; j < Length; j++) { if (position.X == x && position.Y == y) { return true; } if (Direction == ShipDirection.Horizontal) { y++; } else { x++; } } return false; }
private CellStatus GetCell(Position position) { return (CellStatus)this._cells[position.X, position.Y]; }
public CellStatus ProcessShipHit(Position shotPosition) { if (IsCoordinateAlreadyUsed(shotPosition)) return CellStatus.Invalid; var affectedShip = Ships.FirstOrDefault(ship => ship.IsHit(shotPosition)); if (affectedShip == null) { this.SetCell(shotPosition.X, shotPosition.Y, CellStatus.Miss); return CellStatus.Miss; } affectedShip.Hit(); if (affectedShip.IsSunk()) { this.SetCell(shotPosition.X, shotPosition.Y, CellStatus.Hit); return CellStatus.Sunk; } else { this.SetCell(shotPosition.X, shotPosition.Y, CellStatus.Hit); return CellStatus.Hit; } }
public bool IsCoordinateAlreadyUsed(Position shotPosition) { var cell = this.GetCell(shotPosition); return cell == CellStatus.Hit || cell == CellStatus.Miss; }
public void Play() { _userInterface.RenderMessage("Please input your shoot coordinates (x, y) in format [Letter][Number], e.g. B3"); _userInterface.RenderMessage("Board go from A to " + Position.GetLetterFromX(_board.Width + 64) + " and from 0 to " + (_board.Height - 1)); while (true) { var coordinates = _userInterface.GetUserInput(); if (!AreValidCoordinates(coordinates)) { _lastPlay = LastPlay.Error; _userInterface.RenderMessage(GetLastPlayMessage()); _userInterface.RenderMessage("Your coordinates are invalid. Please make sure is in the format [Letter][Number], e.g A7"); _userInterface.RenderMessage("Board go from A to " + Position.GetLetterFromX(_board.Width + 64) + " and from 0 to " + (_board.Height - 1)); continue; } var shootPosition = new Position(coordinates); if (_board.IsCoordinateAlreadyUsed(shootPosition)) { _lastPlay = LastPlay.AlreadyHit; _userInterface.RenderMessage(GetLastPlayMessage()); continue; } var cellStatus = _board.ProcessShipHit(shootPosition); switch (cellStatus) { case CellStatus.Hit: this._lastPlay = LastPlay.Hit; break; case CellStatus.Sunk: this._lastPlay = LastPlay.Sunk; break; case CellStatus.Miss: this._lastPlay = LastPlay.Miss; break; case CellStatus.Invalid: default: this._lastPlay = LastPlay.Error; break; } _userInterface.RenderMessage(GetLastPlayMessage()); if (_board.AreAllShipsSunk()) { ProcessGameEnd(); break; } } }