예제 #1
0
        public void ShouldGetDirectionsInClockwiseOrder()
        {
            var actual   = DirectionExtensions.GetDirections(start: Direction.North, clockWise: true).ToArray();
            var expected = new[] { Direction.North, Direction.East, Direction.South, Direction.West, };

            actual.Should().BeEquivalentTo(expected);
        }
예제 #2
0
        private void MoveMissile(Missile missile, Actor shooter, Point point, bool keepMoving)
        {
            var direction = DirectionExtensions.GetDirection(missile.Location, point);

            missile.Orientation = direction switch {
                Direction.Left => Orientation.Horizontal,
                Direction.Right => Orientation.Horizontal,
                _ => Orientation.Vertical
            };
            missile.Location = point;

            var actor = actors.SingleOrDefault(a => a.Location == point && a != shooter);

            if (actor != null)
            {
                missile.Moving = false;

                var action = actor.GetAction(mapConsole.map, Direction.None);
                var result = action.Perform(player);
                logConsole.Log(result.Message);
            }

            missile.Moving = missile.Moving && keepMoving;

            if (!missile.Moving)
            {
                ActivateActors();
            }
        }
예제 #3
0
        private void FindBlockingTiles()
        {
            Bounds = boundsCalc.GetComponent <MeshRenderer>().bounds;

            foreach (var tile in MapTile.All)
            {
                if (tile.MapPosX < Bounds.min.x || tile.MapPosX > Bounds.max.x)
                {
                    continue;
                }
                if (tile.MapPosZ < Bounds.min.z || tile.MapPosZ > Bounds.max.z)
                {
                    continue;
                }

                tile.TileProp = this;

                var adjTiles = tile.GetAdjacentTiles(false);
                foreach (var adjTile in adjTiles)
                {
                    adjTile.Value.SetBlocks(DirectionExtensions.Reverse(adjTile.Key), coverType, moveBlocker);
                }
            }

            boundsCalc.GetComponent <MeshRenderer>().enabled = false;
        }
예제 #4
0
        //Blasting
        public void BlockBreaker(Vector3i Pos, Vector3 Dir) // consider making this a bool to facilitate feedback?
        {
            //get collar position and facing direction
            Vector3i rung   = Pos;
            Vector3i facing = StyleSet(this.style, Dir);



            //determine blast radius and depth
            if (this.Explosive.Fuel < 5)
            {
                //ChatManager.ServerMessageToAll("Column Mode", false);
                //step to next block until reach bottom - may want to invert this so that it blasts from the bottom up
                for (int a = 0; a < this.blastingDepth; a = a + 1)
                {
                    rung = rung + facing;
                    //break if mineable and replace with rubble
                    Block block = World.GetBlock(rung);
                    if (block.Is <Minable>())
                    {
                        World.DeleteBlock(rung);
                        RubbleObject.TrySpawnFromBlock(block.GetType(), rung);
                    }
                }
            }
            else if (this.Explosive.Fuel > 5)
            {
                //ChatManager.ServerMessageToAll("cylinder Mode", false);
                DirectionAxis dir = LookupDirectionAxis(facing);


                for (int a = 0; a < this.blastingDepth; a = a + 1)
                {
                    rung = rung + facing;
                    Vector3i[] ring = DirectionExtensions.Get8Edges(dir);
                    //break if mineable and replace with rubble
                    Block block = World.GetBlock(rung);
                    if (block.Is <Minable>())
                    {
                        World.DeleteBlock(rung);
                        RubbleObject.TrySpawnFromBlock(block.GetType(), rung);
                    }
                    foreach (Vector3i neighbour in ring)
                    {
                        // ChatManager.ServerMessageToAll("neighbour mode", false);
                        Vector3i tar = rung + neighbour;
                        block = World.GetBlock(tar);
                        if (block.Is <Minable>())
                        {
                            World.DeleteBlock(tar);
                            RubbleObject.TrySpawnFromBlock(block.GetType(), tar);
                        }
                    }
                }
            }
            else
            {
                return;
            }
        }
