Beispiel #1
0
        public void UpdateBoard(IGridSquare square, bool wasHit)
        {
            int gridX = square.Column - 1;
            int gridY = (int)(square.Row - 'A');

            grid[gridX, gridY] = wasHit ? (char)GridResult.Hit : (char)GridResult.Miss;
        }
Beispiel #2
0
        public IGridSquare SelectTarget()
        {
            var nextTarget = GetNextTarget();

            lastTarget = nextTarget;
            return(nextTarget);
        }
        public IEnumerable <IShipPosition> GetShipPositions()
        {
            lastTarget = null; // Forget all our history when we start a new game

            List <Ship> allianceFleet = new List <Ship>();

            allianceFleet.Add(new Carrier());
            allianceFleet.Add(new Battleship());
            allianceFleet.Add(new Destroyer());
            allianceFleet.Add(new Frigate());
            allianceFleet.Add(new PatrolBoat());

            foreach (Ship ship in allianceFleet)
            {
                ourBoard.AddShipToRandomPosition(ship);
            }

            List <IShipPosition> shipPositions = new List <IShipPosition>();

            foreach (Ship ship in allianceFleet)
            {
                shipPositions.Add(ship.GetPosition());
            }

            return(shipPositions);
        }
Beispiel #4
0
    private void UpdateMove()
    {
        if (moveControl.IsMoving)
        {
            return;
        }

        IGridSquare current = moveControl.Position;
        IGridSquare target  = null;

        if (Input.GetKey(KeyCode.UpArrow))
        {
            target = current.GetNext(Direction.UP);
        }
        else if (Input.GetKey(KeyCode.DownArrow))
        {
            target = current.GetNext(Direction.DOWN);
        }
        else if (Input.GetKey(KeyCode.LeftArrow))
        {
            target = current.GetNext(Direction.LEFT);
        }
        else if (Input.GetKey(KeyCode.RightArrow))
        {
            target = current.GetNext(Direction.RIGHT);
        }

        if (target != null)
        {
            moveControl.StartMove(target, this.speed);
        }
    }
Beispiel #5
0
        private IGridSquare GetNeighbourSquare(IGridSquare g, Orientation o, int step = 1)
        {
            int  col = g.Column;
            char row = g.Row;

            switch (o)
            {
            case Orientation.East:
                col += step;
                break;

            case Orientation.West:
                col -= step;
                break;

            case Orientation.North:
                row = (char)(row - step);
                break;

            case Orientation.South:
                row = (char)(row + step);
                break;
            }
            GridSquare result = new GridSquare(row, col);

            return(result);
        }
Beispiel #6
0
    public void StartMove(IGridSquare target, float speed)
    {
        if (target == null)
        {
            throw new System.ArgumentNullException();
        }

        if (speed == 0)
        {
            throw new System.ArgumentException("Speed cannot be zero.");
        }

        if (speed < 0)
        {
            throw new System.ArgumentException("Speed cannot be negative.");
        }

        if (this.IsMoving)
        {
            return;
        }

        this.moveTarget   = target;
        this.currentSpeed = speed;

        var quat = Quaternion.FromToRotation(Vector2.right, this.Target.Center - this.Position.Center);

        this.rotation = quat.eulerAngles.z;

        this.currentRoutine = this.StartCoroutine(MoveCoroutine());
    }
Beispiel #7
0
        private float GetPercentOfMissesWithinRange(IGridSquare square, int range)
        {
            var centerRow = square.Row - 'A';
            var centerCol = square.Column;
            var count     = 0;
            var total     = 0;

            for (int r = centerRow - range; r <= centerRow + range; r++)
            {
                for (int c = centerCol - range; c <= centerCol + range; c++)
                {
                    var idx = r * 10 + centerCol - 1;

                    if (!IsOffBoard(MapToGrid(idx)))
                    {
                        total++;
                        if (battleMap[idx] == Item.Sea)
                        {
                            count++;
                        }
                    }
                }
            }
            return(count / total);
        }
Beispiel #8
0
 public void HandleShotResult(IGridSquare square, bool wasHit)
 {
     if (wasHit)
     {
         shipsHit.Add(square);
     }
 }
Beispiel #9
0
        public static Point ConvertGridSquareToPoint(IGridSquare square)
        {
            int absX = square.Column - 1;
            int absY = (int)(square.Row - 'A');

            return(new Point(absX, absY));
        }
