public GridCoordinate DetermineTargetCoordinate() { GridCoordinate coord; IGridSquare square; bool freeGridSquareFound = false; /* Check status of all grid squares */ for (int i = 0; i < opponentGrid.Size; i++) { for (int j = 0; j < opponentGrid.Size; j++) { if (opponentGrid.Squares[i, j].Status == GridSquareStatus.Untouched) { /* Break out of loop */ freeGridSquareFound = true; break; } } } if (freeGridSquareFound == false) { /* no free (=untouched) grid square found */ throw new ApplicationException("Computer has shot all cells in grid"); } do { /* Generate a random grid coordinate */ coord = GridCoordinate.CreateRandom(opponentGrid.Size); square = opponentGrid.GetSquareAt(coord); }while (square.Status != GridSquareStatus.Untouched); return(coord); }
private void AssertRandomCoordinateCreation(int gridSize) { //Act GridCoordinate coordinate = GridCoordinate.CreateRandom(gridSize); //Assert Assert.That(coordinate.Row >= 0 && coordinate.Row < gridSize, Is.True, $"For a grid of size {gridSize}, the row must be greater than or equal to 0 and smaller than {gridSize}"); Assert.That(coordinate.Column >= 0 && coordinate.Column < gridSize, Is.True, $"For a grid of size {gridSize}, the column must be greater than or equal to 0 and smaller than {gridSize}"); }
public void CreateRandom_ShouldBeRandom() { int gridSize = 1000; bool isRandom = false; GridCoordinate previousCoordinate = GridCoordinate.CreateRandom(gridSize); int numberOfTries = 0; while (numberOfTries <= 15 && !isRandom) { GridCoordinate newCoordinate = GridCoordinate.CreateRandom(gridSize); if (newCoordinate != previousCoordinate) { isRandom = true; } previousCoordinate = newCoordinate; } Assert.That(isRandom, Is.True); }
/// <summary> /// Randomly generates an array of possible ship segment coordinates for the kind of ship. /// This method can be used to position a ship at random on a grid. /// </summary> /// <param name="gridSize">The coordinates will be within this grid size</param> /// <param name="allowDeformedShips"> /// If false (=default), the coordinates will be horizontally or vertically aligned and will touch each other. /// If true, the coordinates will touch each other, but may possibly not be aligned (this is an EXTRA). /// </param> public GridCoordinate[] GenerateRandomSegmentCoordinates(int gridSize, bool allowDeformedShips = false) { bool outOfBounds = true; while (outOfBounds) { GridCoordinate generatePosition = GridCoordinate.CreateRandom(gridSize); GridCoordinate[] output = new GridCoordinate[Size]; Direction generateDirection = Direction.CreateRandomly(allowDeformedShips); output[0] = generatePosition; for (int i = 1; i < Size; i++) { output[i] = new GridCoordinate(output[i - 1].Row + generateDirection.YStep, output[i - 1].Column + generateDirection.XStep); } outOfBounds = GridCoordinateArrayExtensions.HasAnyOutOfBounds(output, gridSize); if (!outOfBounds) { return(output); } } return(null); }