Пример #1
0
 public void CanGetOppositeDirection()
 {
     // Assert
     helper.GetOppositeDirection(Direction.S).ShouldBeEqual(Direction.N);
     helper.GetOppositeDirection(Direction.E).ShouldBeEqual(Direction.W);
     helper.GetOppositeDirection(Direction.NE).ShouldBeEqual(Direction.SW);
 }
Пример #2
0
        protected void Walk()
        {
            if ((DateTime.Now - _lastTimeWalked).TotalMilliseconds <= Server.MobWalkInterval)
            {
                return;
            }

            _lastTimeWalked = DateTime.Now;

            var room = RoomHelper.GetPlayerRoom(Location);

            // get allowed exits
            var allowedExits = room.Exits.Where(e => AllowedRooms.Contains(e.Value.LeadsTo) && e.Value.IsOpen).ToList();

            if (allowedExits.Any() && Server.Current.Random.NextDouble() < 0.5)
            {
                var exit = allowedExits.Skip(Server.Current.Random.Next(allowedExits.Count())).FirstOrDefault();

                room.RemoveNpc(this);
                var newRoom = RoomHelper.GetPlayerRoom(exit.Value.LeadsTo);
                newRoom.AddNpc(this);
                Location = newRoom.Key;
                room.SendPlayers(string.Format("{0} heads {1}.", Name, DirectionHelper.GetDirectionWord(exit.Key)),
                                 null, null, null);
                newRoom.SendPlayers(
                    string.Format("{0} arrives from the {1}.", Name, DirectionHelper.GetOppositeDirection(exit.Key)),
                    null, null, null);
            }
        }
