public TileScene(TileSet tileSet, Point[,] mapIndices, int depth = 0)
 {
     this.tileSet = tileSet;
     this.mapIndices = mapIndices;
     this.depth = depth;
     sprites = null;
 }
Beispiel #2
0
        public Theater(TileSet tileset)
        {
            var allocated = false;
            Func<Sheet> allocate = () =>
            {
                if (allocated)
                    throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter.");
                allocated = true;

                return new Sheet(new Size(tileset.SheetSize, tileset.SheetSize), true);
            };

            sheetBuilder = new SheetBuilder(SheetType.Indexed, allocate);
            templates = new Dictionary<ushort, Sprite[]>();

            var frameCache = new FrameCache(Game.modData.SpriteLoaders, tileset.Extensions);
            foreach (var t in tileset.Templates)
            {
                var allFrames = frameCache[t.Value.Image];
                var frames = t.Value.Frames != null ? t.Value.Frames.Select(f => allFrames[f]).ToArray() : allFrames;
                templates.Add(t.Value.Id, frames.Select(f => sheetBuilder.Add(f)).ToArray());
            }

            // 1x1px transparent tile
            missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1));

            Sheet.ReleaseBuffer();
        }
		protected override string GetSpriteSrc(ModData modData, TileSet tileSet, string sequence, string animation, string sprite, Dictionary<string, MiniYaml> d)
		{
			var loader = (TilesetSpecificSpriteSequenceLoader)Loader;

			var spriteName = sprite ?? sequence;

			if (LoadField<bool>(d, "UseTilesetCode", false))
			{
				string code;
				if (loader.TilesetCodes.TryGetValue(ResolveTilesetId(tileSet, d), out code))
					spriteName = spriteName.Substring(0, 1) + code + spriteName.Substring(2, spriteName.Length - 2);
			}

			if (LoadField<bool>(d, "AddExtension", true))
			{
				var useTilesetExtension = LoadField<bool>(d, "UseTilesetExtension", false);

				string tilesetExtension;
				if (useTilesetExtension && loader.TilesetExtensions.TryGetValue(ResolveTilesetId(tileSet, d), out tilesetExtension))
					return spriteName + tilesetExtension;

				return spriteName + loader.DefaultSpriteExtension;
			}

			return spriteName;
		}
Beispiel #4
0
 public Layer(TileSet tileset, string data, int currentLayerID, int width, int height)
 {
     this._tileset = tileset;
     this._data = data.Split (',');
     this._currentLayerID = currentLayerID;
     this._width = width;
     this._height = height;
 }
 protected TerrainTemplatePreviewWidget(TerrainTemplatePreviewWidget other)
     : base(other)
 {
     worldRenderer = other.worldRenderer;
     tileset = other.worldRenderer.World.Map.Rules.TileSet;
     Template = other.Template;
     GetScale = other.GetScale;
 }
Beispiel #6
0
        public static Bitmap TerrainBitmap(TileSet tileset, Map map, bool actualSize = false)
        {
            var isDiamond = map.TileShape == TileShape.Diamond;
            var b = map.Bounds;

            // Fudge the heightmap offset by adding as much extra as we need / can.
            // This tries to correct for our incorrect assumption that MPos == PPos
            var heightOffset = Math.Min(map.MaximumTerrainHeight, map.MapSize.Y - b.Bottom);
            var width = b.Width;
            var height = b.Height + heightOffset;

            var bitmapWidth = width;
            if (isDiamond)
                bitmapWidth = 2 * bitmapWidth - 1;

            if (!actualSize)
                bitmapWidth = height = Exts.NextPowerOf2(Math.Max(bitmapWidth, height));

            var terrain = new Bitmap(bitmapWidth, height);

            var bitmapData = terrain.LockBits(terrain.Bounds(),
                ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            var mapTiles = map.MapTiles.Value;

            unsafe
            {
                var colors = (int*)bitmapData.Scan0;
                var stride = bitmapData.Stride / 4;
                for (var y = 0; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        var uv = new MPos(x + b.Left, y + b.Top);
                        var type = tileset.GetTileInfo(mapTiles[uv]);
                        var leftColor = type != null ? type.LeftColor : Color.Black;

                        if (isDiamond)
                        {
                            // Odd rows are shifted right by 1px
                            var dx = uv.V & 1;
                            var rightColor = type != null ? type.RightColor : Color.Black;
                            if (x + dx > 0)
                                colors[y * stride + 2 * x + dx - 1] = leftColor.ToArgb();

                            if (2 * x + dx < stride)
                                colors[y * stride + 2 * x + dx] = rightColor.ToArgb();
                        }
                        else
                            colors[y * stride + x] = leftColor.ToArgb();
                    }
                }
            }

            terrain.UnlockBits(bitmapData);
            return terrain;
        }
Beispiel #7
0
        public TileSetRenderer(TileSet tileset, Size tileSize)
        {
            this.TileSet = tileset;
            this.TileSize = Math.Min(tileSize.Width, tileSize.Height);

            templates = new Dictionary<ushort, List<byte[]>>();
            var sourceCache = new Dictionary<string, ISpriteSource>();
            foreach (var t in TileSet.Templates)
                templates.Add(t.Key, LoadTemplate(t.Value.Image, tileset.Extensions, sourceCache, t.Value.Frames));
        }
Beispiel #8
0
		public Theater(TileSet tileset)
		{
			this.tileset = tileset;
			var allocated = false;
			var type = tileset.EnableDepth ? SheetType.DualIndexed : SheetType.Indexed;

			Func<Sheet> allocate = () =>
			{
				if (allocated)
					throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter.");
				allocated = true;

				return new Sheet(type, new Size(tileset.SheetSize, tileset.SheetSize));
			};

			sheetBuilder = new SheetBuilder(type, allocate);
			random = new MersenneTwister();

			var frameCache = new FrameCache(Game.ModData.SpriteLoaders);
			foreach (var t in tileset.Templates)
			{
				var variants = new List<Sprite[]>();

				foreach (var i in t.Value.Images)
				{
					var allFrames = frameCache[i];
					var frameCount = tileset.EnableDepth ? allFrames.Length / 2 : allFrames.Length;
					var indices = t.Value.Frames != null ? t.Value.Frames : Enumerable.Range(0, frameCount);
					variants.Add(indices.Select(j =>
					{
						var f = allFrames[j];
						var s = sheetBuilder.Allocate(f.Size, f.Offset);
						Util.FastCopyIntoChannel(s, 0, f.Data);

						if (tileset.EnableDepth)
							Util.FastCopyIntoChannel(s, 1, allFrames[j + frameCount].Data);

						return s;
					}).ToArray());
				}

				var allSprites = variants.SelectMany(s => s);

				// Ignore the offsets baked into R8 sprites
				if (tileset.IgnoreTileSpriteOffsets)
					allSprites = allSprites.Select(s => new Sprite(s.Sheet, s.Bounds, float2.Zero, s.Channel, s.BlendMode));

				templates.Add(t.Value.Id, new TheaterTemplate(allSprites.ToArray(), variants.First().Count(), t.Value.Images.Length));
			}

			// 1x1px transparent tile
			missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1));

			Sheet.ReleaseBuffer();
		}
