Пример #1
0
        public void IfNoCorridor_ShouldSucceed_IfCorridorExists(Dir dir)
        {
            var cell = new MapCell();
            cell.Sides[dir] = Side.Empty;

            Assert.That(() => ThrowD.IfNoCorridor(cell, dir), Throws.Nothing);
        }
        public TileMap(int width, int height)
        {
            MapWidth = width;
            MapHeight = height;

            _mouseMap =
                GameGraphics.GetTexture("mousemap").SourceTexture;

            Random random = new Random();

            // set cells depths here..
            _maxdepth = (MapWidth + 1) * ((MapHeight + 1) * TileInfo.TileWidth) / 10;

            for (int y = 0; y < MapHeight; y++)
            {
                MapRow thisRow = new MapRow();
                for (int x = 0; x < MapWidth; x++)
                {
                    _depthOffset = 0.7f - ((x + (y * TileInfo.TileWidth)) / _maxdepth);

                    MapCell cell = new MapCell("grass_tile_" + random.Next(0, 4).ToString() + "_" + random.Next(0, 4).ToString()
                       , true);
                    cell.DrawDepth = _depthOffset;

                    cell.Location = new Point(x, y);

                    // determine if this cell resides on an odd row
                    if (y % 2 == 1) cell.OnOddRow = true;
                    else cell.OnOddRow = false;

                    thisRow.Columns.Add(cell);
                }
                Rows.Add(thisRow);
            }
        }
Пример #3
0
        public static QTree Set(QTree root, int x, int y, int leftX, int rightX, int leftY, int rightY, MapCell mapCell)
        {
            QTree newRoot = new QTree();
            if (leftX == rightX && leftY == rightY)
            {
                newRoot.data = mapCell;
                return newRoot;
            }
            int middleX = (leftX + rightX) / 2;
            int middleY = (leftY + rightY) / 2;
            int childId = (x > middleX ? 1 : 0);
            if (y > middleY) childId |= 2;
            newRoot.children = new QTree[4];
            for (int i = 0; i < 4; ++i)
                newRoot.children[i] = root.children[i];

            if (y <= middleY)
            {
                if (x <= middleX)
                    newRoot.children[childId] = Set(root.children[childId], x, y, leftX, middleX, leftY, middleY, mapCell);
                else
                    newRoot.children[childId] = Set(root.children[childId], x, y, middleX + 1, rightX, leftY, middleY, mapCell);
            }
            else
            {
                if (x <= middleX)
                    newRoot.children[childId] = Set(root.children[childId], x, y, leftX, middleX, middleY + 1, rightY, mapCell);
                else
                    newRoot.children[childId] = Set(root.children[childId], x, y, middleX + 1, rightX, middleY + 1, rightY, mapCell);
            }
            return newRoot;
        }
 protected void apply(MapCell[,] map, List<Door> doors)
 {
     terrain = this.gameObject.GetComponent<Terrain>();
     //Debug.Log ("Dimensiones del mapa de alturas:" + terrain.terrainData.heightmapWidth + "x" + terrain.terrainData.heightmapHeight);
     float[,] heights = terrain.terrainData.GetHeights(0, 0, terrain.terrainData.heightmapWidth, terrain.terrainData.heightmapWidth);
     applyCellMap(heights, map);
 }
Пример #5
0
        private static int CalculateRoomScore(Room room, IMap map, MapCell cell)
        {
            var currentScore = 0;

            foreach (var roomCell in room)
            {
                var currentCell = map[
                    roomCell.Location.X + cell.Location.X,
                    roomCell.Location.Y + cell.Location.Y];

                currentScore += AdjacentCorridorBonus
                    * roomCell.Sides
                        .Count(s => HasAdjacentCorridor(map, currentCell, s.Key));

                if (currentCell.IsCorridor)
                {
                    currentScore += OverlappedCorridorBonus;
                }

                currentScore += OverlappedRoomBonus
                    * map.Rooms.Count(r => r.Bounds.Contains(currentCell.Location));
            }

            return currentScore;
        }
Пример #6
0
        public string Serialize(MapCell[,] map, int water, int flooding, int waterproof,
		                        Dictionary<MapCell, MapCell> trampToTarget, int beardGrowth,
		                        int pocketRazorCount)
        {
            var builder = SerializeMapOnly(map);
            builder.AppendLine();
            builder.AppendFormat("Water {0}", water);
            builder.AppendLine();
            builder.AppendFormat("Flooding {0}", flooding);
            builder.AppendLine();
            builder.AppendFormat("Waterproof {0}", waterproof);
            foreach(var trampTargetElem in trampToTarget)
            {
                builder.AppendLine();
                builder.AppendFormat("Trampoline {0} targets {1}", (Char) trampTargetElem.Key, (Char) trampTargetElem.Value);
            }
            if(beardGrowth > 0)
            {
                builder.AppendLine();
                builder.AppendFormat("Growth {0}", beardGrowth);
            }
            if(pocketRazorCount > 0)
            {
                builder.AppendLine();
                builder.AppendFormat("Razors {0}", pocketRazorCount);
            }
            return builder.ToString();
        }
    protected void paintTerrain(MapCell[,] map, Door d)
    {
        terrain = this.gameObject.GetComponent<Terrain>();
        float[,,] splatmapData = new float[terrain.terrainData.alphamapWidth, terrain.terrainData.alphamapHeight, terrain.terrainData.alphamapLayers];

        float[] splatWallWeights = new float[terrain.terrainData.alphamapLayers];
        splatWallWeights[0] = 0f;
        splatWallWeights[1] = 1f;

        float[] splatFloorWeights = new float[terrain.terrainData.alphamapLayers];
        splatFloorWeights[0] = 1f;
        splatFloorWeights[1] = 0f;

        int indexXmap, indexYmap;
        for (int i = 0; i < splatmapData.GetLength(0); i++)
        {
            for (int j = 0; j < splatmapData.GetLength(1); j++)
            {
                indexXmap = Mathf.Clamp(i/factor, 0, map.GetLength(0) - 1);
                indexYmap = Mathf.Clamp(j/factor, 0, map.GetLength(0) - 1);
                if (map[indexXmap, indexYmap].cellKind == MapCell.CellKind.WALL || map[indexXmap, indexYmap].cellKind == MapCell.CellKind.UNUSED)
                {
                    splatmapData = setSplatWeights(i, j, splatWallWeights, splatmapData);
                }
                else
                {
                    splatmapData = setSplatWeights(i, j, splatFloorWeights, splatmapData);
                }
            }
        }
        terrain.terrainData.SetAlphamaps(0, 0, splatmapData);
        terrain.Flush();
    }
Пример #8
0
        private void BuildCorridor(IMap map, MapCell currentCell)
        {
            MapCell nextCell;
            var direction = Dir.Zero;

            bool success;
            do
            {
                _directionPicker.LastDirection = direction;
                _directionPicker.ResetDirections();
                var emptySide = currentCell.Sides
                    .Single(s => s.Value != Side.Wall)
                    .Key;
                success = false;
                do
                {
                    direction = _directionPicker.NextDirectionExcept(emptySide);
                    success = map.TryGetAdjacentCell(currentCell, direction, out nextCell);

                    if (success)
                    {
                        map.CreateCorridorSide(currentCell, nextCell, direction, Side.Empty);
                    }
                } while (_directionPicker.HasDirections && !success);

                if (!success)
                {
                    return;
                }
            } while (currentCell.IsDeadEnd);
        }
Пример #9
0
        public void IfNoCorridor_ShouldThrow_IfOutsideMap(Dir dir)
        {
            var cell = new MapCell();
            cell.Sides[dir] = Side.Wall;

            Assert.That(() => ThrowD.IfNoCorridor(cell, dir),
                Throws.InstanceOf<InvalidOperationException>());
        }
Пример #10
0
	private void CreatePassage (MapCell cell, MapCell otherCell, CellDirection direction) {
		if(cell == null) return;

		Passage passage = Instantiate(passagePrefab) as Passage;
		passage.Initialize(cell, otherCell, direction);
		passage = Instantiate(passagePrefab) as Passage;
		passage.Initialize(otherCell, cell, direction.GetOpposite());
	}
Пример #11
0
 public Miner(int x, int y, MapCell [,] map)
 {
     this.map = map;
     mapWidth = map.GetLength(0) - 2;
     mapHeight = map.GetLength(1) - 2;
     pos = new int[2];
     pos[0] = x;
     pos[1] = y;
 }
Пример #12
0
	public void Initialize (MapCell cell, MapCell otherCell, CellDirection direction) {
		this.cell = cell;
		this.otherCell = otherCell;
		this.direction = direction;
		cell.SetEdge(direction, this);
		transform.parent = cell.transform;
		transform.localPosition = Vector3.zero;
		transform.localRotation = direction.ToRotation();
	}
Пример #13
0
 public Door(int x, int y, int zoneFrom, MapCell[,] map)
 {
     this.x = x;
     this.y = y;
     this.zoneFrom = zoneFrom;
     this.map = map;
     zoneTo = 0;
     doorDirection = -1;
 }
Пример #14
0
 /// <summary>
 /// Clears the map.
 /// </summary>
 public void ClearAllCells(int width, int height)
 {
     lock (Cells)
     {
         Cells = new MapCell[width, height];
         for (var x = 0; x < Cells.GetLength(0); x++)
             for (var y = 0; y < Cells.GetLength(1); y++)
                 Cells[x, y] = new MapCell(this, new Point(x,y), DefaultFloorTile);
     }
 }
 void applyCellMap(float[,] heights , MapCell[,]map)
 {
     for (int i = 0; i < heights.GetLength(0); i++) {
         for(int j = 0; j < heights.GetLength(1); j++){
             heights[i,j] = getSuitableHeightFromMap(map,i,j, heights);
         }
     }
     heights = generateDistanceTransform(heights);
     terrain.terrainData.SetHeights (0, 0, heights);
 }
Пример #16
0
        public static void IfNoCorridor(MapCell cell, Dir direction, string name = "cell")
        {
            Throw.IfNull(cell, name);

            if (cell.Sides[direction] == Side.Wall)
            {
                throw new InvalidOperationException(
                    $"{name} has no corridor in direction '{direction}'.");
            }
        }
Пример #17
0
 protected override Tuple<MapCell[, ], Dictionary<MapCell, MapCell>> GenerateMap(MapCell[,] map)
 {
     var indexX = random.Next(2, map.GetLength(0) - 3);
     var indexY = random.Next(2, map.GetLength(1) - 3);
     for(int i = 0; i < map.GetLength(0); i++)
         map[i, indexY] = MapCell.Wall;
     for(int j = 0; j < map.GetLength(1); j++)
         map[indexX, j] = MapCell.Wall;
     return base.GenerateMap(map);
 }
Пример #18
0
        public void IEquatableMembers_WorksCorrect_IfIsVisitedDiffers()
        {
            _cell.IsVisited = true;
            var other = new MapCell
            {
                IsVisited = false
            };

            CustomAssert.IEquatableMembersWorkForDifferentObjects(_cell, other);
        }
Пример #19
0
        public void IfNoCorridor_ExceptionShouldContainMapBoundsPropertyNameAndValue(
            Dir dir, string name)
        {
            var cell = new MapCell();
            cell.Sides[dir] = Side.Wall;

            Assert.That(() => ThrowD.IfNoCorridor(cell, dir, name),
                Throws.InvalidOperationException
                .With.Message.Contains(dir.ToString())
                .And.Message.Contains(name));
        }
Пример #20
0
 private static char GetCellChar(MapCell mapCell)
 {
     try
     {
         return (char) mapCell;
     }
     catch(Exception)
     {
         throw new ArgumentOutOfRangeException("mapCell");
     }
 }
Пример #21
0
        // it follows a "copy" of Game.Grass.Update and depencies

        private static bool CanGrow_CheckBorderingCell(MapCell cell)
        {
            return (cell != null) 
                && !cell.HasNaturalWall() 
                && !cell.HasEmbeddedFloor() 
                && cell.HasFloor()
                && cell.Floor == 2 //according to savegame-extractor
                && !(cell.HasEmbeddedWall() 
                    && !(cell.EmbeddedWall is Tree) 
                    && !(cell.EmbeddedWall is Crop)
                );
        }