Beispiel #10
0
        public void Constructor_ShouldInitializeTheGridSquares()
        {
            //Arrange
            int size = RandomGenerator.Next(10, 16);

            //Act
            Grid grid = new Grid(size);

            //Assert
            Assert.That(grid.Size, Is.EqualTo(size), "Size property is not initialized correctly.");
            Assert.That(grid.Squares, Is.Not.Null, "The matrix of GridSquares is not initialized.");
            Assert.That(grid.Squares.GetLength(0), Is.EqualTo(size),
                        "The number of rows of the GridSquare matrix should be equal to the size of the grid");
            Assert.That(grid.Squares.GetLength(1), Is.EqualTo(size),
                        "The number of columns of the GridSquare matrix should be equal to the size of the grid");
            for (int i = 0; i < size; i++)
            {
                for (int j = 0; j < size; j++)
                {
                    IGridSquare    square             = grid.Squares[i, j];
                    GridCoordinate expectedCoordinate = new GridCoordinate(i, j);
                    Assert.That(square, Is.Not.Null, $"The GridSquare at {expectedCoordinate} is null");
                    Assert.That(square.Coordinate, Is.EqualTo(expectedCoordinate),
                                $"The GridSquare at {expectedCoordinate} does not have a matching coordinate: {square.Coordinate}");
                }
            }
        }
Beispiel #11
0
        public EnemyShip(IGridSquare seedSquare, EnemyBoard enemyBoard)
        {
            maxSize      = enemyBoard.GetActiveShipMaxSize();
            sizeDetected = 1;

            seed = Utils.ConvertGridSquareToPoint(seedSquare);

            bool addDown  = true;
            bool addRight = true;
            bool addUp    = true;
            bool addLeft  = true;

            possibleTilesAroundSeed = new List <Point>();
            for (int dist = 1; dist <= 4; dist++)
            {
                Point down = seed.Plus(new Point(0, dist));
                if (IsPointOnGrid(down) && enemyBoard.IsTestedSquare(down))
                {
                    addDown = false;
                }

                if (addDown && IsPointOnGrid(down))
                {
                    possibleTilesAroundSeed.Add(down);
                }

                Point right = seed.Plus(new Point(dist, 0));
                if (IsPointOnGrid(right) && enemyBoard.IsTestedSquare(right))
                {
                    addRight = false;
                }

                if (addRight && IsPointOnGrid(right))
                {
                    possibleTilesAroundSeed.Add(right);
                }

                Point up = seed.Plus(new Point(0, -dist));
                if (IsPointOnGrid(up) && enemyBoard.IsTestedSquare(up))
                {
                    addUp = false;
                }

                if (addUp && IsPointOnGrid(up))
                {
                    possibleTilesAroundSeed.Add(up);
                }

                Point left = seed.Plus(new Point(-dist, 0));
                if (IsPointOnGrid(left) && enemyBoard.IsTestedSquare(left))
                {
                    addLeft = false;
                }

                if (addLeft && IsPointOnGrid(left))
                {
                    possibleTilesAroundSeed.Add(left);
                }
            }
        }
        public void CreateFromGrid_GeneratesTheCorrectGridSquareInfos()
        {
            //Arrange
            var grid = ArrangeGrid();

            //Act
            IGridInfo gridInfo = _factory.CreateFromGrid(grid);

            //Assert
            Assert.That(gridInfo, Is.Not.Null, "No instance of a class that implements IGridInfo is returned.");

            for (var i = 0; i < gridInfo.Squares.Length; i++)
            {
                GridSquareInfo[] squareInfoRow = gridInfo.Squares[i];
                for (var j = 0; j < squareInfoRow.Length; j++)
                {
                    GridSquareInfo squareInfo     = squareInfoRow[j];
                    IGridSquare    matchingSquare = grid.Squares[i, j];

                    Assert.That(squareInfo.NumberOfBombs, Is.EqualTo(matchingSquare.NumberOfBombs),
                                $"Number of bombs for square info at [{i}][{j}] is not correct.");
                    Assert.That(squareInfo.Status, Is.EqualTo(matchingSquare.Status),
                                $"Status for square info at [{i}][{j}] is not correct.");
                }
            }
        }
Beispiel #13
0
    // Use this for initialization
    void Start()
    {
        Vector3     position = new Vector3();
        IGridSquare square   = Grid.Current[xpos, ypos];

        position.z = 10;         //Make it the background

        if (direction == Direction.DOWN || direction == Direction.LEFT)
        {
            position.x = square.Left;
            position.y = square.Down;
        }
        else if (direction == Direction.UP)
        {
            position.x = square.Left;
            position.y = square.Up;
        }
        else         //RIGHT
        {
            position.x = square.Right;
            position.y = square.Down;
        }

        this.transform.position = position;

        if (direction == Direction.DOWN || direction == Direction.UP)
        {
            this.transform.rotation = Quaternion.Euler(0, 0, -90);
        }

        this.transform.localScale = new Vector3(1, Grid.SQUARE_SIZE, 1);
    }
        public ShipPositionExtended(IGridSquare start, int direction, int length)
        {
            StartingSquare = start;
            switch (direction)
            {
            case 0:
                horizontal   = true;
                EndingSquare = new GridSquare((char)(StartingSquare.Row + length - 1), StartingSquare.Column);
                break;

            case 1:
                horizontal   = false;
                EndingSquare = new GridSquare(StartingSquare.Row, StartingSquare.Column + length - 1);
                break;

            case 2:
                horizontal   = true;
                EndingSquare = new GridSquare((char)(StartingSquare.Row - length + 1), StartingSquare.Column);
                break;

            case 3:
                horizontal   = false;
                EndingSquare = new GridSquare(StartingSquare.Row, StartingSquare.Column - length + 1);
                break;
            }
        }
