Ejemplo n.º 1
0
    // Creates totalNumberofLoops amount of loops in the given level
    private void CreateLoops(Dictionary <Vector2, Room> level)
    {
        // Get a list of all Positions, and then randomize it
        Vector2[] roomPool = level.Keys.ToArray <Vector2>();
        RandomizeArray <Vector2>(roomPool);
        int       loopCounter = 0;
        int       firstDirection;
        int       randDirection;
        Direction attemptDirection;

        foreach (Vector2 current in roomPool)
        {
            if (loopCounter >= totalNumberOfLoops)
            {
                break;
            }

            firstDirection = r.Next(4);
            randDirection  = firstDirection; // necessary for compiling properly. Is literally changed immediately (we love c#)
            for (int i = 0; i < 4; i++)
            {
                randDirection    = (firstDirection + i) % 4;
                attemptDirection = DirectionMethods.NumberToDirection(randDirection);
                if (IsRoomHere(level, current, attemptDirection))
                {
                    if (!IsConnected(level, current, attemptDirection))
                    {
                        AddConnection(level, current, attemptDirection);
                        loopCounter++;
                    }
                }
            }
        }
    }
Ejemplo n.º 2
0
    /// <summary>
    /// Moves the agent to threshhold distance from target at speed
    /// </summary>
    public bool MoveTo(Vector2 target, float speed, float threshold)
    {
        AiData.currentBehavior = AIData.Behave.Chase;
        Vector2 current = transform.position;

        if (Vector2.Distance(current, target) <= threshold || current == target)
        {
            AnimatorBody.Play("Idle");

            //AiData.path.Clear();

            return(true);
        }
        else
        {
            #region Move
            AnimatorBody.Play("Move");
            target = (target - current);
            target = Vector2.ClampMagnitude(target, speed);
            controller.Direction = DirectionMethods.FromVec2(target);
            if (!AiData.updateBehavior)
            {
                return(false);
            }
            RigidBody.velocity = Vector2.ClampMagnitude(RigidBody.velocity + target, speed);
            #endregion
            return(false);
        }
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Moves the agent away from threshold distance - 1 from target at speed
    /// </summary>
    public bool MoveFrom(Vector2 target, float speed, float threshold)
    {
        Vector2 current = transform.position;

        if (target == current)
        {
            return(true);
        }

        if (Vector2.Distance(current, target) < threshold)
        {
            #region Move
            AiData.currentBehavior = AIData.Behave.Flee;
            AnimatorBody.Play("Move");
            target = (current - target);
            target = Vector2.ClampMagnitude(target, speed);
            controller.Direction = DirectionMethods.FromVec2(target);
            if (!AiData.updateBehavior)
            {
                return(false);
            }
            RigidBody.velocity = target;
            #endregion
            return(false);
        }
        else
        {
            AnimatorBody.Play("Idle");
            return(true);
        }
    }
Ejemplo n.º 4
0
        public void TestJsonSerialize()
        {
            Direction[] allDirections = DirectionMethods.GetAllDirections();
            int         w             = 10;
            int         h             = 15;
            Map         map           = new SimpleMapGenerator().GenerateMap(w, h, IMapGeneratorConstants.NO_SEED);
            IMapSerializer <string, string> jsonSerializer = new JsonMapSerializer();
            string jsonString = jsonSerializer.Serialize(map);

            Assert.IsFalse(jsonString.Length == 0, "Empty string returned!");

            Map deserialized = jsonSerializer.Deserialize(jsonString);

            // compare pre-serialization vs post-serialization
            Assert.AreEqual(map.Width, deserialized.Width, "Wrong width!");
            Assert.AreEqual(map.Height, deserialized.Height, "Wrong width!");
            for (int i = 0; i < map.Width; i++)
            {
                for (int j = 0; j < map.Height; j++)
                {
                    MapBlock orig  = map.Grid[i, j];
                    MapBlock deser = deserialized.Grid[i, j];

                    Assert.AreEqual(orig, deser, $"Blocks at [{i},{j}] have wrong coordinates!");
                    foreach (Direction d in allDirections)
                    {
                        Assert.AreEqual(orig.EntranceInDirection(d), deser.EntranceInDirection(d), $"Blocks at [{i},{j}] have different entrance in direction {d}!");
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public void RotateLeft_on_up_should_return_left()
        {
            var direction = Direction.Up;
            var result    = DirectionMethods.RotateLeft(direction);

            Assert.AreEqual(Direction.Left, result);
        }
Ejemplo n.º 6
0
        public void RotateLeft_on_right_should_return_up()
        {
            var direction = Direction.Right;
            var result    = DirectionMethods.RotateLeft(direction);

            Assert.AreEqual(Direction.Up, result);
        }
Ejemplo n.º 7
0
        private void ExecuteCommand(Tank tank, string command, FightStat fitnessStat)
        {
            switch (command)
            {
            case "Forward":
                CheckAndMove(tank, tank.Coord + Movements[tank.Direction]);
                return;

            case "Backward":
                CheckAndMove(tank, tank.Coord - Movements[tank.Direction]);
                return;

            case "TurnRight":
                tank.Direction = DirectionMethods.RotateRight(tank.Direction);
                return;

            case "TurnLeft":
                tank.Direction = DirectionMethods.RotateLeft(tank.Direction);
                return;

            case "Shoot":
                ShootAction(tank, fitnessStat);
                return;

            case "Finish":
                tank.IsAlive = false;
                return;

            default:
                throw new Exception("Unknown command");
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Decides whether to choose direction of next block or to switch backwardFlag.
        /// </summary>
        /// <return>Next direction. May be null.</return>
        private Direction GoForward()
        {
            Direction nextDirection = Direction.NO_DIRECTION;

            Direction[] allDirections = DirectionMethods.GetAllDirections();
            if (pathStack.Count != stackCapacity)
            {
                // stack is not full, pick next direction
                // keep trying random directions until one (different from the last one) is selected or max attempt count is reached
                int attempt = 0;
                while ((nextDirection.IsNoDirection() || (pathStack.Count > 0 && nextDirection == pathStack.Peek())) && attempt < DEF_MAX_RANDOM_TRIES)
                {
                    Direction randomDirection   = allDirections[randomizer.Next(allDirections.Length)];
                    MapBlock  possibleNextBlock = Position.NextOpenBlock(randomDirection);
                    if (possibleNextBlock != null && !possibleNextBlock.Occupied)
                    {
                        nextDirection = randomDirection;
                    }
                    attempt++;
                }

                // some direction was picked -> add it to stack
                if (!nextDirection.IsNoDirection())
                {
                    pathStack.Push(nextDirection);
                }
            }
            else
            {
                // stack is full set backward flag and do nothing
                goBackwardFlag = true;
            }
            return(nextDirection);
        }
Ejemplo n.º 9
0
        public void Flip_on_up_should_return_down()
        {
            var direction = Direction.Up;
            var result    = DirectionMethods.Flip(direction);

            Assert.AreEqual(Direction.Down, result);
        }
Ejemplo n.º 10
0
        public void Flip_on_right_should_return_left()
        {
            var direction = Direction.Right;
            var result    = DirectionMethods.Flip(direction);

            Assert.AreEqual(Direction.Left, result);
        }
Ejemplo n.º 11
0
 //Flip it around if it's too far from room center
 private void IdleWalkCheckBounds()
 {
     if (Vector2.Distance(transform.position, currentRoom.transform.position) > currentRoom.RoomWidth / 2)
     {
         desiredDirection = DirectionMethods.OppositeDirection(desiredDirection);
         rb.velocity      = new Vector2(walkSpeed * (desiredDirection == Direction.Right ? 1 : -1) * 2, 0);
     }
 }
Ejemplo n.º 12
0
    // Creates mainPathLength amount of rooms. Labels the last one created as the end room
    private void CreateMainPath(Dictionary <Vector2, Room> level)
    {
        Stack <Vector2> stack = new Stack <Vector2>();

        stack.Push(Vector2.zero);
        Vector2   current;
        Vector2   next;
        string    roomTemplate;
        int       firstDirection;
        Direction attemptDirection;

        while (roomCounter <= mainPathLength)
        {
            current          = stack.Peek();
            next             = current;     // Dummy assignment - I literally have to set next to something so the code compiles.
            firstDirection   = r.Next(4);
            attemptDirection = Direction.N; // necessary for compiling properly. Is literally changed immediately (we love c#)
            for (int i = 0; i < 4; i++)
            {
                attemptDirection = DirectionMethods.NumberToDirection((firstDirection + i) % 4);
                if (!IsRoomHere(level, current, attemptDirection))
                {
                    next = GetPositionInDirection(current, attemptDirection);
                    break;
                }
            }
            // If next is still equal to current we know we weren't able to find a new room and must go back a room and try again
            if (next == current)
            {
                stack.Pop();
            }
            else
            {
                if (roomCounter == mainPathLength)
                {
                    roomTemplate = endRoomTemplate;
                }
                else
                {
                    int templateIndex = r.Next(availableTemplates.Count);
                    roomTemplate = availableTemplates[templateIndex];
                    availableTemplates.RemoveAt(templateIndex);
                    if (availableTemplates.Count == 0)
                    {
                        availableTemplates = GetTemplates();
                    }
                }
                Room nextRoom = CreateRoom(roomTemplate);
                level.Add(next, nextRoom);
                stack.Push(next);
                AddConnection(level, current, attemptDirection);
                roomCounter++;
            }
        }
    }
Ejemplo n.º 13
0
    // Creates branches until we have satisfied totalNumberOfRooms. Branches stop either at desiredBranchLength or until they get 'stuck'
    private void CreateBranches(Dictionary <Vector2, Room> level)
    {
        Vector2[] roomPool = level.Keys.ToArray <Vector2>();
        Vector2   current;
        Vector2   next;
        int       firstDirection;
        Direction attemptDirection;

        while (roomCounter <= totalNumberOfRooms)
        {
            // Pick a random room
            current = roomPool[r.Next(0, roomPool.Length)];
            next    = current;

            // Create a branch
            for (int i = 0; i < desiredBranchLength; i++)
            {
                firstDirection   = r.Next(4);
                attemptDirection = Direction.N; // necessary for compiling properly. Is literally changed immediately (we love c#)
                for (int j = 0; j < 4; j++)
                {
                    attemptDirection = DirectionMethods.NumberToDirection((firstDirection + i) % 4);
                    if (!IsRoomHere(level, current, attemptDirection))
                    {
                        next = GetPositionInDirection(current, attemptDirection);
                        break;
                    }
                }
                // room cannot be created - just stop the branch
                if (next == current)
                {
                    break;
                }
                else
                {
                    int  templateIndex = r.Next(availableTemplates.Count);
                    Room nextRoom      = CreateRoom(availableTemplates[templateIndex]);
                    availableTemplates.RemoveAt(templateIndex);
                    if (availableTemplates.Count == 0)
                    {
                        availableTemplates = GetTemplates();
                    }
                    level.Add(next, nextRoom);
                    AddConnection(level, current, attemptDirection);
                    current = next;
                    roomCounter++;
                    if (roomCounter > totalNumberOfRooms)
                    {
                        break;
                    }
                }
            }
        }
    }
Ejemplo n.º 14
0
 private void calculateNeighborsForRow(int row)
 {
     for (int col = 0; col < boardSize; col++)
     {
         Tile currentTile = tiles[row, col];
         Dictionary <Direction, Tile> currentTileNeighbors = new Dictionary <Direction, Tile>();
         foreach (Direction d in Enum.GetValues(typeof(Direction)))
         {
             int[] indeces = DirectionMethods.getNeighborIndex(row, col, d);
             currentTileNeighbors[d] = areValid(indeces) ?
                                       tiles[indeces[0], indeces[1]] : null;
         }
         currentTile.setNeighbors(currentTileNeighbors);
     }
 }
Ejemplo n.º 15
0
        public override string Run(string command, string[] args, string argStr)
        {
            McTcpClient handler = tcpClientRetriever.GetTcpClient();

            if (args.Length == 1)
            {
                string    dirStr    = args[0].Trim().ToLower();
                Direction direction = DirectionMethods.FromString(dirStr);
                if (direction == Direction.None)
                {
                    return("Invalid direction: " + dirStr);
                }

                player.UpdateLocation(player.GetCurrentLocation(), direction);
                return("Looking " + dirStr);
            }
            else if (args.Length == 2)
            {
                try
                {
                    float yaw   = Single.Parse(args[0]);
                    float pitch = Single.Parse(args[1]);

                    player.UpdateLocation(player.GetCurrentLocation(), yaw, pitch);
                    return(String.Format("Looking at YAW: {0} PITCH: {1}", yaw.ToString("0.00"), pitch.ToString("0.00")));
                }
                catch (FormatException) { return(CMDDesc); }
            }
            else if (args.Length == 3)
            {
                try
                {
                    int x = int.Parse(args[0]);
                    int y = int.Parse(args[1]);
                    int z = int.Parse(args[2]);

                    Location block = new Location(x, y, z);
                    player.UpdateLocation(player.GetCurrentLocation(), block);

                    return("Looking at " + block);
                }
                catch (FormatException) { return(CMDDesc); }
            }
            else
            {
                return(CMDDesc);
            }
        }
Ejemplo n.º 16
0
    public void onPlayerMove(PlayerMoveEvent ev)
    {
        Location location = ev.getLocation();
        World    world    = location.getWorld();

        Vector3 movement = ev.getMovement();

        Direction moveDirection   = DirectionMethods.getDominantDirection(movement);
        Location  ordinalMovement = moveDirection.ordinal(world) * Chunk.chunkSize;

        ChunkLocation playerChunkLocation = ChunkLocation.asChunkLocation(location + ordinalMovement);

        loadChunksInRange(playerChunkLocation);

        unloadChunksOutOfRange(playerChunkLocation);
    }
    /// <summary>
    /// Attack an enemy unit
    /// </summary>
    /// <param name="enemyUnit">unitcontroller of enemy unit</param>
    public void Attack(UnitController enemyUnit)
    {
        //rotate towards enemy
        Direction directionToEnemy = DirectionMethods.GetOrientation(GetUnitCoords(), enemyUnit.GetUnitCoords());

        RotateTowards(directionToEnemy);

        //trigger attack animation
        _animator.SetTrigger("Attack");

        //deal damage to enemy
        enemyUnit.TakeDamage(attackDamage);

        //rotate back
        StartCoroutine(ResetRotation());
    }
Ejemplo n.º 18
0
        public void TestOpenMapGenerator()
        {
            IMapGenerator openMapGenerator = MapGeneratorFactory.CreateOpenMapGenerator();
            int           w = 10;
            int           h = 15;

            Direction[] allDirections = DirectionMethods.GetAllDirections();

            MapBlock[,] grid = openMapGenerator.GenerateGrid(w, h, 0);
            Assert.IsNotNull(grid, "Null grid returned!");
            Assert.AreEqual(w, grid.GetLength(0), "Wrong width of map grid!");
            Assert.AreEqual(h, grid.GetLength(1), "Wrong height of map grid!");
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    foreach (Direction dir in allDirections)
                    {
                        Assert.IsTrue(grid[i, j].EntranceInDirection(dir).IsOpen(), $"Entrance in direction {dir} of block [{i},{j}] should be open!");
                    }
                }
            }

            Map map = openMapGenerator.GenerateMap(w, h, 0);

            Assert.IsNotNull(map, "Null map returned!");
            Assert.AreEqual(w, map.Width, "Wrong map width!");
            Assert.AreEqual(h, map.Height, "Wrong map height!");
            MapBlock[,] grid2 = map.Grid;
            Assert.AreEqual(grid.GetLength(0), grid.GetLength(0), "Widths of grids don't match!");
            Assert.AreEqual(grid.GetLength(1), grid.GetLength(1), "Widths of grids don't match!");
            Assert.IsNotNull(map.WinningBlock, "Winning block is null!");
            Assert.AreEqual((w - 1) / 2, map.WinningBlock.X, "Wrong X coordinate of winning block.");
            Assert.AreEqual((h - 1) / 2, map.WinningBlock.Y, "Wrong Y coordinate of winning block.");

            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    foreach (Direction dir in allDirections)
                    {
                        Assert.IsTrue(grid2[i, j].EntranceInDirection(dir).IsOpen(), $"Entrance in direction {dir} of block [{i},{j}] should be open!");
                    }
                }
            }
        }
Ejemplo n.º 19
0
 void Update()
 {
     Direction direction = Direction.None;
     if (Input.GetKeyDown("q"))
     {
         direction = Direction.NW;
     }
     if (Input.GetKeyDown("w"))
     {
         direction = Direction.N;
     }
     if (Input.GetKeyDown("e"))
     {
         direction = Direction.NE;
     }
     if (Input.GetKeyDown("a"))
     {
         direction = Direction.W;
     }
     if (Input.GetKeyDown("d"))
     {
         direction = Direction.E;
     }
     if (Input.GetKeyDown("z"))
     {
         direction = Direction.SW;
     }
     if (Input.GetKeyDown("x"))
     {
         direction = Direction.S;
     }
     if (Input.GetKeyDown("c"))
     {
         direction = Direction.SE;
     }
     if(direction != Direction.None)
     {
         Vector3 nextPos = transform.position + DirectionMethods.GetVector3(direction);
         Vector2Int nextPosXY = new Vector2Int(Mathf.RoundToInt(nextPos.x), Mathf.RoundToInt(nextPos.z)); // shit but eh who cares
         if (world.IsWalkable(nextPosXY.x, nextPosXY.y))
         {
             transform.Translate(DirectionMethods.GetVector3(direction));
         }
     }
 }
    /// <summary>
    /// Find the friendly unit nearest to a given enemy unit
    /// </summary>
    /// <param name="enemyUnitController">unitcontroller of enemy unit</param>
    /// <returns>unitcontroller of nearest friendly unit</returns>
    private UnitController FindNearestFriendlyUnit(UnitController enemyUnitController)
    {
        //loop over each friendly unit and check for the shortest distance

        int            shortestDistance = Int32.MaxValue;     //distance to unit with shortest distance
        UnitController shortestDistanceUnitController = null; //unitcontroller of unit with shortest distance

        foreach (var friendlyUnitController in playerArmy)
        {
            Coords friendlyUnitCoords = friendlyUnitController.GetUnitCoords();

            if (enemyUnitController.CanAttack(friendlyUnitCoords))
            {
                //if enemy unit can attack friendly, return the attackable unit
                return(friendlyUnitController);
            }

            foreach (var direction in DirectionMethods.GetClockwise())
            {
                BFS    bfs           = new BFS();
                Coords coordsToCheck = friendlyUnitCoords.Get(direction); //coords right next to unit in direction

                //check if enemy unit has path to friendly unit
                if (enemyUnitController.HasPath(coordsToCheck, ref bfs))
                {
                    //get length of solution and check if shorter than the previous shortest distance
                    int solutionLength = bfs.GetSolutionLength();
                    if (solutionLength < shortestDistance)
                    {
                        shortestDistance = solutionLength;
                        shortestDistanceUnitController = friendlyUnitController;
                    }
                }
            }
        }

        if (shortestDistanceUnitController == null)
        {
            //there is no path to any friendly unit
            //just select the first enemy
            shortestDistanceUnitController = playerArmy[0];
        }

        return(shortestDistanceUnitController);
    }
Ejemplo n.º 21
0
        public override string Run(string command, string[] args, string argStr)
        {
            McTcpClient handler = tcpClientRetriever.GetTcpClient();

            if (args.Length == 1)
            {
                if (argStr == "get")
                {
                    return(handler.player.GetCurrentLocation().ToString());
                }

                Direction direction = DirectionMethods.FromString(argStr);

                if (Movement.CanMove(handler.GetWorld(), handler.player.GetCurrentLocation(), direction))
                {
                    //handler.player.MoveTo(Movement.Move(handler.player.GetCurrentLocation(), direction));
                    return("Moving " + argStr + '.');
                }
                else
                {
                    return("Cannot move in that direction.");
                }
            }
            else if (args.Length == 3)
            {
                try
                {
                    int      x    = int.Parse(args[0]);
                    int      y    = int.Parse(args[1]);
                    int      z    = int.Parse(args[2]);
                    Location goal = new Location(x, y, z);
                    //if (handler.player.MoveTo(goal))
                    //return "Walking to " + goal;
                    return("Failed to compute path to " + goal);
                }
                catch (FormatException) { return(CMDDesc); }
            }
            else
            {
                return(CMDDesc);
            }
        }
Ejemplo n.º 22
0
        public void TestSimpleMapGeneratorSeed()
        {
            IMapGenerator simpleMapGenerator = MapGeneratorFactory.CreateSimpleMapGenerator();
            int           w    = 5;
            int           h    = 10;
            int           seed = 87452;

            Direction[] allDirections = DirectionMethods.GetAllDirections();

            MapBlock[,] grid  = simpleMapGenerator.GenerateGrid(w, h, seed);
            MapBlock[,] grid2 = simpleMapGenerator.GenerateGrid(w, h, seed);

            Assert.IsNotNull(grid, "Grid 1 is null!");
            Assert.IsNotNull(grid2, "Grid 2 is null!");
            Assert.AreEqual(w, grid.GetLength(0), "Wrong width of map grid!");
            Assert.AreEqual(h, grid.GetLength(1), "Wrong height of map grid!");
            Assert.AreEqual(w, grid2.GetLength(0), "Wrong width of map grid 2!");
            Assert.AreEqual(h, grid2.GetLength(1), "Wrong height of map grid 2!");

            // all map block should be same
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    int entrances = 0;
                    foreach (Direction dir in allDirections)
                    {
                        Assert.AreEqual(grid[i, j].EntranceInDirection(dir).Exists(), grid2[i, j].EntranceInDirection(dir).Exists(), $"Map block at position [{i},{j}] has different entrance in direction {dir}.");
                        if (grid[i, j].EntranceInDirection(dir).Exists())
                        {
                            entrances++;
                        }
                    }

                    Assert.IsTrue(entrances > 0, $"Block at [{i},{j}] has no entrance!");
                }
            }
        }
Ejemplo n.º 23
0
        public void TestSimpleMapGenerator()
        {
            IMapGenerator simpleMapGenerator = MapGeneratorFactory.CreateSimpleMapGenerator();
            int           w = 5;
            int           h = 10;

            Direction[] allDirections = DirectionMethods.GetAllDirections();

            Map map = simpleMapGenerator.GenerateMap(w, h, IMapGeneratorConstants.NO_SEED);

            MapBlock[,] grid = map.Grid;

            Assert.IsNotNull(grid, "Null grid returned!");
            Assert.AreEqual(w, grid.GetLength(0), "Wrong width of map grid!");
            Assert.AreEqual(h, grid.GetLength(1), "Wrong height of map grid!");
            Assert.IsNotNull(map.WinningBlock, "Winning block is null!");
            Assert.AreEqual((w - 1) / 2, map.WinningBlock.X, "Wrong X coordinate of winning block.");
            Assert.AreEqual((h - 1) / 2, map.WinningBlock.Y, "Wrong Y coordinate of winning block.");

            // test that no map block has all entrances closed
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    int entrances = 0;
                    foreach (Direction dir in allDirections)
                    {
                        if (grid[i, j].EntranceInDirection(dir).Exists())
                        {
                            entrances++;
                        }
                    }

                    Assert.IsTrue(entrances > 0, $"Block at [{i},{j}] has no entrance!");
                }
            }
        }