예제 #5
0
        public static void  ApplyTurn(GameState state, string cmds)
        {
            //Backup

            var backup = new Backup(state);



            string pat = @"o\s(\d+)\s(\d+)\s(\w)";
            Regex  r   = new Regex(pat, RegexOptions.IgnoreCase);

            Match m = r.Match(cmds);

            while (m.Success)
            {
                int row = int.Parse(m.Groups[1].Captures[0].Value);
                int col = int.Parse(m.Groups[2].Captures[0].Value);
                var ant = new Ant(row, col, 0);


                var dir = DirectionExtensions.FromChar(m.Groups[3].Captures[0].Value[0]);

                MoveAnt(backup, state, ant, dir);

                m = m.NextMatch();
            }

            backup.Restore(state);
        }
예제 #6
0
        private static Direction SelectDetour(Ship ship, Direction direction, Position target)
        {
            var right_direction = DirectionExtensions.TurnRight(direction);
            var right_position  = game.gameMap.GetTargetPosition(ship.position, right_direction);
            var right_blocked   = HasBlockingShip(ship.owner.id, right_position);

            var left_direction = DirectionExtensions.TurnLeft(direction);
            var left_position  = game.gameMap.GetTargetPosition(ship.position, left_direction);
            var left_blocked   = HasBlockingShip(ship.owner.id, left_position);

            if (right_blocked && left_blocked)
            {
                return(Direction.STILL);                               // no detour avaialable
            }
            // define detour direction to cell closest to target or highest halite value.
            var detour_direction = Direction.STILL;

            if (right_blocked == false && left_blocked == true)
            {
                detour_direction = right_direction;
            }
            if (right_blocked == true && left_blocked == false)
            {
                detour_direction = left_direction;
            }
            if (right_blocked == false && left_blocked == false)
            {
                var right_distance = game.gameMap.CalculateDistance(right_position, target);
                var left_distance  = game.gameMap.CalculateDistance(left_position, target);
                if (right_distance < left_distance)
                {
                    detour_direction = right_direction;
                }
                if (left_distance < right_distance)
                {
                    detour_direction = left_direction;
                }
                if (right_distance == left_distance)
                {
                    if (game.gameMap.At(right_position).halite >= game.gameMap.At(left_position).halite)
                    {
                        detour_direction = right_direction;
                    }
                    else
                    {
                        detour_direction = left_direction;
                    }
                }
            }

            // give a continuation move to avoid coming back to current square
            if (detour_next_move.ContainsKey(ship.id.id))
            {
                detour_next_move.Remove(ship.id.id);
            }
            detour_next_move.Add(ship.id.id, direction);

            return(detour_direction);
        }
예제 #7
0
    public void SetRandomLocation()
    {
        var randomLocation = Maze.GetRandomLocation();

        Location.Row    = randomLocation.Row;
        Location.Column = randomLocation.Column;

        _currentDirection = DirectionExtensions.GetRandomDirection();
    }
예제 #8
0
    public override Direction Flow(Direction comingFrom, int value)
    {
        Value = value;

        List <Direction> remainingSpot = _holeDict.Keys.ToList();

        remainingSpot.Remove(DirectionExtensions.GetOppositeDirection(comingFrom));

        return(remainingSpot[0]);
    }
예제 #9
0
    public void CheckSurrounding()
    {
        Direction missedHole = Direction.None;

        foreach (Direction hole in _holeLocations)
        {
            Point      targetPoint = DirectionExtensions.GetDirectionPoint(hole);
            GameObject side        = GridLevelManager.Instance.GetCircleData(targetPoint.X + GetPoint().X, targetPoint.Y + GetPoint().Y);
            if (side != null)
            {
                CircleData sideData = side.GetComponent <CircleData>();
                if (sideData != null)
                {
                    if (sideData.MatchConnectingHole(hole))
                    {
                        if (sideData.LightOn())
                        {
                            sideData.SetNextCircleData(this);
                            TurnLightOn();
                            if (missedHole != Direction.None)
                            {
                                targetPoint = DirectionExtensions.GetDirectionPoint(missedHole);
                                side        = GridLevelManager.Instance.GetCircleData(targetPoint.X + GetPoint().X, targetPoint.Y + GetPoint().Y);
                                sideData    = side.GetComponent <CircleData>();
                                sideData.CheckSurrounding();
                            }
                        }
                        else if (LightOn())
                        {
                            sideData.CheckSurrounding();
                        }
                        else
                        {
                            missedHole = hole;
                        }
                    }
                }
            }
        }

        if (GridLevelManager.Instance.CheckWinTile(GetPoint()))
        {
            if (_lightUp)
            {
                foreach (Direction hole in _holeLocations)
                {
                    if (GridLevelManager.Instance.DirectionFacingGoal(hole, GetPoint().X, GetPoint().Y))
                    {
                        GridLevelManager.Instance.ExecuteWin();
                    }
                }
            }
        }
    }
    public static bool IfLookDirection(this Block block, Direction dir)
    {
        Direction[] Directionslist = block.Directionslist();

        Direction oppdir = DirectionExtensions.GetOppositeDir(dir);

        if (oppdir == Directionslist[0] || oppdir == Directionslist[1] || oppdir == Directionslist[2] || oppdir == Directionslist[3])
        {
            return(true);
        }

        return(false);
    }