Beispiel #9
0
		// Add the static resources defined in the map; if the map lives
		// in a world use AddCustomTerrain instead
		static Bitmap AddStaticResources(TileSet tileset, Map map, Ruleset resourceRules, Bitmap terrainBitmap)
		{
			var terrain = new Bitmap(terrainBitmap);
			var isRectangularIsometric = map.Grid.Type == MapGridType.RectangularIsometric;
			var b = map.Bounds;

			// Fudge the heightmap offset by adding as much extra as we need / can
			// This tries to correct for our incorrect assumption that MPos == PPos
			var heightOffset = Math.Min(map.Grid.MaximumTerrainHeight, map.MapSize.Y - b.Bottom);
			var width = b.Width;
			var height = b.Height + heightOffset;

			var resources = resourceRules.Actors["world"].TraitInfos<ResourceTypeInfo>()
				.ToDictionary(r => r.ResourceType, r => r.TerrainType);

			var bitmapData = terrain.LockBits(terrain.Bounds(),
				ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

			unsafe
			{
				var colors = (int*)bitmapData.Scan0;
				var stride = bitmapData.Stride / 4;
				for (var y = 0; y < height; y++)
				{
					for (var x = 0; x < width; x++)
					{
						var uv = new MPos(x + b.Left, y + b.Top);
						if (map.MapResources.Value[uv].Type == 0)
							continue;

						string res;
						if (!resources.TryGetValue(map.MapResources.Value[uv].Type, out res))
							continue;

						var color = tileset[tileset.GetTerrainIndex(res)].Color.ToArgb();
						if (isRectangularIsometric)
						{
							// Odd rows are shifted right by 1px
							var dx = uv.V & 1;
							if (x + dx > 0)
								colors[y * stride + 2 * x + dx - 1] = color;

							if (2 * x + dx < stride)
								colors[y * stride + 2 * x + dx] = color;
						}
						else
							colors[y * stride + x] = color;
					}
				}
			}

			terrain.UnlockBits(bitmapData);

			return terrain;
		}
Beispiel #10
0
        public static Bitmap RenderGrid(TileSet tileSet, Palette palette, TileGrid tileGrid, bool transparent)
        {
            Bitmap bitmap = new Bitmap(tileGrid.Width * tileGrid.TileWidth, tileGrid.Height * tileGrid.TileHeight,
                PixelFormat.Format32bppArgb);

            BitmapData canvas = bitmap.LockBits();
            RenderGrid(canvas, 0, 0, tileSet, palette, tileGrid, transparent);
            bitmap.UnlockBits(canvas);

            return bitmap;
        }
Beispiel #11
0
		public void Bind(Map m, TileSet ts, TileSetRenderer tsr, IPalette p, IPalette pp)
		{
			Map = m;
			TileSet = ts;
			TileSetRenderer = tsr;
			Palette = p;
			PlayerPalette = pp;
			playerPalettes = null;
			Chunks.Clear();
			currentTool = null;
		}
Beispiel #12
0
 public void init(string mapName, int mapWidth, int mapHeight, int chunkSize, int tileSize, TileSet tileSet, IEnumerable<Tile> tileList, Sprite background)
 {
     this.mapName = mapName;
     this.mapWidth = mapWidth;
     this.mapHeight = mapHeight;
     this.chunkSize = chunkSize;
     this.tileSize = tileSize;
     this.tileSet = tileSet;
     this.tiles = tileList.ToArray();
     this.backgroundImage = background;
 }
 public TileLayer(string _layerName, string _layerData, int _layerWidth, int _layerHeight, TileSet _myTileSet, int _currentLayer, GameObject _root)
 {
     layerName = _layerName.Trim();
     layerData = _layerData.Split(',');
     layerWidth = _layerWidth;
     layerHeight = _layerHeight;
     layerTileSet = _myTileSet;
     currentLayer = _currentLayer;
     myTextureLocation = _myTileSet.ImageSource.TrimStart('.');
     rootObject = _root;
 }
 public void Refresh()
 {
     TileSet tileset = Linker.Tilesets[0];
     if (Architect.MapLoaded && selectedTileset != tileset)
     {
         clearTilesetButtons();
         selectedTileset = tileset;
         showTileset();
         selectTile(0);
     }
 }
Beispiel #15
0
        public Creature(TileSet animationTile)
        {
            animations = new Dictionary<Direction, Animation>(4);
            facing = Direction.Down;

            animations.Add(Direction.Up, new Animation(animationTile, 500, 2,6,10));
            animations.Add(Direction.Down, new Animation(animationTile, 500, 0, 4, 8));
            animations.Add(Direction.Left, new Animation(animationTile, 500, 1, 5, 9));
            animations.Add(Direction.Right, new Animation(animationTile, 500, 3, 7, 11));

            Abilities = new Collection<Ability>();
        }
Beispiel #16
0
 public void CreatePlatform(int width, Vector3 position, TileSet tileSet)
 {
     this.width = width;
     transform.position = position;
     this.tileSet = tileSet;
     actualWidth = width*tileSet.tileWidth;
     boxCollider.size = new Vector2(actualWidth,tileSet.tileHeight);
     boxCollider.sharedMaterial = tileSet.physicsMaterial;
     SetSprites();
     if(tileSet.HasPlatformDecorations)
         Decorate();
 }
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="node">XmlNode handle</param>
		public DecorationSetForm(XmlNode node)
		{
			InitializeComponent();

			LastMousePosition = Control.MousePosition;

			BgTileSet = new TileSet();

			DecorationSet = new DecorationSet();
			DecorationSet.Load(node);
			ChangeDecorationId(0);
		}
Beispiel #18
0
        public TileSetRenderer(TileSet tileset, Size tileSize)
        {
            this.TileSet = tileset;
            this.TileSize = Math.Min(tileSize.Width, tileSize.Height);

            templates = new Dictionary<ushort, byte[][]>();
            var frameCache = new FrameCache(Game.modData.SpriteLoaders, tileset.Extensions);
            foreach (var t in tileset.Templates)
            {
                var allFrames = frameCache[t.Value.Image];
                var frames = t.Value.Frames != null ? t.Value.Frames.Select(f => allFrames[f]).ToArray() : allFrames;
                templates.Add(t.Value.Id, frames.Select(f => ExtractSquareTile(f)).ToArray());
            }
        }
		string ResolveTilesetId(TileSet tileSet, Dictionary<string, MiniYaml> d)
		{
			var tsId = tileSet.Id;

			MiniYaml yaml;
			if (d.TryGetValue("TilesetOverrides", out yaml))
			{
				var tsNode = yaml.Nodes.FirstOrDefault(n => n.Key == tsId);
				if (tsNode != null)
					tsId = tsNode.Value.Value;
			}

			return tsId;
		}
Beispiel #20
0
		public void Bind(Map m, TileSet ts, TileSetRenderer tsr, IPalette p, IPalette pp)
		{
			Map = m;
			if (m != null)
				Actors = m.ActorDefinitions.ToDictionary(n => n.Key, n => new ActorReference(n.Value.Value, n.Value.ToDictionary()));

			TileSet = ts;
			TileSetRenderer = tsr;
			Palette = p;
			PlayerPalette = pp;
			playerPalettes = null;
			Chunks.Clear();
			currentTool = null;
		}
Beispiel #21
0
        /// <summary>
        /// Initializes an new instance of TileEditControl with a given TileSet
        /// </summary>
        /// <param name="target">Tileset given via parameter</param>
        public CtrlTileEditControl(TileSet target)
        {
            this.RunStartUpMethods();

            // open directly with given Tileset
            // reset all the controls
            this.UncheckButtons();

            // fill tilegrid with tileset
            this.GridView.Fill(this.TargetTile);

            // check type-button and set info text
            this.CheckTypeButton(this.TargetTile.GetID);
        }
Beispiel #22
0
        /// <summary>
        /// Initializes a new instance of SourceGridView
        /// This is the source tileset. Changes here won´t be saved
        /// </summary>
        public CtrlSourceGridView(TileSet sourceTile)
        {
            #region Initialize Member

            #endregion

            #region Initialize GridView
            this.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
            this.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
            this.BackgroundColor = System.Drawing.Color.White;
            this.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
            this.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            #endregion
        }
Beispiel #23
0
        public static void RenderGrid(BitmapData canvas, int x, int y, TileSet tileSet, Palette palette, TileGrid tileGrid,
            bool transparent)
        {
            for (int ty = 0; ty < tileGrid.Height; ty++)
            {
                for (int tx = 0; tx < tileGrid.Width; tx++)
                {
                    TileProperties properties = tileGrid[tx, ty];

                    RenderTile(canvas, x + (tx * tileGrid.TileWidth), y + (ty * tileGrid.TileHeight), tileSet[properties.TileIndex],
                        palette, properties.PaletteIndex, properties.FlipX, properties.FlipY, transparent);
                }
            }
        }
        public World( Game game )
            : base(game)
        {
            input = new InputManager ( game );
            content = new ContentManager ( game.Services );
            content.RootDirectory = "Content";

            tiles = new TileSet ( 5, 5 );

            for ( int i = 0; i < tiles.sizeX; i++ ) {
                for ( int j = 0; j < tiles.sizeY; j++ ) {
                    tiles[ i, j ] = new Tile ( Tile.Type.grass, i, j );
                }
            }

            hero = new Hero ( tiles[ 0, 0 ], "hero" );
        }
        public TileRepository(string filename)
        {
            isSolid[0] = false;

            LoadingScreenForm loadingScreen = new LoadingScreenForm();
            loadingScreen.setSubject("tileset");
            loadingScreen.setMax(100);
            loadingScreen.Show();
            loadingScreen.Refresh();

            if (!File.Exists(filename)) throw new ArgumentException("Tile file not found");

            String basePath = System.IO.Path.GetDirectoryName(filename);

            tileset = new TileSet();
            tileset.Parse(filename);

            // append a TileGroup (misc) with all tiles that are not yet in a TileGroup
            TileGroup miscTiles = new TileGroup();
            foreach (Tile tile in tileset.Tiles) {
                if (tile == null) continue;
                bool found = false;
                foreach (TileGroup tileGroup in tileset.TileGroups) {
                    if (tileGroup.Tiles.Contains(tile.ID)) found = true;
                }
                if (found) continue;
                miscTiles.Name = "(misc)";
                miscTiles.Tiles.Add(tile.ID);
            }
            tileset.TileGroups.Add(miscTiles);

            loadingScreen.setMax(tileset.Tiles.Count);

            int progress = 0;
            foreach (Tile tile in tileset.Tiles) {
                progress++;
                if (tile == null) continue;

                addTile(tile, basePath);

                loadingScreen.setProgress(progress);
            }

            loadingScreen.Close();
        }
Beispiel #26
0
        public Theater(TileSet tileset)
        {
            this.tileset = tileset;
            var allocated = false;
            Func<Sheet> allocate = () =>
            {
                if (allocated)
                    throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter.");
                allocated = true;

                return new Sheet(new Size(tileset.SheetSize, tileset.SheetSize));
            };

            sheetBuilder = new SheetBuilder(SheetType.Indexed, allocate);
            random = new MersenneTwister();

            var frameCache = new FrameCache(Game.ModData.SpriteLoaders);
            foreach (var t in tileset.Templates)
            {
                var variants = new List<Sprite[]>();

                foreach (var i in t.Value.Images)
                {
                    var allFrames = frameCache[i];
                    var frames = t.Value.Frames != null ? t.Value.Frames.Select(f => allFrames[f]).ToArray() : allFrames;
                    variants.Add(frames.Select(f => sheetBuilder.Add(f)).ToArray());
                }

                var allSprites = variants.SelectMany(s => s);

                // Ignore the offsets baked into R8 sprites
                if (tileset.IgnoreTileSpriteOffsets)
                    allSprites = allSprites.Select(s => new Sprite(s.Sheet, s.Bounds, float2.Zero, s.Channel, s.BlendMode));

                templates.Add(t.Value.Id, new TheaterTemplate(allSprites.ToArray(), variants.First().Count(), t.Value.Images.Length));
            }

            // 1x1px transparent tile
            missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1));

            Sheet.ReleaseBuffer();
        }