Ejemplo n.º 24
0
        public MapBlock[,] GenerateGrid(int width, int height, int seed)
        {
            // start with open maze
            MapBlock[,] grid = new MapBlock[width, height];
            // array to hold information about cells which were already visited by algorithm
            bool[,] visitedGrid = new bool[width, height];
            Direction[] allDirections = DirectionMethods.GetAllDirections();
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    visitedGrid[i, j] = false;
                    grid[i, j]        = new MapBlock(i, j);
                }
            }

            // go through maze and demolish walls to create paths
            Stack <MapBlock> stack = new Stack <MapBlock>();
            Random           r;

            if (seed == IMapGeneratorConstants.NO_SEED)
            {
                r = new Random();
            }
            else
            {
                r = new Random(seed);
            }
            MapBlock start = grid[r.Next(width), r.Next(height)];

            stack.Push(start);

            while (stack.Count > 0)
            {
                MapBlock current = stack.Peek();

                // select neighbours of current block which were not visited yet
                List <MapBlock> notVisited = new List <MapBlock>();
                if (current.Y > 0 && !visitedGrid[current.X, current.Y - 1])
                {
                    notVisited.Add(grid[current.X, current.Y - 1]);
                }
                if (current.Y < height - 1 && !visitedGrid[current.X, current.Y + 1])
                {
                    notVisited.Add(grid[current.X, current.Y + 1]);
                }
                if (current.X > 0 && !visitedGrid[current.X - 1, current.Y])
                {
                    notVisited.Add(grid[current.X - 1, current.Y]);
                }
                if (current.X < width - 1 && !visitedGrid[current.X + 1, current.Y])
                {
                    notVisited.Add(grid[current.X + 1, current.Y]);
                }

                // there are some neighbours which were not visited
                // choose one a create entrance between current block and neighbour block
                if (notVisited.Count > 0)
                {
                    int      neighbourIndex = r.Next(notVisited.Count);
                    MapBlock neighbour      = notVisited[neighbourIndex];
                    notVisited.RemoveAt(neighbourIndex);
                    DemolishWalls(current, neighbour);

                    // add neighbour to the stack so the path creation will continue this way
                    stack.Push(neighbour);

                    // mark current cell and neighbour as visited
                    visitedGrid[current.X, current.Y]     = true;
                    visitedGrid[neighbour.X, neighbour.Y] = true;
                }
                else
                {
                    // every neighbour was visited, pop current block and continue with next block in the stack
                    stack.Pop();
                }
            }

            return(grid);
        }