Beispiel #15
0
 private bool IsOffBoard(IGridSquare g)
 {
     if (g.Row < 'A' || g.Row > 'J' || g.Column > 10 || g.Column < 1)
     {
         return(true);
     }
     return(false);
 }
Beispiel #16
0
 private IGridSquare[] ConvertGridCoordinateToGridSquare(GridCoordinate[] gridCoordinates, IGrid grid)
 {
     IGridSquare[] gridSquare = new IGridSquare[gridCoordinates.Length];
     for (int i = 0; i < gridCoordinates.Length; i++)
     {
         gridSquare[i] = grid.GetSquareAt(gridCoordinates[i]);
     }
     return(gridSquare);
 }
Beispiel #17
0
        private List <Orientation> GetPossibleOrientation(IGridSquare square)
        {
            List <Orientation> result = new List <Orientation>()
            {
                Orientation.North, Orientation.East, Orientation.South, Orientation.West
            };

            return(GetRankedOrientation(square, result));
        }
Beispiel #18
0
        public bool IsTargetInShip(IGridSquare target)
        {
            if (IsHorizontal && StartingSquare.Row == target.Row)
            {
                return(IsInRange(target.Column, EndingSquare.Column, StartingSquare.Column));
            }

            return(StartingSquare.Column == target.Column && IsInRange(target.Row, EndingSquare.Row, StartingSquare.Row));
        }
 public bool IsHit(IGridSquare target)
 {
     if (ships.Any(ship => ship.IsTargetInShip(target)))
     {
         cellsOfShipsHit.Add(target);
         return(true);
     }
     return(false);
 }
Beispiel #20
0
        public IGridSquare GetNextTarget()
        {
            Point nextPoint = possibleTilesAroundSeed[0];

            IGridSquare square = Utils.ConvertPointToGridSquare(nextPoint);

            possibleTilesAroundSeed.RemoveAt(0);

            return(square);
        }
Beispiel #21
0
        private bool IsAtCorner(IGridSquare g)
        {
            var corners = new int[] { 0, 9, 90, 99 };

            if (corners.Contains(GridToMap(g)))
            {
                return(true);
            }

            return(false);
        }
Beispiel #22
0
        private IGridSquare GetNextTarget()
        {
            IGridSquare target = GetRandomTarget();

            switch (fightState)
            {
            case State.Explore:
                target = GetRandomTarget();
                break;

            case State.FindingDirection:
                target = GetNeighbourSquare(firstHit, this.possibleOri[0]);
                break;

            case State.ContinueHit:
                target = GetNeighbourSquare(lastTarget, curOrientation);
                if (ShouldNotContinue(target))
                {
                    curOrientation = OppositeOrientation(curOrientation);
                    target         = GetNeighbourSquare(firstHit, curOrientation);
                    fightState     = State.FoundOneEnd;
                    if (ShouldNotContinue(target))
                    {
                        target = GetRandomTarget();
                        Finishedbot(lengthCount);
                        fightState = State.Explore;
                    }
                }
                break;

            case State.FoundOneEnd:
                curOrientation = OppositeOrientation(curOrientation);
                target         = GetNeighbourSquare(firstHit, curOrientation);
                if (ShouldNotContinue(target))
                {
                    Finishedbot(lengthCount);
                    target     = GetRandomTarget();
                    fightState = State.Explore;
                }
                break;

            case State.ContinueToAnotherENd:
                target = GetNeighbourSquare(lastTarget, curOrientation);
                if (ShouldNotContinue(target))
                {
                    Finishedbot(lengthCount);
                    target     = GetRandomTarget();
                    fightState = State.Explore;
                }
                break;
            }

            return(target);
        }
Beispiel #23
0
        private List <IGridSquare> GetAll(IGridSquare center, int[] idxes)
        {
            List <IGridSquare> result = new List <IGridSquare>();
            int cenIdx = GridToMap(center);

            int[] surroundingIdx = idxes;
            for (int i = 0; i < idxes.Length; i++)
            {
                int idx = cenIdx + surroundingIdx[i];
                result.Add(MapToGrid(idx));
            }
            return(result);
        }