Beispiel #27
0
        public static void On_Map_Created(Map self, TileSet set)
        {
            if (DataChanged)
                return;

            //var f = typeof(Map).GetFields(BindingFlags.Instance | BindingFlags.NonPublic).Single(field => field.FieldType == typeof(MaterialProperty[]));

            //var items = GnomanEmpire.Instance.Fortress.StockManager.ItemsByItemID(ItemID.RawHide);

            //var mats = (MaterialProperty[])f.GetValue(GnomanEmpire.Instance.Map);

            //mats.ToArray();
            //items.ToString();

            //var state = new Microsoft.Xna.Framework.Graphics.DepthStencilState();
            //state.DepthBufferFunction = Microsoft.Xna.Framework.Graphics.CompareFunction.Less;
            //state.DepthBufferWriteEnable =
            var bla = new List<MapCell>();
            DataChanged = true;
        }
Beispiel #28
0
        public Theater(TileSet tileset)
        {
            var allocated = false;
            Func<Sheet> allocate = () =>
            {
                if (allocated)
                    throw new SheetOverflowException("Terrain sheet overflow. Try increasing the tileset SheetSize parameter.");
                allocated = true;

                return new Sheet(new Size(tileset.SheetSize, tileset.SheetSize));
            };

            var sourceCache = new Dictionary<string, ISpriteSource>();
            templates = new Dictionary<ushort, Sprite[]>();
            sheetBuilder = new SheetBuilder(SheetType.Indexed, allocate);
            foreach (var t in tileset.Templates)
                templates.Add(t.Value.Id, LoadTemplate(t.Value.Image, tileset.Extensions, sourceCache, t.Value.Frames));

            // 1x1px transparent tile
            missingTile = sheetBuilder.Add(new byte[1], new Size(1, 1));
        }
Beispiel #29
0
        public void Run(ModData modData, string[] args)
        {
            // HACK: The engine code assumes that Game.modData is set.
            Game.ModData = modData;

            var failed = false;
            modData.SpriteSequenceLoader.OnMissingSpriteError = s => { Console.WriteLine("\t" + s); failed = true; };

            foreach (var t in modData.Manifest.TileSets)
            {
                var ts = new TileSet(modData.DefaultFileSystem, t);
                Console.WriteLine("Tileset: " + ts.Name);
                var sc = new SpriteCache(modData.DefaultFileSystem, modData.SpriteLoaders, new SheetBuilder(SheetType.Indexed));
                var nodes = MiniYaml.Merge(modData.Manifest.Sequences.Select(s => MiniYaml.FromStream(modData.DefaultFileSystem.Open(s))));
                foreach (var n in nodes)
                    modData.SpriteSequenceLoader.ParseSequences(modData, ts, sc, n);
            }

            if (failed)
                Environment.Exit(1);
        }
		public void Run(ModData modData, string[] args)
		{
			// HACK: The engine code assumes that Game.modData is set.
			Game.ModData = modData;
			GlobalFileSystem.LoadFromManifest(Game.ModData.Manifest);
			Game.ModData.SpriteSequenceLoader.OnMissingSpriteError = s => Console.WriteLine("\t" + s);

			foreach (var t in Game.ModData.Manifest.TileSets)
			{
				var ts = new TileSet(Game.ModData, t);
				Console.WriteLine("Tileset: " + ts.Name);
				var sc = new SpriteCache(modData.SpriteLoaders, new SheetBuilder(SheetType.Indexed));
				var sequenceFiles = modData.Manifest.Sequences;

				var nodes = sequenceFiles
					.Select(s => MiniYaml.FromFile(s))
					.Aggregate(MiniYaml.MergeLiberal);

				foreach (var n in nodes)
					Game.ModData.SpriteSequenceLoader.ParseSequences(Game.ModData, ts, sc, n);
			}
		}
 public GrantConditionOnTerrain(ActorInitializer init, GrantConditionOnTerrainInfo info)
 {
     this.info = info;
     tileSet   = init.World.Map.Rules.TileSet;
 }
Beispiel #32
0
        private void LevelList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _ignoreChanges = true;
            if (LevelList.SelectedItem is LevelInfo)
            {
                PSwitchSection.IsEnabled      = IceballSection.IsEnabled = FireballSection.IsEnabled = true;
                TileDefinitions.Visibility    = LevelTileSection.Visibility = Visibility.Visible;
                MapTileDefinitions.Visibility = MapTileSection.Visibility = Visibility.Collapsed;

                LevelInfo levelInfo = (LevelInfo)LevelList.SelectedItem;
                _currentLevel = _levelService.LoadLevel(levelInfo);
                _currentWorld = null;

                Tile[]  staticTiles   = _graphicsService.GetTileSection(_currentLevel.StaticTileTableIndex);
                Tile[]  animatedTiles = _graphicsService.GetTileSection(_currentLevel.AnimationTileTableIndex);
                Palette palette       = _palettesService.GetPalette(_currentLevel.PaletteId);

                _graphicsAccessor.SetBottomTable(animatedTiles);
                _graphicsAccessor.SetTopTable(staticTiles);

                _localTileSet = JsonConvert.DeserializeObject <TileSet>(JsonConvert.SerializeObject(_tileService.GetTileSet(_currentLevel.TileSetIndex)));

                _ignoreChanges = false;
                _graphicsSetRenderer.Update(palette);
                BlockSelector.Update(tileSet: _localTileSet, palette: palette, withProjectileInteractions: false);
                UpdateGraphics();
                UpdateTileBlock();
                LoadInteractions();
            }
            else if (LevelList.SelectedItem is WorldInfo)
            {
                PSwitchSection.IsEnabled      = IceballSection.IsEnabled = FireballSection.IsEnabled = false;
                TileDefinitions.Visibility    = LevelTileSection.Visibility = Visibility.Collapsed;
                MapTileDefinitions.Visibility = MapTileSection.Visibility = Visibility.Visible;

                if (MapInteractionList.SelectedIndex == -1)
                {
                    MapInteractionList.SelectedIndex = 0;
                }

                WorldInfo worldInfo = (WorldInfo)LevelList.SelectedItem;
                _currentWorld = _worldService.LoadWorld(worldInfo);
                _currentLevel = null;

                Tile[]  staticTiles   = _graphicsService.GetTileSection(_currentWorld.TileTableIndex);
                Tile[]  animatedTiles = _graphicsService.GetTileSection(_currentWorld.AnimationTileTableIndex);
                Palette palette       = _palettesService.GetPalette(_currentWorld.PaletteId);

                _graphicsAccessor.SetBottomTable(staticTiles);
                _graphicsAccessor.SetTopTable(animatedTiles);

                _localTileSet = JsonConvert.DeserializeObject <TileSet>(JsonConvert.SerializeObject(_tileService.GetTileSet(0)));
                _graphicsSetRenderer.Update(palette);

                _ignoreChanges = false;

                _graphicsSetRenderer.Update(palette);
                BlockSelector.Update(tileSet: _localTileSet, palette: palette, withProjectileInteractions: false);
                UpdateGraphics();
                UpdateTileBlock();
            }
        }
Beispiel #33
0
 public int CalculateTilesetMovementClass(TileSet tileset)
 {
     // collect our ability to cross *all* terraintypes, in a bitvector
     return(TilesetTerrainInfo[tileset].Select(ti => ti.Cost < short.MaxValue).ToBits());
 }
        public SequenceCache(ModData modData, TileSet tileSet)
        {
            this.modData = modData;

            spriteLoader = Exts.Lazy(() => new SpriteLoader(tileSet.Extensions, new SheetBuilder(SheetType.Indexed)));
        }
Beispiel #35
0
 public void SetActiveTileSet(TileSet newTileSet)
 {
     _tileSet = newTileSet;
 }
Beispiel #36
0
        // Add the static resources defined in the map; if the map lives
        // in a world use AddCustomTerrain instead
        static Bitmap AddStaticResources(TileSet tileset, Map map, Ruleset resourceRules, Bitmap terrainBitmap)
        {
            var terrain = new Bitmap(terrainBitmap);
            var isRectangularIsometric = map.Grid.Type == MapGridType.RectangularIsometric;
            var b = map.Bounds;

            // Fudge the heightmap offset by adding as much extra as we need / can
            // This tries to correct for our incorrect assumption that MPos == PPos
            var heightOffset = Math.Min(map.Grid.MaximumTerrainHeight, map.MapSize.Y - b.Bottom);
            var width        = b.Width;
            var height       = b.Height + heightOffset;

            var resources = resourceRules.Actors["world"].TraitInfos <ResourceTypeInfo>()
                            .ToDictionary(r => r.ResourceType, r => r.TerrainType);

            var bitmapData = terrain.LockBits(terrain.Bounds(),
                                              ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            unsafe
            {
                var colors = (int *)bitmapData.Scan0;
                var stride = bitmapData.Stride / 4;
                for (var y = 0; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        var uv = new MPos(x + b.Left, y + b.Top);
                        if (map.MapResources.Value[uv].Type == 0)
                        {
                            continue;
                        }

                        string res;
                        if (!resources.TryGetValue(map.MapResources.Value[uv].Type, out res))
                        {
                            continue;
                        }

                        var color = tileset[tileset.GetTerrainIndex(res)].Color.ToArgb();
                        if (isRectangularIsometric)
                        {
                            // Odd rows are shifted right by 1px
                            var dx = uv.V & 1;
                            if (x + dx > 0)
                            {
                                colors[y * stride + 2 * x + dx - 1] = color;
                            }

                            if (2 * x + dx < stride)
                            {
                                colors[y * stride + 2 * x + dx] = color;
                            }
                        }
                        else
                        {
                            colors[y * stride + x] = color;
                        }
                    }
                }
            }

            terrain.UnlockBits(bitmapData);

            return(terrain);
        }