예제 #11
0
    void Move()
    {
        if (Random.Range(0f, 1f) >= chanceToMove)
        {
            return;
        }

        if (Random.Range(0f, 1f) >= chanceToMoveTowards)
        {
            Direction direction = DirectionExtensions.GetRandomDirection();
            transform.Translate(Constants.GridSize * direction.GetVector().x, Constants.GridSize * direction.GetVector().y, 0);
        }
    }
예제 #12
0
    public bool DirectionFacingGoal(Direction d, int x, int y)
    {
        Point dirFace = DirectionExtensions.GetDirectionPoint(d);

        int xFace = dirFace.X + x;
        int yFace = dirFace.Y + y;

        if (xFace == _endNode.X && yFace == _endNode.Y)
        {
            return(true);
        }

        return(false);
    }
예제 #13
0
    public bool MatchConnectingHole(Direction directionFrom)
    {
        Direction opposite = DirectionExtensions.GetOppositeDirection(directionFrom);

        foreach (Direction hole in _holeLocations)
        {
            if (hole == opposite)
            {
                return(true);
            }
        }

        return(false);
    }
예제 #14
0
        /// <summary>
        /// Moves Drone towards Queen
        /// </summary>
        /// <returns>Returns Position</returns>
        public Position MoveTowardsQueen()
        {
            var nextPosition  = Coordinates.NextCoordinatesInDirection(DirectionExtensions.GetRandomDirection());
            var queenPosition = AntColony.GetTheQueen().GetPosition();

            while (nextPosition.DistanceToCoordinate(queenPosition) > Coordinates.DistanceToCoordinate(queenPosition))
            {
                nextPosition = Coordinates.NextCoordinatesInDirection(DirectionExtensions.GetRandomDirection());
            }

            Coordinates = nextPosition;

            return(Coordinates);
        }
예제 #15
0
    public bool CheckWinTile(Point point)
    {
        Point dir = DirectionExtensions.GetDirectionPoint(DirectionExtensions.GetOppositeDirection(_endNode.Direction));

        int x = dir.X + _endNode.X;
        int y = dir.Y + _endNode.Y;

        if (point.X == x && point.Y == y)
        {
            return(true);
        }


        return(false);
    }
예제 #16
0
    public void BlockMovement(Vector3Int origin)
    {
        //print("Blocking " + origin);
        var movement = movementLookup[origin];

        if (movement.Blocked)
        {
            return;
        }

        // Keep a stack of blocks that need to be checked
        Stack <Vector3Int> originsToBeProcessed = new Stack <Vector3Int>(64);

        originsToBeProcessed.Push(origin);
        movement.Blocked = true;

        // Process all blocks in chain
        while (originsToBeProcessed.Count > 0)
        {
            // Pop movement off the stack
            origin   = originsToBeProcessed.Pop();
            movement = movementLookup[origin];

            // Check for blocking in each direction
            foreach (var dir in DirectionExtensions.Directions())
            {
                // Ignore blocking in the direction we're going
                if (movement.Direction == dir)
                {
                    continue;
                }
                //print("Checking " + (origin + dir.Vector3Int()));
                var behindOrigin = origin + dir.Vector3Int();
                if (movementDependency.ContainsKey(behindOrigin))
                {
                    var behindMovement = movementLookup[behindOrigin];
                    //print("Found dependency: " + behindMovement.Direction + " " + behindMovement.Blocked + " " + dir.Opposite());
                    // If it's moving to us, then it needs to be blocked
                    if (behindMovement.Direction == dir.Opposite() && !behindMovement.Blocked)
                    {
                        //print("Blocking " + behindOrigin);
                        behindMovement.Blocked = true;
                        originsToBeProcessed.Push(behindOrigin);
                    }
                }
            }
        }
    }
