Beispiel #1
0
        public GameObject Draw(MapBlock m)
        {
            GameObject rootGameObject = GameObject.Find("Cell_Head");

            for (int i = 0; i < m.mat.Count; i++)
            {
                var row           = m.mat [i];
                var rowGameObject = new GameObject();
                rowGameObject.name                    = "Cell_Row_" + i.ToString();
                rowGameObject.transform.parent        = rootGameObject.transform;
                rowGameObject.transform.localPosition =
                    new Vector2(0, ((m.mat.Count / 2f) - i) * (cellHeight + verticalSpace));
                for (int j = 0; j < row.Count; j++)
                {
                    var cell           = row [j];
                    var cellGameObject = cellDrawer.Draw(cell);
                    cellGameObject.name                    = "Cell_Column_" + j.ToString();
                    cellGameObject.transform.parent        = rowGameObject.transform;
                    cellGameObject.transform.localPosition =
                        new Vector2((-1 * (row.Count / 2f) + j + 0.5f) * (cellWidth + horitozontalSpace), 0);
                }
            }

            return(rootGameObject);
        }
Beispiel #2
0
		public override void Fill(MapBlock _block, WorldLayer _layer)
		{
			base.Fill(_block, _layer);

            //var innerPerimeter = Room.RoomRectangle.Inflate(-1, -1);
            //var indoor = InDoorWorldCoords.Select(BaseMapBlock.GetInBlockCoords);
            //var doorCoords = BaseMapBlock.GetInBlockCoords(DoorWorldCoords);

            //var corners = innerPerimeter.CornerPoints.Except(indoor).OrderBy(_point => _point.GetDistTill(doorCoords)).ToArray();
            //var allPoints = innerPerimeter.BorderPoints.Except(corners).Except(indoor).OrderByDescending(_point => _point.GetDistTill(doorCoords)).ToArray();

            //var cornerTiles = new[] {ETileset.NONE, ETileset.NONE, ETileset.CHAIR, ETileset.BARREL}.OrderBy(_tiles => World.Rnd.Next()).ToArray();
            //var perimeterTiles = new[] {ETileset.NONE, ETileset.CHEST, ETileset.WEAPON_RACK, ETileset.ARMOR_RACK, ETileset.CABINET}.OrderBy(_tiles => World.Rnd.Next()).ToArray();
            //BedCoords = allPoints[0];
            //_block.AddObject(ETileset.BED.GetThing(), BedCoords);
            //for (var index = 1; index < allPoints.Length; index++)
            //{
            //    var point = allPoints[index];
            //    var tile = perimeterTiles[index%perimeterTiles.Length];
            //    if (tile != ETileset.NONE)
            //    {
            //        _block.AddObject(tile.GetThing(), point);
            //    }
            //}

            //for (var index = 0; index < corners.Length; index++)
            //{
            //    var point = corners[index];
            //    var tile = cornerTiles[index%cornerTiles.Length];
            //    if (tile != ETileset.NONE)
            //    {
            //        _block.AddObject(tile.GetThing(), point);
            //    }
            //}
		}
Beispiel #3
0
        void InitializeCouchbaseView()
        {
            var view = Database.ViewNamed(DefaultViewName);

            var mapBlock = new MapBlock((doc, emit) => {
                var date    = doc.ObjectForKey(CreationDatePropertyName);
                var deleted = doc.ObjectForKey(DeletedKey);

                if (date != null && deleted == null)
                {
                    emit(date, doc);
                }
            });

            view.SetMapBlock(mapBlock, "1.1");

            var validationBlock = new ValidationBlock((revision, context) => {
                if (revision.IsDeleted)
                {
                    return(true);
                }

                NSObject date = revision.Properties.ObjectForKey(CreationDatePropertyName);
                return(date != null);
            });

            Database.DefineValidation(CreationDatePropertyName, validationBlock);
        }
        public override void createGameObject(MapBlock mapBlock, Dictionary <string, GameObject> prefabList, ref GameObject MapObject)
        {
            mapBlock.Initialize();

            base.createGameObject(mapBlock, prefabList, ref MapObject);

            string prefab = selectDecoration(mapBlock);

            GameObject template = prefabList[prefab];

            GameObject decoration = AddObject(mapBlock.Location, template, ref MapObject);

            var decorationConfig = mapBlock.getObjectConfigForType("decoration");

            if (decorationConfig != null && decorationConfig.Rotation != null && decorationConfig.Rotation.Length == 1)
            {
                var direction = (Direction)"NESW".IndexOf(decorationConfig.Rotation[0]);
                decoration.transform.rotation = direction.GetRotation();
            }
            else
            {
                AttachToWall(ref decoration);
            }

            AssignObjectConfigByType(decoration, "decoration", mapBlock);

            mapBlock.addGameObject(decoration);
        }
        public void TestJsonSerialize()
        {
            Direction[] allDirections = DirectionMethods.GetAllDirections();
            int         w             = 10;
            int         h             = 15;
            Map         map           = new SimpleMapGenerator().GenerateMap(w, h, IMapGeneratorConstants.NO_SEED);
            IMapSerializer <string, string> jsonSerializer = new JsonMapSerializer();
            string jsonString = jsonSerializer.Serialize(map);

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

            Map deserialized = jsonSerializer.Deserialize(jsonString);

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

                    Assert.AreEqual(orig, deser, $"Blocks at [{i},{j}] have wrong coordinates!");
                    foreach (Direction d in allDirections)
                    {
                        Assert.AreEqual(orig.EntranceInDirection(d), deser.EntranceInDirection(d), $"Blocks at [{i},{j}] have different entrance in direction {d}!");
                    }
                }
            }
        }
Beispiel #6
0
        private void CreateDoor(MapBlock _mapBlock, ETerrains _floor, IEnumerable <Point> _borderPoints)
        {
            var doorCoords = Room.RoomRectangle.Center;
            var prevPoint  = doorCoords;
            var direction  = World.Rnd.GetRandomDirection();
            var delta      = direction.GetDelta();

            while (!_borderPoints.Contains(doorCoords))
            {
                prevPoint   = doorCoords;
                doorCoords += delta;
            }
            var nextPoint = doorCoords + delta;

            var borders = direction.GetBorders().ToArray();

            DoorWorldCoords = _mapBlock.ToWorldCoords(doorCoords);

            OutDoorWorldCoords = new[] { nextPoint + borders[0].Key, nextPoint, nextPoint + borders[1].Key }.Select(_mapBlock.ToWorldCoords).ToArray();
            InDoorWorldCoords  = new[] { prevPoint + borders[0].Key, prevPoint, prevPoint + borders[1].Key }.Select(_mapBlock.ToWorldCoords).ToArray();

            _mapBlock.Map[doorCoords.X, doorCoords.Y] = _floor;
            var doors = EssenceHelper.GetAllThings <ClosedDoor>().ToArray();

            _mapBlock.AddEssence(doors[0], doorCoords);
        }
        protected string selectDecoration(MapBlock mapBlock)
        {
            var type = getDecorationType(mapBlock);

            switch (type)
            {
            case "ceiling_lamp":
                return("decoration_ceiling_lamp");

            case "spider_web":
                return("decoration_spider_web");

            case "broken_path":
                return("decoration_broken_path");

            case "pillar":
                return("decoration_pillar");

            case "chair":
                return("decoration_chair");

            case "table":
                return("decoration_table");

            default:
                return("decoration_library");
            }
        }
        public override void Fill(MapBlock _block, WorldLayer _layer)
        {
            base.Fill(_block, _layer);
            //var innerPerimeter = Room.RoomRectangle.Inflate(-1, -1);
            //var indoor = InDoorWorldCoords.Select(BaseMapBlock.GetInBlockCoords);
            //var doorCoords = BaseMapBlock.GetInBlockCoords(DoorWorldCoords);
            //var corners = innerPerimeter.CornerPoints.Except(indoor).OrderBy(_point => _point.GetDistTill(doorCoords)).ToArray();
            //var allPoints = innerPerimeter.BorderPoints.Except(corners).Except(indoor).OrderByDescending(_point => _point.GetDistTill(doorCoords)).ToArray();


            //var cornerTiles = new[] {ETileset.NONE, ETileset.BARREL, ETileset.TABLE, ETileset.BARREL}.OrderBy(_tiles => World.Rnd.Next()).ToArray();
            //var perimeterTiles = new[] {ETileset.NONE, ETileset.CHAIR, ETileset.TABLE, ETileset.CHAIR, ETileset.BARREL}.OrderBy(_tiles => World.Rnd.Next()).ToArray();

            //for (var index = 0; index < allPoints.Length; index++)
            //{
            //    var point = allPoints[index];
            //    var tile = perimeterTiles[index%perimeterTiles.Length];
            //    if (tile != ETileset.NONE)
            //    {
            //        _block.AddObject(tile.GetThing(), point);
            //    }
            //}

            //for (var index = 0; index < corners.Length; index++)
            //{
            //    var point = corners[index];
            //    var tile = cornerTiles[index%cornerTiles.Length];
            //    if (tile != ETileset.NONE)
            //    {
            //        _block.AddObject(tile.GetThing(), point);
            //    }
            //}
        }