Beispiel #37
0
        public DefaultSpriteSequence(ModData modData, TileSet tileSet, SpriteCache cache, ISpriteSequenceLoader loader, string sequence, string animation, MiniYaml info)
        {
            Name   = animation;
            Loader = loader;
            var d = info.ToDictionary();

            try
            {
                Start         = LoadField <int>(d, "Start", 0);
                ShadowStart   = LoadField <int>(d, "ShadowStart", -1);
                ShadowZOffset = LoadField <WRange>(d, "ShadowZOffset", DefaultShadowSpriteZOffset).Range;
                ZOffset       = LoadField <WRange>(d, "ZOffset", WRange.Zero).Range;
                Tick          = LoadField <int>(d, "Tick", 40);
                transpose     = LoadField <bool>(d, "Transpose", false);
                Frames        = LoadField <int[]>(d, "Frames", null);

                Facings = LoadField <int>(d, "Facings", 1);
                if (Facings < 0)
                {
                    reverseFacings = true;
                    Facings        = -Facings;
                }

                var offset    = LoadField <float2>(d, "Offset", float2.Zero);
                var blendMode = LoadField <BlendMode>(d, "BlendMode", BlendMode.Alpha);

                // Apply offset to each sprite in the sequence
                // Different sequences may apply different offsets to the same frame
                var src = GetSpriteSrc(modData, tileSet, sequence, animation, info.Value, d);
                sprites = cache[src].Select(
                    s => new Sprite(s.Sheet, s.Bounds, s.Offset + offset, s.Channel, blendMode)).ToArray();

                MiniYaml length;
                if (d.TryGetValue("Length", out length) && length.Value == "*")
                {
                    Length = sprites.Length - Start;
                }
                else
                {
                    Length = LoadField <int>(d, "Length", 1);
                }

                // Plays the animation forwards, and then in reverse
                if (LoadField <bool>(d, "Reverses", false))
                {
                    var frames = Frames ?? Exts.MakeArray(Length, i => Start + i);
                    Frames = frames.Concat(frames.Skip(1).Take(frames.Length - 2).Reverse()).ToArray();
                    Length = 2 * Length - 2;
                }

                Stride = LoadField <int>(d, "Stride", Length);

                if (Length > Stride)
                {
                    throw new InvalidOperationException(
                              "{0}: Sequence {1}.{2}: Length must be <= stride"
                              .F(info.Nodes[0].Location, sequence, animation));
                }

                if (Start < 0 || Start + Facings * Stride > sprites.Length)
                {
                    throw new InvalidOperationException(
                              "{6}: Sequence {0}.{1} uses frames [{2}..{3}] of SHP `{4}`, but only 0..{5} actually exist"
                              .F(sequence, animation, Start, Start + Facings * Stride - 1, src, sprites.Length - 1,
                                 info.Nodes[0].Location));
                }

                if (ShadowStart + Facings * Stride > sprites.Length)
                {
                    throw new InvalidOperationException(
                              "{6}: Sequence {0}.{1}'s shadow frames use frames [{2}..{3}] of SHP `{4}`, but only [0..{5}] actually exist"
                              .F(sequence, animation, ShadowStart, ShadowStart + Facings * Stride - 1, src, sprites.Length - 1,
                                 info.Nodes[0].Location));
                }
            }
            catch (FormatException f)
            {
                throw new FormatException("Failed to parse sequences for {0}.{1} at {2}:\n{3}".F(sequence, animation, info.Nodes[0].Location, f));
            }
        }
Beispiel #38
0
 protected virtual string GetSpriteSrc(ModData modData, TileSet tileSet, string sequence, string animation, string sprite, Dictionary <string, MiniYaml> d)
 {
     return(sprite ?? sequence);
 }
 public TerrainTemplatePreviewWidget(WorldRenderer worldRenderer, World world)
 {
     this.worldRenderer = worldRenderer;
     tileset            = world.Map.Rules.TileSet;
 }
Beispiel #40
0
 public RasterSource(string id, TileSet tileSet, int tileSize = DEFAULT_TILE_SIZE)
 {
     Id       = id;
     TileSet  = tileSet;
     TileSize = tileSize;
 }
Beispiel #41
0
        public DefaultSpriteSequence(ModData modData, TileSet tileSet, SpriteCache cache, ISpriteSequenceLoader loader, string sequence, string animation, MiniYaml info)
        {
            this.sequence = sequence;
            Name          = animation;
            Loader        = loader;
            var d = info.ToDictionary();

            try
            {
                Start                 = LoadField(d, "Start", 0);
                ShadowStart           = LoadField(d, "ShadowStart", -1);
                ShadowZOffset         = LoadField(d, "ShadowZOffset", DefaultShadowSpriteZOffset).Length;
                ZOffset               = LoadField(d, "ZOffset", WDist.Zero).Length;
                ZRamp                 = LoadField(d, "ZRamp", 0);
                Tick                  = LoadField(d, "Tick", 40);
                transpose             = LoadField(d, "Transpose", false);
                Frames                = LoadField <int[]>(d, "Frames", null);
                useClassicFacingFudge = LoadField(d, "UseClassicFacingFudge", false);

                var flipX = LoadField(d, "FlipX", false);
                var flipY = LoadField(d, "FlipY", false);

                Facings = LoadField(d, "Facings", 1);
                if (Facings < 0)
                {
                    reverseFacings = true;
                    Facings        = -Facings;
                }

                if (useClassicFacingFudge && Facings != 32)
                {
                    throw new InvalidOperationException(
                              "{0}: Sequence {1}.{2}: UseClassicFacingFudge is only valid for 32 facings"
                              .F(info.Nodes[0].Location, sequence, animation));
                }

                var offset    = LoadField(d, "Offset", float3.Zero);
                var blendMode = LoadField(d, "BlendMode", BlendMode.Alpha);

                Func <int, IEnumerable <int> > getUsedFrames = frameCount =>
                {
                    MiniYaml length;
                    if (d.TryGetValue("Length", out length) && length.Value == "*")
                    {
                        Length = frameCount - Start;
                    }
                    else
                    {
                        Length = LoadField(d, "Length", 1);
                    }

                    // Plays the animation forwards, and then in reverse
                    if (LoadField(d, "Reverses", false))
                    {
                        var frames = Frames ?? Exts.MakeArray(Length, i => Start + i);
                        Frames = frames.Concat(frames.Skip(1).Take(frames.Length - 2).Reverse()).ToArray();
                        Length = 2 * Length - 2;
                    }

                    Stride = LoadField(d, "Stride", Length);

                    if (Length > Stride)
                    {
                        throw new InvalidOperationException(
                                  "{0}: Sequence {1}.{2}: Length must be <= stride"
                                  .F(info.Nodes[0].Location, sequence, animation));
                    }

                    if (Frames != null && Length > Frames.Length)
                    {
                        throw new InvalidOperationException(
                                  "{0}: Sequence {1}.{2}: Length must be <= Frames.Length"
                                  .F(info.Nodes[0].Location, sequence, animation));
                    }

                    if (Start < 0 || Start + Facings * Stride > frameCount)
                    {
                        throw new InvalidOperationException(
                                  "{5}: Sequence {0}.{1} uses frames [{2}..{3}], but only 0..{4} actually exist"
                                  .F(sequence, animation, Start, Start + Facings * Stride - 1, frameCount - 1,
                                     info.Nodes[0].Location));
                    }

                    if (ShadowStart + Facings * Stride > frameCount)
                    {
                        throw new InvalidOperationException(
                                  "{5}: Sequence {0}.{1}'s shadow frames use frames [{2}..{3}], but only [0..{4}] actually exist"
                                  .F(sequence, animation, ShadowStart, ShadowStart + Facings * Stride - 1, frameCount - 1,
                                     info.Nodes[0].Location));
                    }

                    var usedFrames = new List <int>();
                    for (var facing = 0; facing < Facings; facing++)
                    {
                        for (var frame = 0; frame < Length; frame++)
                        {
                            var i = transpose ? (frame % Length) * Facings + facing :
                                    (facing * Stride) + (frame % Length);

                            usedFrames.Add(Frames != null ? Frames[i] : Start + i);
                        }
                    }

                    if (ShadowStart >= 0)
                    {
                        return(usedFrames.Concat(usedFrames.Select(i => i + ShadowStart - Start)));
                    }

                    return(usedFrames);
                };

                MiniYaml combine;
                if (d.TryGetValue("Combine", out combine))
                {
                    var combined = Enumerable.Empty <Sprite>();
                    foreach (var sub in combine.Nodes)
                    {
                        var sd = sub.Value.ToDictionary();

                        // Allow per-sprite offset, flipping, start, and length
                        var subStart  = LoadField(sd, "Start", 0);
                        var subOffset = LoadField(sd, "Offset", float3.Zero);
                        var subFlipX  = LoadField(sd, "FlipX", false);
                        var subFlipY  = LoadField(sd, "FlipY", false);
                        var subLength = 0;

                        Func <int, IEnumerable <int> > subGetUsedFrames = subFrameCount =>
                        {
                            MiniYaml subLengthYaml;
                            if (sd.TryGetValue("Length", out subLengthYaml) && subLengthYaml.Value == "*")
                            {
                                subLength = subFrameCount - subStart;
                            }
                            else
                            {
                                subLength = LoadField(sd, "Length", 1);
                            }

                            return(Enumerable.Range(subStart, subLength));
                        };

                        var subSrc     = GetSpriteSrc(modData, tileSet, sequence, animation, sub.Key, sd);
                        var subSprites = cache[subSrc, subGetUsedFrames].Select(
                            s => s != null ? new Sprite(s.Sheet,
                                                        FlipRectangle(s.Bounds, subFlipX, subFlipY), ZRamp,
                                                        new float3(subFlipX ? -s.Offset.X : s.Offset.X, subFlipY ? -s.Offset.Y : s.Offset.Y, s.Offset.Z) + subOffset + offset,
                                                        s.Channel, blendMode) : null);

                        combined = combined.Concat(subSprites.Skip(subStart).Take(subLength));
                    }

                    sprites = combined.ToArray();
                    getUsedFrames(sprites.Length);
                }
                else
                {
                    // Apply offset to each sprite in the sequence
                    // Different sequences may apply different offsets to the same frame
                    var src = GetSpriteSrc(modData, tileSet, sequence, animation, info.Value, d);
                    sprites = cache[src, getUsedFrames].Select(
                        s => s != null ? new Sprite(s.Sheet,
                                                    FlipRectangle(s.Bounds, flipX, flipY), ZRamp,
                                                    new float3(flipX ? -s.Offset.X : s.Offset.X, flipY ? -s.Offset.Y : s.Offset.Y, s.Offset.Z) + offset,
                                                    s.Channel, blendMode) : null).ToArray();
                }

                var depthSprite = LoadField <string>(d, "DepthSprite", null);
                if (!string.IsNullOrEmpty(depthSprite))
                {
                    var depthSpriteFrame = LoadField(d, "DepthSpriteFrame", 0);
                    var depthOffset      = LoadField(d, "DepthSpriteOffset", float2.Zero);
                    Func <int, IEnumerable <int> > getDepthFrame = _ => new int[] { depthSpriteFrame };
                    var ds = cache[depthSprite, getDepthFrame][depthSpriteFrame];

                    sprites = sprites.Select(s =>
                    {
                        if (s == null)
                        {
                            return(null);
                        }

                        var cw = (ds.Bounds.Left + ds.Bounds.Right) / 2 + (int)(s.Offset.X + depthOffset.X);
                        var ch = (ds.Bounds.Top + ds.Bounds.Bottom) / 2 + (int)(s.Offset.Y + depthOffset.Y);
                        var w  = s.Bounds.Width / 2;
                        var h  = s.Bounds.Height / 2;

                        var r = Rectangle.FromLTRB(cw - w, ch - h, cw + w, ch + h);
                        return(new SpriteWithSecondaryData(s, ds.Sheet, r, ds.Channel));
                    }).ToArray();
                }

                var boundSprites = SpriteBounds(sprites, Frames, Start, Facings, Length, Stride, transpose);
                if (ShadowStart > 0)
                {
                    boundSprites = boundSprites.Concat(SpriteBounds(sprites, Frames, ShadowStart, Facings, Length, Stride, transpose));
                }

                if (boundSprites.Any())
                {
                    Bounds = boundSprites.First();
                    foreach (var b in boundSprites.Skip(1))
                    {
                        Bounds = Rectangle.Union(Bounds, b);
                    }
                }
            }
            catch (FormatException f)
            {
                throw new FormatException("Failed to parse sequences for {0}.{1} at {2}:\n{3}".F(sequence, animation, info.Nodes[0].Location, f));
            }
        }