예제 #17
0
        public List <(AbstractField, int, Direction)> GetNeighbours(AbstractField field, AbstractField[][] board, int height, int width)
        {
            int[] center = field.GetPosition();
            List <(AbstractField, int, Direction)> neighbours = new List <(AbstractField, int, Direction)>();
            var neighbourCoordinates = DirectionExtensions.GetCoordinatesAroundCenter(center);

            for (int i = 0; i < neighbourCoordinates.Length; i++)
            {
                var(dir, y, x) = neighbourCoordinates[i];
                if (y >= 0 && y < height && x >= 0 && x < width)
                {
                    neighbours.Add((board[y][x], int.MaxValue, dir));
                }
            }
            return(neighbours);
        }
예제 #18
0
    public void Explore()
    {
        _moveTimeLeft = _moveCoolDown;

        Direction direction = _currentDirection;
        Direction direction2;

        if (CanMove(direction))
        {
            direction2 = DirectionExtensions.GetRandomDirection();

            if (CanMove(direction2) && !direction2.IsOpppositeDirection(direction))
            {
                direction = direction2;
            }
        }
        else
        {
            bool turnRight = Random.Range(0, 2) == 1;

            direction2 = (Direction)(((int)direction + (turnRight ? 1 : 3)) % 4);

            if (CanMove(direction2))
            {
                direction = direction2;
            }
            else
            {
                direction2 = (Direction)(((int)direction2 + 2) % 4);

                if (CanMove(direction2))
                {
                    direction = direction2;
                }
                else
                {
                    direction = (Direction)(((int)direction + 2) % 4);
                }
            }
        }

        if (CanMove(direction))
        {
            _currentDirection = direction;
            Move();
        }
    }
예제 #19
0
        public List <MapTile> CornerPeakFrom()
        {
            var peakList = new List <MapTile>();

            foreach (var cardinal in DirectionExtensions.GetCardinals())
            {
                foreach (var rightAngleDirection in DirectionExtensions.GetRightAngleDirections(cardinal))
                {
                    if (MoveBlocked[cardinal] && !GetAdjacentTile(rightAngleDirection).MoveBlocked[cardinal])
                    {
                        peakList.Add(GetAdjacentTile(DirectionExtensions
                                                     .GetDiagonalFromCardinals(cardinal, rightAngleDirection)));
                    }
                }
            }

            return(peakList);
        }
예제 #20
0
    public override void RotateClockwise()
    {
        transform.Rotate(Vector3.forward, -90);
        for (int i = 0; i < _holeLocations.Length; i++)
        {
            _holeLocations[i] = DirectionExtensions.RotateClockwise(_holeLocations[i]);
        }

        Dictionary <Direction, AbstractTube> temp = new Dictionary <Direction, AbstractTube>();

        foreach (Direction dir in _holeDict.Keys)
        {
            temp.Add(DirectionExtensions.RotateClockwise(dir), _holeDict[dir]);
            //Debug.Log(string.Format("Dir: {0} => {1}", dir, DirectionExtensions.RotateClockwise(dir)));
        }

        _holeDict = temp;
    }
예제 #21
0
        private void MoveTo(Actor actor, Point target)
        {
            Point nextStep;

            bool isNextToTarget = actor.Location.IsAdjacent(target);

            if (!isNextToTarget)
            {
                nextStep = mapConsole.GetNextStep(actor, actors, target);
            }
            else
            {
                nextStep = target;
            }

            var direction = DirectionExtensions.GetDirection(actor.Location, nextStep);

            MoveOrAct(actor, direction);
        }