Beispiel #9
0
        public void TestPickUpItem()
        {
            // prepare map block with one item, player and pick up action
            MapBlock mapBlock          = new MapBlock(0, 0);
            AbstractInventoryItem item = new BasicItem("Test item", mapBlock, 10);

            mapBlock.Item = item;
            AbstractPlayer testPlayer   = new EmptyAIPlayer("Test player", mapBlock);
            PickUp         pickUpAction = new PickUp()
            {
                Actor = testPlayer
            };

            // check that inventory is empty
            Assert.AreEqual(0, testPlayer.Inventory.Count, "Inventory should be empty!");
            Assert.IsNotNull(mapBlock.Item, "Item should be placed in map block!");

            // perform pick up action
            pickUpAction.Execute();

            // check that item was picked up
            Assert.AreEqual(1, testPlayer.Inventory.Count, "There should be one item in inventory!");
            Assert.IsNull(mapBlock.Item, "There should be no item in the map block!");
            Assert.AreEqual(item, testPlayer.GetItemFromInventory(0), "Wrong item picked up!");
        }
Beispiel #10
0
        void parseChunk(Chunk toparse, Form1 thisform)
        {
            // Get all of the blocks, and load them into memory.
            for (byte i = 0; i < 16; i++)
            {
                if (Convert.ToBoolean(toparse.pbitmap & (1 << i)))
                {
                    for (int f = 0; f < 4096; f++)
                    {
                        int blockX  = (toparse.x * 16) + (f & 0x0F);      // f & 0x0f
                        int blockY  = (i * 16) + (blockX >> 8);           // i*16 + (f >> 8)
                        int blockZ  = (toparse.z * 16) + (f & 0xF0) >> 4; // (f & F0) >> 4
                        int blockID = toparse.blocks[f];

                        MapBlock myBlock = new MapBlock(blockID, blockX, blockY, blockZ);

                        if (thisform.blocks == null)
                        {
                            thisform.blocks = new MapBlock[] { myBlock }
                        }
                        ;
                        else
                        {
                            MapBlock[] temp = thisform.blocks;
                            thisform.blocks = new MapBlock[temp.Length + 1];
                            Array.Copy(temp, thisform.blocks, temp.Length);
                            thisform.blocks[temp.Length] = myBlock;
                        }
                    }
                }
            }
        }
    public GameMap(List <MapBlock> availableTiles)
    {
        for (int currRow = 0; currRow < desiredRows; currRow++)
        {
            int tilesToChoose = Random.Range(0, (availableTiles.Count));


            List <MapBlock> newRowBlocks = new List <MapBlock>();


            for (int i = 0; i < tilesToChoose; i++)
            {
                int targetLocation = Random.Range(0, availableTiles.Count);

                MapBlock chosenBlock = availableTiles[targetLocation];

                newRowBlocks.Add(chosenBlock);

                availableTiles.Remove(chosenBlock);
            }

            mapRows.Add(new MapRow(currRow, newRowBlocks));
        }
        Debug.Log("Created Game Map");
    }
Beispiel #12
0
    /// <summary>
    /// 有反索引 block 資料 問題, 先不要使用
    /// </summary>
    public static void MoveUnit(MapBlock original, MapBlock dest)
    {
        if (original.CreatureComponent == null)
        {
            GameControl.Instance.DebugLog(" original.CreatureComponent == null");
            return;
        }
        if (original.CreatureComponent.gameObject == null)
        {
            GameControl.Instance.DebugLog(" original.CreatureComponent.gameObject == null");
            return;
        }

        float xPos = offset_x / 2f + Tile_Width * dest.Pos.x;
        float yPos = offset_y / 2f - Tile_Height * dest.Pos.y;

        //移動資料到新 block
        dest.CreatureComponent            = original.CreatureComponent;
        dest.BlockData.Block.LivingObject = original.BlockData.Block.LivingObject;

        //清除 old block
        original.CreatureComponent.gameObject.transform.position   = new Vector3(xPos, yPos, -2);
        original.CreatureComponent.gameObject.transform.localScale = new Vector3(Tile_Width, Tile_Height, 1);
        original.BlockData.Block.LivingObject = Creature.None; //原本的位置變成是 空的
        original.CreatureComponent            = null;          //原本的位置 creature component 索引變成是 空的

        //todo : 要撥 move 特效加這裡
    }
Beispiel #13
0
        void InitializeCouchbaseSummaryView()
        {
            var view = Database.ViewNamed("Done");

            var mapBlock = new MapBlock((doc, emit) => {
                var date       = doc.ObjectForKey(CreationDatePropertyName);
                var checkedOff = doc.ObjectForKey((NSString)"check");

                if (date != null)
                {
                    emit(NSArray.FromNSObjects(checkedOff, date), null);
                }
            });

            var reduceBlock = new ReduceBlock((keys, values, rereduce) => {
                var keyArray = NSArray.FromArray <NSArray> (keys);
                var key      = keyArray.Sum(data => 1 - data.GetItem <NSNumber> (0).IntValue);

                var result = new NSMutableDictionary();
                result.SetValueForKey((NSString)"Items Remaining", (NSString)"Label");
                result.SetValueForKey((NSString)key.ToString(), (NSString)"Count");

                return(result);
            });

            view.SetMapBlock(mapBlock, reduceBlock, "1.1");
        }
Beispiel #14
0
        public void TestInitializeMap()
        {
            // base map
            Map map = new Map();

            // create some grind to initialize map with
            int w = 10;
            int h = 10;

            MapBlock[,] grid = new MapBlock[w, h];
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    grid[i, j] = new MapBlock(i, j);
                }
            }
            map.InitializeMap(grid);

            // test initialitazion
            Assert.IsNotNull(map.Grid, "Grid is not initialized!");
            Assert.AreEqual(w, map.Width, "Wrong width!");
            Assert.AreEqual(h, map.Height, "Wrong height!");
            for (int i = 0; i < w; i++)
            {
                for (int j = 0; j < h; j++)
                {
                    MapBlock curBlock = map.Grid[i, j];
                    Assert.IsNotNull(curBlock, $"Map block at [{i},{j}] not initialized!");
                    Assert.AreEqual(map, curBlock.ParentMap, $"Parent map of block [{i},{j}] set incorrectly!");
                }
            }
        }
Beispiel #15
0
 private SyncBlockInfo Convert(MapBlock block)
 {
     return(new SyncBlockInfo
     {
         BlockIndex = block.BlockIndex,
         BlockSize = block.BlockSize,
         BlockHash = block.BlockHash,
         BlockTime = block.BlockTime,
         NextBlockHash = block.NextBlockHash,
         PreviousBlockHash = block.PreviousBlockHash,
         TransactionCount = block.TransactionCount,
         Nonce = block.Nonce,
         ChainWork = block.ChainWork,
         Difficulty = block.Difficulty,
         Merkleroot = block.Merkleroot,
         PosModifierv2 = block.PosModifierv2,
         PosHashProof = block.PosHashProof,
         PosFlags = block.PosFlags,
         PosChainTrust = block.PosChainTrust,
         PosBlockTrust = block.PosBlockTrust,
         PosBlockSignature = block.PosBlockSignature,
         Confirmations = block.Confirmations,
         Bits = block.Bits,
         Version = block.Version,
         SyncComplete = block.SyncComplete
     });
 }
Beispiel #16
0
    internal void LoadBlock(MapBlock block)
    {
        if (block.items.Count > 0)
        {
            loadedAnyItems = true;
        }
        foreach (var item in block.items)
        {
            removedItems.Remove(item.id);
            ItemModel placedItem;
            if (!sceneItems.ContainsKey(item.id))
            {
                if (itemCount.ContainsKey(item.pos) && itemCount[item.pos] >= GameSettings.Instance.rendering.maxItemsPerTile)
                {
                    continue;
                }

                placedItem          = InstantiateItem(item, transform);
                sceneItems[item.id] = placedItem;
            }
            else
            {
                placedItem = sceneItems[item.id];
            }

            if (itemCount.ContainsKey(item.pos) && itemCount[item.pos] >= GameSettings.Instance.rendering.maxItemsPerTile)
            {
                placedItem.gameObject.SetActive(false);
                continue;
            }
            int currentTileCount = 0;
            if (itemCount.ContainsKey(item.pos))
            {
                currentTileCount = itemCount[item.pos];
            }
            itemCount[item.pos] = currentTileCount + 1;
            //RaycastHit hitInfo;
            //Vector3 position = GameMap.DFtoUnityCoord(item.pos) + Stacker.SpiralHemisphere(currentTileCount);
            //if (Physics.Raycast(position + new Vector3(0, 2.9f, 0), Vector3.down, out hitInfo, 3, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Collide))
            //    placedItem.transform.position = hitInfo.point;
            //else
            placedItem.transform.position = GameMap.DFtoUnityCoord(item.pos.x + item.subpos_x, item.pos.y + item.subpos_y, item.pos.z + item.subpos_z);
            if (item.projectile)
            {
                placedItem.transform.position += new Vector3(0, GameMap.tileHeight / 2, 0);
                if (item.velocity_x > 0 || item.velocity_y > 0 || item.velocity_z > 0)
                {
                    placedItem.transform.rotation = Quaternion.LookRotation(GameMap.DFtoUnityDirection(item.velocity_x, item.velocity_y, item.velocity_z), Vector3.up);
                }
            }
            else
            {
                placedItem.transform.position += (Stacker.SpiralHemisphere(currentTileCount) + new Vector3(0, GameMap.floorHeight, 0));
                if (item.velocity_x > 0 || item.velocity_y > 0 || item.velocity_z > 0)
                {
                    placedItem.transform.rotation = Quaternion.LookRotation(GameMap.DFtoUnityDirection(item.velocity_x, item.velocity_y, item.velocity_z), Vector3.up);
                }
            }
        }
    }