Beispiel #42
0
        private void DistributeTilesForSelfKongToPong(Game game)
        {
            List <Tile>  tiles = game.Board.Tiles;
            ActivePlayer p1, p2, p3, p4;

            if (game.DiceRoller == game.Player1.ConnectionId)
            {
                p1 = game.Player1;
                p2 = game.Player2;
                p3 = game.Player3;
                p4 = game.Player4;
            }
            else if (game.DiceRoller == game.Player2.ConnectionId)
            {
                p1 = game.Player2;
                p2 = game.Player3;
                p3 = game.Player4;
                p4 = game.Player1;
            }
            else if (game.DiceRoller == game.Player3.ConnectionId)
            {
                p1 = game.Player3;
                p2 = game.Player4;
                p3 = game.Player1;
                p4 = game.Player2;
            }
            else
            {
                p1 = game.Player4;
                p2 = game.Player1;
                p3 = game.Player2;
                p4 = game.Player3;
            }

            for (var i = 0; i < 14; i++)
            {
                if (i == 2 || i == 3 || i == 4 || i == 5)
                {
                    continue;
                }
                tiles[i].Owner  = p1.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p1.ActiveTiles.Add(tiles[i]);
            }

            List <Tile> tempTile1 = new List <Tile>();

            tempTile1.Add(tiles[4]);
            tempTile1.Add(tiles[38]);
            tempTile1.Add(tiles[72]);
            TileSet newbie1 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile1, TileSetType = TileSetType.Pong, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie1);

            tiles[4].Owner  = p1.ConnectionId;
            tiles[4].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[4]);

            tiles[38].Owner  = p1.ConnectionId;
            tiles[38].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[38]);

            tiles[72].Owner  = p1.ConnectionId;
            tiles[72].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[72]);

            tiles[0].Status = TileStatus.JustPicked;

            tiles[106].Owner  = p1.ConnectionId;
            tiles[106].Status = TileStatus.UserActive;
            p1.ActiveTiles.Add(tiles[106]);

            for (var i = 14; i < 27; i++)
            {
                tiles[i].Owner  = p2.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p2.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 27; i < 41; i++)
            {
                if (i == 38)
                {
                    continue;
                }
                tiles[i].Owner  = p3.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p3.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 53; i < 66; i++)
            {
                tiles[i].Owner  = p4.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p4.ActiveTiles.Add(tiles[i]);
            }
        }
Beispiel #43
0
 public static void On_Map_Created(Map self, TileSet set, System.IO.BinaryReader reader)
 {
     On_Map_Created(self, set);
 }
Beispiel #44
0
        private void DistributeTilesForWinWaitingForEyeWithPureHand(Game game)
        {
            List <Tile>  tiles = game.Board.Tiles;
            ActivePlayer p1, p2, p3, p4;

            if (game.DiceRoller == game.Player1.ConnectionId)
            {
                p1 = game.Player1;
                p2 = game.Player2;
                p3 = game.Player3;
                p4 = game.Player4;
            }
            else if (game.DiceRoller == game.Player2.ConnectionId)
            {
                p1 = game.Player2;
                p2 = game.Player3;
                p3 = game.Player4;
                p4 = game.Player1;
            }
            else if (game.DiceRoller == game.Player3.ConnectionId)
            {
                p1 = game.Player3;
                p2 = game.Player4;
                p3 = game.Player1;
                p4 = game.Player2;
            }
            else
            {
                p1 = game.Player4;
                p2 = game.Player1;
                p3 = game.Player2;
                p4 = game.Player3;
            }

            for (var i = 0; i < 9; i++)
            {
                tiles[i].Owner  = p1.ConnectionId;
                tiles[i].Status = TileStatus.UserGraveyard;
                p1.GraveYardTiles.Add(tiles[i]);
            }
            List <Tile> tempTile1 = new List <Tile>();

            tempTile1.Add(tiles[0]);
            tempTile1.Add(tiles[1]);
            tempTile1.Add(tiles[2]);
            TileSet newbie1 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile1, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie1);

            List <Tile> tempTile2 = new List <Tile>();

            tempTile2.Add(tiles[3]);
            tempTile2.Add(tiles[4]);
            tempTile2.Add(tiles[5]);
            TileSet newbie2 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile2, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie2);

            List <Tile> tempTile3 = new List <Tile>();

            tempTile3.Add(tiles[6]);
            tempTile3.Add(tiles[7]);
            tempTile3.Add(tiles[8]);
            TileSet newbie3 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile3, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie3);

            for (var i = 34; i < 37; i++)
            {
                tiles[i].Owner  = p1.ConnectionId;
                tiles[i].Status = TileStatus.UserGraveyard;
                p1.GraveYardTiles.Add(tiles[i]);
            }
            List <Tile> tempTile4 = new List <Tile>();

            tempTile4.Add(tiles[34]);
            tempTile4.Add(tiles[35]);
            tempTile4.Add(tiles[36]);
            TileSet newbie4 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile4, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie4);

            tiles[70].Owner  = p1.ConnectionId;
            tiles[70].Status = TileStatus.UserActive;
            p1.ActiveTiles.Add(tiles[70]);

            tiles[121].Owner  = p1.ConnectionId;
            tiles[121].Status = TileStatus.UserActive;
            p1.ActiveTiles.Add(tiles[121]);

            tiles[136].Owner  = p1.ConnectionId;
            tiles[136].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[136]);

            tiles[140].Owner  = p1.ConnectionId;
            tiles[140].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[140]);

            for (var i = 14; i < 27; i++)
            {
                tiles[i].Owner  = p2.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p2.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 27; i < 40; i++)
            {
                tiles[i].Owner  = p3.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p3.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 53; i < 65; i++)
            {
                tiles[i].Owner  = p4.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p4.ActiveTiles.Add(tiles[i]);
            }
            tiles[80].Owner  = p4.ConnectionId;
            tiles[80].Status = TileStatus.UserActive;
            p4.ActiveTiles.Add(tiles[80]);
        }