Beispiel #24
0
 private void OrientateShipCorrectly(IShipPosition shipPosition)
 {
     if (shipPosition.StartingSquare.Column <= shipPosition.EndingSquare.Column && shipPosition.StartingSquare.Row <= shipPosition.EndingSquare.Row)
     {
         StartingSquare = shipPosition.StartingSquare;
         EndingSquare   = shipPosition.EndingSquare;
     }
     else
     {
         StartingSquare = shipPosition.EndingSquare;
         EndingSquare   = shipPosition.StartingSquare;
     }
 }
Beispiel #25
0
        public IEnumerable <IShipPosition> GetShipPositions()
        {
            lastTarget = null; // Forget all our history when we start a new game

            return(new List <IShipPosition>
            {
                GetShipPosition('A', 1, 'A', 5), // Aircraft Carrier
                GetShipPosition('C', 1, 'C', 4), // Battleship
                GetShipPosition('E', 1, 'E', 3), // Destroyer
                GetShipPosition('G', 1, 'G', 3), // Submarine
                GetShipPosition('I', 1, 'I', 2)  // Patrol boat
            });
        }
Beispiel #26
0
        public void GetSquareAt_ShouldReturnCorrectSquare()
        {
            //Arrange
            int            gridSize   = RandomGenerator.Next(10, 16);
            Grid           grid       = new Grid(gridSize);
            GridCoordinate coordinate = new GridCoordinateBuilder(gridSize).Build();

            //Act
            IGridSquare square = grid.GetSquareAt(coordinate);

            //Assert
            Assert.That(square, Is.Not.Null);
            Assert.That(square.Coordinate, Is.EqualTo(coordinate));
        }
Beispiel #27
0
        public void UpdateBasedOnShotResult(IGridSquare shot, bool wasHit)
        {
            Point shotPoint = Utils.ConvertGridSquareToPoint(shot);

            if (!wasHit)
            {
                possibleTilesAroundSeed.RemoveAll(point => ShouldRemovePointsBeyondMiss(point, shotPoint));
            }
            else
            {
                possibleTilesAroundSeed.RemoveAll(point => ShouldRemovePointsNoInShipDirection(point, shotPoint));
                sizeDetected++;
            }
        }
        private void RegisterSunkenShip(ShipKind sunkenShipKind)
        {
            var shipBuilder = new ShipBuilder(sunkenShipKind).WithSquares(GridSquareStatus.Hit);
            var ship        = shipBuilder.Build();

            for (var index = 0; index < ship.Squares.Length - 1; index++)
            {
                IGridSquare shipSquare = ship.Squares[index];
                _strategy.RegisterShotResult(shipSquare.Coordinate, ShotResult.CreateHit(ship, true));
            }

            shipBuilder.WithHasSunk(true);
            _strategy.RegisterShotResult(ship.Squares[ship.Kind.Size - 1].Coordinate, ShotResult.CreateHit(ship, true));
        }
 public bool Contains(IGridSquare square)
 {
     if (horizontal && square.Row == StartingSquare.Row)
     {
         return(Between(StartingSquare.Column, EndingSquare.Column, square.Column));
     }
     else if (!horizontal && square.Column == StartingSquare.Column)
     {
         return(Between(StartingSquare.Row, EndingSquare.Row, square.Row));
     }
     else
     {
         return(false);
     }
 }
Beispiel #30
0
 public void HandleShotResult(IGridSquare square, bool wasHit)
 {
     firedSquares.Add(square);
     if (wasHit)
     {
         var newTargets = NeighbourhoodGridSquares(new ShipPosition(square, square), 1)
                          .Where(neighbour => (neighbour.Column + Rows.IndexOf(neighbour.Row)) % 2 !=
                                 (square.Column + Rows.IndexOf(square.Row)) % 2)
                          .Where(neighbour => !firedSquares.Contains(neighbour));
         foreach (var target in newTargets)
         {
             firingStack.RemoveAll(s => s.Equals(target));
             firingStack.Add(target);
         }
     }
 }
Beispiel #31
0
 private void DoStopMove()
 {
     this.moveTarget = null;
     this.currentSpeed = 0;
     this.currentRoutine = null;
 }
Beispiel #32
0
 public void SetPosition(IGridSquare square)
 {
     this.SetPosition(square.XIndex, square.YIndex);
 }
Beispiel #33
0
    public void StartMove(IGridSquare target, float speed)
    {
        if (target == null)
            throw new System.ArgumentNullException();

        if (speed == 0)
            throw new System.ArgumentException("Speed cannot be zero.");

        if (speed < 0)
            throw new System.ArgumentException("Speed cannot be negative.");

        if (this.IsMoving)
            return;

        this.moveTarget = target;
        this.currentSpeed = speed;

        var quat = Quaternion.FromToRotation(Vector2.right, this.Target.Center - this.Position.Center);
        this.rotation = quat.eulerAngles.z;

        this.currentRoutine = this.StartCoroutine(MoveCoroutine());
    }