예제 #22
0
    //rewrite too lazy to check all given path now
    public override bool Valid()
    {
        foreach (Direction hole in _holeDict.Keys)
        {
            Point targetPoint = GetPoint().AddPoint(DirectionExtensions.GetDirectionPoint(hole));

            GameObject obj = LevelManager_v2.Instance.GetTubePositioning(targetPoint);

            if (obj != null)
            {
                if (obj.tag.ToLower().Contains("operator"))
                {
                    return(false);
                }
            }
        }

        return(true);
    }
예제 #23
0
            public Command GetMove()
            {
                var dirs = valuer.Target.position.GetAllDirectionsTo(ship.position);

                dirs = dirs.OrderBy(d => GameInfo.CellAt(ship.position.DirectionalOffset(d)).halite).ToList();
                if (dirs.Count == 1 && GameInfo.Distance(ship, valuer.Target.position) > 1)
                {
                    var extraDirs = DirectionExtensions.GetLeftRightDirections(dirs[0]);
                    dirs.AddRange(extraDirs);
                }
                foreach (var d in dirs)
                {
                    var cell = GameInfo.CellAt(ship, d);
                    if (Safety.IsSafeAndAvoids2Cells(ship, d) && Navigation.IsAccessible(cell.position, valuer.Target.position))
                    {
                        return(ship.Move(d, $"moving towards best projection {valuer.Target.position.ToString()}... Expected turns: {numTurns}"));
                    }
                }
                return(null);
            }
예제 #24
0
        public void TestGetCoordinatesAroundCenterMiddleField()
        {
            // Arrange
            (int y, int x)center = (5, 4);

            // Act
            var result = DirectionExtensions.GetCoordinatesAroundCenter(center);

            // Assert
            Assert.Equal(9, result.Length);
            Assert.Contains((Direction.SW, center.y - 1, center.x - 1), result);
            Assert.Contains((Direction.S, center.y - 1, center.x), result);
            Assert.Contains((Direction.SE, center.y - 1, center.x + 1), result);
            Assert.Contains((Direction.W, center.y, center.x - 1), result);
            Assert.Contains((Direction.FromCurrent, center.y, center.x), result);
            Assert.Contains((Direction.E, center.y, center.x + 1), result);
            Assert.Contains((Direction.NW, center.y + 1, center.x - 1), result);
            Assert.Contains((Direction.N, center.y + 1, center.x), result);
            Assert.Contains((Direction.NE, center.y + 1, center.x + 1), result);
        }
예제 #25
0
    public static MazeGrid CreateMaze(Options options)
    {
        int width  = options.Width;
        int height = options.Height;

        bool[,] verticalWalls   = CreateVerticalWalls(width, height);
        bool[,] horizontalWalls = CreateHorizontalWalls(width, height);
        int[] sets = CreateSets(width, height);

        Direction direction = 0;
        int       cellIndex = 0;

        while (!AreAllSameSet(sets))
        {
            while (true)
            {
                cellIndex = UnityEngine.Random.Range(0, sets.Length);
                direction = DirectionExtensions.GetRandomDirection();

                if (!IsValidDirection(direction, cellIndex, width, height))
                {
                    continue;
                }

                GetSets(direction, sets, cellIndex, width, out int classe1, out int classe2);

                if (classe1 == classe2)
                {
                    continue;
                }

                RemoveWall(direction, verticalWalls, horizontalWalls, cellIndex, width);

                UnionSets(sets, classe1, classe2);

                break;
            }
        }

        return(new MazeGrid(options, verticalWalls, horizontalWalls));
    }
예제 #26
0
    private void Update()
    {
        /*
         * Basic movement
         */

        //Do not move if game is finished or you are stunned
        if (!this.GetGameManager().GetComponent <Level>().GameRunning || Stunned)
        {
            return;
        }

        //Get movement axis
        Vector2 axis = new Vector2(
            x: Input.GetAxis(HorizontalAxis),
            y: Input.GetAxis(VerticalAxis)
            );

        //Store direction of the player
        if (axis != Vector2.zero)
        {
            Direction = DirectionExtensions.Construct(axis.x, axis.y);
        }


        //Apply movement to player
        if (GetComponentInChildren <Grabber>().IsGrabbing)
        {
            Move(axis, MoveSpeed * GetComponentInChildren <Grabber>().GrabbedItems.Average(i => i.GetComponent <Junk>().SpeedMultipler));
        }
        else
        {
            Move(axis, MoveSpeed);
        }


        //Rotate the player
        transform.SetEuler2D(CommonExtensions.RealAngleBetween(transform.Position2D(), transform.Position2D() + Direction.ToVector2()));
    }