Beispiel #17
0
        private void PlaceTilesIntoNewlyLoadedBlock(MapBlock block)
        {
            int px = Position.X;
            int py = Position.Y;

            Rectangle bounds = new Rectangle(block.X * 8, block.Y * 8, 8, 8);

            foreach (MultiComponentList.MultiItem item in m_Components.Items)
            {
                int x = px + item.OffsetX;
                int y = py + item.OffsetY;

                if (bounds.Contains(x, y))
                {
                    // would it be faster to get the tile from the block?
                    MapTile tile = Map.GetMapTile(x, y);
                    if (tile != null)
                    {
                        if (!tile.ItemExists(item.ItemID, item.OffsetZ))
                        {
                            StaticItem staticItem = new StaticItem(item.ItemID, 0, 0, Map);
                            staticItem.Position.Set(x, y, Z + item.OffsetZ);
                        }
                    }
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// Decides whether to choose direction of next block or to switch backwardFlag.
        /// </summary>
        /// <return>Next direction. May be null.</return>
        private Direction GoForward()
        {
            Direction nextDirection = Direction.NO_DIRECTION;

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

                // some direction was picked -> add it to stack
                if (!nextDirection.IsNoDirection())
                {
                    pathStack.Push(nextDirection);
                }
            }
            else
            {
                // stack is full set backward flag and do nothing
                goBackwardFlag = true;
            }
            return(nextDirection);
        }
Beispiel #19
0
        /// <summary>
        /// Returns vertical boundaries for rendering map blocks around center block.
        /// [minY,maxY].
        /// </summary>
        /// <param name="map">Map.</param>
        /// <param name="centerBlock">Center block.</param>
        /// <param name="verticalBlockCount">NUmber of blocks to be rendered in vertical direction.</param>
        /// <returns>Array with two items. First is the Y coordinate of the top block to be rendered, second is the Y coordinate of the bottom block to be rendered.</returns>
        private int[] GetYBoundaries(MapBlock[,] map, MapBlock centerBlock, int verticalBlockCount)
        {
            int[] boundaries = new int[2];

            // number of blocks on each side from center block
            int numOfTopBlocks    = verticalBlockCount / 2;
            int numOfBottomBlocks = (int)Math.Ceiling(verticalBlockCount / 2.0) - 1;

            // too close to the top border
            if (centerBlock.Y - numOfTopBlocks < 0)
            {
                boundaries[0] = 0;
                boundaries[1] = verticalBlockCount - 1;


                // too close to the bottom border
            }
            else if (centerBlock.Y + numOfBottomBlocks >= map.GetLength(1))
            {
                boundaries[0] = map.GetLength(1) - verticalBlockCount;
                boundaries[1] = map.GetLength(1) - 1;


                // ok, somewhere in the middle
            }
            else
            {
                boundaries[0] = centerBlock.Y - numOfTopBlocks;
                boundaries[1] = centerBlock.Y + numOfBottomBlocks;
            }

            return(boundaries);
        }
Beispiel #20
0
        public override void createGameObject(MapBlock mapBlock, Dictionary <string, GameObject> prefabList, ref GameObject MapObject)
        {
            mapBlock.Initialize();

            base.createGameObject(mapBlock, prefabList, ref MapObject);

            GameObject template = prefabList[GetModel(mapBlock)];

            GameObject ducat = AddObject(mapBlock.Location, template, ref MapObject);

            if (EnableRotation(mapBlock))
            {
                var ducatConfig = mapBlock.getObjectConfigForType("ducat");
                if (ducatConfig != null && ducatConfig.Rotation != null && ducatConfig.Rotation.Length == 1)
                {
                    var direction = (Direction)"NESW".IndexOf(ducatConfig.Rotation[0]);
                    ducat.transform.rotation = direction.GetRotation();
                }
                else
                {
                    AttachToWall(ref ducat);
                }
            }

            AssignObjectConfigByType(ducat, "ducat", mapBlock);

            mapBlock.addGameObject(ducat);
        }
        public override void createGameObject(MapBlock mapBlock, Dictionary <string, GameObject> prefabList, ref GameObject MapObject)
        {
            mapBlock.Initialize();

            base.createGameObject(mapBlock, prefabList, ref MapObject);

            GameObject template = prefabList["teleport"];

            GameObject teleport = AddObject(mapBlock.Location, template, ref MapObject);

            var teleportConfig = mapBlock.getObjectConfigForType("teleport");

            if (teleportConfig != null)
            {
                if (teleportConfig.Teleport != null)
                {
                    if (teleportConfig.Teleport.Target != null && teleportConfig.Teleport.Target.Length == 2)
                    {
                        var teleportController = teleport.GetComponent <TeleportController>();
                        teleportController.TargetColumn = teleportConfig.Teleport.Target[0] - 1;
                        teleportController.TargetRow    = teleportConfig.Teleport.Target[1] - 1;
                    }

                    if (teleportConfig.Teleport.Rotation != null && teleportConfig.Teleport.Rotation.Length == 1)
                    {
                        var teleportController = teleport.GetComponent <TeleportController>();
                        teleportController.RotationDirection = teleportConfig.Teleport.Rotation[0];
                    }
                }
            }

            mapBlock.addGameObject(teleport);
        }
Beispiel #22
0
        /// <summary>
        /// Render map (with background) and returns it as a set of shapes.
        /// </summary>
        /// <param name="mapGrid">Map to be rendered.</param>
        /// <param name="centerBlock">Center block to render map around.</param>
        /// <param name="canvasW">Width of target canvas.</param>
        /// <param name="canvasH">Height of target canvas.</param>
        /// <returns>Map rendered as a list of shapes.</returns>
        public List <UIElement> RenderMap(Map map, MapBlock centerBlock, double canvasW, double canvasH)
        {
            List <UIElement> renderedMap = new List <UIElement>();

            // target area is too small to render anything
            if (canvasW < this.blockSize || canvasH < this.blockSize)
            {
                return(renderedMap);
            }

            MapBlock[,] mapGrid = map.Grid;
            int verticalBlockCount   = (int)Math.Min((double)map.Height, canvasH / blockSize);
            int horizontalBlockCount = (int)Math.Min((double)map.Width, canvasW / blockSize);

            renderedMap.Add(new Rectangle()
            {
                Height = verticalBlockCount * blockSize, Width = horizontalBlockCount * blockSize, Fill = new SolidColorBrush(Color.FromRgb(255, 204, 102))
            });

            int[] xBoundaries = GetXBoundaries(mapGrid, centerBlock, horizontalBlockCount);
            int[] yBoundaries = GetYBoundaries(mapGrid, centerBlock, verticalBlockCount);
            for (int i = xBoundaries[0]; i <= xBoundaries[1]; i++)
            {
                for (int j = yBoundaries[0]; j <= yBoundaries[1]; j++)
                {
                    List <Shape> renderedMapBlock = RenderMapBlock(mapGrid[i, j], (i - xBoundaries[0]) * blockSize, (j - yBoundaries[0]) * blockSize, blockSize, map.WinningBlock.X, map.WinningBlock.Y);
                    renderedMap.AddRange(renderedMapBlock);
                }
            }

            return(renderedMap);
        }
Beispiel #23
0
        /// <summary>
        /// Demolishes walls between two blocks. Determines fromDirection - direction in which the wall in fromBlock will be demolished.
        /// </summary>
        /// <param name="fromBlock">Wall which lies in fromDirection in this block will be demolished.</param>
        /// <param name="toBlock">Wall which lies in oposite to fromDirection in this block will be demolished.</param>
        private void DemolishWalls(MapBlock fromBlock, MapBlock toBlock)
        {
            // determine fromDirection
            Direction fromDirection = Direction.NORTH;

            if (fromBlock.X < toBlock.X)
            {
                fromDirection = Direction.EAST;
            }
            else if (fromBlock.X > toBlock.X)
            {
                fromDirection = Direction.WEST;
            }
            else if (fromBlock.Y < toBlock.Y)
            {
                fromDirection = Direction.SOUTH;
            }
            else
            {
                fromDirection = Direction.NORTH;
            }

            fromBlock.EntranceInDirection(fromDirection).DemolishWall();
            toBlock.EntranceInDirection(fromDirection.OppositeDirection()).DemolishWall();
        }
Beispiel #24
0
        /// <summary>
        /// Returns horizontal boundaries for rendering map blocks around center block.
        /// [minX,maxX].
        /// </summary>
        /// <param name="map">Map.</param>
        /// <param name="centerBlock">Center blocks.</param>
        /// <param name="horizontalBlockCount">Number of blocks to be rendered in horizontal direction.</param>
        /// <returns>Array with two items. First is the X coordinate of the leftmost block to be rendered, second is the X coordinate of the rightmost block to be rendered.</returns>
        private int[] GetXBoundaries(MapBlock[,] map, MapBlock centerBlock, int horizontalBlockCount)
        {
            int[] boundaries = new int[2];

            // number of blocks on each side from center block
            int numOfLeftBlocks  = horizontalBlockCount / 2;
            int numOfRightBlocks = (int)Math.Ceiling(horizontalBlockCount / 2.0) - 1;

            // too close to the right border
            if (centerBlock.X + numOfRightBlocks >= map.GetLength(0))
            {
                boundaries[1] = map.GetLength(0) - 1;
                boundaries[0] = map.GetLength(0) - horizontalBlockCount;

                // too close to the left border
            }
            else if (centerBlock.X - numOfLeftBlocks < 0)
            {
                boundaries[0] = 0;
                boundaries[1] = horizontalBlockCount - 1;

                // ok, somewhere in the middle
            }
            else
            {
                boundaries[0] = centerBlock.X - numOfLeftBlocks;
                boundaries[1] = centerBlock.X + numOfRightBlocks;
            }

            return(boundaries);
        }
Beispiel #25
0
        public IEnumerable <SyncBlockInfo> BlockGetIncompleteBlocks()
        {
            // note this field is not indexed
            FilterDefinition <MapBlock> filter = Builders <MapBlock> .Filter.Eq(info => info.SyncComplete, false);

            return(MapBlock.Find(filter).ToList().Select(Convert));
        }
Beispiel #26
0
    void ReleaseResource(int block_id)
    {
        MapBlock mb = blocks[block_id];

        //Debug.LogFormat("ReleaseResource block {0}", block_id);
        mb.ReleaseResource();
    }
Beispiel #27
0
        public override void createGameObject(MapBlock mapBlock, Dictionary <string, GameObject> prefabList, ref GameObject MapObject)
        {
            mapBlock.Initialize();

            base.createGameObject(mapBlock, prefabList, ref MapObject);

            GameObject template = prefabList["torch"];

            GameObject torch = AddObject(mapBlock.Location, template, ref MapObject);

            var torchConfig = mapBlock.getObjectConfigForType("torch");

            if (torchConfig != null && torchConfig.Rotation != null && torchConfig.Rotation.Length == 1)
            {
                var direction = (Direction)"NESW".IndexOf(torchConfig.Rotation[0]);
                torch.transform.rotation = direction.GetRotation();
            }
            else
            {
                AttachToWall(ref torch);
            }

            AssignObjectConfigByType(torch, "torch", mapBlock);

            mapBlock.addGameObject(torch);
        }
Beispiel #28
0
        public Vector3 MapPositionToWorldCoords(int block, int vertex, int pixelOffsetX = 0, int pixelOffsetY = 0)
        {
            float halfX2 = 2.28f / 2f;
            float halfY2 = 1.28f / 2f;


            var x = block % blocksMapSide;
            var y = block / blocksMapSide;

            var i = vertex % verticesBlockSide;
            var j = vertex / verticesBlockSide;

            Vector3 BasePosition = new Vector3((x * verticesBlockSide) + i,
                                               (y * verticesBlockSide) + j,
                                               MapBlock.terrainElevation(block, vertex));

            Vector3 IsoPosition = Vector3.zero;


            IsoPosition.x = ((BasePosition.x - BasePosition.y) * halfX2) + (pixelOffsetX / 100f);                                                     //
            IsoPosition.y = ((BasePosition.x + BasePosition.y) * -halfY2) + ((BasePosition.z) * (MetersPerElevLevel / 100f)) - (pixelOffsetY / 100f); //

            IsoPosition.z = 0;                                                                                                                        // (BasePosition.z * ((float)MetersPerElevLevel / 100));

            return(IsoPosition);
        }
Beispiel #29
0
        private void CreateBlock(BlockInfo block)
        {
            var blockInfo = new MapBlock
            {
                BlockIndex        = block.Height,
                BlockHash         = block.Hash,
                BlockSize         = block.Size,
                BlockTime         = block.Time,
                NextBlockHash     = block.NextBlockHash,
                PreviousBlockHash = block.PreviousBlockHash,
                TransactionCount  = block.Transactions.Count(),
                Bits              = block.Bits,
                Confirmations     = block.Confirmations,
                Merkleroot        = block.Merkleroot,
                Nonce             = block.Nonce,
                ChainWork         = block.ChainWork,
                Difficulty        = block.Difficulty,
                PosBlockSignature = block.PosBlockSignature,
                PosBlockTrust     = block.PosBlockTrust,
                PosChainTrust     = block.PosChainTrust,
                PosFlags          = block.PosFlags,
                PosHashProof      = block.PosHashProof,
                PosModifierv2     = block.PosModifierv2,
                Version           = block.Version,
                SyncComplete      = false
            };

            this.data.InsertBlock(blockInfo);
        }
Beispiel #30
0
    private Block CreateBlock()
    {
        BlockSaveData saveData = ScriptableObject.CreateInstance <BlockSaveData> ();

        saveData.id            = blockID;
        saveData.name          = "Block_" + blockID;
        saveData.tileColor     = currentColor;
        saveData.slotPosition  = Vector3.zero;
        saveData.hintPosition  = mapTiles[0].transform.localPosition;
        saveData.tilePositions = new List <Vector3> ();
        foreach (MapTile mapTile in mapTiles)
        {
            saveData.tilePositions.Add(mapTile.transform.localPosition - saveData.hintPosition);
        }

        MapBlock block = GameObject.Instantiate <MapBlock> (Map.Instance.mapBlockPrefab);

        block.Init(saveData);
        blocks.Add(block.id, block);

        blockID++;
        mapTiles     = new List <MapTile>();
        currentColor = colors[Random.Range(0, colors.Length)];
        return(block);
    }
Beispiel #31
0
    private void OnDrawGizmos()
    {
        blc = block;
        if (blc.Grid == null)
        {
            string path = @"Assets\Resources\" + Ground.PATH_TO_GRIDS + Ground.PATH_TO_BLOCK_OF_TYPE(block.type) + name + ".xml";
            blc = Tools.FileManagement.Deserialize(path);
        }

        if (blc.Grid != null)
        {
            int rc = blc.Grid.Length;
            int cc = blc.Grid[0].Length;
            for (int row = 0; row < rc; row++)
            {
                for (int col = 0; col < cc; col++)
                {
                    if (blc.Grid[row][col])
                    {
                        Gizmos.DrawWireCube(
                            new Vector3(
                                transform.position.x + col * MapBlock.BLOCK_SCALE - MapBlock.WORLD_BLOCK_SIZE / 2f + MapBlock.BLOCK_SCALE / 2f,
                                transform.position.y + row * MapBlock.BLOCK_SCALE - MapBlock.WORLD_BLOCK_SIZE / 2f + MapBlock.BLOCK_SCALE / 2f
                                ),
                            new Vector3(MapBlock.BLOCK_SCALE, MapBlock.BLOCK_SCALE) / 1.1f
                            );
                    }
                }
            }
        }
    }
 public MapGrid() {
     InitializeComponent();
     MapBlocks = new MapBlock[50][];
     MapObjects = new ArrayList();
     for(int i = 0; i < 50; i++) {
         MapBlocks[i] = new MapBlock[50];
     }
 }
Beispiel #33
0
        public static AttackSpaceEvent CreateAttackSpaceEvent(Creature nAtt, MapBlock nSpa)
        {
            AttackSpaceEvent aEvent = new AttackSpaceEvent(nAtt, nSpa);

            aEvent.CreateTime = Game.TurnsPassed;
            aEvent.ActivateTime = Game.TurnsPassed + 0;

            return aEvent;
        }
        public void SetBlock(MapPosition Target ,MapBlock Block) {
            MapBlocks[Target.X][Target.Y] = Block;

            float Screen_X = Target.X * -_nextX + _startX;//取得X軸起點(X,0)座標
            float Screen_Y = Target.X * _nextY + _startY;

            
            Screen_X += Target.Y * _nextX;//加入Y軸偏移
            Screen_Y += Target.Y * _nextY;

            MapBlocks[Target.X][Target.Y].Margin = new Thickness(Screen_X ,Screen_Y ,0 ,0);
        }
Beispiel #35
0
 public Map(int _width, int _height)
 {
     width = _width;
     height = _height;
     lights = new List<Light>();
     mapBlocks = new MapBlock[_width, _height];
     lightMap = new Color[_width, _height];
     for (int i = 0; i < _width; i++)
     {
         for (int j = 0; j < _height; j++)
         {
             mapBlocks[i, j] = new MapBlock(this);
             mapBlocks[i, j].Coordinates = new Coord(i, j);
             lightMap[i, j] = Color.Gray;
         }
     }
     mapZombies = new List<Creature>();
 }
		public override void Fill(MapBlock _block, WorldLayer _layer)
		{
			var rnd = new Random(_block.RandomSeed);

			InDoorWorldCoords = Room.RoomRectangle.Inflate(-1, -1).BorderPoints.ToArray();
			OutDoorWorldCoords = Room.RoomRectangle.BorderPoints.ToArray();

			MapBlockHelper.Fill(_block, rnd, _layer, _layer.DefaultEmptySpaces, Room.AreaRectangle);

		    var graves = EssenceHelper.GetAllThings<Grave>().ToArray();

			foreach (var point in Room.RoomRectangle.AllPoints)
			{
				if (rnd.Next(4) == 0 && !InDoorWorldCoords.Contains(point))
				{
					_block.AddEssence(graves.RandomItem(rnd), point);
				}
			}
		}
Beispiel #37
0
		public virtual void Fill(MapBlock _block, WorldLayer _layer)
		{
			var mapBlock = _block;
			var roomRectangle = Room.RoomRectangle;

			var wall = Walls.ToArray().RandomItem(World.Rnd);
			var floor = Floors.ToArray().RandomItem(World.Rnd);

			foreach (var point in roomRectangle.AllPoints)
			{
				mapBlock.Map[point.X, point.Y] = floor;
			}

			var borderPoints = roomRectangle.BorderPoints.ToArray();
			var cornerPoints = roomRectangle.CornerPoints;
			var i = 0;
			foreach (var point in borderPoints)
			{
				if (cornerPoints.Contains(point))
				{
					mapBlock.Map[point.X, point.Y] = wall.Item1;
				}
				else
				{
					if (i++%3 == 0)
					{
						mapBlock.Map[point.X, point.Y] = wall.Item2;
					}
					else
					{
						mapBlock.Map[point.X, point.Y] = wall.Item1;
					}
				}
			}

			CreateDoor(mapBlock, floor, borderPoints);

			mapBlock.AddEssence(new IndoorLight(new LightSource(10, new FColor(3f, 1f, 1f, 0.5f)), EssenceHelper.GetFirstFoundedMaterial<MetalMaterial>()), roomRectangle.Inflate(-1, -1).Random(World.Rnd));
		}
Beispiel #38
0
	/// <summary>
	/// Gets a random adjacent block allowed with the mask.
	/// </summary>
	/// <param name='mask'>
	/// Binary Or together types which you want allowed.
	/// </param>
	MapBlock GetAdjBlock(MapBlock block, Sector.SectorType mask)
	{
		MapBlock b = null;;
		
		int dir = Random.Range(0,4);
		int num = 0;
		do
		{
			dir++;
			if (dir >= 4) dir = 0;
			
			switch (dir)
			{
			case 0:
				b = WorldToBlock(block.transform.position + new Vector3(1f, 0f, 0f));
				break;
			case 1:
				b = WorldToBlock(block.transform.position + new Vector3(-1f, 0f, 0f));
				break;
			case 2:
				b = WorldToBlock(block.transform.position + new Vector3(0f, 0f, 1f));
				break;
			case 3:
				b = WorldToBlock(block.transform.position + new Vector3(0f, 0f, -1f));
				break;
			}
			
			num++;
		}
		while ((b == null 
			|| (b.SectorType & mask) == 0)
			&& num < 4);
		
		if (b == null 
			|| (b.SectorType & mask) == 0)
			return null;
		
		return b;
	}
Beispiel #39
0
		protected override MapBlock GenerateBlock(Point _blockId)
		{
			var block = new MapBlock(_blockId);
			var rnd = new Random(block.RandomSeed);
			MapBlockHelper.Clear(block, rnd, this, DefaultEmptySpaces);

			const int v = Constants.MAP_BLOCK_SIZE/2 - 2;

			for (var i = 0; i < v; ++i)
			{
				block.Map[i, 0] = ETerrains.STONE_WALL;
				block.Map[0, i] = ETerrains.STONE_WALL;
				block.Map[Constants.MAP_BLOCK_SIZE - 1 - i, 0] = ETerrains.STONE_WALL;
				block.Map[0, Constants.MAP_BLOCK_SIZE - 1 - i] = ETerrains.STONE_WALL;
			}

			block.AddEssence(new OnWallTorch(new LightSource(8, new FColor(5f, 1f, 0, 0)), EDirections.DOWN, EssenceHelper.GetFirstFoundedMaterial<WoodMaterial>()), new Point(1, 1));
			block.AddEssence(new OnWallTorch(new LightSource(8, new FColor(1f, 0f, 1f, 0f)), EDirections.UP, EssenceHelper.GetFirstFoundedMaterial<WoodMaterial>()), new Point(Constants.MAP_BLOCK_SIZE - 1, Constants.MAP_BLOCK_SIZE - 1));
			block.AddEssence(new OnWallTorch(new LightSource(8, new FColor(1f, 0f, 0f, 1f)), EDirections.RIGHT, EssenceHelper.GetFirstFoundedMaterial<WoodMaterial>()), new Point(Constants.MAP_BLOCK_SIZE - 1, 1));
			block.AddEssence(new OnWallTorch(new LightSource(8, new FColor(1f, 1f, 0f, 1f)), EDirections.LEFT, EssenceHelper.GetFirstFoundedMaterial<WoodMaterial>()), new Point(1, Constants.MAP_BLOCK_SIZE - 1));

			{
				var x = rnd.Next(Constants.MAP_BLOCK_SIZE);
				var y = rnd.Next(Constants.MAP_BLOCK_SIZE);
				block.CreaturesAdd(EssenceHelper.GetFirstFoundedCreature<AbstractMonster>(), new Point(x, y));
			}

			block.Map[9, 9] = ETerrains.RED_BRICK_WALL;
			block.Map[10, 9] = ETerrains.RED_BRICK_WINDOW;
			block.Map[11, 9] = ETerrains.RED_BRICK_WALL;
			block.Map[11, 10] = ETerrains.RED_BRICK_WINDOW;
			block.Map[9, 10] = ETerrains.RED_BRICK_WINDOW;
			block.Map[9, 11] = ETerrains.RED_BRICK_WALL;
			block.AddEssence(new ClosedDoor(null), new Point(10, 11));
			block.Map[11, 11] = ETerrains.RED_BRICK_WALL;
			//block.AddLightSource(new Point(10, 10), new LightSource(18, new FColor(53f, 0f, 1f, 1f)));

			return block;
		}
Beispiel #40
0
        private List<MapBlock> OuterBlocksOf(MapBlock center)
        {
            List<MapBlock> blocks = new List<MapBlock>();
            Map map = center.GameMap;
            //blocks.Add(map.GetBlockAt(center.Coordinates.X-1, center.Coordinates.Y+1));
            if (map.IsInMap(center.Coordinates.X-1, center.Coordinates.Y)) {
                blocks.Add(map.GetBlockAt(center.Coordinates.X-1, center.Coordinates.Y));
            }
            if (map.IsInMap(center.Coordinates.X+1, center.Coordinates.Y) ){
                blocks.Add(map.GetBlockAt(center.Coordinates.X+1, center.Coordinates.Y));
            }
            if (map.IsInMap(center.Coordinates.X, center.Coordinates.Y+1) ){
                blocks.Add(map.GetBlockAt(center.Coordinates.X, center.Coordinates.Y+1));
            }
            if (map.IsInMap(center.Coordinates.X, center.Coordinates.Y-1) ){
                blocks.Add(map.GetBlockAt(center.Coordinates.X, center.Coordinates.Y-1));
            }
            //blocks.Add(map.GetBlockAt(center.Coordinates.X-1, center.Coordinates.Y-1));
            //blocks.Add(map.GetBlockAt(center.Coordinates.X+1, center.Coordinates.Y+1));
            //blocks.Add(map.GetBlockAt(center.Coordinates.X+1, center.Coordinates.Y-1));

            return blocks;
        }
Beispiel #41
0
        public static MakeNoiseEvent CreateMakeNoiseEvent(MapBlock mb, int strength)
        {
            MakeNoiseEvent nEvent = new MakeNoiseEvent(mb, strength);
            nEvent.CreateTime = Game.TurnsPassed;
            nEvent.ActivateTime = Game.TurnsPassed + 0;

            return nEvent;
        }
Beispiel #42
0
        int strength; //the stronger the sound, the further it goes

        #endregion Fields

        #region Constructors

        public MakeNoiseEvent(MapBlock nLocation, int nStrength)
        {
            location = nLocation;
            strength = nStrength;
        }
		private static void AddCreatures(MapBlock _block, Random _rnd)
		{
			var itmcnt = 2 + _rnd.Next(_rnd.Next(2));
			for (var i = 0; i < itmcnt; ++i)
			{
				var x = _rnd.Next(Constants.MAP_BLOCK_SIZE);
				var y = _rnd.Next(Constants.MAP_BLOCK_SIZE);

				var attr = TerrainAttribute.GetAttribute(_block.Map[x, y]);
				if (attr.IsPassable)
				{
					var point = new Point(x, y);
					if (_block.Creatures.Values.Contains(point))
					{
						continue;
					}
					
					var creature = (AbstractMonster)EssenceHelper.GetRandomFakedCreature<AbstractMonster>(World.Rnd).Essence.Clone(World.TheWorld.Avatar);

					if (creature.Is<Stair>() && (x == Constants.MAP_BLOCK_SIZE - 1 || y == Constants.MAP_BLOCK_SIZE - 1))
					{
						continue;
					}

					if (!_block.Rooms.Any(_room => _room.RoomRectangle.Contains(point) && _room.IsConnected))
					{
						continue;
					}

					_block.CreaturesAdd(creature, point);
				}
			}
		}
        void InitializeCouchbaseView()
        {
            var view = Database.ViewNamed (DefaultViewName);

            NSObject key = new NSString("created_at");
            var mapBlock = new MapBlock ((doc, aview) => {
                NSObject date  = doc.ObjectForKey (key);
                if (date  != null) {
                    aview.Emit (date, doc);
                }
            });

            view.SetMapBlock (mapBlock, null, "1.1");

            var validationBlock = new ValidationBlock ((revision, context)=>{
                if (revision.IsDeleted) return true;

                NSObject date = revision.Properties.ObjectForKey(key);
                return (date != null);
            });

            Database.DefineValidation ((NSString)key, validationBlock);
        }
Beispiel #45
0
        public List<PathBlock> AStarPath(MapBlock from, MapBlock to, bool willBreakThroughStuff)
        {
            if (!to.Passable)
            {
                //int closestH = 1000;
                foreach (MapBlock mb in to.SurroundingBlocks)
                {
                    PathBlock p = new PathBlock(mb, null);
                    p.CalculateH(from);
                }
            }
            List<PathBlock> pathToTake = new List<PathBlock>(); //final result
            List<PathBlock> openList = new List<PathBlock>(); //possible paths to check
            List<PathBlock> closedList = new List<PathBlock>(); //all spaces that have been checked

            PathBlock first = new PathBlock(from, null);
            first.G = 0;
            first.CalculateH(to);

            openList.Add(new PathBlock(from, null));

            if (from.Equals(to))
            {
                return pathToTake;
            }

            while (openList.Count > 0)
            {
                PathBlock blockToCheck = openList[0];

                if (blockToCheck.AttachedBlock.Equals(to))
                {
                    //path found, work backwards from blockToCheck's parent.
                    //
                    PathBlock backtracker = blockToCheck;
                    while (backtracker.Parent != null)
                    {
                        pathToTake.Insert(0, backtracker);
                        backtracker = backtracker.Parent;
                    }
                    return pathToTake;
                }
                openList.Remove(blockToCheck);
                closedList.Add(blockToCheck);

                foreach (MapBlock mb in blockToCheck.AttachedBlock.SurroundingBlocks)
                {
                    PathBlock p = new PathBlock(mb, blockToCheck);
                    p.G = blockToCheck.G + 1;
                    p.CalculateH(to);

                    //ignore blocks in the closed list and those that aren't passable unless smashy smashy
                    //
                    if (!closedList.Contains(p))
                    {
                        int gScore = blockToCheck.G + 1;
                        if (!mb.Passable) //!passable means a prop is there. That means more time smashing.
                        {
                            gScore += 3;
                        }

                        if (!openList.Contains(p))
                        {
                            bool inserted = false;
                            for (int i = 0; i < openList.Count; i++)
                            {
                                if (openList[i].F > p.F)
                                {
                                    openList.Insert(i, p);
                                    inserted = true;
                                    break;
                                }
                            }
                            if (!inserted)
                            {
                                openList.Add(p);
                            }
                        }
                        else
                        {
                            //if the block is already in the openList, take the one with the lowest G value. If needed, switch the parent and recalculate G.
                            PathBlock blockInList = openList.Find((i) => i.Equals(p));
                            if (p.G < blockInList.G)
                            {
                                openList.Remove(blockInList);
                                bool inserted = false;
                                for (int i = 0; i < openList.Count; i++)
                                {
                                    if (openList[i].F > p.F)
                                    {
                                        openList.Insert(i, p);
                                        inserted = true;
                                        break;
                                    }
                                }
                                if (!inserted)
                                {
                                    openList.Add(p);
                                }
                                //blockInList.G = p.G;
                                //blockInList.Parent = blockToCheck;
                            }
                        }
                    }
                }
            }

            return pathToTake;
        }
Beispiel #46
0
 public override void Move(MapBlock aDestination)
 {
     // check for objects here, etc.
     //
     if (aDestination.Passable)
     {
         iMove(this, aDestination.Coordinates);
         return;
     }
     if (aDestination.CreatureInBlock is Zombie)
     {
         Attack(aDestination.CreatureInBlock);
     }
 }
		private void ConnectTwoRooms(Room _room1, Room _room2, IDictionary<Point, EDirections> _forbid, IDictionary<Point, Connector> _connectors, params Point[] _points)
		{
			var rnd = new Random(m_mazeBlocks[_room1.BlockId].RandomSeed);
			var pnt = _points[0];
			var defEmpty = DefaultEmptySpaces.ToArray();
			Point point = null;
			for (var i = 1; i < _points.Length; ++i)
			{
				var line = pnt.GetLineToPoints(_points[i]).ToArray();
				var border = Util.GetDirection(pnt, _points[i]).GetBorders().ToArray();
				for (var index = 0; index < line.Length; index++)
				{
					if (point == line[index]) continue;
					point = line[index];

					Connector connector;
					if (_connectors.TryGetValue(point, out connector))
					{
						_room1.Connect(connector.Rooms.ToArray());
						connector.Rooms.Add(_room1);

						if (_room2 != null)
						{
							ConnectTwoRooms(_room2, null, _forbid, _connectors, _points.Reverse().ToArray());
						}
						return;
					}
					if (_room2 != null)
					{
						_connectors.Add(point, new Connector(_room1, _room2));
					}
					else
					{
						_connectors.Add(point, new Connector(_room1));
					}
					var inBlock = BaseMapBlock.GetInBlockCoords(point);
					var blockId = BaseMapBlock.GetBlockId(point);

					BaseMapBlock block;
					if (!m_mazeBlocks.TryGetValue(blockId, out block))
					{
						block = new MapBlock(blockId);
						MapBlockHelper.Clear(block, rnd, this, DefaultWalls);
						m_mazeBlocks[blockId] = block;
					}
					block.Map[inBlock.X, inBlock.Y] = defEmpty.RandomItem(rnd);

					if (index != 0 && index < line.Length - 1)
					{
						foreach (var delta in border)
						{
							var borderPnt = point + delta.Key;

							EDirections dir;
							if (!_forbid.TryGetValue(borderPnt, out dir))
							{
								dir = EDirections.DOWN | EDirections.UP | EDirections.LEFT | EDirections.RIGHT;
							}
							_forbid[borderPnt] = dir & delta.Value;
						}
					}
				}
				pnt = _points[i];
			}
			_room1.Connect(_room2);
		}
        void InitializeCouchbaseSummaryView()
        {
            var view = Database.ViewNamed ("Done");

              var mapBlock = new MapBlock ((doc, emit) => {
            var date = doc.ObjectForKey (CreationDatePropertyName);
            var checkedOff = doc.ObjectForKey ((NSString)"check");

            if (date != null) {
              emit (NSArray.FromNSObjects (checkedOff, date), null);
            }
              });

              var reduceBlock = new ReduceBlock ((keys, values, rereduce) => {
            var keyArray = NSArray.FromArray<NSArray> (keys);
            var key = keyArray.Sum(data => 1 - data.GetItem<NSNumber> (0).IntValue);

            var result = new NSMutableDictionary ();
            result.SetValueForKey ((NSString)"Items Remaining", (NSString)"Label");
            result.SetValueForKey ((NSString)key.ToString (), (NSString)"Count");

            return result;
              });

              view.SetMapBlock (mapBlock, reduceBlock, "1.1");
        }
Beispiel #49
0
 public MoveEvent(Creature nMover, MapBlock nDestination)
 {
     mover = nMover;
     destination = nDestination;
 }
Beispiel #50
0
 public PathBlock(MapBlock m, PathBlock p)
 {
     attachedBlock = m;
     parent = p;
     G = 0;
 }
Beispiel #51
0
 /// <summary>
 /// //H is calculated using the Manhattan method - just check the difference in X and Y, then add them together
 /// </summary>
 /// <param name="to">The block to check to.</param>
 public void CalculateH(MapBlock to)
 {
     H = Math.Abs(this.AttachedBlock.Coordinates.X - to.Coordinates.X) +
                      Math.Abs(this.AttachedBlock.Coordinates.Y - to.Coordinates.Y);
 }
Beispiel #52
0
        public static BaseEvent CreateMoveEvent(Creature nMov, MapBlock nDest)
        {
            if (nMov.State != Creature.EntityState.BUSY)
            {
                MoveEvent mEvent = new MoveEvent(nMov, nDest);
                mEvent.CreateTime = Game.TurnsPassed;
                mEvent.ActivateTime = Game.TurnsPassed + 1;

                nMov.State = Creature.EntityState.BUSY;
                return mEvent;
            }
            else
            {
                return EventFactory.CreateEmptyEvent(nMov);
            }
        }
		protected override MapBlock GenerateBlock(Point _blockId)
		{
			BaseMapBlock baseMapBlock;
			if (!m_mazeBlocks.TryGetValue(_blockId, out baseMapBlock))
			{
				var eblock = new MapBlock(_blockId);
				var ernd = new Random(eblock.RandomSeed);
				MapBlockHelper.Clear(eblock, ernd, this, DefaultWalls);
				return eblock;
			}
			var block = new MapBlock(_blockId, baseMapBlock);
			var rnd = new Random(block.RandomSeed);
			AddItems(block, rnd);
			AddCreatures(block, rnd);

			return block;
		}
Beispiel #54
0
        static void WriteBlockClass(TextWriter writer, MapBlock block, MapPacket packet)
        {
            bool variableFields = false;
            bool floatFields = false;

            //writer.WriteLine("        /// <summary>" + block.Name + " block</summary>");
            writer.WriteLine("        /// <exclude/>");
            writer.WriteLine("        [XmlType(\"" + packet.Name.ToLower() + "_" + block.Name.ToLower() + "\")]");
            writer.WriteLine("        public class " + block.Name + "Block" + Environment.NewLine + "        {");

            foreach (MapField field in block.Fields)
            {
                WriteFieldMember(writer, field);

                if (field.Type == FieldType.Variable) { variableFields = true; }
                if (field.Type == FieldType.F32 || field.Type == FieldType.F64) { floatFields = true; }
            }

            // Length property
            writer.WriteLine("");
            //writer.WriteLine("            /// <summary>Length of this block serialized in bytes</summary>");
            writer.WriteLine("            [XmlIgnore]" + Environment.NewLine +
                             "            public int Length" + Environment.NewLine +
                             "            {" + Environment.NewLine + 
                             "                get" + Environment.NewLine +
                             "                {");
            int length = 0;

            // Figure out the length of this block
            foreach (MapField field in block.Fields)
            {
                length += GetFieldLength(writer, field);
            }

            if (!variableFields)
            {
                writer.WriteLine("                    return " + length + ";");
            }
            else
            {
                writer.WriteLine("                    int length = " + length + ";");

                foreach (MapField field in block.Fields)
                {
                    if (field.Type == FieldType.Variable)
                    {
                        writer.WriteLine("                    if (" + field.Name +
                            " != null) { length += " + field.Count + " + " + field.Name + ".Length; }");
                    }
                }

                writer.WriteLine("                    return length;");
            }

            writer.WriteLine("                }" + Environment.NewLine + "            }" + Environment.NewLine);

            // Default constructor
            //writer.WriteLine("            /// <summary>Default constructor</summary>");
            writer.WriteLine("            public " + block.Name + "Block() { }");

            // Constructor for building the class from bytes
            //writer.WriteLine("            /// <summary>Constructor for building the block from a byte array</summary>");
            writer.WriteLine("            public " + block.Name + "Block(byte[] bytes, ref int i)" + Environment.NewLine + 
                "            {");

            // Declare a length variable if we need it for variable fields in this constructor
            if (variableFields) { writer.WriteLine("                int length;"); }

            // Start of the try catch block
            writer.WriteLine("                try" + Environment.NewLine + "                {");

            foreach (MapField field in block.Fields)
            {
                WriteFieldFromBytes(writer, field);
            }

            writer.WriteLine("                }" + Environment.NewLine + 
                "                catch (Exception)" + Environment.NewLine +
                "                {" + Environment.NewLine + 
                "                    throw new MalformedDataException();" + Environment.NewLine +
                "                }" + Environment.NewLine + "            }" + Environment.NewLine);

            // ToBytes() function
            //writer.WriteLine("            /// <summary>Serialize this block to a byte array</summary>");
            writer.WriteLine("            public void ToBytes(byte[] bytes, ref int i)" + Environment.NewLine + 
                "            {");

            // Declare a byte[] variable if we need it for floating point field conversions
            if (floatFields) { writer.WriteLine("                byte[] ba;"); }

            foreach (MapField field in block.Fields)
            {
                WriteFieldToBytes(writer, field);
            }

            writer.WriteLine("            }" + Environment.NewLine);

            // ToString() function
            writer.WriteLine("            public override string ToString()" + Environment.NewLine + "            {");
            writer.WriteLine("                StringBuilder output = new StringBuilder();");
            writer.WriteLine("                output.AppendLine(\"-- " + block.Name + " --\");");

            for (int i = 0; i < block.Fields.Count; i++)
            {
                MapField field = block.Fields[i];

                if (field.Type == FieldType.Variable || field.Type == FieldType.Fixed)
                {
                    writer.WriteLine("                Helpers.FieldToString(output, " + field.Name + ", \"" + field.Name + "\");");
                    if (i != block.Fields.Count - 1) writer.WriteLine("                output.Append(Environment.NewLine);");
                }
                else
                {
                    if (i != block.Fields.Count - 1) writer.WriteLine("                output.AppendLine(String.Format(\"" + field.Name + ": {0}\", " + field.Name + "));");
                    else writer.WriteLine("                output.Append(String.Format(\"" + field.Name + ": {0}\", " + field.Name + "));");
                }
            }

            writer.WriteLine("                return output.ToString();" + Environment.NewLine + "            }");
            writer.WriteLine("        }" + Environment.NewLine);
        }
Beispiel #55
0
	void AddBlockToSector(Sector s, MapBlock b)
	{
		b.sector = s;
		b.transform.parent = s.transform;
		
		if (s.blocks != null)
		{
			MapBlock[] temp = new MapBlock[s.blocks.Length + 1];
			for (int i = 0; i < s.blocks.Length; i++)
				temp[i] = s.blocks[i];
			temp[s.blocks.Length] = b;
			s.blocks = temp;
		}
		else
		{
			s.blocks = new MapBlock[1];
			s.blocks[0] = b;
		}
	}
 public void ClearBlock() {
     this.MapBlocks = new MapBlock[50][];
     for(int i = 0; i < 50; i++) {
         MapBlocks[i] = new MapBlock[50];
     }
 }
		private static void AddItems(MapBlock _block, Random _rnd)
		{
			var itmcnt = 20 + _rnd.Next(_rnd.Next(20));
			for (var i = 0; i < itmcnt; ++i)
			{
				var x = _rnd.Next(Constants.MAP_BLOCK_SIZE);
				var y = _rnd.Next(Constants.MAP_BLOCK_SIZE);

				var attr = TerrainAttribute.GetAttribute(_block.Map[x, y]);
				if (attr.IsPassable)
				{
					var point = new Point(x, y);
					var any = _block.Objects.Where(_tuple => _tuple.Item2 == point).Select(_tuple => _tuple.Item1);
					var thing = EssenceHelper.GetRandomFakedItem(_rnd);

					if (any.Any(_thing => !(_thing is Item)))
					{
						continue;
					}
					
					_block.AddEssence(thing, point);
				}
			}
		}
Beispiel #58
0
 public abstract void GenerateCityBlock(MapBlock _block, Random _rnd, WorldLayer _worldLayer);
        void InitializeCouchbaseView()
        {
            var view = Database.ViewNamed (DefaultViewName);

              var mapBlock = new MapBlock ((doc, emit) => {

            var date = doc.ObjectForKey (CreationDatePropertyName);
            var deleted = doc.ObjectForKey (DeletedKey);

            if (date != null && deleted == null) {
              emit (date, doc);
            }
              });

              view.SetMapBlock (mapBlock, "1.1");

              var validationBlock = new ValidationBlock ((revision, context) => {
            if (revision.IsDeleted)
              return true;

            NSObject date = revision.Properties.ObjectForKey (CreationDatePropertyName);
            return (date != null);
              });

              Database.DefineValidation (CreationDatePropertyName, validationBlock);
        }
        private void ReadNode(ref GbxParser parserd, qint32 classid, int pushdepth)
        {
            GbxClass dclass = new GbxClass();
            Classes.Add(pushdepth, dclass);
            dclass.Id = classid;
            switch (classid)
            {
                case unchecked((int)0x03043000):
                    dclass.Structure = new CGameCtnChallenge();
                    break;
                case unchecked((int)0x03093000):
                    dclass.Structure = new CGameCtnReplayRecord();
                    break;
                case unchecked((int)0x03059000):
                    dclass.Structure = new CGameCtnBlockSkin();
                    break;
                case unchecked((int)0x0313B000):
                    dclass.Structure = new CGameWaypointSpecialProperty();
                    break;
                default:
                    Debug.Log("Can not find a class struct..");
                    break;
            }

            // Parse data section

            while (true)
            {
                GbxChunk dchunk = new GbxChunk();
                oldcid = cid;
                cid = parserd.ReadInt32();
                dchunk.Id = cid;
                // Quit once we see this..
                if (cid == unchecked((int)0xFACADE01))
                    break;

                qint32 skip = parserd.ReadInt32();
                qint32 skipsize = -1;
                dchunk.Skipable = false;
                if (skip == 1397442896)
                {
                    skipsize = parserd.ReadInt32();
                    dchunk.Skipable = true;
                }
                else
                {
                    parserd.position -= 4;
                }
                qint32 start = parserd.position;
                switch (cid)
                {
                    // MAPS //
                    case unchecked((int)0x0304300D):
                        {
                            parserd.ReadStringLB();
                            parserd.ReadStringLB();
                            parserd.ReadStringLB();
                            break;
                        }
                    case unchecked((int)0x03043011):
                        {
                            // NodeReference
                            qint32 nodid = parserd.ReadInt32();
                            if (nodid >= 0 && !Classes.ContainsKey(nodid))
                            {
                                qint32 nodeclassid = parserd.ReadInt32();
                                ReadNode(ref parserd, nodeclassid, nodid);
                            }
                            // NodeReference
                            qint32 nodid2 = parserd.ReadInt32();
                            if (nodid2 >= 0 && !Classes.ContainsKey(nodid2))
                            {
                                qint32 nodeclassid = parserd.ReadInt32();
                                ReadNode(ref parserd, nodeclassid, nodid2);
                            }
                            parserd.ReadInt32();
                            break;
                        }
                    case unchecked((int)0x0301B000):
                        {
                            qint32 itemsct = parserd.ReadInt32();
                            for (int i = 0; i < itemsct; i++)
                            {
                                parserd.ReadStringLB();
                                parserd.ReadStringLB();
                                parserd.ReadStringLB();
                                parserd.ReadInt32();
                            }
                            break;

                        }
                    case unchecked((int)0x0305B000):
                        {
                            //    parserd.Skip(8*4);
                            break;
                        }
                    case unchecked((int)0x0305B001):
                        {
                            parserd.ReadString();
                            parserd.ReadString();
                            parserd.ReadString();
                            parserd.ReadString();
                            break;
                            //} case unchecked((int)0x0305B002): {
                            //} case unchecked((int)0x0305B003): {
                        }
                    case unchecked((int)0x0305B004):
                        {
                            parserd.Skip(5 * 4);
                            break;
                            //} case unchecked((int)0x0305B005): {
                            //} case unchecked((int)0x0305B006): {
                        }
                    case unchecked((int)0x0305B008):
                        {
                            parserd.Skip(2 * 4);
                            break;
                        }
                    case unchecked((int)0x0305B00A):
                        {
                            parserd.Skip(9 * 4);
                            break;
                        }
                    case unchecked((int)0x0305B00D):
                        {
                            parserd.Skip(1 * 4);
                            break;
                        }
                    case unchecked((int)0x0304301F):
                        {
                            // Blocks chunk
                            //if (parserd.position == 344) Debugger.Break();
                            //var pos = parserd.position;
                            var c = dclass.Structure;
                            c.MapUId = parserd.ReadStringLB();
                            c.Environment = parserd.ReadStringLB();
                            c.MapAuthor = parserd.ReadStringLB();
                            c.MapName = parserd.ReadString();
                            c.Mood = parserd.ReadStringLB();
                            c.EnvironmentBackground = parserd.ReadStringLB();
                            c.EnvironmentAuthor = parserd.ReadStringLB();

                            c.MapSizeX = parserd.ReadInt32();
                            c.MapSizeY = parserd.ReadInt32();
                            c.MapSizeZ = parserd.ReadInt32();
                            c.ReqUnlock = parserd.ReadInt32();
                            c.Flags32 = parserd.ReadInt32();
                            int numblocks = parserd.ReadInt32();
                            // Read every single block..
                            bool oneMore = false;
                            for (int i = 0; i < numblocks; i++)
                            {
                                MapBlock block = new MapBlock();
                                mapBlocks.Add(block);
                                block.BlockName = parserd.ReadStringLB();
                                block.Rotation = parserd.ReadByte();
                                block.PositionX = parserd.ReadByte();
                                block.PositionY = parserd.ReadByte();
                                block.PositionZ = parserd.ReadByte();
                                block.Flags = (c.Flags32 > 0) ? parserd.ReadUInt32() : parserd.ReadUInt16();
                                if (block.Flags != 0xFFFFFFFF)
                                    if ((block.Flags & 0x8000) != 0)
                                    {
                                        block.BlockSkinAuthor = parserd.ReadStringLB();
                                        // NodeReference
                                        block.BlockSkin = parserd.ReadInt32();
                                        if (block.BlockSkin >= 0 && !Classes.ContainsKey(block.BlockSkin)) // If not yet read..
                                        {
                                            qint32 cidd = parserd.ReadInt32();
                                            ReadNode(ref parserd, cidd, block.BlockSkin);
                                        }
                                    }
                                if (block.Flags != 0xFFFFFFFF && (block.Flags & 0x100000) != 0)
                                {
                                    // NodeReference
                                    block.BlockParams = parserd.ReadInt32();
                                    if (block.BlockParams >= 0 && !Classes.ContainsKey(block.BlockParams)) // If not yet read..
                                    {
                                        qint32 cidd = parserd.ReadInt32();
                                        ReadNode(ref parserd, cidd, block.BlockParams);
                                    }
                                }
                                c.Blocks.Add(block);
                                if (block.Flags == 0xFFFFFFFF)
                                    i -= 1;
                                if (oneMore)
                                    break;
                                if (i + 1 == numblocks) // We're at the latest block now, check if there could be an undefined block next...
                                {
                                    if (parserd.ReadInt32() == 10)
                                    {
                                        oneMore = true;
                                        i -= 1;
                                    }
                                    parserd.Skip(-4);
                                }
                            }
                            c.Trails = parserd.ReadBytes(12);
                            break;
                        } 
                    case unchecked((int)0x03043022):
                        {
                            parserd.ReadInt32();
                            break;
                        }
                    case unchecked((int)0x03043024):
                        {
                            var c = Classes[-1].Structure;
                            parserd.ReadChar();
                            parserd.Skip(32); // ?
                            c.PMapMusic = parserd.ReadString();
                            c.PMapMusicLoc = parserd.ReadString();
                            break;
                        }
                    case unchecked((int)0x03043025):
                        {
                            parserd.Skip(16); // 2x vec2d, float: 4 bytes
                            break;
                        }
                    case unchecked((int)0x03043026):
                        {
                            qint32 ind = parserd.ReadInt32();
                            if (ind >= 0 && !Classes.ContainsKey(ind))
                            {
                                qint32 cidd = parserd.ReadInt32();
                                ReadNode(ref parserd, cidd, ind);
                            }
                            break;
                        }
                    case unchecked((int)0x03043028):
                        {
                            qint32 p = parserd.ReadInt32();
                            if (p != 0)
                            {
                                parserd.Skip(1 + 4 * 3 * 3 + 4 * 3 + 4 + 4 + 4);
                            }
                            // Ugly temporarily fix, just to show it
                            CGameCtnChallenge_Header c = Classes[-2].Structure;
                            c.PMapComments = parserd.ReadString();
                            break;
                        }
                    case unchecked((int)0x0304302A):
                        {
                            parserd.ReadInt32();
                            break;
                        }
                    case unchecked((int)0x03043049):
                        {
                            // MT stuff
                            // No idea how to parse it so for now just read the rest
                            parserd.ReadBytes((int)(parserd.Length() - parserd.position - 4)); // the rest of the data - 4 (final unchecked((int)0xfacade01) )
                            //return;
                            break;
                        }
                    case unchecked((int)0x03043029):
                        {
                            var c = Classes[-1].Structure;
                            c.PMapPasswordHash = parserd.ReadBytes(16);
                            c.PMapPasswordCrc = parserd.ReadInt32();
                            break;
                        }
                    case unchecked((int)0x03059002):
                        {
                            dclass.StructureName = parserd.ReadString();
                            int version = parserd.ReadChar();
                            if (version != 3)
                                throw new Exception("Please re-save your map in the latest ManiaPlanet version in order to load the map in MapEdit.\nReason: FileReference version is outdated.");
                            parserd.Skip(32); // ?
                            QString a = parserd.ReadString();
                            dclass.Structure.Path = a;
                            //if (a.length() > 0)
                            dclass.Structure.PathLoc = parserd.ReadString();
                            parserd.ReadChar();
                            parserd.Skip(32); // ?
                            QString b = parserd.ReadString();
                            dclass.Structure.LocPath = b;
                            //if (b.length() > 0)
                            dclass.Structure.LocPathLoc = parserd.ReadString();
                            break;
                        }
                    case unchecked((int)0x0313B000):
                        {
                            dclass.Structure.Unknown = parserd.ReadInt32();
                            if (dclass.Structure.Unknown != 2)
                                throw new Exception("Please re-save your map in the latest ManiaPlanet version in order to load the map in MapEdit.\nReason: CGameWaypointSpecialProperty version is outdated.");
                            dclass.Structure.Tag = parserd.ReadString();
                            dclass.Structure.Order = parserd.ReadInt32();
                            break;

                            // REPLAYS //
                        }
                    case unchecked((int)0x03093002):
                        {
                            qint32 size = parserd.ReadInt32();
                            dclass.Structure.mapGbx = parserd.ReadBytes(size);
                            return; // Stop parsing after this part, replays are not fully parsed besides this.

                            // DEFAULT HANDLING //
                        }
                    default:
                        {
                            if (skipsize != -1)
                            {
                                parserd.Skip(skipsize);
                                cid = oldcid;
                            }
                            else
                            {
                                Debug.Log("Unknown chunk id 0x");
                                return; // temporarily
                            }
                            break;
                        }
                }
                dchunk.Data = parserd.GetChars(start, parserd.position - start);
                dclass.Chunks.Add(dchunk);
            }
        }