Пример #22
0
        public void IfNotAdjacent_ExceptionShouldContainCellsAndDirection()
        {
            var startCell = new MapCell();
            var endCell = new MapCell { Location = new Point(1, 1) };

            Assert.That(
                () => ThrowD.IfNotAdjacent(startCell, endCell, Dir.W),
                Throws.InvalidOperationException
                .With.Message.Contains(startCell.Location.ToString())
                .With.Message.Contains(endCell.Location.ToString())
                .And.Message.Contains(Dir.W.ToString()));
        }
Пример #23
0
        public static void IfNotAdjacent(MapCell startCell, MapCell endCell, Dir direction)
        {
            Throw.IfNull(startCell, nameof(startCell));
            Throw.IfNull(endCell, nameof(endCell));

            var endPoint = DirHelper.MoveInDir(startCell.Location, direction);
            if (endPoint != endCell.Location)
            {
                throw new InvalidOperationException(
                    $"{startCell.Location} and {endCell.Location} are not adjacent in direction '{direction}'.");
            }
        }
Пример #24
0
        //  Remember to update Clone() before adding any more instance variables!

        /// <summary>
        /// Constructor.
        /// </summary>
        public MapDefinition(ZTile defaultFloorTile, Isometry iso, string baseContentDir)
        {
            _baseContentDir = baseContentDir;
            Iso = iso;
            DefaultFloorTile = defaultFloorTile;

            TileHeight = 37;
            TileWidth = 73;
            
            UndoInfo = new HashSet<Point>();
            Cells = new MapCell[0, 0];
            ClearAllCells(26, 45);
        }
Пример #25
0
 public void Configure(int x, int y, MapCell[,] map, DungeonGeneratorIA dungeon)
 {
     id = idSeed;
     idSeed++;
     this.map = map;
     mapWidth = map.GetLength(0) - 2;
     mapHeight = map.GetLength(1) - 2;
     pos = new int[2];
     pos[0] = x;
     pos[1] = y;
     this.dungeon = dungeon;
     probabilities = new float[4] { 8.0f, 3.0f, 3.0f, 1.0f };
 }
Пример #26
0
 public StringBuilder SerializeMapOnly(MapCell[,] map)
 {
     var builder = new StringBuilder();
     int xUpperBound = map.GetLength(0);
     int yUpperBound = map.GetLength(1);
     for(int y = yUpperBound - 1; y >= 0; y--)
     {
         for(int x = 0; x < xUpperBound; x++)
             builder.Append(GetCellChar(map[x, y]));
         builder.AppendLine();
     }
     return builder;
 }
Пример #27
0
 protected override Tuple<MapCell[, ], Dictionary<MapCell, MapCell>> GenerateMap(MapCell[,] map)
 {
     PutLift(map);
     PutWalls(map);
     PutElements(map, Enumerable.Repeat(MapCell.Rock, options.RockCount));
     PutElements(map, Enumerable.Repeat(MapCell.Earth, options.EarthCount));
     PutElements(map, Enumerable.Repeat(MapCell.Lambda, options.LambdaCount));
     PutElements(map, Enumerable.Repeat(MapCell.Beard, options.BeardCount));
     PutElements(map, Enumerable.Repeat(MapCell.Razor, options.MapRazorCount));
     PutElements(map, Enumerable.Repeat(MapCell.LambdaRock, options.HighRockCount));
     var trampToTarget = PutTrampolines(map);
     PutElements(map, new[] {MapCell.Robot});
     return Tuple.Create(map, trampToTarget);
 }
Пример #28
0
        private bool TryPickRandomUnvisitedAdjacentCell(
            IMap map, MapCell currentCell, out MapCell nextCell, out Dir direction)
        {
            var success = false;
            do
            {
                direction = _directionPicker.NextDirection();
                success = map.TryGetAdjacentCell(currentCell, direction, out nextCell)
                    && !nextCell.IsVisited;
            }
            while (_directionPicker.HasDirections && !success);

            return success;
        }
    private void CreateCollectables(MapCell[,] map, int zoneIDmark)
    {
        items = 0;

        for (int i = 0; i < map.GetLength(0); i++)
        {
            for (int j = 0; j < map.GetLength(1); j++)
            {
                if (map[i, j].zoneID > zoneIDmark)
                {
                    Instantiate(collectablePrefab, new Vector3(j * factor + factor / 2, 1f, i * factor + factor / 2), Quaternion.identity);
                    items++;
                }
            }
        }
    }
Пример #30
0
    void createDoors(MapCell[,] map, List<Door> doors)
    {
        terrain = GameObject.FindObjectOfType<Terrain> ();
        for (int i = 0; i<doors.Count; i++)
        {
            doors[i].x_t *= terrain.terrainData.heightmapWidth;
            doors[i].y_t *= terrain.terrainData.heightmapHeight;

            if (doors[i].doorDirection == 1)
                GameObject.Instantiate(doorPrefab, new Vector3(doors[i].y_t, 5f, doors[i].x_t),
                Quaternion.FromToRotation(Vector3.forward, Vector3.right));
            else
                GameObject.Instantiate(doorPrefab, new Vector3(doors[i].y_t, 5f, doors[i].x_t),
                Quaternion.identity);

        }
    }
Пример #31
0
        private void CalculateBounds()
        {
            int weight = GameConstants.MinVoxelActorWeight;
            int size   = m_map.GetMapSizeWith(weight);

            Debug.Assert(size >= m_minMapBoundsSize, "map size < m_minMapBoundsSize");

            MapPos min = new MapPos(0, 0);
            MapPos max = new MapPos(size - 1, size - 1);

            MapCell col0 = m_map.Get(0, 0, weight);

            for (int row = 0; row < size; ++row)
            {
                MapCell cell     = col0;
                bool    nonEmpty = false;
                for (int col = 0; col < size; ++col)
                {
                    nonEmpty = IsNonEmpty(cell);
                    if (nonEmpty)
                    {
                        break;
                    }
                    cell = cell.SiblingPCol;
                }

                if (nonEmpty)
                {
                    min.Row = row;
                    break;
                }
                else
                {
                    min.Row = row;
                }

                col0 = col0.SiblingPRow;
            }

            col0 = m_map.Get(size - 1, 0, weight);
            for (int row = size - 1; row >= 0; --row)
            {
                MapCell cell     = col0;
                bool    nonEmpty = false;
                for (int col = 0; col < size; ++col)
                {
                    nonEmpty = IsNonEmpty(cell);
                    if (nonEmpty)
                    {
                        break;
                    }
                    cell = cell.SiblingPCol;
                }

                if (nonEmpty)
                {
                    max.Row = row;
                    break;
                }
                else
                {
                    max.Row = row;
                }

                col0 = col0.SiblingMRow;
            }

            MapCell row0 = m_map.Get(0, 0, weight);

            for (int col = 0; col < size; ++col)
            {
                MapCell cell     = row0;
                bool    nonEmpty = false;
                for (int row = 0; row < size; ++row)
                {
                    nonEmpty = IsNonEmpty(cell);
                    if (nonEmpty)
                    {
                        break;
                    }
                    cell = cell.SiblingPRow;
                }

                if (nonEmpty)
                {
                    min.Col = col;
                    break;
                }
                else
                {
                    min.Col = col;
                }

                row0 = row0.SiblingPCol;
            }

            row0 = m_map.Get(0, size - 1, weight);
            for (int col = size - 1; col >= 0; --col)
            {
                MapCell cell     = row0;
                bool    nonEmpty = false;
                for (int row = 0; row < size; ++row)
                {
                    nonEmpty = IsNonEmpty(cell);
                    if (nonEmpty)
                    {
                        break;
                    }
                    cell = cell.SiblingPRow;
                }

                if (nonEmpty)
                {
                    max.Col = col;
                    break;
                }
                else
                {
                    max.Col = col;
                }

                row0 = row0.SiblingMCol;
            }

            if (min.Col > max.Col)
            {
                min.Col = max.Col;
            }

            if (min.Row > max.Row)
            {
                min.Row = max.Row;
            }

            int centerCol = min.Col + (max.Col - min.Col) / 2;
            int centerRow = min.Row + (max.Row - min.Row) / 2;

            int minCol = Mathf.Max(0, centerCol - m_minMapBoundsSize / 2);
            int minRow = Mathf.Max(0, centerRow - m_minMapBoundsSize / 2);

            int maxCol = minCol + m_minMapBoundsSize;
            int maxRow = minRow + m_minMapBoundsSize;

            if (maxCol >= size)
            {
                maxCol = size - 1;
                minCol = maxCol - m_minMapBoundsSize;
            }

            if (maxRow >= size)
            {
                maxRow = size - 1;
                minRow = maxRow - m_minMapBoundsSize;
            }

            if (minCol < min.Col)
            {
                min.Col = minCol;
            }
            if (minRow < min.Row)
            {
                min.Row = minRow;
            }
            if (maxCol > max.Col)
            {
                max.Col = maxCol;
            }
            if (maxRow > max.Row)
            {
                max.Row = maxRow;
            }


            m_mapBounds = new MapRect(min, max);
        }