Ejemplo n.º 25
0
 public TraversableNode getNeighbour(Direction direction)
 {
     return(movableNodes[DirectionMethods.directionToArrayIndex(direction)]);
 }
Ejemplo n.º 26
0
 //Insert a Traversable node in the direction slot this node can get to it by moving
 public void insertAt(Direction direction, TraversableNode node)
 {
     movableNodes[DirectionMethods.directionToArrayIndex(direction)] = node;
 }
Ejemplo n.º 27
0
        public void TestSerializeMaze()
        {
            int w   = 4;
            int h   = 4;
            Map map = MapGeneratorFactory.CreateSimpleMapGenerator().GenerateMap(w, h, IMapGeneratorConstants.NO_SEED);

            map.MapName = "Test map";

            // add creatures to map
            Monster origMonster = new Monster("Test monster", map.Grid[0, 0], 4, 3654123, 87621235);

            map.AddCreature(origMonster);
            SimpleAIPlayer aiPlayer = new SimpleAIPlayer("Test player", map.Grid[3, 2]);

            map.AddCreature(aiPlayer);
            HumanPlayer hPlayer = new HumanPlayer("Příliš žluťoučký kůň úpěl ďábelské ódy", map.Grid[1, 3])
            {
                BaseHitPoints = 98432156, BaseAttack = 112348, BaseDeffense = 41226987
            };

            map.AddCreature(hPlayer);

            // add items to map
            AbstractWeapon weapon = ItemFactory.CreateAxe(map.Grid[1, 3]);

            map.AddItem(weapon);
            AbstractArmor armor = ItemFactory.CreateLeatherArmor(map.Grid[1, 1]);

            map.AddItem(armor);
            AbstractInventoryItem item = new BasicItem("Příliš žluťoučký kůň úpěl ďábelské ódy.!?_/()':123456789<>&@{}[]", map.Grid[2, 2], 514)
            {
                UniqueId = 6284
            };

            map.AddItem(item);


            // serialize - deserialize
            IMapSerializer <byte[], byte[]> byteSerializer = new BinaryMapSerializer();

            byte[] serializedMap   = byteSerializer.Serialize(map);
            Map    deserializedMap = byteSerializer.Deserialize(serializedMap);


            // check map
            Assert.AreEqual(map.MapName, deserializedMap.MapName, "Wrong map name!");
            Assert.AreEqual(w, deserializedMap.Width, "Wrong width after deserialization!");
            Assert.AreEqual(h, deserializedMap.Width, "Wrong height after deserialization!");
            Assert.AreEqual(map.WinningBlock.X, deserializedMap.WinningBlock.X, "Wrong x coordinate of winning block!");
            Assert.AreEqual(map.WinningBlock.Y, deserializedMap.WinningBlock.Y, "Wrong Y coordinate of winning block!");


            // check map blocks
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    MapBlock origBlock   = map.Grid[i, j];
                    MapBlock testedBlock = deserializedMap.Grid[i, j];

                    foreach (Direction dir in  DirectionMethods.GetAllDirections())
                    {
                        Assert.AreEqual(origBlock.EntranceInDirection(dir).IsOpen(), testedBlock.EntranceInDirection(dir).IsOpen(), $"Wrong entrance in direction {dir} in block [{i},{j}].");
                    }
                }
            }


            // check creatures
            Monster m = (Monster)deserializedMap.Grid[0, 0].Creature;

            CheckCreature(origMonster, m);

            SimpleAIPlayer p = (SimpleAIPlayer)deserializedMap.Grid[3, 2].Creature;

            CheckCreature(aiPlayer, p);

            HumanPlayer hp = (HumanPlayer)deserializedMap.Grid[1, 3].Creature;

            CheckCreature(hPlayer, hp);


            // check items
            AbstractWeapon weap = (AbstractWeapon)map.Grid[1, 3].Item;

            CheckItem(weap, weapon);

            AbstractArmor arm = (AbstractArmor)map.Grid[1, 1].Item;

            CheckItem(arm, armor);

            AbstractInventoryItem itm = (AbstractInventoryItem)map.Grid[2, 2].Item;

            CheckItem(item, itm);
        }