Beispiel #45
0
        public static Bitmap TerrainBitmap(TileSet tileset, Map map, bool actualSize = false)
        {
            var isRectangularIsometric = map.Grid.Type == MapGridType.RectangularIsometric;
            var b = map.Bounds;

            // Fudge the heightmap offset by adding as much extra as we need / can.
            // This tries to correct for our incorrect assumption that MPos == PPos
            var heightOffset = Math.Min(map.Grid.MaximumTerrainHeight, map.MapSize.Y - b.Bottom);
            var width        = b.Width;
            var height       = b.Height + heightOffset;

            var bitmapWidth = width;

            if (isRectangularIsometric)
            {
                bitmapWidth = 2 * bitmapWidth - 1;
            }

            if (!actualSize)
            {
                bitmapWidth = height = Exts.NextPowerOf2(Math.Max(bitmapWidth, height));
            }

            var terrain = new Bitmap(bitmapWidth, height);

            var bitmapData = terrain.LockBits(terrain.Bounds(),
                                              ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);

            var mapTiles = map.MapTiles.Value;

            unsafe
            {
                var colors = (int *)bitmapData.Scan0;
                var stride = bitmapData.Stride / 4;
                for (var y = 0; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        var uv        = new MPos(x + b.Left, y + b.Top);
                        var type      = tileset.GetTileInfo(mapTiles[uv]);
                        var leftColor = type != null ? type.LeftColor : Color.Black;

                        if (isRectangularIsometric)
                        {
                            // Odd rows are shifted right by 1px
                            var dx         = uv.V & 1;
                            var rightColor = type != null ? type.RightColor : Color.Black;
                            if (x + dx > 0)
                            {
                                colors[y * stride + 2 * x + dx - 1] = leftColor.ToArgb();
                            }

                            if (2 * x + dx < stride)
                            {
                                colors[y * stride + 2 * x + dx] = rightColor.ToArgb();
                            }
                        }
                        else
                        {
                            colors[y * stride + x] = leftColor.ToArgb();
                        }
                    }
                }
            }

            terrain.UnlockBits(bitmapData);
            return(terrain);
        }
Beispiel #46
0
 public virtual ISpriteSequence CreateSequence(ModData modData, TileSet tileSet, SpriteCache cache, string sequence, string animation, MiniYaml info)
 {
     return(new DefaultSpriteSequence(modData, tileSet, cache, this, sequence, animation, info));
 }
Beispiel #47
0
 void FetchTileSet()
 {
     tiles = Resources.Load <TileSet>("MainTiles");
 }
Beispiel #48
0
        public IReadOnlyDictionary <string, ISpriteSequence> ParseSequences(ModData modData, TileSet tileSet, SpriteCache cache, MiniYamlNode node)
        {
            var sequences = new Dictionary <string, ISpriteSequence>();
            var nodes     = node.Value.ToDictionary();

            MiniYaml defaults;

            if (nodes.TryGetValue("Defaults", out defaults))
            {
                nodes.Remove("Defaults");
                nodes = nodes.ToDictionary(kv => kv.Key, kv => MiniYaml.MergeStrict(kv.Value, defaults));

                foreach (var n in nodes)
                {
                    n.Value.Value = n.Value.Value ?? defaults.Value;
                }
            }

            foreach (var kvp in nodes)
            {
                using (new Support.PerfTimer("new Sequence(\"{0}\")".F(node.Key), 20))
                {
                    try
                    {
                        sequences.Add(kvp.Key, CreateSequence(modData, tileSet, cache, node.Key, kvp.Key, kvp.Value));
                    }
                    catch (FileNotFoundException ex)
                    {
                        // Eat the FileNotFound exceptions from missing sprites
                        OnMissingSpriteError(ex.Message);
                    }
                }
            }

            return(new ReadOnlyDictionary <string, ISpriteSequence>(sequences));
        }
Beispiel #49
0
        private static void RebuildMesh(TileLayer layer, IntRect cells, Vector2f position, TileSet tileSet)
        {
            numTiles = CountTiles(layer, cells);

            meshCache.Clear();

            RebuildMeshVertices(layer, cells, position, new Vector2i(tileSet.tileWidth, tileSet.tileHeight), new Vector2i(layer.map.tileWidth, layer.map.tileHeight));
            RebuildMeshTriangles();
            RebuildMeshUV(layer, cells, tileSet);

            meshCache.ApplyMeshData();
        }
Beispiel #50
0
 internal void SetTerrainTileSet(TileSet tileSet)
 {
     terrainMap.TileSet = tileSet;
 }
Beispiel #51
0
 public TileSetReader(TileSet tileSet)
 {
     _rawTileSet   = tileSet;
     _pickAnyUnits = new ImageSource[tileSet.PickAnyTileUnits.Count];
 }
Beispiel #52
0
        private void RecreateTexturedBackground(TileSet levelTileset, ref TileMapLayer layer)
        {
            int w = layer.LayoutWidth;
            int h = layer.Layout.Length / w;

            Texture targetTexture;

            if (cachedTexturedBackground.IsAvailable)
            {
                targetTexture = cachedTexturedBackground.Res;
            }
            else
            {
                targetTexture = new Texture(w * 32, h * 32, TextureSizeMode.NonPowerOfTwo, TextureMagFilter.Linear, TextureMinFilter.Linear, TextureWrapMode.Repeat, TextureWrapMode.Repeat);
            }

            using (DrawDevice device = new DrawDevice()) {
                device.VisibilityMask = VisibilityFlag.AllFlags;
                device.Projection     = ProjectionMode.Screen;

                RenderTarget target = new RenderTarget(AAQuality.Off, false, targetTexture);
                device.Target       = target;
                device.TargetSize   = new Vector2(w * 32, h * 32);
                device.ViewportRect = new Rect(device.TargetSize);

                device.PrepareForDrawcalls();

                // ToDo
                Material material = levelTileset.GetDefaultTile(0).Material.Res;
                Texture  texture  = material.MainTexture.Res;

                // Reserve the required space for vertex data in our locally cached buffer
                int neededVertices = 4 * w * h;
                if (cachedVertices == null || cachedVertices.Length < neededVertices)
                {
                    cachedVertices = new VertexC1P3T2[neededVertices];
                }

                int vertexIndex = 0;

                for (int x = 0; x < w; x++)
                {
                    for (int y = 0; y < h; y++)
                    {
                        LayerTile tile = layer.Layout[x + y * layer.LayoutWidth];
                        if (tile.IsAnimated)
                        {
                            continue;
                        }

                        Point2 offset     = tile.MaterialOffset;
                        bool   isFlippedX = tile.IsFlippedX;
                        bool   isFlippedY = tile.IsFlippedY;

                        Rect uvRect = new Rect(
                            offset.X * texture.UVRatio.X / texture.ContentWidth,
                            offset.Y * texture.UVRatio.Y / texture.ContentHeight,
                            levelTileset.TileSize * texture.UVRatio.X / texture.ContentWidth,
                            levelTileset.TileSize * texture.UVRatio.Y / texture.ContentHeight
                            );

                        if (isFlippedX)
                        {
                            uvRect.X += uvRect.W;
                            uvRect.W *= -1;
                        }
                        if (isFlippedY)
                        {
                            uvRect.Y += uvRect.H;
                            uvRect.H *= -1;
                        }

                        Vector3 renderPos = new Vector3(x * 32, y * 32, 0);

                        renderPos.X = MathF.Round(renderPos.X);
                        renderPos.Y = MathF.Round(renderPos.Y);
                        if (MathF.RoundToInt(device.TargetSize.X) != (MathF.RoundToInt(device.TargetSize.X) / 2) * 2)
                        {
                            renderPos.X += 0.5f;
                        }
                        if (MathF.RoundToInt(device.TargetSize.Y) != (MathF.RoundToInt(device.TargetSize.Y) / 2) * 2)
                        {
                            renderPos.Y += 0.5f;
                        }

                        Vector2 tileXStep = new Vector2(32, 0);
                        Vector2 tileYStep = new Vector2(0, 32);

                        cachedVertices[vertexIndex + 0].Pos.X      = renderPos.X;
                        cachedVertices[vertexIndex + 0].Pos.Y      = renderPos.Y;
                        cachedVertices[vertexIndex + 0].Pos.Z      = renderPos.Z;
                        cachedVertices[vertexIndex + 0].TexCoord.X = uvRect.X;
                        cachedVertices[vertexIndex + 0].TexCoord.Y = uvRect.Y;
                        cachedVertices[vertexIndex + 0].Color      = ColorRgba.White;

                        cachedVertices[vertexIndex + 1].Pos.X      = renderPos.X + tileYStep.X;
                        cachedVertices[vertexIndex + 1].Pos.Y      = renderPos.Y + tileYStep.Y;
                        cachedVertices[vertexIndex + 1].Pos.Z      = renderPos.Z;
                        cachedVertices[vertexIndex + 1].TexCoord.X = uvRect.X;
                        cachedVertices[vertexIndex + 1].TexCoord.Y = uvRect.Y + uvRect.H;
                        cachedVertices[vertexIndex + 1].Color      = ColorRgba.White;

                        cachedVertices[vertexIndex + 2].Pos.X      = renderPos.X + tileXStep.X + tileYStep.X;
                        cachedVertices[vertexIndex + 2].Pos.Y      = renderPos.Y + tileXStep.Y + tileYStep.Y;
                        cachedVertices[vertexIndex + 2].Pos.Z      = renderPos.Z;
                        cachedVertices[vertexIndex + 2].TexCoord.X = uvRect.X + uvRect.W;
                        cachedVertices[vertexIndex + 2].TexCoord.Y = uvRect.Y + uvRect.H;
                        cachedVertices[vertexIndex + 2].Color      = ColorRgba.White;

                        cachedVertices[vertexIndex + 3].Pos.X      = renderPos.X + tileXStep.X;
                        cachedVertices[vertexIndex + 3].Pos.Y      = renderPos.Y + tileXStep.Y;
                        cachedVertices[vertexIndex + 3].Pos.Z      = renderPos.Z;
                        cachedVertices[vertexIndex + 3].TexCoord.X = uvRect.X + uvRect.W;
                        cachedVertices[vertexIndex + 3].TexCoord.Y = uvRect.Y;
                        cachedVertices[vertexIndex + 3].Color      = ColorRgba.White;

                        vertexIndex += 4;
                    }
                }

                device.AddVertices(material, VertexMode.Quads, cachedVertices, 0, vertexIndex);

                device.Render();

                target.Dispose();
            }

            cachedTexturedBackground = targetTexture;
        }