Пример #32
0
        private void draw()
        {
            if (canvas != null)
            {
                canvas.Dispose();
                canvas = null;
            }

            int x, y, w, h, gx, gy, i;
            Graphics gfx = null;

            Font font = new Font(SystemFonts.DefaultFont.FontFamily, 9, FontStyle.Regular);

            if (currentBitmap != null)
            {
                x = 0;
                y = 0;
                w = currentBitmap.Width * currentZoom;
                h = currentBitmap.Height * currentZoom;

                canvas = new Bitmap(w, h);
                gfx = Graphics.FromImage(canvas);
                gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                gfx.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                gfx.DrawImage(currentBitmap,
                    new Rectangle(x, y, w, h),
                    new Rectangle(0, 0, currentBitmap.Width, currentBitmap.Height),
                    GraphicsUnit.Pixel);
            }
            else if (currentMap != null)
            {
                int cellSize = 8 * currentZoom;

                w = currentMap.Width * cellSize;
                h = currentMap.Height * cellSize;

                canvas = new Bitmap(w, h);
                gfx = Graphics.FromImage(canvas);
                gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                gfx.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                // map tiles
                for (y = 0; y < currentMap.Height; y++)
                {
                    for (x = 0; x < currentMap.Width; x++)
                    {
                        i = x + y * currentMap.Width;
                        MapCell cell = currentMap.Cells[i];
                        MapTile tile = currentMap.Tiles[cell.TileID];

                        gx = x * cellSize;
                        gy = y * cellSize;

                        gfx.DrawImage(tile.Bitmap, new Rectangle(gx, gy, cellSize, cellSize), new Rectangle(0, 0, 8, 8), GraphicsUnit.Pixel);

                        if (cell.EntityID > 0)
                        {
                            Color col = Game.EntitySpriteName(cell.EntityID, x % 2 == 0).Length == 0 ? Color.Red : Color.FromArgb(150, 0, 255, 0);
                            gfx.FillRectangle(new SolidBrush(col), new Rectangle(gx, gy, cellSize, cellSize));
                        }

                        if (cell.ShootableID > 0)
                        {
                            //gfx.DrawImage(currentMap.Tiles[cell.SolidEntityID].Bitmap, new Rectangle(gx, gy, cellSize, cellSize), new Rectangle(0, 0, 8, 8), GraphicsUnit.Pixel);
                            Color col = Game.ShootableSpriteName(cell.ShootableID, x % 2 == 0).Length == 0 ? Color.Red : Color.FromArgb(150, 255, 105, 180);
                            gfx.FillPie(new SolidBrush(col), new Rectangle(gx, gy, cellSize, cellSize), 0, 360);
                        }
                    }
                } 
                
                // texts on top
                for (y = 0; y < currentMap.Height; y++)
                {
                    for (x = 0; x < currentMap.Width; x++)
                    {
                        i = x + y * currentMap.Width;
                        MapCell cell = currentMap.Cells[i];
                        MapTile tile = currentMap.Tiles[cell.TileID];

                        gx = x * cellSize;
                        gy = y * cellSize;

                        if (cell.EntityID > 0)
                        {
                            string info = Game.EntitySpriteName(cell.EntityID, x % 2 == 0);
                            if (info.Length == 0) info = cell.EntityID.ToString();
                            gfx.DrawString("entity: " + info, font, Brushes.White, gx, gy);
                        }

                        if (cell.ShootableID > 0)
                        {
                            string info = Game.ShootableSpriteName(cell.ShootableID, gx % 2 == 0);
                            if (info.Length == 0) info = cell.ShootableID.ToString();
                            gfx.DrawString("shootable: " + info, font, Brushes.White, gx, gy);
                        }
                    }
                }

                // positions
                for (i = 0; i < currentMap.Triggers.Length; i++)
                {
                    int pos = currentMap.Triggers[i];
                    if (pos == 0) continue;

                    string caption = Game.TriggerEntryTypeByNumber(i, pos);
                    if (i >= 30) 
                    {
                        if (i % 2 == 1) continue; // don't draw message entries containing text id instead of position (see Map.PositionEntryTypeByNumber)
                        caption = Game.TriggerEntryTypeByNumber(i + 1, currentMap.Triggers[i + 1]);
                    }

                    gx = cellSize * (pos % currentMap.Width);
                    gy = cellSize * (pos / currentMap.Width);
                    gfx.FillPie(new SolidBrush(Color.FromArgb(160, 255, 255, 0)), new Rectangle(gx, gy, cellSize, cellSize), 0, 360);
                    
                    var size = gfx.MeasureString(caption, font);
                    x = (int)Math.Min(currentMap.Width * cellSize - size.Width, Math.Max(0, gx + cellSize / 2 - size.Width / 2));
                    gfx.DrawString(caption, font, Brushes.Black, x + 1, gy + 2 + 1);
                    gfx.DrawString(caption, font, Brushes.White, x    , gy + 2    );

                    // connect teleports with a line
                    if (i >= 10 && i < 30 && i % 2 == 1)
                    {
                        int prevPos = currentMap.Triggers[i - 1];
                        int halfSize = cellSize / 2;
                        gfx.DrawLine(Pens.Yellow, cellSize * (prevPos % currentMap.Width) + halfSize, cellSize * (prevPos / currentMap.Width) + halfSize, gx + halfSize, gy + halfSize);
                    }
                }

                // draw grid on top
                Pen gridPen = new Pen(Color.FromArgb(50, 0, 0, 0));

                for (x = 0; x <= currentMap.Width; x++)
                {
                    gx = x * cellSize;
                    gfx.DrawLine(gridPen, gx, 0, gx, h);
                }

                for (y = 0; y <= currentMap.Height; y++)
                {
                    gy = y * cellSize;
                    gfx.DrawLine(gridPen, 0, gy, w, gy);
                }
            }

            canvasBox.Image = canvas;
            if (gfx != null) gfx.Dispose();
            font.Dispose();
        }