예제 #27
0
    public Turn OnTurn()
    {
        var steps = new List <Step>();

        if (CurrentHp > 0)
        {
            //Direction? direction = DirectionExtensions.RelativeDirection(controller.Row, controller.Col, player.Row, player.Col);
            Direction?direction = DirectionExtensions.RelativeDirection(transform.position, player.transform.position);
            if (direction == null)
            {
                if (controller.Elevation > player.Elevation && player.IsClimbing && player.Climbing == controller.Climbing)
                {
                    direction = controller.Climbing.Value.Opposite();
                }
                else
                {
                    direction = player.Climbing;
                }
            }

            if (direction != null)
            {
                Step moveStep = controller.Move(direction.Value);
                if (moveStep != null)
                {
                    steps.Add(moveStep);
                }
            }

            if (!controller.IsClimbing)
            {
                steps.Add(AttackMyTile());
            }
        }

        return(new Turn(steps, GameManager.standardTurnTime));
    }
예제 #28
0
        public void ExecuteCommand(string command)
        {
            if (command == null)
            {
                ThrowArgumentNullExceptionOnNullArgument(nameof(command), nameof(ExecuteCommand));
            }

            //Ignore not relevant spaces and case
            command = command.Trim().ToUpperInvariant();

            if (command.StartsWith(SimulatorCommands.Place))
            {
                var parts = command.Split(' ');
                if (parts.Length == 2 && parts[0] == SimulatorCommands.Place)
                {
                    var parameters = parts[1].Split(',');
                    if (parameters.Length != 3)
                    {
                        ThrowArgumentExceptionOnInvalidCommand(command, nameof(ExecuteCommand), null);
                    }
                    else
                    {
                        try {
                            int x         = int.Parse(parameters[0].Trim());
                            int y         = int.Parse(parameters[1].Trim());
                            var position  = new Point.Point(x, y);
                            var direction = DirectionExtensions.ConvertStringToDirection(parameters[2].Trim());

                            Robot.Place(Table, position, direction);
                        } catch (InvalidOperationException ioe) {
                            // Handle exceptions from Robot.Place
                            LogNotAllowedCommand(command, ioe);
                        } catch (Exception e) when(e is FormatException || e is OverflowException || e is ArgumentOutOfRangeException)
                        {
                            // Handle exceptions from parameters parsing
                            ThrowArgumentExceptionOnInvalidCommand(command, nameof(ExecuteCommand), e);
                        }
                    }
                }
                else
                {
                    ThrowArgumentExceptionOnInvalidCommand(command, nameof(ExecuteCommand), null);
                }
            }
            else
            {
                try {
                    switch (command)
                    {
                    case SimulatorCommands.Move:
                        Robot.Move();
                        break;

                    case SimulatorCommands.Left:
                        Robot.RotateToTheLeft();
                        break;

                    case SimulatorCommands.Right:
                        Robot.RotateToTheRight();
                        break;

                    case SimulatorCommands.Report:
                        var robotStatus = Robot.GetStatus();
                        MainTextWriter.WriteLine($"{robotStatus.Position.x},{robotStatus.Position.y},{robotStatus.Direction.ToString().ToUpperInvariant()}");
                        break;

                    default:
                        ThrowArgumentExceptionOnInvalidCommand(command, nameof(ExecuteCommand), null);
                        break;
                    }
                } catch (InvalidOperationException ioe) {
                    LogNotAllowedCommand(command, ioe);
                }
            }
        }
        public void An_Empty_Direction_Cannot_Be_Converted_Into_An_Arrow()
        {
            Action action = () => DirectionExtensions.ToArrow(null);

            action.Should().Throw <ArgumentNullException>();
        }
        public void Cannot_Convert_SecondaryInterCardinalDirection_Into_Arrow()
        {
            Action action = () => DirectionExtensions.ToArrow("NNE");

            action.Should().Throw <ArgumentException>();
        }