Beispiel #53
0
 public uint GetMovementClass(TileSet tileset)
 {
     return((uint)TilesetMovementClass[tileset]);
 }
Beispiel #54
0
        private void PrerenderTexturedBackground()
        {
            try {
                IImageCodec codec = ImageCodec.GetRead(ImageCodec.FormatPng);

                // Try to use "The Secret Files" background
                string levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "secretf", "01_easter1");
                if (!DirectoryOp.Exists(levelPath))
                {
                    // Try to use "Base Game" background
                    levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "prince", "03_carrot1");
                    if (!DirectoryOp.Exists(levelPath))
                    {
                        // Try to use "Holiday Hare '98" background
                        levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "xmas98", "03_xmas3");
                        if (!DirectoryOp.Exists(levelPath))
                        {
                            // Try to use "Christmas Chronicles" background
                            levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "xmas99", "03_xmas3");
                            if (!DirectoryOp.Exists(levelPath))
                            {
                                // Try to use "Shareware Demo" background;
                                levelPath = PathOp.Combine(DualityApp.DataDirectory, "Episodes", "share", "02_share2");
                                if (!DirectoryOp.Exists(levelPath))
                                {
                                    // No usable background found
                                    throw new FileNotFoundException();
                                }
                            }
                        }
                    }
                }

                // Load metadata
                JsonParser json = new JsonParser();
                LevelHandler.LevelConfigJson config;
                using (Stream s = FileOp.Open(PathOp.Combine(levelPath, ".res"), FileAccessMode.Read)) {
                    config = json.Parse <LevelHandler.LevelConfigJson>(s);
                }

                LevelHandler.LevelConfigJson.LayerSection layer;
                if (config.Layers.TryGetValue("Sky", out layer))
                {
                    if (layer.BackgroundColor != null && layer.BackgroundColor.Count >= 3)
                    {
                        horizonColor = new Vector4(layer.BackgroundColor[0] / 255f, layer.BackgroundColor[1] / 255f, layer.BackgroundColor[2] / 255f, 1f);
                    }

                    switch ((BackgroundStyle)layer.BackgroundStyle)
                    {
                    case BackgroundStyle.Sky:
                    default:
                        texturedBackgroundShader = ContentResolver.Current.RequestShader("TexturedBackground");
                        break;

                    case BackgroundStyle.Circle:
                        texturedBackgroundShader = ContentResolver.Current.RequestShader("TexturedBackgroundCircle");
                        break;
                    }
                }

                // Render background layer to texture
                string tilesetPath = PathOp.Combine(DualityApp.DataDirectory, "Tilesets", config.Description.DefaultTileset);

                ColorRgba[] tileMapPalette = TileSet.LoadPalette(PathOp.Combine(tilesetPath, ".palette"));
                ContentResolver.Current.ApplyBasePalette(tileMapPalette);

                TileSet levelTileset = new TileSet(config.Description.DefaultTileset);
                if (!levelTileset.IsValid)
                {
                    throw new InvalidDataException();
                }

                using (Stream s = FileOp.Open(PathOp.Combine(levelPath, "Sky.layer"), FileAccessMode.Read)) {
                    using (DeflateStream deflate = new DeflateStream(s, CompressionMode.Decompress))
                        using (BinaryReader r = new BinaryReader(deflate)) {
                            int width  = r.ReadInt32();
                            int height = r.ReadInt32();

                            TileMapLayer newLayer = new TileMapLayer();
                            newLayer.Layout = new LayerTile[width * height];

                            for (int i = 0; i < newLayer.Layout.Length; i++)
                            {
                                ushort tileType = r.ReadUInt16();

                                byte flags = r.ReadByte();
                                if (flags == 0)
                                {
                                    newLayer.Layout[i] = levelTileset.GetDefaultTile(tileType);
                                    continue;
                                }

                                bool isFlippedX        = (flags & 0x01) > 0;
                                bool isFlippedY        = (flags & 0x02) > 0;
                                bool isAnimated        = (flags & 0x04) > 0;
                                bool legacyTranslucent = (flags & 0x80) > 0;

                                // Invalid tile numbers (higher than tileset tile amount) are silently changed to empty tiles
                                if (tileType >= levelTileset.TileCount && !isAnimated)
                                {
                                    tileType = 0;
                                }

                                LayerTile tile;

                                // Copy the default tile and do stuff with it
                                tile            = levelTileset.GetDefaultTile(tileType);
                                tile.IsFlippedX = isFlippedX;
                                tile.IsFlippedY = isFlippedY;
                                tile.IsAnimated = isAnimated;

                                if (legacyTranslucent)
                                {
                                    tile.MaterialAlpha = /*127*/ 140;
                                }

                                newLayer.Layout[i] = tile;
                            }

                            newLayer.LayoutWidth = width;

                            RecreateTexturedBackground(levelTileset, ref newLayer);
                        }
                }
            } catch (Exception ex) {
                Console.WriteLine("Cannot prerender textured background: " + ex);

                cachedTexturedBackground = new Texture(new Pixmap(new PixelData(2, 2, ColorRgba.Black)));
            }
        }