Пример #3
0
    /*
     * Iterating through the nodes to see which is closer to targetTile (Pac-man)
     */
    private Direction ChooseNewDirection()
    {
        if (_reverseDirection)
        {
            _reverseDirection = false;
            return(DirectionHelper.GetOppositeDirection(currentDirection));
        }

        Direction chosenDirection = currentDirection;
        var       currentTile     = gameManager.GetEntityCurrentTileCoordinates(entityId, currentDirection);

        var validDirections = levelManager.GetValidDirectionsForTile(currentTile,
                                                                     currentState == GhostState.LeavingBox || currentState == GhostState.Consumed);

        if (validDirections.Count == 1)
        {
            return(validDirections[0]);
        }

        if (currentState == GhostState.LeavingBox)
        {
            chosenDirection = ChooseDirection(currentTile, levelManager.BoxDoorEntranceCoordinates, validDirections);
        }
        else if (currentState == GhostState.Consumed)
        {
            consumedBoxTile = levelManager.GetRandomBoxTileCoordinates();
            chosenDirection = ChooseDirection(currentTile, consumedBoxTile, validDirections);
        }
        else if (currentState == GhostState.Roaming)
        {
            var mode = modeManager.currentMode;
            switch (mode)
            {
            case ModeManager.Mode.Chase:
                Vector2Int targetTile = ChooseTargetTile();
                chosenDirection = ChooseDirection(currentTile, targetTile, validDirections);
                break;

            case ModeManager.Mode.Scatter:
                chosenDirection = ChooseDirection(currentTile, levelManager.GetOwnCorner(entityId), validDirections);
                break;

            case ModeManager.Mode.Frightened:
                chosenDirection = ChooseFrightenedModeDirection(validDirections);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }

        return(chosenDirection);
    }
        public Map GenerateRandomMap()
        {
            while (true)
            {
                var mapBuilder = CreateMapBuilder();
                var directions = new List <Direction>();

                var seenPoints = new HashSet <Point>();

                var repeatedFailureCount = 0;

                var currentDirection = Direction.Top;
                while (repeatedFailureCount < 100)
                {
                    var previousDirection = currentDirection;
                    var newDirection      = directionHelper.GetRandomDirectionOtherThan(
                        previousDirection,
                        DirectionHelper.GetOppositeDirection(
                            previousDirection));

                    mapBuilder.MoveInDirection(newDirection);

                    repeatedFailureCount = 0;

                    var currentPoint = mapBuilder.CurrentPoint;
                    currentDirection = newDirection;

                    directions.Add(newDirection);
                    seenPoints.Add(currentPoint);

                    if (currentPoint.X == 0 && currentPoint.Y == 0)
                    {
                        if (directions.Count == 4)
                        {
                            break;
                        }

                        return(mapBuilder.Build());
                    }
                }
            }

            throw new NotImplementedException();
        }
        public MapBuilder MoveInDirection(Direction direction)
        {
            var node = GenerateMapSegmentNode(
                nodes.Count,
                origin,
                DirectionHelper.GetOppositeDirection(previousDirection),
                direction);

            var offset   = DirectionHelper.GetDirectionalOffset(direction);
            var newPoint = new Point(
                origin.X + offset.X,
                origin.Y + offset.Y);

            origin            = newPoint;
            previousDirection = direction;

            nodes.Add(node);

            return(this);
        }
Пример #6
0
        public override bool Update()
        {
            bool finish      = false;
            var  world       = EntityManager.Instance.World;
            var  destination = Entity.Position.NextPosition(direction);

            if (world.CanMove(destination))
            {
                world.MoveEntity(Entity, destination);
                if (Entity.Position.Equals(EntityManager.Instance.Player.Position))
                {
                    finish = true;
                    EntityManager.Instance.AddDeadEntity(EntityManager.Instance.Player);
                }
            }

            if (!world.CanMove(destination.NextPosition(direction)))
            {
                direction = DirectionHelper.GetOppositeDirection(direction);
            }

            return(finish);
        }
        /* Trying to move checker
         * Calculating the movement
         * ------------------------------------------------------------------------------
         */
        private void DoMovement(BaseChecker previouslySelectedChecker, Point toPosition)
        {
            string    logMessage = Constants.localized.logTurn + ' ';
            PathPoint turns;

            // Erase highlighting on all checkers
            DeselectAllCheckers();

            // If the move does not start
            if (state.ActiveCheckerPathPoint == null)
            {
                turns = previouslySelectedChecker.GetPossibleTurns(); // Calculation of all possible chains of moves for a checker
                state.ActiveCheckerPathPoint = turns;
            }
            else
            {
                turns = state.ActiveCheckerPathPoint; // Continuation of the movement
            }
            // If the position is not a deadlock
            if (!turns.IsDeadEnd())
            {
                state.ActiveChecker = previouslySelectedChecker;

                // Movement
                for (int i = 0; i < 4; i++)
                {
                    foreach (PathPoint point in turns[i])
                    {
                        if (toPosition == point.Position)
                        {
                            Point fromPosition = new Point()
                            {
                                X = previouslySelectedChecker.Position.BoardPosition.X,
                                Y = previouslySelectedChecker.Position.BoardPosition.Y
                            };
                            logMessage += previouslySelectedChecker.GetPrintablePosition() + $" {Constants.localized.logMoveTo} ";
                            // Moving the checker to the selected position
                            previouslySelectedChecker.MoveTo(new Point(toPosition.X, toPosition.Y));
                            logMessage += previouslySelectedChecker.GetPrintablePosition();
                            Game.userLogController.WriteMessage(logMessage);
                            // Defining the direction of movement
                            Point moveDirection = new Point()
                            {
                                X = toPosition.X - fromPosition.X > 0 ? 1 : -1,
                                Y = toPosition.Y - fromPosition.Y > 0 ? 1 : -1
                            };

                            // Determination of the eaten checkers
                            TryEatEnemyCheckers(previouslySelectedChecker, toPosition, fromPosition, moveDirection);

                            // If the checker can become a king
                            if (previouslySelectedChecker is Pawn && previouslySelectedChecker.Position.BoardPosition.Y ==
                                (previouslySelectedChecker.Direction == CheckerMoveDirection.Upstairs ? 0 : 7))
                            {
                                // Replacement of a checker by a king
                                King newKing = new King(previouslySelectedChecker.Side, previouslySelectedChecker.Position);
                                state.AllCheckers.Remove(previouslySelectedChecker);
                                state.AllCheckers.Add(newKing);

                                // Adding to the list of drawings
                                Game.drawingController.AddToDrawingList(newKing);
                                previouslySelectedChecker.Destroy();

                                // Calculation of the further path for a king
                                state.ActiveChecker = newKing;
                                if (state.ActiveCheckerPathPoint.afterAggression)
                                {
                                    state.ActiveCheckerPathPoint = newKing.GetPossibleTurns(DirectionHelper.GetOppositeDirection(DirectionHelper.GetDirection(moveDirection)));
                                    if (state.ActiveCheckerPathPoint.TryGetAggresiveDirections().Count == 0)
                                    {
                                        // End of turn
                                        EndTurn();
                                        return;
                                    }
                                    else
                                    {
                                        DeselectAllCheckers();
                                        state.ActiveChecker.selected = true;
                                        HighlightPossibleTurns(state.ActiveChecker);
                                    }
                                }
                                else
                                {
                                    EndTurn();
                                    return;
                                }
                            }

                            // Find the point he went to
                            // Calculate whether it is possible to continue the movement
                            foreach (PathPoint waypoint in state.ActiveCheckerPathPoint[DirectionHelper.GetDirection(moveDirection)])
                            {
                                if (waypoint.Position == toPosition)
                                {
                                    if (!waypoint.IsOnlyFinalTraces())
                                    {
                                        // Continuation of the movement
                                        state.ActiveCheckerPathPoint = waypoint;
                                        DeselectAllCheckers();
                                        state.ActiveChecker.selected = true;
                                        HighlightPossibleTurns(state.ActiveChecker);
                                    }
                                    else
                                    {
                                        // End of turn
                                        EndTurn();
                                    }
                                }
                            }
                            return;
                        }
                    }
                }
            }
            else
            {
                // Deadlock position, end of turn
                if (state.ActiveChecker != null || state.ActiveCheckerPathPoint != null)
                {
                    state.ActiveChecker          = null;
                    state.ActiveCheckerPathPoint = null;
                }
            }
        }
Пример #8
0
        private void TryExecuteCommand(string input)
        {
            if (input.ToLower() == "exitmapping")
            {
                Session.PopState();
                return;
            }

            var room = RoomHelper.GetPlayerRoom(Session.Player);

            if (_status == MappingStatus.Walking)
            {
                var direction = DirectionHelper.GetDirectionWord(input);

                if (string.IsNullOrEmpty(direction))
                {
                    Session.WriteLine("That's not a direction.");
                    return;
                }

                if (room.HasExit(direction))
                {
                    var commandInfo = Server.Current.CommandLookup.FindCommand(direction, Session.Player);
                    commandInfo.Command.Execute(Session, CommandContext.Create(direction));
                    return;
                }

                // set mode to request title
                Session.WriteLine("`RCreating exit, Please enter a title...");
                _status    = MappingStatus.NeedsTitle;
                _direction = direction;
            }
            else
            {
                // user is inputting a title
                var checkRoom     = Server.Current.Database.Get <Room>(input.ToLower());
                var calculatedKey = input.ToLower();

                if (checkRoom != null)
                {
                    calculatedKey = RoomHelper.GenerateKey(input);
                    Session.WriteLine("`RRoom already exists. Using title: `G{0}`R.", calculatedKey);
                }

                var newRoom = new Room()
                {
                    Area        = room.Area,
                    Description = RoomHelper.GetDefaultRoomDescription(),
                    Key         = calculatedKey.ToLower(),
                    Title       = input,
                };

                newRoom.Exits.Add(DirectionHelper.GetOppositeDirection(_direction), new RoomExit()
                {
                    IsDoor  = false,
                    IsOpen  = true,
                    LeadsTo = room.Key
                });

                Server.Current.Database.Save(newRoom);

                room.Exits.Add(_direction, new RoomExit()
                {
                    IsDoor  = false,
                    IsOpen  = true,
                    LeadsTo = newRoom.Key
                });

                Server.Current.Database.Save(room);

                var commandInfo = Server.Current.CommandLookup.FindCommand(_direction, Session.Player);
                commandInfo.Command.Execute(Session, CommandContext.Create(_direction));
                _status = MappingStatus.Walking;
            }
        }
Пример #9
0
        public override void Execute(Session session, CommandContext context)
        {
            var currentRoom = RoomHelper.GetRoom(session.Player.Location);

            if (currentRoom != null)
            {
                try
                {
                    string direction = context.Arguments[0];
                    context.Arguments.Remove(direction);

                    if (!DirectionHelper.isValidDirection(direction))
                    {
                        session.WriteLine("{0} is not a valid direction", direction);
                        PrintSyntax(session);
                    }
                    if (currentRoom.HasExit(direction))
                    {
                        session.WriteLine("Room already has {0} exit", direction);
                        PrintSyntax(session);
                        return;
                    }

                    // handle doors
                    string openClose = context.Arguments[0];
                    bool   isDoor;
                    bool   isOpen;
                    if (openClose == "<open>" || openClose == "<close>")
                    {
                        isDoor = true;
                        isOpen = openClose == "<open>";
                        context.Arguments.Remove(openClose);
                    }
                    else
                    {
                        isDoor = false;
                        isOpen = true;
                    }

                    // at this point, direction has been removed. all that remains if the new room key/name
                    string dstRoomKey = string.Join(" ", context.Arguments).Trim().ToLower();
                    var    dstRoom    = RoomHelper.GetRoom(dstRoomKey);
                    if (dstRoom == null)
                    {
                        session.WriteLine("Room key not found: {0}", dstRoomKey);
                        PrintSyntax(session);
                        return;
                    }

                    // fixme: confirm dstRoom doesn't already have the opposite exit e.g. if creating
                    // north exit, dstRoom should not already have south exit

                    currentRoom.Exits.Add(direction, new RoomExit()
                    {
                        LeadsTo = dstRoomKey,
                        IsDoor  = isDoor,
                        IsOpen  = isOpen
                    });

                    string oppositeDirection = DirectionHelper.GetOppositeDirection(direction);

                    dstRoom.Exits.Add(oppositeDirection, new RoomExit()
                    {
                        LeadsTo = currentRoom.Key,
                        IsDoor  = isDoor,
                        IsOpen  = isOpen
                    });

                    RoomHelper.SaveRoom(currentRoom);
                    RoomHelper.SaveRoom(dstRoom);
                }
                catch
                {
                    PrintSyntax(session);
                }
            }
        }
Пример #10
0
        public void Grow()
        {
            _logger.Debug($"Snake.Grow()");

            if (Head == null)
            {
                Head = new SnakeSegment(new Vector2((float)_gameSettings.TileSize), new Size2(_gameSettings.TileSize, _gameSettings.TileSize), Direction.Left); //GenerateRandomSegment();
            }
            else
            {
                var last = Tail.Any() ? Tail.LastOrDefault() : Head;

                if (last != null)
                {
                    var position = last.Position + DirectionHelper.RotateVector(_unitVector, DirectionHelper.GetOppositeDirection(last.Direction));
                    _tail.Add(new SnakeSegment(position, last.Size, last.Direction));
                }
            }
        }