Пример #33
0
        public void DrawMap()
        {
            try
            {
                using (StreamReader sr = new StreamReader("../../../map.txt"))
                {
                    for (int row = 0; row < 20; row++)
                    {
                        String line = sr.ReadLine();
                        for (int col = 0; col < 20; col++)
                        {
                            MapCell cell = new MapCell(row, col, Resources.earth);
                            //butt.BackgroundImageLayout = ImageLayout.Stretch;
                            string name = "not recognized";
                            switch (line[col])
                            {
                            case 'W':
                                cell.Image = Resources.tree;
                                name       = "tree";
                                break;

                            case 'S':
                                cell.Image = Resources.stone;
                                name       = "stone";
                                break;

                            case 'C':
                                cell.Image = Resources.castle;
                                name       = "castle";
                                break;

                            case 'H':
                                cell.Image = Resources.player;
                                name       = "player";
                                break;

                            case 'X':
                                cell.Image = Resources.enemy;
                                name       = "enemy";
                                break;

                            case 'E':
                                cell.Image = Resources.earth;
                                name       = "earth";
                                break;

                            case 'T':
                                cell.Image = Resources.chest;
                                name       = "chest"; //tresure
                                break;
                            }

                            this.Controls.Add(generateButton(cell, name));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                this.textBoxType.Text = "The file could not be read:";
                this.gameLog.Text     = e.Message;
            }
        }
Пример #34
0
        public string ToFullString()
        {
            string result = "";

            var   MAPCELL_TERRAIN_SHIFT = 0;
            ulong MAPCELL_TERRAIN_MASK  = 0xF;

            var   MAPCELL_OVERLAY_SHIFT = 4;
            ulong MAPCELL_OVERLAY_MASK  = 0x00000030;

            var   MAPCELL_MOVER_SHIFT = 6;
            ulong MAPCELL_MOVER_MASK  = 0x00000040;

            var   MAPCELL_HEIGHT_SHIFT = 18;
            ulong MAPCELL_HEIGHT_MASK  = 0x003C0000;

            var   MAPCELL_PASSABLE_SHIFT = 10;
            ulong MAPCELL_PASSABLE_MASK  = 0x00004000;

            var   MAPCELL_FOREST_SHIFT = 28;
            ulong MAPCELL_FOREST_MASK  = 0x10000000;

            var   MAPCELL_WALL_SHIFT = 24;
            ulong MAPCELL_WALL_MASK  = 0x01000000;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    var arr = this.auxlst[(x * width) + y];

                    var a = BitConverter.ToUInt32(arr, 0);
                    //var b = BitConverter.ToUInt32(arr, 4);

                    // var a = BitConverter.ToUInt64(arr, 0);

                    if ((a & MAPCELL_TERRAIN_MASK).ToString() != "0")
                    {
                        var ab = 2;
                    }

                    MapCell z = (MapCell)a;

                    if ((z & MapCell.MAPCELL_TERRAIN_MASK).ToString() == (a & MAPCELL_TERRAIN_MASK).ToString())
                    {
                        var st = 0;
                    }

                    //  result += ((a & MAPCELL_TERRAIN_MASK) >> MAPCELL_TERRAIN_SHIFT).ToString("D2") + "|";


                    result += ((a & 0x1F0000) >> MAPCELL_WALL_SHIFT).ToString("D2") + "|";

                    // result += ((a & MAPCELL_WALL_MASK) >> MAPCELL_WALL_SHIFT).ToString("D2") + "|";
                    // result += ((a & MAPCELL_HEIGHT_MASK) >> MAPCELL_HEIGHT_SHIFT).ToString("D2") + "|";
                    //
                    // result += ((a & MAPCELL_OVERLAY_MASK) >> MAPCELL_OVERLAY_SHIFT).ToString("D2") + "|";
                    //   result += ((a & MAPCELL_MOVER_MASK) >> MAPCELL_MOVER_SHIFT).ToString("D2") + "|";

                    // result += ((a & MAPCELL_FOREST_MASK)).ToString("D2") + "|";
                    //  result += ((a & MAPCELL_PASSABLE_MASK)).ToString("D2") + "|";
                    // result += a + "-" + b + "|";
                    // result += a+"-"+b+"|";
                }

                result += "\r\n";
            }

            return(result);
        }
Пример #35
0
 private void DefaultInitializer(ref MapCell cell)
 {
     cell.TerrainCost = 100;
     cell.Walkability = (byte)Directions.All;
 }
        private void Update()
        {
            if (m_gameState.IsActionsMenuOpened(LocalPlayerIndex))
            {
                return;
            }

            if (m_gameState.IsMenuOpened(LocalPlayerIndex))
            {
                return;
            }

            if (m_gameState.IsContextActionInProgress(LocalPlayerIndex))
            {
                return;
            }

            if (m_gameState.IsPaused || m_gameState.IsPauseStateChanging)
            {
                return;
            }

            int playerIndex = PlayerIndex;

            if (m_mapCursor != m_cameraController.MapCursor)
            {
                m_mapCursor = m_cameraController.MapCursor;


                VoxelData newSelectedTarget = null;
                VoxelData target            = null;
                int       width             = m_map.Map.GetMapSizeWith(GameConstants.MinVoxelActorWeight);
                if (m_mapCursor.Row >= 0 && m_mapCursor.Col >= 0 && m_mapCursor.Row < width && m_mapCursor.Col < width)
                {
                    MapCell cell = m_map.Map.Get(m_mapCursor.Row, m_mapCursor.Col, m_cameraController.Weight);

                    for (int i = 0; i < m_selectedUnitDescriptors.Length; ++i)
                    {
                        SelectionDescriptor descriptor = m_selectedUnitDescriptors[i];
                        bool lowestPossible            = true;
                        cell.GetDefaultTargetFor(descriptor.Type, descriptor.Weight, playerIndex, lowestPossible, out target, playerIndex);
                        if (target != null)
                        {
                            break;
                        }
                    }
                }

                if (target != null && target.VoxelRef != null && target.UnitOrAssetIndex != -1)
                {
                    //Player could not destroy own units (and should not be able to select them as target)
                    if (!VoxelData.IsControllableUnit(target.Type) || target.Owner != playerIndex)
                    {
                        newSelectedTarget = target;
                    }
                }

                if (m_previouslySelected != newSelectedTarget)
                {
                    if (newSelectedTarget == null)
                    {
                        ClearSelection();
                        m_selectedTarget     = null;
                        m_previouslySelected = null;
                    }
                    else
                    {
                        m_previouslySelected = newSelectedTarget;
                        TryEnableTargetAutoSelectionMode();
                        if (m_isTargetAutoSelectionMode)
                        {
                            m_selectedTarget = newSelectedTarget;
                            TargetSelectionSelect(playerIndex, target.Owner, m_selectedTarget.UnitOrAssetIndex);
                        }
                    }
                }
            }
            else
            {
                if (m_selectedTarget != null)
                {
                    IVoxelDataController dc = m_gameState.GetVoxelDataController(m_selectedTarget.Owner, m_selectedTarget.UnitOrAssetIndex);
                    if (dc != null && dc.IsAlive)
                    {
                        Coordinate cursorCoord = new Coordinate(m_cameraController.MapCursor, GameConstants.MinVoxelActorWeight, 0).ToWeight(dc.ControlledData.Weight);
                        if (cursorCoord.MapPos != dc.Coordinate.MapPos)
                        {
                            Coordinate coord = dc.Coordinate.ToWeight(GameConstants.MinVoxelActorWeight);
                            m_cameraController.MapPivot = coord.MapPos;
                            m_cameraController.SetVirtualMousePosition(coord, true, false);
                            m_mapCursor = m_cameraController.MapCursor;
                        }
                    }
                }
            }

            if (m_inputManager.GetButtonDown(InputAction.X, LocalPlayerIndex))
            {
                bool hasSelected = m_targetSelection.HasSelected(playerIndex);

                Select(playerIndex);

                if (!hasSelected)
                {
                    m_isTargetAutoSelectionMode = true;
                }
            }
            else if (m_inputManager.GetButtonUp(InputAction.RB, LocalPlayerIndex))
            {
                m_isTargetAutoSelectionMode = false;

                ClearSelection();
            }
        }
Пример #37
0
 public void CalculateG(MapCell neighbor)
 {
     G = neighbor.G + CalculateNeighborDist(neighbor);
 }
Пример #38
0
    public void CalculateH(MapCell end)
    {
        int dis = Mathf.Abs(end.Row - Row) + Mathf.Abs(end.Column - Column);

        H = dis * 10;
    }
Пример #39
0
 public void SetParent(MapCell mc)
 {
     m_parent = mc;
 }
Пример #40
0
 public void DeleteAllMarkers(MapCell cell)
 {
     DeleteAllMarkers(cell.X, cell.Y);
 }
Пример #41
0
        private void ExecuteHandler(ClientSession session)
        {
            try
            {
                Character character =
                    new Character(DAOFactory.CharacterDAO.LoadBySlot(session.Account.AccountId, Slot));
                if (session.Account != null && !session.HasSelectedCharacter)
                {
                    character.Initialize();

#if !DEBUG
                    if (session.Account.Authority > Domain.AuthorityType.Moderator)
                    {
                        character.Invisible = true;
                        character.InvisibleGm = true;
                    }
#endif

                    character.GeneralLogs = new ThreadSafeGenericList<GeneralLogDTO>();
                    character.GeneralLogs.AddRange(DAOFactory.GeneralLogDAO.LoadByAccount(session.Account.AccountId)
                        .Where(s => s.CharacterId == character.CharacterId).ToList());
                    character.MapInstanceId = ServerManager.GetBaseMapInstanceIdByMapId(character.MapId);
                    character.PositionX = character.MapX;
                    character.PositionY = character.MapY;
                    character.Authority = session.Account.Authority;
                    session.SetCharacter(character);
                    if (!session.Character.GeneralLogs.Any(s =>
                        s.Timestamp == DateTime.UtcNow && s.LogData == "World" && s.LogType == "Connection"))
                    {
                        session.Character.SpAdditionPoint += session.Character.SpPoint;
                        session.Character.SpPoint = 10000;
                    }

                    if (session.Character.Hp > session.Character.HPLoad())
                    {
                        session.Character.Hp = (int)session.Character.HPLoad();
                    }

                    if (session.Character.Mp > session.Character.MPLoad())
                    {
                        session.Character.Mp = (int)session.Character.MPLoad();
                    }

                    session.Character.Respawns =
                        DAOFactory.RespawnDAO.LoadByCharacter(session.Character.CharacterId).ToList();
                    session.Character.StaticBonusList = DAOFactory.StaticBonusDAO
                        .LoadByCharacterId(session.Character.CharacterId).ToList();
                    session.Character.LoadInventory();
                    session.Character.LoadQuicklists();
                    session.Character.GenerateMiniland();
                    Map miniland = ServerManager.GetMapInstanceByMapId(20001).Map;
                    DAOFactory.MateDAO.LoadByCharacterId(session.Character.CharacterId).ToList().ForEach(s =>
                    {
                        Mate mate = new Mate(s)
                        {
                            Owner = session.Character
                        };
                        mate.GenerateMateTransportId();
                        mate.Monster = ServerManager.GetNpcMonster(s.NpcMonsterVNum);
                        mate.IsAlive = true;
                        if (!mate.IsTeamMember && miniland.IsBlockedZone(mate.MapX, mate.MapY))
                        {
                            MapCell cell = miniland.GetRandomPosition();
                            mate.MapX = cell.X;
                            mate.MapY = cell.Y;
                        }

                        if (mate.MateType == MateType.Pet && mate.MateSlot == -1)
                        {
                            mate.MateSlot = session.Character.GetNextMateSlot(mate.MateType);
                            mate.PartnerSlot = 0;
                        }
                        else if (mate.MateType == MateType.Partner && mate.PartnerSlot == -1)
                        {
                            mate.PartnerSlot = session.Character.GetNextMateSlot(mate.MateType);
                            mate.MateSlot = 0;
                        }

                        session.Character.Mates.Add(mate);
                        mate.StartLife();
                    });
                    session.Character.CharacterLifeDisposable = Observable.Interval(TimeSpan.FromMilliseconds(300))
                        .Subscribe(x => session.Character.CharacterLife());
                    session.Character.GeneralLogs.Add(new GeneralLogDTO
                    {
                        AccountId = session.Account.AccountId,
                        CharacterId = session.Character.CharacterId,
                        IpAddress = session.IpAddress,
                        LogData = "World",
                        LogType = "Connection",
                        Timestamp = DateTime.UtcNow
                    });
                    session.SendPacket("OK");

                    // Inform everyone about connected character
                    CommunicationServiceClient.Instance.ConnectCharacter(ServerManager.Instance.WorldId,
                        character.CharacterId);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Select character failed.", ex);
            }
        }
Пример #42
0
        public override void DrawTile(MapCell cell, int cell_x, int cell_y, double draw_x, double draw_y)
        {
            if (cell.Kind == MapCell.Kind_e.WALL || cell.IsCookie())
            {
                // cell.敵接近_Rate 更新
                {
                    double rate = GetEnemyNearlyRate(
                        DDGround.Camera.X + draw_x,
                        DDGround.Camera.Y + draw_y
                        );

                    DDUtils.Maxim(ref cell.敵接近_Rate, rate);

                    cell.敵接近_Rate *= 0.97;
                }

                double p = cell.ColorPhase;

                if (this.市松tic)
                {
                    if ((cell_x + cell_y) % 2 == 0)
                    {
                        p = p * 0.7;
                    }
                    else
                    {
                        p = p * 0.3 + 0.7;
                    }
                }

                //DDDraw.SetAlpha(0.9 - cell.敵接近_Rate * 0.6); // old
                DDDraw.SetAlpha(this.WallAlpha * (1.0 - cell.敵接近_Rate * 0.5));
                DDDraw.SetBright(new I3Color(
                                     SCommon.ToInt(DDUtils.AToBRate(this.Color_A.R, this.Color_B.R, p)),
                                     SCommon.ToInt(DDUtils.AToBRate(this.Color_A.G, this.Color_B.G, p)),
                                     SCommon.ToInt(DDUtils.AToBRate(this.Color_A.B, this.Color_B.B, p))
                                     ));
                DDDraw.DrawBegin(Ground.I.Picture.WhiteBox, draw_x, draw_y);
                DDDraw.DrawSetSize(GameConsts.TILE_W, GameConsts.TILE_H);
                DDDraw.DrawEnd();
                DDDraw.Reset();

                if (cell.IsCookie())
                {
                    DDDraw.SetBright(this.CookieAxisColor);
                    DDDraw.DrawBegin(Ground.I.Picture.WhiteBox, draw_x, draw_y);
                    DDDraw.DrawSetSize(GameConsts.TILE_W / 2, GameConsts.TILE_H / 2);
                    DDDraw.DrawEnd();
                    DDDraw.Reset();
                }
            }
            else if (cell.Kind == MapCell.Kind_e.GOAL)
            {
                //double bright =
                //    Math.Sin(DDEngine.ProcFrame / 37.0) * 0.3 +
                //    Math.Sin(DDEngine.ProcFrame / 0.7) * 0.1 +
                //    0.6;
                double bright = Math.Sin(DDEngine.ProcFrame / 13.0) * 0.4 + 0.6;

                DDDraw.SetBright(
                    bright * 0.5,
                    bright * 0.9,
                    bright * 1.0
                    );
                DDDraw.DrawBegin(Ground.I.Picture.WhiteBox, draw_x, draw_y);
                DDDraw.DrawSetSize(GameConsts.TILE_W, GameConsts.TILE_H);
                DDDraw.DrawEnd();
                DDDraw.Reset();
            }
        }
Пример #43
0
 public MapBoundaries(MapCell minPoint, MapCell maxPoint)
 {
     Min = minPoint;
     Max = maxPoint;
 }
Пример #44
0
 /// <summary>
 /// Creates an orientation effect such that the specified element would
 /// face towards the specified cell
 /// </summary>
 /// <param name="actor"></param>
 /// <param name="cell"></param>
 public ActorOrientationEffect(Element actor, MapCell cell)
 {
     OrientTo = actor?.GetData <MapData>()?.Position.AngleTo(cell.Position) ?? 0;
 }
Пример #45
0
        public static void DrawTiles()
        {
            int cam_l = DDGround.ICamera.X;
            int cam_t = DDGround.ICamera.Y;
            int cam_r = cam_l + DDConsts.Screen_W;
            int cam_b = cam_t + DDConsts.Screen_H;

            I2Point lt = GameCommon.ToTablePoint(cam_l, cam_t);
            I2Point rb = GameCommon.ToTablePoint(cam_r, cam_b);

            for (int x = lt.X; x <= rb.X; x++)
            {
                for (int y = lt.Y; y <= rb.Y; y++)
                {
                    MapCell cell  = Game.I.Map.GetCell(x, y);
                    I3Color color = new I3Color(0, 0, 0);
                    string  name  = "";

                    switch (cell.Kind)
                    {
                    case MapCell.Kind_e.EMPTY:
                        goto endDraw;

                    case MapCell.Kind_e.START:
                        color = new I3Color(0, 255, 0);
                        break;

                    case MapCell.Kind_e.GOAL:
                        color = new I3Color(0, 255, 255);
                        break;

                    case MapCell.Kind_e.WALL:
                        color = new I3Color(255, 255, 0);
                        break;

                    case MapCell.Kind_e.WALL_ENEMY_THROUGH:
                        color = new I3Color(255, 255, 0);
                        name  = "E通";
                        break;

                    case MapCell.Kind_e.DEATH:
                        color = new I3Color(255, 0, 0);
                        break;

                    default:
                        color = new I3Color(128, 128, 255);
                        name  = MapCell.Kine_e_Names[(int)cell.Kind];

                        if (name.Contains(':'))
                        {
                            name = name.Substring(0, name.IndexOf(':'));
                        }

                        if (name.Contains('/'))
                        {
                            name = name.Substring(name.IndexOf('/') + 1);
                        }

                        break;
                    }

                    {
                        int tileL = x * GameConsts.TILE_W;
                        int tileT = y * GameConsts.TILE_H;

                        DDDraw.SetBright(color);
                        DDDraw.DrawRect(
                            Ground.I.Picture.WhiteBox,
                            tileL - cam_l,
                            tileT - cam_t,
                            GameConsts.TILE_W,
                            GameConsts.TILE_H
                            );
                        DDDraw.Reset();

                        DDDraw.SetAlpha(0.1);
                        DDDraw.SetBright(new I3Color(0, 0, 0));
                        DDDraw.DrawRect(
                            Ground.I.Picture.WhiteBox,
                            tileL - cam_l,
                            tileT - cam_t,
                            GameConsts.TILE_W,
                            GameConsts.TILE_H / 2
                            );
                        DDDraw.Reset();

                        DDDraw.SetAlpha(0.2);
                        DDDraw.SetBright(new I3Color(0, 0, 0));
                        DDDraw.DrawRect(
                            Ground.I.Picture.WhiteBox,
                            tileL - cam_l,
                            tileT - cam_t,
                            GameConsts.TILE_W / 2,
                            GameConsts.TILE_H
                            );
                        DDDraw.Reset();

                        DDGround.EL.Add(() =>
                        {
                            DDPrint.SetBorder(new I3Color(0, 64, 64));
                            DDPrint.SetPrint(tileL - cam_l, tileT - cam_t);
                            DDPrint.DebugPrint(name);
                            DDPrint.Reset();

                            return(false);
                        });
                    }

endDraw:
                    ;
                }
            }
        }
Пример #46
0
        public void RunEvent(EventContainer evt, ClientSession session = null, MapMonster monster = null)
        {
            if (evt != null)
            {
                if (session != null)
                {
                    evt.MapInstance = session.CurrentMapInstance;
                    switch (evt.EventActionType)
                    {
                        #region EventForUser

                    case EventActionType.NPCDIALOG:
                        session.SendPacket(session.Character.GenerateNpcDialog((int)evt.Parameter));
                        break;

                    case EventActionType.SENDPACKET:
                        session.SendPacket((string)evt.Parameter);
                        break;

                        #endregion
                    }
                }
                if (evt.MapInstance != null)
                {
                    try
                    {
                        switch (evt.EventActionType)
                        {
                            #region EventForUser

                        case EventActionType.NPCDIALOG:
                        case EventActionType.SENDPACKET:
                            if (session == null)
                            {
                                evt.MapInstance.Sessions.ToList().ForEach(e => RunEvent(evt, e));
                            }
                            break;

                            #endregion

                            #region MapInstanceEvent

                        case EventActionType.REGISTEREVENT:
                            Tuple <string, List <EventContainer> > even = (Tuple <string, List <EventContainer> >)evt.Parameter;
                            switch (even.Item1)
                            {
                            case "OnCharacterDiscoveringMap":
                                even.Item2.ForEach(s => evt.MapInstance.OnCharacterDiscoveringMapEvents.Add(new Tuple <EventContainer, List <long> >(s, new List <long>())));
                                break;

                            case "OnMoveOnMap":
                                evt.MapInstance.OnMoveOnMapEvents.AddRange(even.Item2);
                                break;

                            case "OnMapClean":
                                evt.MapInstance.OnMapClean.AddRange(even.Item2);
                                break;

                            case "OnLockerOpen":
                                evt.MapInstance.UnlockEvents.AddRange(even.Item2);
                                break;
                            }
                            break;

                        case EventActionType.REGISTERWAVE:
                            evt.MapInstance.WaveEvents.Add((EventWave)evt.Parameter);
                            break;

                        case EventActionType.SETAREAENTRY:
                            ZoneEvent even2 = (ZoneEvent)evt.Parameter;
                            evt.MapInstance.OnAreaEntryEvents.Add(even2);
                            break;

                        case EventActionType.REMOVEMONSTERLOCKER:
                            EventContainer evt2 = (EventContainer)evt.Parameter;
                            if (evt.MapInstance.InstanceBag.MonsterLocker.Current > 0)
                            {
                                evt.MapInstance.InstanceBag.MonsterLocker.Current--;
                            }
                            if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 && evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                            {
                                evt.MapInstance.UnlockEvents.ForEach(s => RunEvent(s));
                                evt.MapInstance.UnlockEvents.RemoveAll(s => s != null);
                            }
                            break;

                        case EventActionType.REMOVEBUTTONLOCKER:
                            try
                            {
                                evt2 = (EventContainer)evt.Parameter;
                                if (evt.MapInstance.InstanceBag.ButtonLocker.Current > 0)
                                {
                                    evt.MapInstance.InstanceBag.ButtonLocker.Current--;
                                }
                                if (evt.MapInstance.InstanceBag.MonsterLocker.Current == 0 && evt.MapInstance.InstanceBag.ButtonLocker.Current == 0)
                                {
                                    evt.MapInstance.UnlockEvents.ForEach(s => RunEvent(s));
                                    evt.MapInstance.UnlockEvents.RemoveAll(s => s != null);
                                }
                            }
                            catch
                            {
                            }
                            break;

                        case EventActionType.EFFECT:
                            short evt3 = (short)evt.Parameter;
                            if (monster != null)
                            {
                                monster.LastEffect = DateTime.Now;
                                evt.MapInstance.Broadcast(StaticPacketHelper.GenerateEff(UserType.Monster, monster.MapMonsterId, evt3));
                            }
                            break;

                        case EventActionType.CONTROLEMONSTERINRANGE:
                            if (monster != null)
                            {
                                Tuple <short, byte, List <EventContainer> > evnt = (Tuple <short, byte, List <EventContainer> >)evt.Parameter;
                                List <MapMonster> MapMonsters = evt.MapInstance.GetListMonsterInRange(monster.MapX, monster.MapY, evnt.Item2);
                                if (evnt.Item1 != 0)
                                {
                                    MapMonsters.RemoveAll(s => s.MonsterVNum != evnt.Item1);
                                }
                                MapMonsters.ForEach(s => evnt.Item3.ForEach(e => RunEvent(e, monster: s)));
                            }
                            break;

                        case EventActionType.ONTARGET:
                            if (monster.MoveEvent?.InZone(monster.MapX, monster.MapY) == true)
                            {
                                monster.MoveEvent = null;
                                monster.Path      = new List <Node>();
                                ((List <EventContainer>)evt.Parameter).ForEach(s => RunEvent(s, monster: monster));
                            }
                            break;

                        case EventActionType.MOVE:
                            ZoneEvent evt4 = (ZoneEvent)evt.Parameter;
                            if (monster != null)
                            {
                                monster.MoveEvent = evt4;
                                monster.Path      = BestFirstSearch.FindPathJagged(new Node {
                                    X = monster.MapX, Y = monster.MapY
                                }, new Node {
                                    X = evt4.X, Y = evt4.Y
                                }, evt.MapInstance?.Map.JaggedGrid);
                            }
                            break;

                        case EventActionType.CLOCK:
                            evt.MapInstance.InstanceBag.Clock.TotalSecondsAmount = Convert.ToInt32(evt.Parameter);
                            evt.MapInstance.InstanceBag.Clock.SecondsRemaining   = Convert.ToInt32(evt.Parameter);
                            break;

                        case EventActionType.SETMONSTERLOCKERS:
                            evt.MapInstance.InstanceBag.MonsterLocker.Current = Convert.ToByte(evt.Parameter);
                            evt.MapInstance.InstanceBag.MonsterLocker.Initial = Convert.ToByte(evt.Parameter);
                            break;

                        case EventActionType.SETBUTTONLOCKERS:
                            evt.MapInstance.InstanceBag.ButtonLocker.Current = Convert.ToByte(evt.Parameter);
                            evt.MapInstance.InstanceBag.ButtonLocker.Initial = Convert.ToByte(evt.Parameter);
                            break;

                        case EventActionType.SCRIPTEND:
                            switch (evt.MapInstance.MapInstanceType)
                            {
                            case MapInstanceType.TimeSpaceInstance:
                                evt.MapInstance.InstanceBag.EndState = (byte)evt.Parameter;
                                ClientSession client = evt.MapInstance.Sessions.FirstOrDefault();
                                if (client != null)
                                {
                                    Guid             MapInstanceId = ServerManager.GetBaseMapInstanceIdByMapId(client.Character.MapId);
                                    MapInstance      map           = ServerManager.GetMapInstance(MapInstanceId);
                                    ScriptedInstance si            = map.ScriptedInstances.Find(s => s.PositionX == client.Character.MapX && s.PositionY == client.Character.MapY);
                                    byte             penalty       = 0;
                                    if (penalty > (client.Character.Level - si.LevelMinimum) * 2)
                                    {
                                        penalty = penalty > 100 ? (byte)100 : penalty;
                                        client.SendPacket(client.Character.GenerateSay(string.Format(Language.Instance.GetMessageFromKey("TS_PENALTY"), penalty), 10));
                                    }
                                    int    point      = evt.MapInstance.InstanceBag.Point * (100 - penalty) / 100;
                                    string perfection = string.Empty;
                                    perfection += evt.MapInstance.InstanceBag.MonstersKilled >= si.MonsterAmount ? 1 : 0;
                                    perfection += evt.MapInstance.InstanceBag.NpcsKilled == 0 ? 1 : 0;
                                    perfection += evt.MapInstance.InstanceBag.RoomsVisited >= si.RoomAmount ? 1 : 0;
                                    evt.MapInstance.Broadcast($"score  {evt.MapInstance.InstanceBag.EndState} {point} 27 47 18 {si.DrawItems.Count} {evt.MapInstance.InstanceBag.MonstersKilled} {si.NpcAmount - evt.MapInstance.InstanceBag.NpcsKilled} {evt.MapInstance.InstanceBag.RoomsVisited} {perfection} 1 1");
                                }
                                break;

                            case MapInstanceType.RaidInstance:
                                evt.MapInstance.InstanceBag.EndState = (byte)evt.Parameter;
                                client = evt.MapInstance.Sessions.FirstOrDefault();
                                if (client != null)
                                {
                                    Group grp = client?.Character?.Group;
                                    if (grp == null)
                                    {
                                        return;
                                    }
                                    if (evt.MapInstance.InstanceBag.EndState == 1 && evt.MapInstance.Monsters.Any(s => s.IsBoss))
                                    {
                                        foreach (ClientSession sess in grp.Characters.Where(s => s.CurrentMapInstance.Monsters.Any(e => e.IsBoss)))
                                        {
                                            foreach (Gift gift in grp?.Raid?.GiftItems)
                                            {
                                                const byte rare = 0;
                                                if (sess.Character.Inventory.CanAddItem(gift.VNum))
                                                {
                                                    sess.Character.GiftAdd(gift.VNum, gift.Amount, rare, 0, gift.Design, gift.IsRandomRare);
                                                }
                                                else
                                                {
                                                    sess.Character.SendGift(0, gift.VNum, gift.Amount, 0, (byte)gift.Design, true, 0);
                                                }
                                                sess.Character.GenerateFamilyXp(2500);
                                            }
                                        }
                                        foreach (MapMonster mon in evt.MapInstance.Monsters)
                                        {
                                            mon.CurrentHp = 0;
                                            evt.MapInstance.Broadcast(StaticPacketHelper.Out(UserType.Monster, mon.MapMonsterId));
                                            evt.MapInstance.RemoveMonster(mon);
                                        }
                                        Logger.LogUserEvent("RAID_SUCCESS", grp.Characters.ElementAt(0).Character.Name, $"RaidId: {grp.GroupId}");

                                        ServerManager.Instance.Broadcast(UserInterfaceHelper.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("RAID_SUCCEED"), grp?.Raid?.Label, grp.Characters.ElementAt(0).Character.Name), 0));
                                    }

                                    Observable.Timer(TimeSpan.FromSeconds(evt.MapInstance.InstanceBag.EndState == 1 ? 30 : 0)).Subscribe(o =>
                                    {
                                        ClientSession[] grpmembers = new ClientSession[40];
                                        grp.Characters.CopyTo(grpmembers);
                                        foreach (ClientSession targetSession in grpmembers)
                                        {
                                            if (targetSession != null)
                                            {
                                                if (targetSession.Character.Hp <= 0)
                                                {
                                                    targetSession.Character.Hp = 1;
                                                    targetSession.Character.Mp = 1;
                                                }
                                                targetSession.SendPacket(Character.GenerateRaidBf(evt.MapInstance.InstanceBag.EndState));
                                                targetSession.SendPacket(targetSession.Character.GenerateRaid(1, true));
                                                targetSession.SendPacket(targetSession.Character.GenerateRaid(2, true));
                                                grp.LeaveGroup(targetSession);
                                            }
                                        }
                                        ServerManager.Instance.GroupList.RemoveAll(s => s.GroupId == grp.GroupId);
                                        ServerManager.Instance.GroupsThreadSafe.Remove(grp.GroupId);
                                        evt.MapInstance.Dispose();
                                    });
                                }
                                break;

                            case MapInstanceType.Act4Morcos:
                            case MapInstanceType.Act4Hatus:
                            case MapInstanceType.Act4Calvina:
                            case MapInstanceType.Act4Berios:
                                client = evt.MapInstance.Sessions.FirstOrDefault();
                                if (client != null)
                                {
                                    Family fam = evt.MapInstance.Sessions.FirstOrDefault(s => s?.Character?.Family != null)?.Character.Family;
                                    if (fam != null)
                                    {
                                        fam.Act4Raid.Portals.RemoveAll(s => s.DestinationMapInstanceId.Equals(fam.Act4RaidBossMap.MapInstanceId));
                                        short destX      = 38;
                                        short destY      = 179;
                                        short rewardVNum = 882;
                                        switch (evt.MapInstance.MapInstanceType)
                                        {
                                        //Morcos is default
                                        case MapInstanceType.Act4Hatus:
                                            destX      = 18;
                                            destY      = 10;
                                            rewardVNum = 185;
                                            break;

                                        case MapInstanceType.Act4Calvina:
                                            destX      = 25;
                                            destY      = 7;
                                            rewardVNum = 942;
                                            break;

                                        case MapInstanceType.Act4Berios:
                                            destX      = 16;
                                            destY      = 25;
                                            rewardVNum = 999;
                                            break;
                                        }
                                        int count = evt.MapInstance.Sessions.Count(s => s?.Character != null);
                                        foreach (ClientSession sess in evt.MapInstance.Sessions)
                                        {
                                            if (sess?.Character != null)
                                            {
                                                sess.Character.GiftAdd(rewardVNum, 1, forceRandom: true, minRare: 1, design: 255);
                                                sess.Character.GenerateFamilyXp(10000 / count);
                                            }
                                        }
                                        Logger.LogEvent("FAMILYRAID_SUCCESS", $"[fam.Name]FamilyRaidId: {evt.MapInstance.MapInstanceType.ToString()}");

                                        //TODO: Famlog
                                        CommunicationServiceClient.Instance.SendMessageToCharacter(new SCSCharacterMessage
                                        {
                                            DestinationCharacterId = fam.FamilyId,
                                            SourceCharacterId      = client.Character.CharacterId,
                                            SourceWorldId          = ServerManager.Instance.WorldId,
                                            Message = UserInterfaceHelper.GenerateMsg(Language.Instance.GetMessageFromKey("FAMILYRAID_SUCCESS"), 0),
                                            Type    = MessageType.Family
                                        });
                                        //ServerManager.Instance.Broadcast(UserInterfaceHelper.Instance.GenerateMsg(string.Format(Language.Instance.GetMessageFromKey("FAMILYRAID_SUCCESS"), grp?.Raid?.Label, grp.Characters.ElementAt(0).Character.Name), 0));

                                        Observable.Timer(TimeSpan.FromSeconds(30)).Subscribe(o =>
                                        {
                                            foreach (ClientSession targetSession in evt.MapInstance.Sessions.ToArray())
                                            {
                                                if (targetSession != null)
                                                {
                                                    if (targetSession.Character.Hp <= 0)
                                                    {
                                                        targetSession.Character.Hp = 1;
                                                        targetSession.Character.Mp = 1;
                                                    }

                                                    ServerManager.Instance.ChangeMapInstance(targetSession.Character.CharacterId, fam.Act4Raid.MapInstanceId, destX, destY);
                                                }
                                            }
                                            evt.MapInstance.Dispose();
                                        });
                                    }
                                }
                                break;

                            case MapInstanceType.CaligorInstance:

                                FactionType winningFaction = CaligorRaid.AngelDamage > CaligorRaid.DemonDamage ? FactionType.Angel : FactionType.Demon;

                                foreach (ClientSession sess in evt.MapInstance.Sessions)
                                {
                                    if (sess?.Character != null)
                                    {
                                        if (CaligorRaid.RemainingTime > 2400)
                                        {
                                            if (sess.Character.Faction == winningFaction)
                                            {
                                                sess.Character.GiftAdd(5960, 1);
                                            }
                                            else
                                            {
                                                sess.Character.GiftAdd(5961, 1);
                                            }
                                        }
                                        else
                                        {
                                            if (sess.Character.Faction == winningFaction)
                                            {
                                                sess.Character.GiftAdd(5961, 1);
                                            }
                                            else
                                            {
                                                sess.Character.GiftAdd(5958, 1);
                                            }
                                        }
                                        sess.Character.GiftAdd(5959, 1);
                                        sess.Character.GenerateFamilyXp(500);
                                    }
                                }
                                evt.MapInstance.Broadcast(UserInterfaceHelper.GenerateCHDM(ServerManager.GetNpc(2305).MaxHP, CaligorRaid.AngelDamage, CaligorRaid.DemonDamage, CaligorRaid.RemainingTime));
                                break;
                            }
                            break;

                        case EventActionType.MAPCLOCK:
                            evt.MapInstance.Clock.TotalSecondsAmount = Convert.ToInt32(evt.Parameter);
                            evt.MapInstance.Clock.SecondsRemaining   = Convert.ToInt32(evt.Parameter);
                            break;

                        case EventActionType.STARTCLOCK:
                            Tuple <List <EventContainer>, List <EventContainer> > eve = (Tuple <List <EventContainer>, List <EventContainer> >)evt.Parameter;
                            evt.MapInstance.InstanceBag.Clock.StopEvents    = eve.Item1;
                            evt.MapInstance.InstanceBag.Clock.TimeoutEvents = eve.Item2;
                            evt.MapInstance.InstanceBag.Clock.StartClock();
                            evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                            break;

                        case EventActionType.TELEPORT:
                            Tuple <short, short, short, short> tp = (Tuple <short, short, short, short>)evt.Parameter;
                            List <Character> characters           = evt.MapInstance.GetCharactersInRange(tp.Item1, tp.Item2, 5).ToList();
                            characters.ForEach(s =>
                            {
                                s.PositionX = tp.Item3;
                                s.PositionY = tp.Item4;
                                evt.MapInstance?.Broadcast(s.Session, s.GenerateTp(), ReceiverType.Group);
                            });
                            break;

                        case EventActionType.STOPCLOCK:
                            evt.MapInstance.InstanceBag.Clock.StopClock();
                            evt.MapInstance.Broadcast(evt.MapInstance.InstanceBag.Clock.GetClock());
                            break;

                        case EventActionType.STARTMAPCLOCK:
                            eve = (Tuple <List <EventContainer>, List <EventContainer> >)evt.Parameter;
                            evt.MapInstance.Clock.StopEvents    = eve.Item1;
                            evt.MapInstance.Clock.TimeoutEvents = eve.Item2;
                            evt.MapInstance.Clock.StartClock();
                            evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                            break;

                        case EventActionType.STOPMAPCLOCK:
                            evt.MapInstance.Clock.StopClock();
                            evt.MapInstance.Broadcast(evt.MapInstance.Clock.GetClock());
                            break;

                        case EventActionType.SPAWNPORTAL:
                            evt.MapInstance.CreatePortal((Portal)evt.Parameter);
                            break;

                        case EventActionType.REFRESHMAPITEMS:
                            evt.MapInstance.MapClear();
                            break;

                        case EventActionType.NPCSEFFECTCHANGESTATE:
                            evt.MapInstance.Npcs.ForEach(s => s.EffectActivated = (bool)evt.Parameter);
                            break;

                        case EventActionType.CHANGEPORTALTYPE:
                            Tuple <int, PortalType> param = (Tuple <int, PortalType>)evt.Parameter;
                            Portal portal = evt.MapInstance.Portals.Find(s => s.PortalId == param.Item1);
                            if (portal != null)
                            {
                                portal.Type = (short)param.Item2;
                            }
                            break;

                        case EventActionType.CHANGEDROPRATE:
                            evt.MapInstance.DropRate = (int)evt.Parameter;
                            break;

                        case EventActionType.CHANGEXPRATE:
                            evt.MapInstance.XpRate = (int)evt.Parameter;
                            break;

                        case EventActionType.DISPOSEMAP:
                            evt.MapInstance.Dispose();
                            break;

                        case EventActionType.SPAWNBUTTON:
                            evt.MapInstance.SpawnButton((MapButton)evt.Parameter);
                            break;

                        case EventActionType.UNSPAWNMONSTERS:
                            evt.MapInstance.DespawnMonster((int)evt.Parameter);
                            break;

                        case EventActionType.SPAWNMONSTER:
                            evt.MapInstance.SummonMonster((MonsterToSummon)evt.Parameter);
                            break;

                        case EventActionType.SPAWNMONSTERS:
                            evt.MapInstance.SummonMonsters((List <MonsterToSummon>)evt.Parameter);
                            break;

                        case EventActionType.REFRESHRAIDGOAL:
                            ClientSession cl = evt.MapInstance.Sessions.FirstOrDefault();
                            if (cl?.Character != null)
                            {
                                ServerManager.Instance.Broadcast(cl, cl.Character?.Group?.GeneraterRaidmbf(cl), ReceiverType.Group);
                                ServerManager.Instance.Broadcast(cl, UserInterfaceHelper.GenerateMsg(Language.Instance.GetMessageFromKey("NEW_MISSION"), 0), ReceiverType.Group);
                            }
                            break;

                        case EventActionType.SPAWNNPC:
                            evt.MapInstance.SummonNpc((NpcToSummon)evt.Parameter);
                            break;

                        case EventActionType.SPAWNNPCS:
                            evt.MapInstance.SummonNpcs((List <NpcToSummon>)evt.Parameter);
                            break;

                        case EventActionType.DROPITEMS:
                            evt.MapInstance.DropItems((List <Tuple <short, int, short, short> >)evt.Parameter);
                            break;

                        case EventActionType.THROWITEMS:
                            Tuple <int, short, byte, int, int> parameters = (Tuple <int, short, byte, int, int>)evt.Parameter;
                            if (monster != null)
                            {
                                parameters = new Tuple <int, short, byte, int, int>(monster.MapMonsterId, parameters.Item2, parameters.Item3, parameters.Item4, parameters.Item5);
                            }
                            evt.MapInstance.ThrowItems(parameters);
                            break;

                        case EventActionType.SPAWNONLASTENTRY:
                            Character lastincharacter = evt.MapInstance.Sessions.OrderByDescending(s => s.RegisterTime).FirstOrDefault()?.Character;
                            List <MonsterToSummon> summonParameters = new List <MonsterToSummon>();
                            MapCell hornSpawn = new MapCell
                            {
                                X = lastincharacter?.PositionX ?? 154,
                                Y = lastincharacter?.PositionY ?? 140
                            };
                            long hornTarget = lastincharacter?.CharacterId ?? -1;
                            summonParameters.Add(new MonsterToSummon(Convert.ToInt16(evt.Parameter), hornSpawn, hornTarget, true));
                            evt.MapInstance.SummonMonsters(summonParameters);
                            break;

                            #endregion
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Пример #47
0
 public LocallSectionCell(MapCell pos, int x, int y)
 {
     Position = pos;
     Xsize    = x;
     Ysize    = y;
 }
Пример #48
0
 private void create_city()
 {
     city_cell = (CityCell)MapCell.create_cell(MapCell.CITY_ID, 1, city, new Pos(12, 12));
     city_cell.discover();
     map.Add(city_cell.pos, city_cell);
 }
Пример #49
0
 public void add_oscillating_cell(MapCell cell)
 {
     oscillating_cells.Add(cell);
 }
        private void CreateMovementCmd(bool serverSide, Action <List <Cmd> > callback)
        {
            Guid playerId    = m_gameState.GetLocalPlayerId(m_localPlayerIndex);
            int  playerIndex = m_gameState.GetPlayerIndex(playerId);

            long[] selectedUnitIds = m_unitSelection.GetSelection(playerIndex, playerIndex);
            if (selectedUnitIds.Length > 0)
            {
                List <Cmd> commandsToSubmit = new List <Cmd>();

                for (int i = 0; i < selectedUnitIds.Length; ++i)
                {
                    long unitIndex = selectedUnitIds[i];
                    IVoxelDataController dataController = m_gameState.GetVoxelDataController(playerIndex, unitIndex);

                    MapCell cell        = m_map.GetCell(m_cameraController.MapCursor, m_cameraController.Weight, null);
                    int     deltaWeight = dataController.ControlledData.Weight - m_cameraController.Weight;
                    while (deltaWeight > 0)
                    {
                        cell = cell.Parent;
                        deltaWeight--;
                    }

                    VoxelData selectedTarget = null;
                    //MapCell selectedTargetCell = null;
                    for (int p = 0; p < m_gameState.PlayersCount; ++p)
                    {
                        long[] targetSelection = m_targetSelection.GetSelection(playerIndex, p);
                        if (targetSelection.Length > 0)
                        {
                            MatchAssetCli asset = m_gameState.GetAsset(p, targetSelection[0]);
                            if (asset != null)
                            {
                                selectedTarget = asset.VoxelData;
                                // selectedTargetCell = asset.Cell;
                            }
                            else
                            {
                                IVoxelDataController dc = m_gameState.GetVoxelDataController(p, targetSelection[0]);
                                selectedTarget = dc.ControlledData;
                                // selectedTargetCell = m_map.GetCell(dc.Coordinate.MapPos, dc.Coordinate.Weight, null);
                            }
                        }
                    }

                    int dataType   = dataController.ControlledData.Type;
                    int dataWeight = dataController.ControlledData.Weight;


                    VoxelData beneath = null;
                    if (cell != null)
                    {
                        if (selectedTarget == null)
                        {
                            VoxelData defaultTarget;
                            beneath = cell.GetDefaultTargetFor(dataType, dataWeight, playerIndex, false, out defaultTarget);
                        }
                        else
                        {
                            beneath = cell.GetPreviousFor(selectedTarget, dataType, dataWeight, playerIndex);
                        }
                    }

                    VoxelData closestBeneath = beneath;
                    float     minDistance    = float.MaxValue;

                    if (closestBeneath == null && cell != null)
                    {
                        MapPos pos = cell.GetPosition();
                        for (int r = -1; r <= 1; r++)
                        {
                            for (int c = -1; c <= 1; c++)
                            {
                                MapCell neighbourCell = m_map.GetCell(new MapPos(pos.Row + r, pos.Col + c), dataController.ControlledData.Weight, null);
                                if (neighbourCell != null)
                                {
                                    VoxelData defaultTarget;
                                    VoxelData data       = neighbourCell.GetDefaultTargetFor(dataType, dataWeight, playerIndex, false, out defaultTarget);
                                    Vector3   worldPoint = m_map.GetWorldPosition(new MapPos(pos.Row + r, pos.Col + c), dataWeight);
                                    if (data != null)
                                    {
                                        worldPoint.y = (data.Altitude + data.Height) * GameConstants.UnitSize;
                                    }

                                    Vector2 screenPoint = m_cameraController.WorldToScreenPoint(worldPoint);
                                    if (m_cameraController.InScreenBounds(screenPoint))
                                    {
                                        float distance = (screenPoint - m_cameraController.VirtualMousePosition).magnitude;
                                        if (data != null && distance < minDistance)
                                        {
                                            minDistance    = distance;
                                            closestBeneath = data;
                                            cell           = neighbourCell;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    beneath = closestBeneath;

                    if (beneath != null)
                    {
                        int weight = dataController.ControlledData.Weight;
                        // Vector3 hitPoint = beneath.Weight <= weight ? m_map.GetWorldPosition(m_cameraController.MapCursor, m_cameraController.Weight) : m_cameraController.Cursor;
                        //MapPos mapPos = m_map.GetMapPosition(hitPoint, weight);

                        MapPos mapPos   = cell.GetPosition();
                        int    altitude = beneath.Altitude + beneath.Height;

                        if (serverSide)
                        {
                            MovementCmd movementCmd = new MovementCmd();

                            if (selectedTarget != null)
                            {
                                movementCmd.HasTarget         = true;
                                movementCmd.TargetIndex       = selectedTarget.UnitOrAssetIndex;
                                movementCmd.TargetPlayerIndex = selectedTarget.Owner;
                            }


                            Coordinate targetCoordinate = new Coordinate(mapPos, weight, altitude);
                            movementCmd.Code        = CmdCode.Move;
                            movementCmd.Coordinates = new[] { targetCoordinate };
                            movementCmd.UnitIndex   = unitIndex;
                            commandsToSubmit.Add(movementCmd);
                        }
                        else
                        {
                            Coordinate targetCoordinate = new Coordinate(mapPos, weight, altitude);
                            m_engine.GetPathFinder(m_gameState.LocalToPlayerIndex(LocalPlayerIndex)).Find(unitIndex, -1, dataController.Clone(), new[] { dataController.Coordinate, targetCoordinate },
                                                                                                          (unitId, path) =>
                            {
                                MovementCmd movementCmd = new MovementCmd();
                                movementCmd.Code        = CmdCode.Move;
                                movementCmd.Coordinates = path;
                                movementCmd.UnitIndex   = unitIndex;
                                commandsToSubmit.Add(movementCmd);
                                callback(commandsToSubmit);
                            },
                                                                                                          null);
                        }
                    }
                }

                if (serverSide)
                {
                    callback(commandsToSubmit);
                }
            }
            callback(null);
        }
Пример #51
0
 public void SetMarker(MapCell cell, Marker marker)
 {
     SetMarker(cell.X, cell.Y, marker);
 }
Пример #52
0
        private void CreateVoxel(Vector3 hitPoint)
        {
            int weight = BrushWeight;
            int type   = m_selectedPrefab.Prefab.Type;

            int selectedWeight = Mathf.Min(m_voxelMap.Map.Weight, weight + BrushSize - 1);

            MapPos  mappos = m_voxelMap.GetMapPosition(hitPoint, selectedWeight);
            MapCell cell   = m_voxelMap.GetCell(mappos, selectedWeight, m_voxelCameraRef);

            if (cell != null && m_lastModifiedCell != cell)
            {
                if (cell.HasDescendantsWithVoxelData())
                {
                    Debug.LogWarning("Unable to create in cell with child data available");
                    m_lastModifiedCell = cell;
                    return;
                }

                if (type == (int)KnownVoxelTypes.Ground)
                {
                    if (cell.First != null && cell.First.GetLast().Type != type)
                    {
                        Debug.LogWarning("Unable to create voxel of type GROUND attached to voxel of another type");
                        m_lastModifiedCell = cell;
                        return;
                    }
                    else if (cell.Parent != null)
                    {
                        MapCell parent = cell.Parent;
                        while (parent != null)
                        {
                            if (parent.First != null && parent.First.GetLast().Type != type)
                            {
                                Debug.LogWarning("Unable to create voxel of type GROUND attached to voxel of another type");
                                m_lastModifiedCell = cell;
                                return;
                            }

                            parent = parent.Parent;
                        }
                    }
                }


                if (BrushHeight == 0 && m_selectedAbilities.VariableHeight)
                {
                    //Following lines should prevent stacking of zero height voxels.

                    DestroyVoxels(cell, type);

                    MapCell parent = cell.Parent;
                    while (parent != null)
                    {
                        if (parent.First != null)
                        {
                            VoxelData data = parent.First.GetFirstOfType(type);
                            DestroyVoxel(parent, data);
                        }
                        parent = parent.Parent;
                    }
                }

                //if(CanSimplify(type))
                //{
                //    //If type is ground -> simplify (fill one big cell instead of multiple small cells);
                //    CreateVoxels(cell, type, selectedWeight, selectedWeight);
                //}
                //else
                //{
                CreateVoxels(cell, type, weight, selectedWeight);
                ///}

                m_lastModifiedCell = cell;
            }
        }
Пример #53
0
        private void Draw(MapCell cell, Coordinate coord, Color32[] colors, int textureSize, Func <MapCell, VoxelData> voxelDataSelector, Func <VoxelData, Color> colorSelector)
        {
            Coordinate zeroCoord = coord.ToWeight(0);
            MapPos     p0        = zeroCoord.MapPos;
            int        size      = (1 << coord.Weight);
            MapPos     p1        = p0;

            p1.Add(size, size);

            p0.Row = Mathf.Max(p0.Row, m_bounds.Row);
            p0.Col = Math.Max(p0.Col, m_bounds.Col);
            p1.Row = Mathf.Min(p1.Row, m_bounds.Row + m_bounds.RowsCount);
            p1.Col = Mathf.Min(p1.Col, m_bounds.Col + m_bounds.ColsCount);

            int cols = p1.Col - p0.Col;
            int rows = p1.Row - p0.Row;

            if (cols <= 0 || rows <= 0)
            {
                return;
            }

            cols *= m_scale;
            rows *= m_scale;

            p0.Row -= m_bounds.Row;
            p0.Col -= m_bounds.Col;

            p0.Row *= m_scale;
            p0.Col *= m_scale;

            VoxelData data = null;

            if (cell.First != null)
            {
                data = voxelDataSelector(cell);
            }

            if (data != null)
            {
                float   height     = data.Altitude + data.Height;
                float   deltaColor = Mathf.Max(0, (1.0f - (height / m_staticMapHeight))) * 0.1f;
                Color32 color      = colorSelector(data) - new Color(deltaColor, deltaColor, deltaColor, 0);
                for (int r = 0; r < rows; ++r)
                {
                    for (int c = 0; c < cols; ++c)
                    {
                        colors[(p0.Row + r) * textureSize + p0.Col + c] = color;
                    }
                }
            }

            if (cell.Children != null && cell.Children.Length > 0 && coord.Weight > GameConstants.MinVoxelActorWeight)
            {
                coord.Weight--;
                coord.Col *= 2;
                coord.Row *= 2;

                for (int i = 0; i < 4; i++)
                {
                    Coordinate childCoord = coord;
                    childCoord.Row += i / 2;
                    childCoord.Col += i % 2;

                    Draw(cell.Children[i], childCoord, colors, textureSize, voxelDataSelector, colorSelector);
                }
            }
        }
Пример #54
0
        /// <summary>
        /// Shows Map and the details of the map
        /// used Prof.Holmes' code for showing the map
        /// </summary>
        public void ShowContent()
        {
            grdGameBorad.Children.Clear();

            CreateAGrid(grdGameBorad, 10, 10);
            for (int row = 0; row <= Game.Map.Cells.GetUpperBound(0); row++)
            {
                for (int col = 0; col <= Game.Map.Cells.GetUpperBound(1); col++)
                {
                    Button    btn        = new Button();
                    MapCell   mcToCheck  = Game.Map.Cells[row, col]; // get the current mapcell
                    TextBlock tbContents = new TextBlock();          // create a textblock to display contents
                    tbContents.TextAlignment = TextAlignment.Center;
                    //mapcell will be black if hasn't been seen
                    if (mcToCheck.HasBeenSeen == false)
                    {
                        tbContents.Background = new SolidColorBrush(Colors.Black);
                    }
                    else if (mcToCheck.HasItem)
                    {
                        if (mcToCheck.Item.GetType() == typeof(Weapon))
                        {
                            tbContents.Background = new SolidColorBrush(Colors.Gray);
                        }

                        else if (mcToCheck.Item.GetType() == typeof(Potion))
                        {
                            Potion ptn = (Potion)mcToCheck.Item;
                            tbContents.Background = GetColorBrush(ptn);
                        }

                        else if (mcToCheck.Item.GetType() == typeof(Door))
                        {
                            tbContents.Background = new SolidColorBrush(Colors.Peru);
                        }

                        else if (mcToCheck.Item.GetType() == typeof(DoorKey))
                        {
                            tbContents.Background = new SolidColorBrush(Colors.Gold);
                        }

                        tbContents.Text = mcToCheck.Item.Name;
                    }
                    else if (mcToCheck.HasMonster)
                    {
                        tbContents.Background = new SolidColorBrush(Colors.DarkRed);
                        tbContents.Foreground = new SolidColorBrush(Colors.White);
                        tbContents.Text       = Game.Map.Cells[row, col].Monster.Name(false);
                    }
                    else if (Game.Map.Adventurer.PositionX == col && Game.Map.Adventurer.PositionY == row)
                    {
                        tbContents.Text       = Game.Map.Adventurer.Name(true);
                        tbContents.Foreground = new SolidColorBrush(Colors.White);
                        tbContents.Background = new SolidColorBrush(Colors.DarkBlue);
                    }
                    tbContents.TextWrapping = TextWrapping.Wrap;
                    Grid.SetRow(tbContents, row);
                    Grid.SetColumn(tbContents, col);
                    grdGameBorad.Children.Add(tbContents);
                }
            }

            string weapName = "";

            if (Game.Map.Adventurer.HasWeapon == true)
            {
                weapName = Game.Map.Adventurer.Weapon.Name;
            }
            else
            {
                weapName = "NONE";
            }
            //details to be shown

            tbMapDet.Text  = String.Format("{5}\r\nMonsters count: {0} \r\n Items count: {1} \r\n Map Discovered: {2} % \r\n Current Location: {3},{4}", Game.Map.CountMonsters, Game.Map.CountItems, Game.Map.MapDiscPercent, Game.Map.Adventurer.PositionX, Game.Map.Adventurer.PositionY, Game.Map.Adventurer.Name(true));
            tbItemDet.Text = String.Format("Max Monster HP: {0} \r\n Min Weapon Damage: {1} \r\n Average Potion Effect: {2} \r\n Weapon: {3}", Game.Map.MostHP, Game.Map.LeastWeaponDamageValue, Game.Map.PotionAVG, weapName);
        }
Пример #55
0
 public void reset() { // New game, new player
     cell = active_disc.cell;
     MapUI.I.set_active_ask_to_enterP(false);
     MapUI.I.update_cell_text(cell.name);
 }
Пример #56
0
 public static bool CanStay(
     this MapUnit unit,
     MapCell cell)
 {
     return(cell.isFilled);
 }
        /// <summary>
        /// Loops through game board array of mapcells and displays the cells to the user.
        /// Images retrieved from: https://itch.io/game-assets/free/tag-pixel-art
        ///                        https://opengameart.org/
        ///                        https://www.pinterest.com/pin/471752129697165710/
        ///                        http://pixelartmaker.com/art/e97fe18f09c317a
        ///                        https://scratchwars.com/photos/zbrane_avatar/f/0/23.png?m=1485028045
        ///
        /// </summary>
        public void DrawMap()
        {
            grdMapCells.Children.Clear();

            // Loop through the entire game board.
            for (int row = 0; row < Game.Map.GameBoard.GetLength(0); row++)
            {
                for (int column = 0; column < Game.Map.GameBoard.GetLength(1); column++)
                {
                    TextBlock tbCell  = new TextBlock();
                    MapCell   mapCell = Game.Map.GameBoard[row, column];
                    tbCell.Name          = "mapCell" + row + column;
                    tbCell.Tag           = mapCell;
                    tbCell.TextAlignment = TextAlignment.Center;
                    tbCell.TextWrapping  = TextWrapping.Wrap;

                    // Display the contents in map cells that have different potions.
                    if (mapCell.HasItem)
                    {
                        if (mapCell.Item.GetType() == typeof(Potion) && mapCell.IsDiscovered)
                        {
                            Potion potion = (Potion)mapCell.Item;
                            if (potion.Color == Potion.Colors.Blue)
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/BluePotion.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (potion.Color == Potion.Colors.Green)
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/GreenPotion.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (potion.Color == Potion.Colors.Red)
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/RedPotion.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (potion.Color == Potion.Colors.Purple)
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/PurplePotion.png");
                                tbCell.Inlines.Add(container);
                            }
                            // Display the map cell that contains the door.
                        }
                        else if (mapCell.Item.GetType() == typeof(Door) && mapCell.IsDiscovered)
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Door.png");
                            tbCell.Inlines.Add(container);
                            // Display the map cell that contains the key.
                        }
                        else if (mapCell.Item.GetType() == typeof(DoorKey) && mapCell.IsDiscovered)
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Key.png");
                            tbCell.Inlines.Add(container);
                        }
                        else if (mapCell.Item.GetType() == typeof(Weapon) && mapCell.IsDiscovered)
                        {
                            if (mapCell.Item.Name == "Dagger")
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/Dagger.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (mapCell.Item.Name == "Club")
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/Club.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (mapCell.Item.Name == "Sword")
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/Sword.png");
                                tbCell.Inlines.Add(container);
                            }
                            else if (mapCell.Item.Name == "Claymore")
                            {
                                InlineUIContainer container = CreateImageContainer(@"assets/Claymore.png");
                                tbCell.Inlines.Add(container);
                            }
                        }
                    }
                    else if (mapCell.HasMonster && mapCell.IsDiscovered)
                    {
                        if (mapCell.Monster.Name == "Goblin")
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Goblin.png");
                            tbCell.Inlines.Add(container);
                        }
                        else if (mapCell.Monster.Name == "Orc")
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Orc.png");
                            tbCell.Inlines.Add(container);
                        }
                        else if (mapCell.Monster.Name == "Giant Slime")
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/GiantSlime.png");
                            tbCell.Inlines.Add(container);
                        }
                        else if (mapCell.Monster.Name == "Rat")
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Rat.png");
                            tbCell.Inlines.Add(container);
                        }
                        else if (mapCell.Monster.Name == "Skeleton")
                        {
                            InlineUIContainer container = CreateImageContainer(@"assets/Skeleton.png");
                            tbCell.Inlines.Add(container);
                        }
                    }
                    if (mapCell == Game.Map.GetCurrentPosition())
                    {
                        InlineUIContainer container = CreateImageContainer(@"assets/Adventurer.png");
                        tbCell.Inlines.Add(container);
                    }
                    // Make cell black if its not discovered.
                    if (mapCell.IsDiscovered == false)
                    {
                        tbCell.Background = Brushes.Black;
                        tbCell.Foreground = Brushes.Black;
                    }

                    // Add the cells to the grid, showing the game board.
                    Grid.SetColumn(tbCell, column);
                    Grid.SetRow(tbCell, row);
                    grdMapCells.Children.Add(tbCell);
                }
            }
        }
Пример #58
0
        private void Update()
        {
            if (m_inputManager.GetButtonDown(InputAction.EditorCreate, m_mapEditorOwner))
            {
                m_lastModifiedCell       = null;
                m_editorCreateButtonDown = true;
            }

            if (m_inputManager.GetButtonUp(InputAction.EditorCreate, m_mapEditorOwner))
            {
                m_lastModifiedCell       = null;
                m_editorCreateButtonDown = false;
            }

            if (m_inputManager.GetButtonDown(InputAction.EditorDestroy, m_mapEditorOwner))
            {
                m_lastModifiedCell        = null;
                m_editorDestroyButtonDown = true;
            }

            if (m_inputManager.GetButtonUp(InputAction.EditorDestroy, m_mapEditorOwner))
            {
                m_lastModifiedCell        = null;
                m_editorDestroyButtonDown = false;
            }

            if (m_inputManager.GetButton(InputAction.EditorCreate, m_mapEditorOwner))
            {
                if (m_editorCreateButtonDown)
                {
                    CreateVoxel();
                }
            }
            else if (m_inputManager.GetButton(InputAction.EditorDestroy, m_mapEditorOwner))
            {
                if (m_editorDestroyButtonDown)
                {
                    DestroyVoxel();
                }
            }

            if (m_inputManager.GetButtonDown(InputAction.EditorPan, m_mapEditorOwner))
            {
                m_lastMousePosition = m_inputManager.MousePosition;
                m_prevPivotPosition = m_pivot.transform.position;
            }
            else if (m_inputManager.GetButtonUp(InputAction.EditorPan, m_mapEditorOwner))
            {
                m_editorCamera.enabled = false;
            }

            bool pan    = m_inputManager.GetButton(InputAction.EditorPan, m_mapEditorOwner);
            bool rotate = m_inputManager.GetButton(InputAction.EditorRotate, m_mapEditorOwner);

            if (!pan && !rotate)
            {
                m_editorCamera.Zoom();
            }

            if (rotate)
            {
                if (pan)
                {
                    m_editorCamera.enabled = true;
                }
            }
            else
            {
                m_editorCamera.enabled = false;
                if (pan)
                {
                    Pan();
                }
            }
        }
Пример #59
0
        private bool TryToMove(bool checkTarget, PathFinderTask task, Coordinate from, Coordinate next, out Coordinate result, out VoxelData resultData)
        {
            resultData = null;

            MapCell cell = task.Map.Get(next.Row, next.Col, next.Weight);

            int type   = task.ControlledData.Type;
            int weight = task.ControlledData.Weight;
            int height = task.ControlledData.Height;

            MapCell targetCell;

            if (checkTarget)
            {
                VoxelData targetData = cell.GetById(task.TargetId);
                if (targetData != null)
                {
                    next.Altitude = targetData.Altitude;
                    CmdResultCode canMove = VoxelDataController.CanMove(task.ControlledData, task.Abilities, task.Map, task.MapSize, from, next, false, false, false, out targetCell);
                    if (canMove == CmdResultCode.Success)
                    {
                        resultData = targetData;
                        result     = next;
                        return(true);
                    }
                }
            }

            //Change altitude if failed with target coordinate
            VoxelData target;
            VoxelData beneath = cell.GetDefaultTargetFor(type, weight, task.PlayerIndex, false, out target);

            if (beneath == null)
            {
                result = from;
                return(false);
            }

            // This will allow bomb movement
            bool isLastStep = task.Waypoints[task.Waypoints.Length - 1].MapPos == next.MapPos;

            if (isLastStep)
            {
                //Try target coordinate first
                next = task.Waypoints[task.Waypoints.Length - 1];

                //last step is param false -> force CanMove to check next coordinate as is
                CmdResultCode canMove = VoxelDataController.CanMove(task.ControlledData, task.Abilities, task.Map, task.MapSize, from, next, false, false, false, out targetCell);
                if (canMove == CmdResultCode.Success)
                {
                    result = next;
                    return(true);
                }
            }

            if (target != beneath) //this will allow bombs to move over spawners
            {
                if (!isLastStep && target != null && !(target.IsCollapsableBy(type, weight) || target.IsAttackableBy(task.ControlledData)))
                {
                    result = from;
                    return(false);
                }
            }

            next.Altitude = beneath.Altitude + beneath.Height;

            //last step param is false -> force CanMove to check next coordinate as is
            CmdResultCode canMoveResult = VoxelDataController.CanMove(task.ControlledData, task.Abilities, task.Map, task.MapSize, from, next, false, false, false, out targetCell);

            if (canMoveResult != CmdResultCode.Success)
            {
                result = from;
                return(false);
            }

            result = next;
            return(true);
        }
Пример #60
0
    /*
     *   Create a GameObject for a map cell on the grid, add walls, floors, decorations etc.
     */
    private GameObject buildGameObj(MapCell cell, Map map)
    {
        GameObject cellGameObj = new GameObject();

        // Floor and ceiling
        cellGameObj.name = "Map cell: " + cell.x + ", " + cell.y;
        GameObject floor   = (GameObject)Instantiate(Resources.Load("Floor"), new Vector3(0, 0, 0), Quaternion.identity);
        GameObject ceiling = (GameObject)Instantiate(Resources.Load("Ceiling"), new Vector3(0, 0, 0), Quaternion.identity);

        floor.transform.parent   = cellGameObj.transform;
        ceiling.transform.parent = cellGameObj.transform;

        // Look for walls, and build them
        if (map.getCellSouth(cell) == null || map.getCellSouth(cell).solid)
        {
            addWall(0, cellGameObj, cell);
        }
        if (map.getCellWest(cell) == null || map.getCellWest(cell).solid)
        {
            addWall(90, cellGameObj, cell);
        }
        if (map.getCellNorth(cell) == null || map.getCellNorth(cell).solid)
        {
            addWall(180, cellGameObj, cell);
        }
        if (map.getCellEast(cell) == null || map.getCellEast(cell).solid)
        {
            addWall(270, cellGameObj, cell);
        }

        // Look for features; doors, pillars, pits, statues
        if (cell.hasFeature())
        {
            GameObject feat = null;

            if (cell.getFeature().type == "door")
            {
                feat = (GameObject)Instantiate(Resources.Load("Door"), new Vector3(0, 0, 0), Quaternion.identity);
            }
            if (cell.getFeature().type == "pillar")
            {
                feat = (GameObject)Instantiate(Resources.Load("Pillar"), new Vector3(0, 0, 0), Quaternion.identity);
            }

            int featureRotate = 0;
            switch (cell.getFeature().facing)
            {
            case Map.SOUTH: featureRotate = 0; break;

            case Map.WEST: featureRotate = 90; break;

            case Map.NORTH: featureRotate = 180; break;

            case Map.EAST: featureRotate = 270; break;
            }
            feat.transform.rotation = Quaternion.Euler(0, featureRotate, 0);
            feat.transform.parent   = cellGameObj.transform;
            cell.getFeature().gameObj = feat;
        }

        // Puddles and floor decals, grime etc
        if (Random.Range(0, 100) > 50)
        {
            GameObject decal = (GameObject)Instantiate(Resources.Load("FloorSlime"), new Vector3(0, 0, 0), Quaternion.identity);
            decal.transform.rotation = Quaternion.Euler(0, Random.Range(0, 360), 0);
            float s = Random.Range(0.3f, 1.9f);
            decal.transform.localScale = new Vector3(s, s, s);
            decal.transform.parent     = cellGameObj.transform;
        }

        if (cell.monster != null)
        {
            addMonster(cell, cellGameObj);
        }

        // Place into the world
        cellGameObj.transform.position = new Vector3(cell.x * Main.CELL_SIZE, 0, -(cell.y * Main.CELL_SIZE));

        return(cellGameObj);
    }