Ejemplo n.º 28
0
        public override void Think()
        {
            // TODO: algorithm is not optimal because when returning from child to parent, child nodes will be listed again (not so big problem, but it something to improve)

            // timing
            double currentTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            double mspa        = 1000 / aiSpeed;

            if (!IgnoreSpeed)
            {
                if ((currentTime - lastActionTime) < mspa)
                {
                    return;
                }
            }

            Map.Map map = Position.ParentMap;

            // if the stack is empty AI may be in dead end
            // put its current position to the stack and run the DFS again
            if (blockStack.Count == 0)
            {
                blockStack.Push(new VisitedBlock(Position));
            }

            // get current node and his neighbours
            VisitedBlock currVisitedBlock = blockStack.Peek();

            currVisitedBlock.state = BlockState.OPEN;
            visitedBlocks.Add(currVisitedBlock);
            MapBlock        curr       = map.Grid[currVisitedBlock.x, currVisitedBlock.y];
            List <MapBlock> neighbours = curr.AccessibleNeighbours();

            // choose the next neighbour to go to
            // those neighbours must not be in CLOSED state and should not contain monster
            MapBlock nextBlock = null;

            foreach (MapBlock neighbour in neighbours)
            {
                // check if the neighbour wasn't already visited and is not occupied
                // visited block hash code is calculated only by its coordinates so this can be used
                VisitedBlock neighbourVb = new VisitedBlock(neighbour);
                if (!visitedBlocks.Contains(neighbourVb) && !neighbour.Occupied)
                {
                    // get the last not-visited, unoccupied neighbour
                    // add it to the stack later
                    nextBlock = neighbour;
                }
            }


            // if some neighbours were found, create move action to the last block on the stack
            if (nextBlock != null)
            {
                blockStack.Push(new VisitedBlock(nextBlock));
                Direction nextDirection = DirectionMethods.GetDirection(Position, nextBlock);
                NextAction = new Move()
                {
                    Actor = this, Direction = nextDirection
                };
            }
            else
            {
                // no possible neighbours were found
                // this opens up two possibilities
                // 1. assume current block is a dead end
                // 2. check if there are monster to fight in neighbour blocks and try to fight them
                // for now lets just pick the first one

                // mark current block as closed and pop it from the stack
                currVisitedBlock.state = BlockState.CLOSED;
                blockStack.Pop();

                // move one step back
                if (blockStack.Count > 0)
                {
                    VisitedBlock prevBlock = blockStack.Peek();
                    nextBlock  = map.Grid[prevBlock.x, prevBlock.y];
                    NextAction = new Move()
                    {
                        Actor = this, Direction = DirectionMethods.GetDirection(Position, nextBlock)
                    };
                }
            }

            lastActionTime = currentTime;
        }