Beispiel #55
0
        private bool SelectBrushInternal(Brush brush, PaletteType palette)
        {
            paletteType_CB.SelectedIndex = getPaletteType_CBIndex(palette);
            foreach (var item in tileSet_CB.Items)
            {
                TileSet tileset = (TileSet)item;

                TilesetCategory category = null;

                switch (palette)
                {
                case PaletteType.TERRAIN:
                    category = tileset.getCategory(TilesetCategoryType.TILESET_TERRAIN);
                    break;

                case PaletteType.DOODAD:
                    category = tileset.getCategory(TilesetCategoryType.TILESET_DOODAD);
                    break;

                case PaletteType.RAW:
                    category = tileset.getCategory(TilesetCategoryType.TILESET_RAW);
                    break;

                case PaletteType.ITEM:
                    category = tileset.getCategory(TilesetCategoryType.TILESET_ITEM);
                    break;

                case PaletteType.CREATURE:
                    category = tileset.getCategory(TilesetCategoryType.TILESET_CREATURE);
                    break;
                }

                foreach (Brush ibrush in category.brushlist)
                {
                    if (ibrush.Equals(brush))
                    {
                        tileSet_CB.SelectedItem = item;
                        if (panelEditor.Controls.Contains(brushListItems))
                        {
                            foreach (Control control in brushListItems.Controls)
                            {
                                if (control.Tag.Equals(brush))
                                {
                                    Panel panel = (Panel)control;
                                    brushClick(panel, null);
                                    return(true);
                                }
                            }
                        }
                        else if (panelEditor.Controls.Contains(ItemListView))
                        {
                            foreach (ListViewItem lvitem in ItemListView.Items)
                            {
                                if (lvitem.Tag.Equals(brush))
                                {
                                    lvitem.Selected = true;
                                    lvitem.Focused  = true;
                                    ItemListView.Select();
                                    ItemListView.EnsureVisible(lvitem.Index);
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            return(false);
        }
        void IUtilityCommand.Run(Utility utility, string[] args)
        {
            // HACK: The engine code assumes that Game.modData is set.
            var modData = Game.ModData = utility.ModData;

            var imageField             = typeof(TerrainTemplateInfo).GetField("Image");
            var pickAnyField           = typeof(TerrainTemplateInfo).GetField("PickAny");
            var tileInfoField          = typeof(TerrainTemplateInfo).GetField("tileInfo", BindingFlags.NonPublic | BindingFlags.Instance);
            var terrainTypeField       = typeof(TerrainTileInfo).GetField("TerrainType");
            var terrainLeftColorField  = typeof(TerrainTileInfo).GetField("LeftColor");
            var terrainRightColorField = typeof(TerrainTileInfo).GetField("RightColor");
            var empty = new Size(0, 0);
            var single = new int2(1, 1);
            var exts = new[] { "" }.Concat(args[1].Split(','));

            foreach (var t in modData.Manifest.TileSets)
            {
                var ts         = new TileSet(modData.DefaultFileSystem, t);
                var frameCache = new FrameCache(modData.DefaultFileSystem, modData.SpriteLoaders);

                Console.WriteLine("Tileset: " + ts.Name);
                foreach (var template in ts.Templates.Values)
                {
                    // Find the sprite associated with this template
                    foreach (var ext in exts)
                    {
                        Stream s;
                        if (modData.DefaultFileSystem.TryOpen(template.Images[0] + ext, out s))
                        {
                            s.Dispose();
                        }
                        else
                        {
                            continue;
                        }

                        // Rewrite the template image (normally readonly) using reflection
                        imageField.SetValue(template, template.Images[0] + ext);

                        // Fetch the private tileInfo array so that we can write new entries
                        var tileInfo = (TerrainTileInfo[])tileInfoField.GetValue(template);

                        // Open the file and search for any implicit frames
                        var allFrames = frameCache[template.Images[0]];
                        var frames    = template.Frames != null?template.Frames.Select(f => allFrames[f]).ToArray() : allFrames;

                        // Resize array for new entries
                        if (frames.Length > template.TilesCount)
                        {
                            var ti = new TerrainTileInfo[frames.Length];
                            Array.Copy(tileInfo, ti, template.TilesCount);
                            tileInfoField.SetValue(template, ti);
                            tileInfo = ti;
                        }

                        for (var i = 0; i < template.TilesCount; i++)
                        {
                            if (template[i] == null && frames[i] != null && frames[i].Size != empty)
                            {
                                tileInfo[i] = new TerrainTileInfo();
                                var ti = ts.GetTerrainIndex("Clear");
                                terrainTypeField.SetValue(tileInfo[i], ti);
                                terrainLeftColorField.SetValue(tileInfo[i], ts[ti].Color);
                                terrainRightColorField.SetValue(tileInfo[i], ts[ti].Color);
                                Console.WriteLine("Fixing entry for {0}:{1}", template.Images[0], i);
                            }
                        }

                        if (template.TilesCount > 1 && template.Size == single)
                        {
                            pickAnyField.SetValue(template, true);
                        }
                    }
                }

                ts.Save(t);
            }
        }
Beispiel #57
0
 public static Bitmap RenderMapPreview(TileSet tileset, Map map, bool actualSize)
 {
     return(RenderMapPreview(tileset, map, map.Rules, actualSize));
 }
Beispiel #58
0
 public static Bitmap RenderMapPreview(TileSet tileset, Map map, Ruleset resourceRules, bool actualSize)
 {
     using (var terrain = TerrainBitmap(tileset, map, actualSize))
         return(AddStaticResources(tileset, map, resourceRules, terrain));
 }
Beispiel #59
0
        private void DistributeTilesForWinWaitingForEye(Game game)
        {
            List <Tile> tiles = game.Board.Tiles;
            Player      p1, p2, p3, p4;

            p1 = game.Player1;
            p2 = game.Player2;
            p3 = game.Player3;
            p4 = game.Player4;

            for (var i = 0; i < 12; i++)
            {
                tiles[i].Owner  = p1.ConnectionId;
                tiles[i].Status = TileStatus.UserGraveyard;
            }
            List <Tile> tempTile1 = new List <Tile>();

            tempTile1.Add(tiles[0]);
            tempTile1.Add(tiles[1]);
            tempTile1.Add(tiles[2]);
            TileSet newbie1 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile1, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie1);

            List <Tile> tempTile2 = new List <Tile>();

            tempTile2.Add(tiles[3]);
            tempTile2.Add(tiles[4]);
            tempTile2.Add(tiles[5]);
            TileSet newbie2 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile2, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie2);

            List <Tile> tempTile3 = new List <Tile>();

            tempTile3.Add(tiles[6]);
            tempTile3.Add(tiles[7]);
            tempTile3.Add(tiles[8]);
            TileSet newbie3 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile3, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie3);

            List <Tile> tempTile4 = new List <Tile>();

            tempTile4.Add(tiles[9]);
            tempTile4.Add(tiles[10]);
            tempTile4.Add(tiles[11]);
            TileSet newbie4 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile4, TileSetType = TileSetType.Chow, TileType = TileType.Round
            };

            p1.TileSets.Add(newbie4);

            tiles[12].Owner  = p1.ConnectionId;
            tiles[12].Status = TileStatus.UserActive;

            tiles[66].Owner   = p1.ConnectionId;
            tiles[66].Status  = TileStatus.UserActive;
            tiles[136].Owner  = p1.ConnectionId;
            tiles[136].Status = TileStatus.UserGraveyard;
            tiles[140].Owner  = p1.ConnectionId;
            tiles[140].Status = TileStatus.UserGraveyard;

            for (var i = 14; i < 27; i++)
            {
                tiles[i].Owner  = p2.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
            }
            for (var i = 27; i < 40; i++)
            {
                tiles[i].Owner  = p3.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
            }
            for (var i = 53; i < 65; i++)
            {
                tiles[i].Owner  = p4.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
            }
            tiles[80].Owner  = p4.ConnectionId;
            tiles[80].Status = TileStatus.UserActive;
        }
Beispiel #60
0
        private void DistributeTilesForWinWaitingForEyeWithMixPureHandWithDragon(Game game)
        {
            List <Tile>  tiles = game.Board.Tiles;
            ActivePlayer p1, p2, p3, p4;

            if (game.DiceRoller == game.Player1.ConnectionId)
            {
                p1 = game.Player1;
                p2 = game.Player2;
                p3 = game.Player3;
                p4 = game.Player4;
            }
            else if (game.DiceRoller == game.Player2.ConnectionId)
            {
                p1 = game.Player2;
                p2 = game.Player3;
                p3 = game.Player4;
                p4 = game.Player1;
            }
            else if (game.DiceRoller == game.Player3.ConnectionId)
            {
                p1 = game.Player3;
                p2 = game.Player4;
                p3 = game.Player1;
                p4 = game.Player2;
            }
            else
            {
                p1 = game.Player4;
                p2 = game.Player1;
                p3 = game.Player2;
                p4 = game.Player3;
            }

            for (var i = 0; i < 6; i++)
            {
                tiles[i].Owner  = p1.ConnectionId;
                tiles[i].Status = TileStatus.UserGraveyard;
                p1.GraveYardTiles.Add(tiles[i]);
            }
            List <Tile> tempTile1 = new List <Tile>();

            tempTile1.Add(tiles[0]);
            tempTile1.Add(tiles[1]);
            tempTile1.Add(tiles[2]);
            TileSet newbie1 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile1, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie1);

            List <Tile> tempTile2 = new List <Tile>();

            tempTile2.Add(tiles[3]);
            tempTile2.Add(tiles[4]);
            tempTile2.Add(tiles[5]);
            TileSet newbie2 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile2, TileSetType = TileSetType.Chow, TileType = TileType.Money
            };

            p1.TileSets.Add(newbie2);

            tiles[27].Owner  = p1.ConnectionId;
            tiles[27].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[27]);

            tiles[61].Owner  = p1.ConnectionId;
            tiles[61].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[61]);

            tiles[95].Owner  = p1.ConnectionId;
            tiles[95].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[95]);

            List <Tile> tempTile3 = new List <Tile>();

            tempTile3.Add(tiles[27]);
            tempTile3.Add(tiles[61]);
            tempTile3.Add(tiles[95]);
            TileSet newbie3 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile3, TileSetType = TileSetType.Pong, TileType = TileType.Dragon
            };

            p1.TileSets.Add(newbie3);

            tiles[28].Owner  = p1.ConnectionId;
            tiles[28].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[28]);

            tiles[62].Owner  = p1.ConnectionId;
            tiles[62].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[62]);

            tiles[96].Owner  = p1.ConnectionId;
            tiles[96].Status = TileStatus.UserGraveyard;
            p1.GraveYardTiles.Add(tiles[96]);

            List <Tile> tempTile4 = new List <Tile>();

            tempTile4.Add(tiles[28]);
            tempTile4.Add(tiles[62]);
            tempTile4.Add(tiles[96]);
            TileSet newbie4 = new TileSet()
            {
                isRevealed = true, Tiles = tempTile4, TileSetType = TileSetType.Pong, TileType = TileType.Dragon
            };

            p1.TileSets.Add(newbie4);

            tiles[121].Owner  = p1.ConnectionId;
            tiles[121].Status = TileStatus.UserActive;
            p1.ActiveTiles.Add(tiles[121]);

            tiles[66].Owner  = p1.ConnectionId;
            tiles[66].Status = TileStatus.UserActive;
            p1.ActiveTiles.Add(tiles[66]);

            for (var i = 14; i < 27; i++)
            {
                tiles[i].Owner  = p2.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p2.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 27; i < 42; i++)
            {
                if (i == 27 || i == 28)
                {
                    continue;
                }
                tiles[i].Owner  = p3.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p3.ActiveTiles.Add(tiles[i]);
            }
            for (var i = 53; i < 68; i++)
            {
                if (i == 61 || i == 62 || i == 66)
                {
                    continue;
                }
                tiles[i].Owner  = p4.ConnectionId;
                tiles[i].Status = TileStatus.UserActive;
                p4.ActiveTiles.Add(tiles[i]);
            }
            tiles[80].Owner  = p4.ConnectionId;
            tiles[80].Status = TileStatus.UserActive;
            p4.ActiveTiles.Add(tiles[80]);
        }