Ejemplo n.º 29
0
    public static Tile[] GenerateRoom(RoomTemplate roomTemplate, bool[] doors, bool hasTreasure, bool hasPOI)
    {
        // Extract dimension data from json object
        var dimensions = roomTemplate.dimensions;
        var width      = dimensions.width;
        var height     = dimensions.height;

        var tiles = new Tile[width * height];

        // Initialize the tiles
        for (uint z = 0, i = 0; z < height; ++z)
        {
            for (uint x = 0; x < width; ++x)
            {
                tiles[i]      = new Tile(i);
                tiles[i].Type = TileType.Floor;
                ++i;
            }
        }

        // Fill Walls
        foreach (var wall in roomTemplate.walls)
        {
            tiles[wall.index].IsWall = true;
        }

        // Fill Doors
        foreach (var door in roomTemplate.doors)
        {
            Direction direction = (Direction)System.Enum.Parse(typeof(Direction), door.direction);
            if (doors[DirectionMethods.DirectionToNumber(direction)])
            {
                tiles[door.index].IsDoor        = true;
                tiles[door.index].DoorDirection = direction;
            }
            else
            {
                tiles[door.index].IsWall = true;
            }

            //tiles[door.index].IsDoor = true;
        }

        // Fill nones
        foreach (var none in roomTemplate.nones)
        {
            tiles[none.index].IsNone = true;
        }

        // Fill all enemy nests
        foreach (var nest in roomTemplate.enemyNests)
        {
            tiles[nest.index].IsEnemyNest = true;
        }

        // Fill treasures
        bool treasureAssigned = false;

        foreach (var treasure in roomTemplate.treasures)
        {
            if (hasTreasure)
            {
                if (!treasureAssigned)
                {
                    tiles[treasure.index].IsTreasure = true;
                    treasureAssigned = true;
                }
            }
        }

        // fill pois
        foreach (var poi in roomTemplate.pois)
        {
            if (hasPOI)
            {
                tiles[poi.index].IsPOI = true;
            }
            //tiles[poi.index].POIType = (POIType)assignedPOI;
        }

        // Fill lavas
        if (roomTemplate.lavas != null)
        {
            foreach (var lava in roomTemplate.lavas)
            {
                tiles[lava.index].Type = TileType.Lava;
            }
        }

        // Fill portal, if it exists
        if (roomTemplate.portal != null)
        {
            tiles[roomTemplate.portal.index].Type = TileType.Portal;
        }

        return(tiles);
    }
Ejemplo n.º 30
0
 public void CreateConnection(Direction direction)
 {
     Neighbors[DirectionMethods.DirectionToNumber(direction)] = true;
 }