/// <summary> /// Dient eenmalig uitgevoerd te worden /// </summary> private void InitializeTiles(ISessionFactory factory) { Random random = new Random(); int result = 0; var nhSession = factory.OpenSession(); MapTiles = nhSession.QueryOver<MapTile>().List(); if (MapTiles.IsEmpty()) { MapTiles = new List<MapTile>(); using (var transaction = nhSession.BeginTransaction()) { for (int x = 0; x < 8; x++) { for (int y = 0; y < 8; y++) { result = random.Next(0, 10); var tile = new MapTile() {Name = "Wasteland", X = x, Y = y}; MapTiles.Add(tile); nhSession.Save(tile); } } transaction.Commit(); } } }
void Awake() { Debug.Log("Awake WorldMap"); MapTile tempMapTile; BitMapDecoder bmd = new BitMapDecoder(heightmap); terrainData = terrain.terrainData; int heighMapWidth = terrainData.heightmapWidth; int heighMapHeight = terrainData.heightmapHeight; float[,] tempFloat = terrainData.GetHeights(0, 0, heighMapWidth, heighMapHeight); tilesDictionary = new Dictionary<string, MapTile>(); for (int z = 0; z < mapSizeZ; z++ ) { for (int x = 0; x < mapSizeX; x++) { tempMapTile = new MapTile(x,z); int height = BitMapDecoder.getHeightPos(x, z); tempMapTile.setY(height); //tempFloat[x*2+1, z*2+1] = height / 5; tempFloat[x * 2, z*2 * 2] = (float)height / 10; //tempFloat[x*2, z * 2+1] = height / 5; //tempFloat[x * 2 + 1, z * 2] = height / 5; tilesDictionary.Add(("x" + x.ToString() + "z" + z.ToString()), tempMapTile); } } terrain.terrainData.SetHeights(0, 0, tempFloat); }
public void EnrollToMove(Ant ant, MapTile destination) { if (destination.State == TileState.Water) goto enrollSelf; // we do not want many ants moving into the same tile. // first one in will move there successfully // todo: notify the ant of the collision. We will then ask the ant to reroute itself than forcing it to yield. if (this._enrolledDestinations.ContainsKey(destination)) goto enrollSelf; Direction direction; MapTile currentPosition = ant.CurrentPosition; if (currentPosition.North == destination) direction = Direction.North; else if (currentPosition.South == destination) direction = Direction.South; else if (currentPosition.East == destination) direction = Direction.East; else if (currentPosition.West == destination) direction = Direction.West; else goto enrollSelf; var enrolledDetinationKey = new EnrolledDestinationKey(ant, direction); this._enrolledDestinations.Add(destination, enrolledDetinationKey); this._quickFastForwardMapping.Add(currentPosition, destination); return; enrollSelf: this.EnrollCurrentLocation(ant); }
public PlayerMapTile(string gameId, string userId, MapTile mapTile) { this.UserId = userId; this.Path = this.GetType().Name;// +"/" + this.UserId; this.GameId = gameId; this.Tile = mapTile; }
public void CreateWorldFromMapTiles(MapTile[,] map) { world = (MapTile[,])map.Clone(); worldSizeX = map.GetLength(0); worldSizeY = map.GetLength(1); MapGenerator.singleton.CreateLoadedWorldMesh(true); }
public void HasCompletedMoveTo(MapTile destination) { if (this.MovementStrategy == null) return; if (this.NextMove == destination) this.MovementStrategy.HasMovedIntoStep(); else this.MovementStrategy.MovementWasNotMade(); }
internal MapChunk(int width, int height, string typeString) { Width = width; Height = height; Seams = new List<Point>(); TreasureChests = new List<Point>(); Doors = new List<Point>(); Cosmetics = new List<Point>(); PlayerPosition = Point.Invalid; Type = (MapNodeType)Enum.Parse(typeof(MapNodeType), typeString, false); MapSegment = new MapTile[Width, Height]; }
public DoorHorizontalTileSet() : base() { MapTile upperTile = new MapTile("Images/MapTiles/DoorHorizontalTop.png", false, false, false, false, true, false, false, false, true, false); MapTile lowerTile = new MapTile("Images/MapTiles/DoorHorizontalBottom.png", false, false, true, false, false, false, true, false, false, false); OpenDoorAction openDoorAction = new OpenDoorAction(upperTile, lowerTile); upperTile.AddAction(openDoorAction); lowerTile.AddAction(openDoorAction); AddTile(upperTile, new Point(0, 0)); AddTile(lowerTile, new Point(0, 1)); }
public DoorVerticalTileSet() : base() { MapTile leftTile = new MapTile("Images/MapTiles/DoorVerticalLeft.png", false, false, false, true, false, false, false, true, false, false); MapTile rightTile = new MapTile("Images/MapTiles/DoorVerticalRight.png", false, true, false, false, false, false, false, false, false, true); OpenDoorAction openDoorAction = new OpenDoorAction(leftTile, rightTile); leftTile.AddAction(openDoorAction); rightTile.AddAction(openDoorAction); AddTile(leftTile, new Point(0, 0)); AddTile(rightTile, new Point(1, 0)); }
public void Init() { mRowCount = vMapWidth / vTileSize; mColCount = vMapHeight / vTileSize; mMapTiles = new MapTile[mRowCount, mColCount]; for (int iCol = 0; iCol < mColCount; iCol++) { for (int iRow = 0; iRow < mRowCount; iRow++) { //MapTile lMapTile = new MapTile(iCol * vMapWidth + iRow, new Vector2((iRow * vTileSize), (iCol * vTileSize)), vTileSize); MapTile lMapTile = new MapTile(iCol * vMapWidth + iRow, iRow, iCol, vTileSize); mMapTiles[iRow, iCol] = lMapTile; } } }
internal MapChunk(MapChunk chunk) { Width = chunk.Width; Height = chunk.Height; Seams = new List<Point>(chunk.Seams); TreasureChests = new List<Point>(chunk.TreasureChests); Doors = new List<Point>(chunk.Doors); Cosmetics = new List<Point>(chunk.Cosmetics); PlayerPosition = chunk.PlayerPosition; Type = chunk.Type; MapSegment = new MapTile[Width, Height]; for (int i = 0; i < Width; ++i) { for (int j = 0; j < Height; ++j) { MapSegment[i, j] = new MapTile(chunk.MapSegment[i, j]); } } }
public void Insert(int idx, MapTile t) { tiles.Insert(idx, t); }
public void Add(MapTile t) { tiles.Add(t); }
public ASPathNode pathNode; // A node to build a path public LocalTile(MapTile tile) { this.tile = tile; }
void LoadTile() { IsolatedStorageSettings tilesettings = IsolatedStorageSettings.ApplicationSettings; if (tilesettings.Contains("Tile")) { tile = (MapTile)tilesettings["Tile"]; } else { tile = MapTile.road; } }
public void Delete(MapTile mapTile) { db.MapTiles.DeleteOnSubmit(mapTile); }
/// <summary> /// Find the mapTile we want to move to. Respecting selected attack and target. /// </summary> /// <returns>The move destination.</returns> /// <param name="attack">The selected attack</param> /// <param name="attackTarget">The target we want to attack</param> MapTile FindMoveDestination(Attack attack, Unit attackTarget) { // by default we don't move (= move to the current mapTile) MapTile moveDestionation = controlledUnit.mapTile; // if all mapTiles have penalty 1 // this is the highes range we can attack someone this turn int moveRangWithAttack = controlledUnit.MovePoints; int maxRange = attack.range + moveRangWithAttack; int maxTargetDst = Distance(attackTarget.mapTile, controlledUnit.mapTile); if (maxRange > maxTargetDst) { // we can propably hit the target this turn // find the mapTile furthes away from target where we still can hit it Vector pos = new Vector(controlledUnit.mapTile.x, controlledUnit.mapTile.y); byte[][] dstMatrix = controller.GetDistanceMatrix(pos, moveRangWithAttack, false); for (int i = 0; i < dstMatrix.Length; i++) { for (int j = 0; j < dstMatrix[i].Length; j++) { if (dstMatrix[i][j] > 0) { // this mapTile is reachable int dstTarget = Distance(model.mapTiles[i][j], attackTarget.mapTile); if (dstTarget <= attack.range) { // this mapTile is close enough to the target to attack if (dstTarget > maxTargetDst) { // take the furthest mapTile (still in range) maxTargetDst = dstTarget; moveDestionation = model.mapTiles[i][j]; } } } } } } // if we found a new destination stop here if (moveDestionation != controlledUnit.mapTile) { return(moveDestionation); } // we couldn't find a mapTile in range where we can hit the target // get as close as possible to the target Debug.Log("Target out of range - get closer!"); // use the pathfinder to get closed path to enemies and cut depending on remaining Action Points model.UseMoveGrid(); byte[,] grid = model.grid; // ignore target unit on grid so a* can get a result grid[attackTarget.mapTile.x, attackTarget.mapTile.y] = attackTarget.mapTile.PenaltyAttack; Path path = controller.GetPath(controlledUnit.mapTile, attackTarget.mapTile, grid); if (path.Empty) { attackTarget = null; // clear attack target and search a new one next turn return(moveDestionation); } path.DropLast(); while (path.Cost > controlledUnit.MovePoints) { // remove last maptile from path until the cost are lower than action points path.DropLast(); } return(path[path.Length - 1]); }
private void CalculateMapPVS() { for (int i = 0; i < tileList.Count; i++) { MapTile tile1 = tileList[i]; XmlDocument xmlDoc = new XmlDocument(); XmlElement xmlRoot = xmlDoc.CreateElement("root"); XmlElement tileElement = xmlDoc.CreateElement("tile"); tileElement.SetAttribute("x", tile1.x.ToString()); tileElement.SetAttribute("z", tile1.z.ToString()); xmlRoot.AppendChild(tileElement); for (int j = 0; j < tile1.portalList.Count; j++) { Portal portal = tile1.portalList[j]; XmlElement portalElement = xmlDoc.CreateElement("portal"); portalElement.SetAttribute("x", portal.x.ToString()); portalElement.SetAttribute("z", portal.z.ToString()); tileElement.AppendChild(portalElement); for (int k = 0; k < tileList.Count; k++) { MapTile tile2 = tileList[k]; Vector3 t1Center = new Vector3(tile1.x + tile1.tileSize / 2, 0, tile1.z + tile1.tileSize / 2); Vector3 t2Center = new Vector3(tile2.x + tile2.tileSize / 2, 0, tile2.z + tile2.tileSize / 2); if (Vector3.Distance(t1Center, t2Center) <= visibleRange) { for (int c1 = 0; c1 < tile2.bigAreaList.Count; c1++) { Cell cell = tile2.bigAreaList[c1]; XmlElement cellElement = CalculateCellPVS(cell, portal, xmlDoc); if (cellElement != null) { portalElement.AppendChild(cellElement); } } for (int c2 = 0; c2 < tile2.middleAreaList.Count; c2++) { Cell cell = tile2.middleAreaList[c2]; XmlElement cellElement = CalculateCellPVS(cell, portal, xmlDoc); if (cellElement != null) { portalElement.AppendChild(cellElement); } } for (int c3 = 0; c3 < tile2.smallAreaList.Count; c3++) { Cell cell = tile2.smallAreaList[c3]; XmlElement cellElement = CalculateCellPVS(cell, portal, xmlDoc); if (cellElement != null) { portalElement.AppendChild(cellElement); } } } } } string xmlDataPath = Application.dataPath + "/Resources/" + tile1.id + ".xml"; xmlDoc.AppendChild(xmlRoot); xmlDoc.Save(xmlDataPath); } }
private void CaptureCellGrid(MapTile tile, MapItemSize size) { Vector3 cellSize = Vector3.zero; targetAreaPointCount = 0; switch (size) { case MapItemSize.Big: cellSize = bigCellSize; targetAreaPointCount = UnityEngine.Random.Range((int)endPortalPointList.y, (int)endPortalPointList.x); break; case MapItemSize.Middle: cellSize = middleCellSize; targetAreaPointCount = UnityEngine.Random.Range((int)endPortalPointList.x, (int)endPortalPointList.y); break; case MapItemSize.Small: cellSize = smallCellSize; targetAreaPointCount = UnityEngine.Random.Range((int)endPortalPointList.w, (int)endPortalPointList.z); break; default: cellSize = bigCellSize; targetAreaPointCount = UnityEngine.Random.Range(16, 16); break; } int tileHorizontalCells = Mathf.CeilToInt(tileSize.x / cellSize.x); int tileVerticalCells = Mathf.CeilToInt(tileSize.z / cellSize.z); List <Cell> cellList = new List <Cell>(tileHorizontalCells * tileVerticalCells); for (int i = 0; i < tileHorizontalCells; i++) { for (int j = 0; j < tileVerticalCells; j++) { Cell cell = new Cell(); cell.size = size; cell.Id = cellList.Count + 1 + (tile.id - 1) * tileHorizontalCells * tileVerticalCells; cell.x = (int)(tile.x + i * cellSize.x); cell.z = (int)(tile.z + j * cellSize.z); cell.rayEndPointList = new List <Vector3>(targetAreaPointCount); for (int k = 0; k < targetAreaPointCount; k++) { Vector3 point = new Vector3(); float x = UnityEngine.Random.Range(0, cellSize.x); float z = UnityEngine.Random.Range(0, cellSize.z); point.x = cell.x + x; point.z = cell.z + z; cell.rayEndPointList.Add(point); } cellList.Add(cell); } } switch (size) { case MapItemSize.Big: tile.bigAreaList = cellList; break; case MapItemSize.Middle: tile.middleAreaList = cellList; break; case MapItemSize.Small: tile.smallAreaList = cellList; break; default: tile.bigAreaList = cellList; break; } }
private MapTile getAvailabelStep(Troop unit) { MapTile mt = null; List <string> keys = new List <string>(); keys.Add((unit.x + 1) + "_" + unit.y); keys.Add((unit.x - 1) + "_" + unit.y); keys.Add(unit.x + "_" + (unit.y + 1)); keys.Add(unit.x + "_" + (unit.y - 1)); List <MapTile> tiles = new List <MapTile>(); foreach (string key in keys) { MapTile tile = null; if (modelGame.mapTiles.TryGetValue(key, out tile)) { tiles.Add(tile); } } tiles.Sort((MapTile t1, MapTile t2) => { int v1 = 0; int v2 = 0; if (t1.troop) { if (t1.troop.country == eCountry.A) { v1 += 1; } else { v1 -= 1; } } else { if (t1.type == eTileType.CrossLand) { v1 += 3; } else { v1 += 2; } } if (t2.troop) { if (t2.troop.country == eCountry.A) { v2 += 1; } else { v2 -= 1; } } else { if (t2.type == eTileType.CrossLand) { v2 += 3; } else { v2 += 2; } } return(v2 - v1); }); if (tiles[0].troop == null || tiles[0].troop.country != eCountry.B) { mt = tiles[0]; } return(mt); }
public BehaviorOnTile(MapTile mapTile, Curio curio) { MapTile = mapTile; Curio = curio; }
MapTile[,] GenTilePos(MapTile[,] previousMap) { int width = previousMap.GetLength(0); int height = previousMap.GetLength(1); MapTile[,] newMap = new MapTile[width, height]; int nbOfNeighbor; BoundsInt bounds = new BoundsInt(-1, -1, 0, 3, 3, 1); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { nbOfNeighbor = 0; foreach (Vector3Int b in bounds.allPositionsWithin) { if (b.x == 0 && b.y == 0) { continue; } if (x + b.x >= 0 && x + b.x < width && y + b.y >= 0 && y + b.y < height) { if (previousMap[x + b.x, y + b.y].isSolid) { nbOfNeighbor += 1; } } else { nbOfNeighbor++; } } if (previousMap[x, y].isSolid) { bool isSolid; if (nbOfNeighbor < rule_deathLimit) { isSolid = false; } else { isSolid = true; } newMap[x, y] = new MapTile(new Vector2Int(x, y), isSolid); } if (!previousMap[x, y].isSolid) { bool isSolid; if (nbOfNeighbor > rule_birthLimit) { isSolid = true; } else { isSolid = false; } newMap[x, y] = new MapTile(new Vector2Int(x, y), isSolid); } } } return(newMap); }
public IEnumerator AddOre(MapTile[,] map) { isGenerating = true; int width = map.GetLength(0); int height = map.GetLength(1); BoundsInt bounds = new BoundsInt(-1, -1, 0, 3, 3, 1); int nbChunk = map.GetLength(0) / rule_chunkSize; for (int i = 0; i < nbChunk; i++) { for (int j = 0; j < nbChunk; j++) { #region Get solid tiles in chunk List <MapTile> solidTiles = new List <MapTile>(); for (int x = 0; x < rule_chunkSize; x++) { for (int y = 0; y < rule_chunkSize; y++) { Vector2Int pos = new Vector2Int(x + i * rule_chunkSize, y + j * rule_chunkSize); if (pos.x >= 0 && pos.x < width && pos.y >= 0 && pos.y < height) { MapTile t = map[pos.x, pos.y]; if (t.type == MapTile.TileType.SOLID) { solidTiles.Add(t); } } } } #endregion #region Create vein int nbVein = Random.Range(1, rule_veinPerChunk); while (nbVein > 0 && solidTiles.Count > 0) { MapTile currentTile = solidTiles[Random.Range(0, solidTiles.Count)]; solidTiles.Remove(currentTile); if (!currentTile.isOccuped) { SO_Ore selectedOre = GetRandomOre(); int veinSize = Random.Range(0, rule_maxOrePerVein + 1); List <MapTile> possibleTile = new List <MapTile>(); possibleTile.Add(currentTile); while (possibleTile.Count > 0 && veinSize > 0) { MapTile t = possibleTile[Random.Range(0, possibleTile.Count)]; foreach (Vector3Int b in bounds.allPositionsWithin) { if (t.position.x + b.x >= 0 && t.position.x + b.x < width && t.position.y + b.y >= 0 && t.position.y + b.y < height) { if (solidTiles.Contains(map[t.position.x + b.x, t.position.y + b.y])) { if (!map[t.position.x + b.x, t.position.y + b.y].isOccuped) { possibleTile.Add(map[t.position.x + b.x, t.position.y + b.y]); } } } } possibleTile.Remove(t); t.AddOre(selectedOre); veinSize--; } nbVein--; } } #endregion } } isGenerating = false; yield return(null); }
public IEnumerator AssociateRegions(MapTile[,] mapTile, List <MapRegion> previousRegions) { isGenerating = true; int width = mapTile.GetLength(0); int height = mapTile.GetLength(1); List <MapRegion> regionTooSmall = new List <MapRegion>(); List <MapRegion> regions = new List <MapRegion>(); foreach (MapRegion region in previousRegions) { regions.Add(new MapRegion(region)); } #region Get region that need to be fussioned //On récupère les régions plus petite que le nombre minimum et qui ne sont pas fermée for (int i = 0; i < regions.Count; i++) { MapRegion region = regions[i]; if (region.tiles.Count < rule_maximumTileToBefusionned && region.type != MapRegion.TypeRegion.CLOSED) { regionTooSmall.Add(region); regions.Remove(region); i--; } } #endregion #region Fussion all region with bigger one BoundsInt bounds = new BoundsInt(-1, -1, 0, 3, 3, 1); //On parcourt la lsite des régions trop petite pour les fussionner aux région voisines foreach (MapRegion region in regionTooSmall) { List <MapTile> tilesToCheck = new List <MapTile>(); foreach (MapTile t in region.tiles) { tilesToCheck.Add(t); } for (int i = 0; i < tilesToCheck.Count; i++) { MapTile currentTile = tilesToCheck[i]; foreach (Vector3Int b in bounds.allPositionsWithin) { if (b.x == 0 && b.y == 0) { continue; } if (currentTile.position.x + b.x >= 0 && currentTile.position.x + b.x < width && currentTile.position.y + b.y >= 0 && currentTile.position.y + b.y < height) //Is in the map { MapTile testTile = mapTile[currentTile.position.x + b.x, currentTile.position.y + b.y]; foreach (MapRegion r in regions) { if (r.tiles.Contains(testTile)) { r.Fusion(region); i = tilesToCheck.Count; break; } } } } } yield return(null); } #endregion #region Associate regions to type of regions int corner = Random.Range(0, 3); //for the spawn area we use a region in a corner Vector2Int closestPoint = new Vector2Int(0, 0); switch (corner) { case 0: //top left closestPoint = new Vector2Int(0, mapTile.GetLength(1) - 1); break; case 1: //top right closestPoint = new Vector2Int(mapTile.GetLength(0) - 1, mapTile.GetLength(1) - 1); break; case 2: // bottom right closestPoint = new Vector2Int(mapTile.GetLength(0) - 1, 0); break; case 3: // bottom left break; } bool regionFound = false; List <MapTile> possibleTile = new List <MapTile>(); for (int x = 0; x < mapTile.GetLength(0); x++) { for (int y = 0; y < mapTile.GetLength(1); y++) { possibleTile.Add(mapTile[x, y]); } } possibleTile = possibleTile.OrderBy(x => Vector2Int.Distance(x.position, closestPoint)).ToList(); while (!regionFound) { MapTile currentTile = possibleTile.First(); possibleTile.Remove(currentTile); if (!currentTile.isSolid) { foreach (MapRegion region in regions) { if (region.tiles.Contains(currentTile) && region.type != MapRegion.TypeRegion.CLOSED) { region.SetType(MapRegion.TypeRegion.PLAYER_SPAWN); regionFound = true; break; } } } } //for the nest region we use some regions in the opposite corner switch (corner) { case 0: //top left for player => bottom right closestPoint = new Vector2Int(mapTile.GetLength(0) - 1, 0); break; case 1: //top right for player => bottom left closestPoint = new Vector2Int(0, 0); break; case 2: // bottom right for player => top left closestPoint = new Vector2Int(0, mapTile.GetLength(1) - 1); break; case 3: // bottom left for player => top right closestPoint = new Vector2Int(mapTile.GetLength(0) - 1, mapTile.GetLength(1) - 1); break; } int regionToFoundForNest = 1; // TO CHANGE possibleTile = new List <MapTile>(); for (int x = 0; x < mapTile.GetLength(0); x++) { for (int y = 0; y < mapTile.GetLength(1); y++) { possibleTile.Add(mapTile[x, y]); } } possibleTile = possibleTile.OrderBy(x => Vector2Int.Distance(x.position, closestPoint)).ToList(); while (regionToFoundForNest > 0) { MapTile currentTile = possibleTile[0]; possibleTile.Remove(currentTile); if (!currentTile.isSolid) { foreach (MapRegion region in regions) { if (region.tiles.Contains(currentTile) && region.type == MapRegion.TypeRegion.NORMAL) { region.SetType(MapRegion.TypeRegion.NEST); regionToFoundForNest--; break; } } } } #endregion GetComponent <MapController>().ClearRegions(); foreach (MapRegion region in regions) { GetComponent <MapController>().AddRegion(region); } isGenerating = false; }
Carto.Graphics.Bitmap CreateBitmap(HTTPTileDataSource source, MapTile tile) { return(Carto.Graphics.Bitmap.CreateFromCompressed(source.LoadTile(tile).Data)); }
unsafe public static void Draw(MapTile tile, TmpFile tmp, DrawingSurface ds) { tmp.Initialize(); if (tile.SubTile >= tmp.Images.Count) { return; } TmpFile.TmpImage img = tmp.Images[tile.SubTile]; var zBuffer = ds.GetZBuffer(); var heightBuffer = ds.GetHeightBuffer(); Palette p = tile.Palette; // calculate tile index -> pixel index Point offset = new Point(tile.Dx * tmp.BlockWidth / 2, (tile.Dy - tile.Z) * tmp.BlockHeight / 2); // make touched tiles (used for determining image cutoff) Point center = offset + new Size(tmp.BlockWidth / 2, tmp.BlockHeight / 2); var centerGridTile = tile.Layer.GetTileScreen(center, true, true); if (centerGridTile != null) { tile.Layer.GridTouched[centerGridTile.Dx, centerGridTile.Dy / 2] |= TileLayer.TouchType.ByNormalData; tile.Layer.GridTouchedBy[centerGridTile.Dx, centerGridTile.Dy / 2] = tile; } Logger.Trace("Drawing TMP file {0} (subtile {1}) at ({2},{3})", tmp.FileName, tile.SubTile, offset.X, offset.Y); int stride = ds.BitmapData.Stride; int halfCx = tmp.BlockWidth / 2, halfCy = tmp.BlockHeight / 2; // writing bounds var w_low = (byte *)ds.BitmapData.Scan0; byte *w_high = (byte *)ds.BitmapData.Scan0 + stride * ds.BitmapData.Height; byte *w = (byte *)ds.BitmapData.Scan0 + stride * offset.Y + (offset.X + halfCx - 2) * 3; int rIdx = 0, x, y = 0; int zIdx = offset.Y * ds.Width + offset.X + halfCx - 2; int cx = 0; // Amount of pixel to copy for (; y < halfCy; y++) { cx += 4; for (ushort c = 0; c < cx; c++) { byte paletteValue = img.TileData[rIdx]; short zBufVal = (short)((tile.Rx + tile.Ry) * tmp.BlockHeight / 2 - (img.ZData != null ? img.ZData[rIdx] : 0)); if (paletteValue != 0 && w_low <= w && w < w_high && zBufVal >= zBuffer[zIdx]) { *(w + 0) = p.Colors[paletteValue].B; *(w + 1) = p.Colors[paletteValue].G; *(w + 2) = p.Colors[paletteValue].R; zBuffer[zIdx] = zBufVal; heightBuffer[zIdx] = (short)(tile.Z * Drawable.TileHeight / 2); } w += 3; zIdx++; rIdx++; } w += stride - 3 * (cx + 2); zIdx += ds.Width - (cx + 2); } w += 12; zIdx += 4; for (; y < tmp.BlockHeight; y++) { cx -= 4; for (ushort c = 0; c < cx; c++) { byte paletteValue = img.TileData[rIdx]; short zBufVal = (short)((tile.Rx + tile.Ry) * tmp.BlockHeight / 2 - (img.ZData != null ? img.ZData[rIdx] : 0)); if (paletteValue != 0 && w_low <= w && w < w_high && zBufVal >= zBuffer[zIdx]) { *(w + 0) = p.Colors[paletteValue].B; *(w + 1) = p.Colors[paletteValue].G; *(w + 2) = p.Colors[paletteValue].R; zBuffer[zIdx] = zBufVal; heightBuffer[zIdx] = (short)(tile.Z * Drawable.TileHeight / 2); } w += 3; zIdx++; rIdx++; } w += stride - 3 * (cx - 2); zIdx += ds.Width - (cx - 2); } if (!img.HasExtraData) { return; // we're done now } offset.X += img.ExtraX - img.X; offset.Y += img.ExtraY - img.Y; w = w_low + stride * offset.Y + 3 * offset.X; zIdx = offset.X + offset.Y * ds.Width; rIdx = 0; // identify extra-data affected tiles for cutoff var extraScreenBounds = Rectangle.FromLTRB( Math.Max(0, offset.X), Math.Max(0, offset.Y), Math.Min(offset.X + img.ExtraWidth, ds.Width), Math.Min(offset.Y + img.ExtraHeight, ds.Height)); for (int by = extraScreenBounds.Top; by < extraScreenBounds.Bottom; by += tmp.BlockHeight / 2) { for (int bx = extraScreenBounds.Left; bx < extraScreenBounds.Right; bx += tmp.BlockWidth / 2) { var gridTileNoZ = tile.Layer.GetTileScreen(new Point(bx, by), true, true); if (gridTileNoZ != null) { Logger.Trace("Tile at ({0},{1}) has extradata affecting ({2},{3})", tile.Dx, tile.Dy, gridTileNoZ.Dx, gridTileNoZ.Dy); tile.Layer.GridTouched[gridTileNoZ.Dx, gridTileNoZ.Dy / 2] |= TileLayer.TouchType.ByExtraData; tile.Layer.GridTouchedBy[gridTileNoZ.Dx, gridTileNoZ.Dy / 2] = tile; } } } // Extra graphics are just a square for (y = 0; y < img.ExtraHeight; y++) { for (x = 0; x < img.ExtraWidth; x++) { // Checking per line is required because v needs to be checked every time byte paletteValue = img.ExtraData[rIdx]; short zBufVal = (short)((tile.Rx + tile.Ry) * tmp.BlockHeight / 2 + (img.ExtraZData != null ? img.ExtraZData[rIdx] : 0)); if (paletteValue != 0 && w_low <= w && w < w_high && zBufVal >= zBuffer[zIdx]) { *w++ = p.Colors[paletteValue].B; *w++ = p.Colors[paletteValue].G; *w++ = p.Colors[paletteValue].R; zBuffer[zIdx] = zBufVal; heightBuffer[zIdx] = (short)(img.ExtraHeight - y + tile.Z * Drawable.TileHeight / 2); } else { w += 3; } zIdx++; rIdx++; } w += stride - img.ExtraWidth * 3; zIdx += ds.Width - img.ExtraWidth; } }
private void drawImage(System.Drawing.Graphics g, MapTile tile, TileType tileType, ImageAttributes imageA) { ClassImage img = FindImage(baseNames[tileType] + tile.Name); string baseUrl = tile.Url; IDataHelper data = dataHelpers[tileType]; if (img == null) { img = data.GetImage(baseUrl, tile.Name); if (img == null) { img = new ClassImage(); } if (img.PicImage != null) listImages.Add(img); } img.IsDiscard = false; img.Left = tile.Left; img.Top = tile.Top; if (img.Left < -nPerWidth || img.Left > _width || img.Top > _height || img.Top < -nPerWidth) { return; } Rectangle rect = new Rectangle(img.Left, img.Top, nPerWidth, nPerWidth); if (img.PicImage != null && g != null) g.DrawImage(img.PicImage, rect, 0, 0, nPerWidth, nPerWidth, GraphicsUnit.Pixel, imageA); }
// ONLY USED BY THE MAP EDITOR public void CreateEmptyWorld(Vector2 size) { // create a new array world = WorldController.singleton.world; worldSize = size; WorldController.singleton.chunkSize = chunkSize; // create the world chunk array // get the sizes for the array int chunkXSize = Mathf.CeilToInt(size.x/chunkSize); int chunkYSize = Mathf.CeilToInt(size.y/chunkSize); // create the array worldChunks = new WorldChunk[chunkXSize,chunkYSize]; // determine the offset required so that the world starts at 0,0 Vector3 extraPos = new Vector3(chunkSize/2,0,chunkSize/2); // fill in the array for(int i=0;i<worldChunks.GetLength(0);i++){ for(int j=0;j<worldChunks.GetLength(1);j++){ // instantiate a new chunk GameObject newChunk = (GameObject)Instantiate(chunkPrefab,Vector3.zero,Quaternion.identity); // set the position worldChunks[i,j] = newChunk.GetComponent<WorldChunk>(); worldChunks[i,j].SetChunk(new Vector3(i*chunkSize,0,j*chunkSize)+extraPos,i,j); if(worldContainer != null){ newChunk.transform.parent = worldContainer; } } } // random thing here /*for(int n=0;n<ripple.Length;n++){ if(n < (ripple.Length-1)){ ripple[n] = ripple[n+1]; } else{ ripple[n] = ripple[0]; } }*/ // populate the array for(int i=0;i<world.GetLength(0);i++){ for(int j=0;j<world.GetLength(1);j++){ // for minecraft like world, do this //world[i,j] = new MapTile((byte)(j+i)); // draw some borders if((i==0 || i==(size.x-1)) || (j==0 || j==(size.y-1))){ world[i,j] = new MapTile(10); } else{ world[i,j] = new MapTile(1); } } } // create the world mesh CreateNewWorldMesh(); // TODO remove this MapEditor.CreateColliders(); /*CreateWorldMesh(size); floorMeshFilter.mesh = floorMesh; wallMeshFilter.mesh = wallMesh; print ("Floor:"); print ("Total Vertices: "+floorMesh.vertexCount); print ("Total Triangles: "+(floorMesh.triangles.Length/3)); print ("Walls:"); print ("Total Vertices: "+wallMesh.vertexCount); print ("Total Triangles: "+(wallMesh.triangles.Length/3));*/ }
//근접한 타일 검색 public void CalcNearbyTile() { if (_emptyTile == true) { return; } int width = TileWidth; int height = TileHeight; //int width = GameManager.Instance.TileWidth; //int height = GameManager.Instance.TileHeight; //_tileT = GameManager.Instance.GetTile(_index - width); //_tileB = GameManager.Instance.GetTile(_index + width); _tileT = GetTile(_index - width); _tileB = GetTile(_index + width); //if( _index % 2 == 0) int widthIDX = _index % width; if (widthIDX % 2 == 0) { if (widthIDX != 0) { //_tileLT = GameManager.Instance.GetTile(_index - width - 1); //_tileLB = GameManager.Instance.GetTile(_index - 1); _tileLT = GetTile(_index - width - 1); _tileLB = GetTile(_index - 1); } else { _tileLT = null; _tileLB = null; } if (widthIDX < width - 1) { //_tileRT = GameManager.Instance.GetTile(_index - width + 1); //_tileRB = GameManager.Instance.GetTile(_index + 1); _tileRT = GetTile(_index - width + 1); _tileRB = GetTile(_index + 1); } else { _tileRT = null; _tileRB = null; } } else { if (widthIDX != 0) { //_tileLT = GameManager.Instance.GetTile(_index - 1); //_tileLB = GameManager.Instance.GetTile(_index + width - 1); _tileLT = GetTile(_index - 1); _tileLB = GetTile(_index + width - 1); } else { _tileLT = null; _tileLB = null; } if (widthIDX < width - 1) { //_tileRT = GameManager.Instance.GetTile(_index + 1); //_tileRB = GameManager.Instance.GetTile(_index + width + 1); _tileRT = GetTile(_index + 1); _tileRB = GetTile(_index + width + 1); } else { _tileRT = null; _tileRB = null; } } }
private async Task LoadDataAsync() { using (var reader = new StreamReader(DataConstants.AssemblyLocation + "/Data/Maps.json")) { _maps = new List <Map>(); var mapTiles = await _mapTileRepo.GetDataAsync(); var formations = await _enemyFormationTemplate.GetDataAsync(); JContainer mapsAsList = JsonConvert.DeserializeObject <JContainer>(reader.ReadToEnd()); foreach (var mapObject in mapsAsList) { var map = mapObject.ToObject <Map>(); var mapConnections = new List <int>(); List <Transport> transports = null; if (mapObject["transportAssignments"] != null) { transports = mapObject["transportAssignments"].ToObject <List <Transport> >(); foreach (var transport in transports) { mapConnections.Add(transport.TransportMapId); } map.MapConnections = mapConnections; } if (mapObject["enemies"] != null) { var spawnData = new List <SpawnEntityData>(); var enemyData = mapObject["enemies"].ToObject <List <EnemyData> >(); foreach (var enemy in enemyData) { var foundTemplate = formations.FirstOrDefault(f => f.Id == enemy.FormationId); if (foundTemplate != null) { spawnData.Add(new SpawnEntityData { FormationTemplate = foundTemplate, MaxEntities = enemy.Amount, RespawnTime = enemy.RespawnTime }); } } map.SpawnData = spawnData; } if (mapObject["mapTileIds"] != null) { var mapTileIds = mapObject["mapTileIds"].ToObject <List <List <int> > >(); var uniqueTiles = new List <MapTile>(); var mapData = new List <List <MapTile> >(); for (int i = 0; i < mapTileIds.Count(); i++) { mapData.Add(new List <MapTile>()); for (int j = 0; j < mapTileIds[i].Count(); j++) { var foundTile = mapTiles.First(tile => tile.Id == mapTileIds[i][j]); if (!uniqueTiles.Contains(foundTile)) { uniqueTiles.Add(mapTiles.First(tile => tile.Id == mapTileIds[i][j])); } if (foundTile.CanTransport && transports != null) { foundTile = new MapTile(foundTile); var transport = transports.FirstOrDefault (tr => tr.TransportFrom.PositionX == i && tr.TransportFrom.PositionY == j); if (transport != null) { foundTile.TransportLocation = transport.TransportTo; foundTile.TransportMapId = transport.TransportMapId; } } mapData[i].Add(foundTile); } } map.MapData = mapData; map.UniqueTiles = uniqueTiles; } _maps.Add(map); } } }
internal void ReadSegmentFromFile(StreamReader reader) { for (int j = 0; j < Height; ++j) { string tileLine = reader.ReadLine(); for (int i = 0; i < Width; ++i) { MapSegment[i, j] = new MapTile(); switch (tileLine[i]) { case '#': MapSegment[i, j].Terrain = TerrainType.Wall; break; case '.': MapSegment[i, j].Terrain = TerrainType.Floor; break; case '^': MapSegment[i, j].Terrain = TerrainType.Floor; Seams.Add(new Point(i, j)); break; case '@': MapSegment[i, j].Terrain = TerrainType.Floor; if (PlayerPosition != Point.Invalid) throw new InvalidOperationException("Can't have multiple player position on a mapchunk"); PlayerPosition = new Point(i, j); break; case '+': MapSegment[i, j].Terrain = TerrainType.Floor; TreasureChests.Add(new Point(i, j)); break; case 'D': MapSegment[i, j].Terrain = TerrainType.Floor; Doors.Add(new Point(i, j)); break; case 'C': MapSegment[i, j].Terrain = TerrainType.Floor; Cosmetics.Add(new Point(i, j)); break; } } } }
private PathFigure FigureRender(MapTile tile, TileSide direction = TileSide.Left, bool inside = false) { var pathFigure = new PathFigure(); AddTile(tile); var position = CalcPosition(direction, tile); pathFigure.StartPoint = position; var insidePath = new Dictionary <Point, KeyValuePair <TileSide, MapTile> >(); do { if (!inside) { var opposite = Opposite(direction); if (GetTile(tile, opposite) is MapTile opTile && opTile.Item != _wallType) { var checkPoint = CalcPosition(opposite, tile); if (!insidePath.ContainsKey(checkPoint)) { insidePath.Add(checkPoint, new KeyValuePair <TileSide, MapTile>(opposite, tile)); } } } switch (direction) { case TileSide.Left: if (UpLeft(tile) is MapTile upLeft) { tile = upLeft; direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else if (Up(tile) is MapTile up) { tile = up; direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else if (tile.X == 0) { if (Up(tile, true) is MapTile upEdge) { position = CalcPosition(TileSide.Left, upEdge); pathFigure.Segments.Add(new LineSegment { Point = position }); direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else { pathFigure.Segments.Add(new LineSegment { Point = new Point(0, 0) }); direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } } else if (tile.Y == 0) { pathFigure.Segments.Add(new ArcSegment { Point = CalcPosition(TileSide.Top, Left(tile, true)), Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else { direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = CornerSize, SweepDirection = SweepDirection.Clockwise }); } break; case TileSide.Top: if (UpRight(tile) is MapTile upRight) { tile = upRight; direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else if (Right(tile) is MapTile right) { tile = right; direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else if (tile.X == _map.MaxWidth) { if (Up(tile, true) is MapTile upEdge) { pathFigure.Segments.Add(new ArcSegment { Point = CalcPosition(TileSide.Right, upEdge), Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else { pathFigure.Segments.Add(new LineSegment { Point = new Point(_map.Width * 10, 0) }); direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } } else if (tile.Y == 0) { pathFigure.Segments.Add(new LineSegment { Point = CalcPosition(TileSide.Top, Right(tile, true)) }); direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else { direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = CornerSize, SweepDirection = SweepDirection.Clockwise }); } break; case TileSide.Right: if (DownRight(tile) is MapTile downRight) { tile = downRight; direction = TileSide.Top; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else if (Down(tile) is MapTile down) { tile = down; direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else if (tile.X == _map.MaxWidth) { if (Down(tile, true) is MapTile downEdge) { pathFigure.Segments.Add(new LineSegment { Point = CalcPosition(TileSide.Right, downEdge) }); direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else { pathFigure.Segments.Add(new LineSegment { Point = new Point(_map.Width * 10, _map.Height * 10) }); direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } } else if (tile.Y == _map.MaxHeight) { pathFigure.Segments.Add(new ArcSegment { Point = CalcPosition(TileSide.Bottom, Right(tile, true)), Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else { direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = CornerSize, SweepDirection = SweepDirection.Clockwise }); } break; case TileSide.Bottom: if (DownLeft(tile) is MapTile downLeft) { tile = downLeft; direction = TileSide.Right; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else if (Left(tile) is MapTile left) { tile = left; direction = TileSide.Bottom; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } else if (tile.X == 0) { if (Down(tile, true) is MapTile downEdge) { pathFigure.Segments.Add(new ArcSegment { Point = CalcPosition(TileSide.Left, downEdge), Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } if (tile.Y == _map.MaxHeight) { pathFigure.Segments.Add(new LineSegment { Point = new Point(0, _map.Height * 10) }); direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new LineSegment { Point = position }); } } else if (tile.Y == _map.MaxHeight) { pathFigure.Segments.Add(new LineSegment { Point = CalcPosition(TileSide.Bottom, Left(tile, true)) }); direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = ArcSize, SweepDirection = SweepDirection.Counterclockwise }); } else { direction = TileSide.Left; position = CalcPosition(direction, tile); pathFigure.Segments.Add(new ArcSegment { Point = position, Size = CornerSize, SweepDirection = SweepDirection.Clockwise }); } break; default: throw new ArgumentOutOfRangeException(); } AddTile(tile); if (insidePath.ContainsKey(position)) { insidePath.Remove(position); } } while (pathFigure.StartPoint != position); if (!inside && insidePath.Any()) { foreach (var segment in pathFigure.Segments) { if (segment is ArcSegment arc) { if (insidePath.ContainsKey(arc.Point)) { insidePath.Remove(arc.Point); } } else if (segment is LineSegment line) { if (insidePath.ContainsKey(line.Point)) { insidePath.Remove(line.Point); } } } if (insidePath.Any()) { var insideWall = insidePath.Values.First(); Combine(insideWall.Value, insideWall.Key); } } return(pathFigure); }
public void Generate() { int room_count = Random.Range(this.minimumRoomCount, this.maximumRoomCount); int min_size = this.min_size; int max_size = this.max_size; map_size = (maximumRoomCount + roomMargin) * max_size ; map = new MapTile[map_size, map_size]; for (var x = 0; x < map_size; x++) { for (var y = 0; y < map_size; y++) { map[x,y] = new MapTile(); map[x,y].type = 0; } } rooms = new List<Room> (); this.roomMarginTemp = this.roomMargin; for (var i = 0; i < room_count; i++) { Room room = new Room(); if(rooms.Count == 0) { room.x = Random.Range(10,20); room.y = Random.Range(10,20); room.w = Random.Range(min_size, max_size); room.h = Random.Range(min_size, max_size); } else{ Room lastRoom = rooms[rooms.Count -1]; if (lastRoom.x > 1 + max_size) { room.x = Random.Range(1 , lastRoom.x + lastRoom.w + this.roomMargin); } else { room.x = Random.Range(lastRoom.x , lastRoom.x + lastRoom.w + this.roomMargin); } if (lastRoom.y > 1 + max_size) { room.y = Random.Range(1 , lastRoom.y + lastRoom.h + this.roomMargin); } else { room.y = Random.Range(lastRoom.y , lastRoom.y + lastRoom.h + this.roomMargin); } room.w = Random.Range(min_size, max_size); room.h = Random.Range(min_size, max_size); } bool doesCollide = this.DoesCollide(room,0); if (doesCollide && prune) { i--; this.roomMargin += 1; } else { this.roomMargin = roomMarginTemp; room.w--; room.h--; rooms.Add(room); } } //corridor making if (maximumRoomCount != 1) { for (int i = 0; i < 10; i++) { Room roomA = null; Room roomB = null; while (roomA == roomB) { roomA = rooms[Random.Range(0, rooms.Count)]; roomB = rooms[Random.Range(0, rooms.Count)]; } var pointA = new Room(); pointA.x = Random.Range(roomA.x, roomA.x + roomA.w); pointA.y = Random.Range(roomA.y, roomA.y + roomA.h); var pointA2 = new Room(); pointA2.x = pointA.x + 1; pointA2.y = pointA.y; var pointB = new Room(); pointB.x = Random.Range(roomB.x, roomB.x + roomB.w); pointB.y = Random.Range(roomB.y, roomB.y + roomB.h); var pointB2 = new Room(); pointB2.x = pointB.x; pointB2.y = pointB.y + 1; roomA.connectedTo = roomB; while ( (pointB.x != pointA.x) || (pointB.y != pointA.y) || (pointB2.x != pointA2.x) || (pointB2.y != pointA2.y) ) { if (pointB.x != pointA.x) { if (pointB.x > pointA.x) { pointB.x--; } else { pointB.x++; } } else if (pointB.y != pointA.y) { if (pointB.y > pointA.y) { pointB.y--; } else { pointB.y++; } } if (pointB2.x != pointA2.x) { if (pointB2.x > pointA2.x) { pointB2.x--; } else { pointB2.x++; } } else if (pointB2.y != pointA2.y) { if (pointB2.y > pointA2.y) { pointB2.y--; } else { pointB2.y++; } } map[pointB.x,pointB.y].type = 3; map[pointB2.x, pointB2.y].type = 3; } } } //room making for (int i = 0; i < rooms.Count; i++) { Room room = rooms[i]; for (int x = room.x; x < room.x + room.w; x++) { for (int y = room.y; y < room.y + room.h; y++) { map[x,y].type = 1; map[x,y].room = room; } } } //walls for (int x = 0; x < map_size -1 ; x++) { for (int y = 0; y < map_size -1 ; y++) { if (map[x,y].type == 0) { if( (map[x + 1,y].type == 1 || map[x + 1,y].type == 3) || (map[x,y + 1].type == 1 || map[x,y + 1].type == 3) || (x > 0 && (map[x - 1,y].type == 1 || map[x - 1,y].type == 3)) || (y > 0 && (map[x,y - 1].type == 1 || map[x,y - 1].type == 3)) ) { map[x,y].type = 2; } } } } //corners for (int x = 0; x < map_size -1 ; x++) { for (int y = 0; y < map_size -1 ; y++) { if (map[x,y + 1].type == 2 && map[x + 1,y].type == 2 && roomsandfloors.Contains(map[x + 1,y +1].type) ) { map[x,y].type = 4; } if(y > 0){ if (map[x + 1,y].type == 2 && map[x,y - 1].type == 2 && roomsandfloors.Contains(map[x + 1,y - 1].type) ) { map[x,y].type = 5; } } if(x > 0){ if (map[x - 1,y].type == 2 && map[x,y + 1].type == 2 && roomsandfloors.Contains(map[x - 1,y + 1].type) ) { map[x,y].type = 7; } } if(x > 0 && y >0){ if (map[x - 1,y].type == 2 && map[x,y - 1].type == 2 && roomsandfloors.Contains(map[x - 1,y - 1].type) ) { map[x,y].type = 6; } } } } //find far away room goalRoom = rooms[rooms.Count -1 ]; if (goalRoom != null) { goalRoom.x = goalRoom.x + (goalRoom.w / 2); goalRoom.y = goalRoom.y + (goalRoom.h / 2); } //starting point startRoom = rooms[0]; startRoom.x = startRoom.x + (startRoom.w / 2); startRoom.y = startRoom.y + (startRoom.h / 2); }
public MainPage() : base(typeof(MainViewModel), typeof(MainContentUI), Device.Idiom == TargetIdiom.Phone ? PanelSetEnum.psLeftRight : PanelSetEnum.psRight) { BackgroundColor = MainStyles.ListBackgroundColor.FromResources <Color>(); appBar = new TitleBar(this, TitleBar.BarBtnEnum.bbLeftRight, TitleBar.BarAlignEnum.baBottom) { BarColor = Color.Transparent, BtnRight = { Source = contentUI.IconMenuSideBar } }; appBar.BtnRight.Click += viewModel.AppBar_BtnRightClick; MapLocation = new MapTile { HasScrollEnabled = true, HasZoomEnabled = true, Context = contentUI }; MapLocation.ClickPinDetail += viewModel.MapLocation_ClickPinDetail; mainLayout = new RelativeLayout(); mainLayout.Children.Add(MapLocation.MapLayout, Constraint.Constant(0), Constraint.Constant(0), Constraint.RelativeToParent(parent => parent.Width), Constraint.RelativeToParent(parent => parent.Height)); mainLayout.Children.Add(appBar, Constraint.Constant(0), Constraint.RelativeToParent( parent => parent.Height - appBar.HeightBar - appBar.Margin.VerticalThickness), Constraint.RelativeToParent(parent => parent.Width)); PanelChanged += (sender, args) => { if (args.IsShow) { MapLocation.CloseDetailInfo(); } }; InitPanelsAndLayout(); var safeAreaHelper = new SafeAreaHelper(); safeAreaHelper.UseSafeArea(this, SafeAreaHelper.CustomSafeAreaFlags.None); safeAreaHelper.UseSafeArea(appBar, SafeAreaHelper.CustomSafeAreaFlags.Horizontal | SafeAreaHelper.CustomSafeAreaFlags.Bottom); safeAreaHelper.UseSafeArea(RightPanel.Content, SafeAreaHelper.CustomSafeAreaFlags.Top | SafeAreaHelper.CustomSafeAreaFlags.Right); if (LeftPanel != null) { safeAreaHelper.UseSafeArea(LeftPanel.Content, SafeAreaHelper.CustomSafeAreaFlags.Top | SafeAreaHelper.CustomSafeAreaFlags.Left); } if (btnLocation != null) { safeAreaHelper.UseSafeArea(btnLocation, SafeAreaHelper.CustomSafeAreaFlags.Left); } if (Device.RuntimePlatform == Device.Android) { safeAreaHelper.UseSafeArea(MapLocation.MapPinDetail, SafeAreaHelper.CustomSafeAreaFlags.All); } ContentLayout.Children.Add(mainLayout); }
void FromCenterAndEdges(int middle, int maxDiffs, MapTile MT) { int temp = middle; for (int i = 0; i < (BlocksInTile / 4 + 1); i++) { temp += UnityEngine.Random.Range(-maxDiffs, (maxDiffs + 1)); for (int j = 0; j < 9; j++) { MT.blocks[j][i] = ((j < temp) ? 4 : 3);//4-empty; 3-solid without topping } /*temp = UnityEngine.Random.Range(-maxDiffs, (maxDiffs+1)); * for (int j = 4 + temp; j != 4- (int)Mathf.Sign(temp); j -= (int)Mathf.Sign(temp)) * { * MT.blocks[j][i] = ((j < (4-(int)Mathf.Sign(temp))) ? 3 : 4);//4-empty; 3-solid without topping * }*/ } temp = 4; for (int i = BlocksInTile / 2; i > (BlocksInTile / 4); i--) { temp += UnityEngine.Random.Range(-maxDiffs, (maxDiffs + 1)); for (int j = 0; j < 9; j++) { MT.blocks[j][i] = ((j < temp) ? 4 : 3);//4-empty; 3-solid without topping } } temp = 4; for (int i = BlocksInTile / 2 + 1; i < (3 * (BlocksInTile / 4) + 1); i++) { temp += UnityEngine.Random.Range(-maxDiffs, (maxDiffs + 1)); for (int j = 0; j < 9; j++) { MT.blocks[j][i] = ((j < temp) ? 4 : 3);//4-empty; 3-solid without topping } } temp = 4; for (int i = BlocksInTile - 1; i > (3 * (BlocksInTile / 4)); i--) { temp += UnityEngine.Random.Range(-maxDiffs, (maxDiffs + 1)); for (int j = 0; j < 9; j++) { MT.blocks[j][i] = ((j < temp) ? 4 : 3);//4-empty; 3-solid without topping } }/**/ } void SetBiomeCenter(int biome_index) { //prevents biome centers overlap if (biome_index != 0) { while (true) { Biomes[biome_index].Center.x = UnityEngine.Random.Range(0, Width); Biomes[biome_index].Center.y = UnityEngine.Random.Range(0, Height); for (int prev_biomes = 0; prev_biomes < biome_index; prev_biomes++) { if ((Biomes[biome_index].Center.x == Biomes[prev_biomes].Center.x) && (Biomes[biome_index].Center.y == Biomes[prev_biomes].Center.y)) { continue; } } break; } } else { Biomes[biome_index].radius = 0; Biomes[biome_index].Center.x = Width / 2; Biomes[biome_index].Center.y = Height / 2; } } int SetBiomeRadius(int min_radius, List <BiomeTilesData> BTD, int biomeIndex) { if (biomeIndex > 0) { return(UnityEngine.Random.Range(min_radius, (Width * (int)BTD[biomeIndex].Size) / 100)); } else { return((int)(Math.Sqrt(Width * Width + Height * Height) + 1)); } } /*void GenerateAllTilesStuffing(List<AllBiomePrefabs> PrefabsOfAllBiomes) * { * //fix; both this parameters must be calculated, considering biome and some diapasone of values * int MaxBGObjectAmount = 10; * int MaxBarricadesAmount = 10; * * for (int y = 0; y < Height; y++) * { * for (int x = 0; x < Width; x++) * { * //Tiles.Tiles [y] [x].FrontalBackgroundIndex = Random.Range (0, PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].FrontalBackground.Count); * //Tiles.Tiles [y] [x].RoadIndex = Random.Range (0, PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].Road.Count); * for (int BGObjectAmount = 0; BGObjectAmount < MaxBGObjectAmount; BGObjectAmount++) * { * Tiles.Tiles [y] [x].TileBackgroundObjects [BGObjectAmount] = PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].BackgroundObjects[Random.Range (0, PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].BackgroundObjects.Count)]; * //fix; choose their coordinates somehow * } * for (int BarricadesAmount = 0; BarricadesAmount < MaxBarricadesAmount; BarricadesAmount++) * { * Tiles.Tiles [y] [x].TileBarrcicades [BarricadesAmount] = PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].Barricades[Random.Range (0, PrefabsOfAllBiomes [(int)Tiles.Tiles [y] [x].biome].Barricades.Count)]; * //fix; choose their coordinates somehow; maybe add point array, or make new class int+point; maybe make list of objects instead of list of ints * } * } * } * }*/ void SetTiles() { List <List <BiomeTilesData> > B = GameObject.Find("WorldManager").GetComponent <WorldManagement>().BiomePrefabs; GenerateHorizontalCorridors(); GenerateVerticalCorridors(); FixCorridors(); for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { SetTileBiome(x, y); GenerateBlocks(Tiles[y][x], 1); GeneratePlatforms(x, y, B); AdjustPlatformPositions(x, y); //PrintTileToFile(Tiles[y][x].blocks, x, y); } } //SaveGame(); } void SetTileBiome(int x, int y) { int chosen = 0; float shortestDistance = 100000.0f; float newDistance; for (int i = 1; i < BiomeTilesData.BiomesAmount; i++) { newDistance = GetDistance(x, y, (int)Biomes[i].Center.x, (int)Biomes[i].Center.y); if ((newDistance < shortestDistance) && (newDistance <= Biomes[i].radius)) { shortestDistance = newDistance; chosen = i; } } Tiles[y][x].biome1 = (BiomesTypes)chosen; } float GetDistance(int x1, int y1, int x2, int y2) { float x = x1 - x2; float y = y1 - y2; return((float)(Math.Sqrt(x * x + y * y))); } void GenerateHorizontalCorridors() { int corridor_length = 0; for (int y = 0; y < Height; y++) { for (int x = 0; x < Width; x++) { if (corridor_length == 0) { if (UnityEngine.Random.Range(0, 2) == 1) { corridor_length = UnityEngine.Random.Range(MinimumCorridorLength, MaximumCorridorLength) + 1; if (UnityEngine.Random.Range(0, 2) == 1) { if (x > 0) { Tiles [y] [x - 1].passages[1] = PassageType.Door; Tiles [y] [x].passages[3] = PassageType.Door; } } } } if (corridor_length != 0) { if ((x + 1) < Width) { Tiles [y] [x].passages[1] = PassageType.Corridor; Tiles [y] [x + 1].passages[3] = PassageType.Corridor; } corridor_length--; } } } } void GenerateVerticalCorridors() { int corridor_length = 0; for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { if (corridor_length == 0) { if (UnityEngine.Random.Range(0, 2) == 1) { corridor_length = UnityEngine.Random.Range(MinimumCorridorLength, MaximumCorridorLength) + 1; if (UnityEngine.Random.Range(0, 2) == 1) { if (y > 0) { Tiles [y - 1] [x].passages[2] = PassageType.Door; Tiles [y] [x].passages[0] = PassageType.Door; } } } } if (corridor_length != 0) { if ((y + 1) < Height) { if ((Tiles [y] [x].passages[1] == PassageType.Corridor) || (Tiles [y] [x].passages[3] == PassageType.Corridor)) { if (UnityEngine.Random.Range(0, 2) == 1) { Tiles [y] [x].passages[2] = PassageType.Door; Tiles [y + 1] [x].passages[0] = PassageType.Door; } else { if (Tiles [y] [x].passages[1] == PassageType.Corridor) { Tiles [y] [x].passages[1] = PassageType.Door; Tiles [y] [x + 1].passages[3] = PassageType.Door; } if (Tiles [y] [x].passages[3] == PassageType.Corridor) { Tiles [y] [x - 1].passages[1] = PassageType.Door; Tiles [y] [x].passages[3] = PassageType.Door; } if (Tiles [y + 1] [x].passages[1] == PassageType.Corridor) { Tiles [y + 1] [x].passages[1] = PassageType.Door; Tiles [y + 1] [x + 1].passages[3] = PassageType.Door; } if (Tiles [y + 1] [x].passages[3] == PassageType.Corridor) { Tiles [y + 1] [x - 1].passages[1] = PassageType.Door; Tiles [y + 1] [x].passages[3] = PassageType.Door; } Tiles [y] [x].passages[2] = PassageType.Corridor; Tiles [y + 1] [x].passages[0] = PassageType.Corridor; } } else { Tiles [y] [x].passages[2] = PassageType.Door; Tiles [y + 1] [x].passages[0] = PassageType.Door; } } corridor_length--; } } } } void FixCorridors() { for (int y = 0; y < Height - 1; y++) { for (int x = 0; x < Width - 1; x++) { if (Tiles[y][x].passages[2] != Tiles[y + 1][x].passages[0]) { Tiles[y][x].passages[2] = FixConnection(Tiles[y][x].passages[2], Tiles[y + 1][x].passages[0]); Tiles[y + 1][x].passages[0] = FixConnection(Tiles[y][x].passages[2], Tiles[y + 1][x].passages[0]); } if (Tiles[y][x].passages[1] != Tiles[y][x + 1].passages[3]) { Tiles[y][x].passages[1] = FixConnection(Tiles[y][x].passages[1], Tiles[y][x + 1].passages[3]); Tiles[y][x + 1].passages[3] = FixConnection(Tiles[y][x].passages[1], Tiles[y][x + 1].passages[3]); } } } for (int x = 0; x < Width; x++) { Tiles[0][x].passages[0] = PassageType.No; } for (int y = 0; y < Height; y++) { Tiles[y][Width - 1].passages[1] = PassageType.No; } for (int x = 0; x < Width; x++) { Tiles[Height - 1][x].passages[2] = PassageType.No; } for (int y = 0; y < Height; y++) { Tiles[y][0].passages[3] = PassageType.No; } } PassageType FixConnection(PassageType pass1, PassageType pass2) { if ((pass1 == PassageType.No) || (pass2 == PassageType.No)) { return(PassageType.No); } if ((pass1 == PassageType.SecretDoor) || (pass2 == PassageType.SecretDoor)) { return(PassageType.SecretDoor); } if ((pass1 == PassageType.Door) || (pass2 == PassageType.Door)) { return(PassageType.Door); } return(PassageType.Corridor); } void GeneratePlatforms(int x, int y, List <List <BiomeTilesData> > BiomePrefabs) { for (int i = 0; i < BiomePrefabs[(int)Tiles[y][x].biome1][(int)Tiles[y][x].biome2].PlatformPrefab.Count; i++) { if (!BiomePrefabs[(int)Tiles[y][x].biome1][(int)Tiles[y][x].biome2].PlatformPrefab[i].GetComponent <Platform>().sub) { Tiles[y][x].TilePlatforms.AddRange(BiomePrefabs[(int)Tiles[y][x].biome1][(int)Tiles[y][x].biome2].PlatformPrefab[i].GetComponent <Platform>().GeneratePlatforms(Tiles[y][x].blocks)); } } } void AdjustPlatformPositions(int x, int y) { int midlevel = 4; float inclinedOffsety = 0.0f; int j; int k; for (int i = 0; i < Tiles[y][x].TilePlatforms.Count; i++)//need children of active child of BGPartNumberAsChild { k = (int)(Tiles[y][x].TilePlatforms[i].location.x / 1.5f) + Tiles[y][x].blocks[0].Count / 2; if (k < 0) { k = 0; } if (k > Tiles[y][x].blocks[0].Count - 1) { k = Tiles[y][x].blocks[0].Count - 1; } for (j = 0; j < 9; j++) { if (Tiles[y][x].blocks[j][k] != 4) { break; } } Tiles[y][x].TilePlatforms[i].location = new SVector3(Tiles[y][x].TilePlatforms[i].location.x, Tiles[y][x].TilePlatforms[i].location.y + (midlevel - j - inclinedOffsety) * 1.5f, Tiles[y][x].TilePlatforms[i].location.z + 0.0f); } }/* * float inclinedOffsety = 0.0f; * int j = 0; * int k = 0; * for (int i=0; i<Tiles[y][x].TilePlatforms.Count; i++) * { * j = 0; * k = ((int)(Tiles[y][x].TilePlatforms[i].location.x / 1.5f) + Tiles[y][x].blocks[0].Count / 2); * if (k < 0) * k = 0; * if (k > Tiles[y][x].blocks[0].Count - 1) * k = Tiles[y][x].blocks[0].Count - 1; * for (j = 0; j < 9; j++) * { * if (Tiles[y][x].blocks[j][k] != 4) * break; * } * if (Tiles[y][x].blocks[j][k] == 1) * { * if (k != 0) * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x % k; * if (inclinedOffsety > 1.5f) * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x % (k - 1); * } * } * else * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x; * } * inclinedOffsety = 1.5f - inclinedOffsety; * } * if (Tiles[y][x].blocks[j][k] == 2) * { * if (k != 0) * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x % k; * if (inclinedOffsety > 1.5f) * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x % (k - 1); * } * } * else * { * inclinedOffsety = Tiles[y][x].TilePlatforms[i].location.x; * } * } * Tiles[y][x].TilePlatforms[i].location = new SVector3(Tiles[y][x].TilePlatforms[i].location.x, * Tiles[y][x].TilePlatforms[i].location.y + (4-j- inclinedOffsety) *1.5f, * Tiles[y][x].TilePlatforms[i].location.z + 0.0f); * } * }*/ /*bool LoadTiles() * { * // 1 * //Debug.Log(Application.persistentDataPath); * if (File.Exists(Application.persistentDataPath + "/gamesave.save"))//"C:/Users/Василий.Василий-ПК/Documents/Grimoire Forest/Exe" * { * BinaryFormatter bf = new BinaryFormatter(); * FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open);//"C:/Users/Василий.Василий-ПК/Documents/Grimoire Forest/Exe" * try * { * Tiles = (SaveLoad)bf.Deserialize(file); * } * catch(System.Exception exc) * { * Debug.Log ("Whoopsy-doodle!"); * file.Close(); * return false; * } * file.Close(); * return true; * } * return false; * } * public void SaveGame() * { * // 1 * /*for (int x = 0; x < Width; x++) * for (int y = 0; y < Height; y++) * { * if (Save.SavedTiles.Count < (x * Height + y)) * Save.SavedTiles.Add (new TileSave()); * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].FrontalBackgroundIndex = Tiles [y] [x].FrontalBackgroundIndex; * Save.SavedTiles [x * Height + y].RoadIndex = Tiles [y] [x].RoadIndex; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * Save.SavedTiles [x * Height + y].biome = Tiles [y] [x].biome; * } * foreach (GameObject targetGameObject in targets) * { * Target target = targetGameObject.GetComponent<Target>(); * if (target.activeRobot != null) * { * Save.livingTargetPositions.Add(target.position); * Save.livingTargetsTypes.Add((int)target.activeRobot.GetComponent<Robot>().type); * i++; * } * } * * * * Save.hits = hits; * Save.shots = shots;*/ // 2 /*BinaryFormatter bf = new BinaryFormatter(); * FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");//"C:/Users/Василий.Василий-ПК/Documents/Grimoire Forest/Exe" * bf.Serialize(file, Tiles); * file.Close(); * } */ void PrintTileToFile(List <List <int> > Tiles, int x1, int y1, bool noPass = false) { string name; if (noPass) { name = "TestTile" + y1.ToString() + x1.ToString() + "1.txt"; } else { name = "TestTile" + y1.ToString() + x1.ToString() + ".txt"; } var sr = File.CreateText(name); for (int y = 0; y < 9; y++) { for (int x = 0; x < 50; x++) { switch (Tiles[y][x]) { case 0: sr.Write("="); // break; case 1: sr.Write("/"); // break; case 2: sr.Write("\\"); // break; case 3: sr.Write("#"); // break; default: break; } } sr.WriteLine(); } sr.Close(); } void PrintMapToFile(bool noPass = false) { string name; if (noPass) { name = "TestMap1.txt"; } else { name = "TestMap.txt"; } var sr = File.CreateText(name); for (int y = 0; y < Height; y++) { if (!noPass) { for (int x = 0; x < Width; x++) { switch (Tiles[y][x].passages[0]) { case PassageType.No: sr.Write(" "); // break; case PassageType.Door: sr.Write(" |"); // break; case PassageType.SecretDoor: sr.Write(" :"); // break; case PassageType.Corridor: sr.Write(" H"); // break; default: break; } } sr.WriteLine(); } for (int x = 0; x < Width; x++) { if (!noPass) { switch (Tiles[y][x].passages[3]) { case PassageType.No: sr.Write(" "); break; case PassageType.Door: sr.Write("-"); break; case PassageType.SecretDoor: sr.Write("~"); break; case PassageType.Corridor: sr.Write("="); break; default: break; } } switch (Tiles [y] [x].biome1) { case BiomesTypes.Forest: sr.Write('T'); break; case BiomesTypes.Dump: sr.Write('%'); break; /*case BiomesTypes.DumpWaterfall: * sr.Write ('!'); * break; * case BiomesTypes.DumpShroom: * sr.Write ('&'); * break; * case BiomesTypes.DumpRiver: * sr.Write ('@'); * break; * case BiomesTypes.DumpCaves: * sr.Write ('8'); * break; * case BiomesTypes.DumpSwamp: * sr.Write ('+'); * break; * case BiomesTypes.DumpMill: * sr.Write ('M'); * break; * case BiomesTypes.DumpMaze: * sr.Write ('='); * break;*/ case BiomesTypes.Waterfall: sr.Write('|'); break; /*case BiomesTypes.WaterfallShroom: * sr.Write ('F'); * break; * case BiomesTypes.WaterfallRiver: * sr.Write ('^'); * break; * case BiomesTypes.WaterfallCaves: * sr.Write ('0'); * break; * case BiomesTypes.WaterfallSwamp: * sr.Write ('K'); * break; * case BiomesTypes.WaterfallMill: * sr.Write ('['); * break; * case BiomesTypes.WaterfallMaze: * sr.Write ('{'); * break;*/ case BiomesTypes.Shroom: sr.Write('P'); break; /*case BiomesTypes.ShroomRiver: * sr.Write ('R'); * break; * case BiomesTypes.ShroomCaves: * sr.Write ('9'); * break; * case BiomesTypes.ShroomSwamp: * sr.Write ('*'); * break; * case BiomesTypes.ShroomMill: * sr.Write ('p'); * break; * case BiomesTypes.ShroomMaze: * sr.Write ('Y'); * break;*/ case BiomesTypes.River: sr.Write('~'); break; /*case BiomesTypes.RiverCaves: * sr.Write ('s'); * break; * case BiomesTypes.RiverSwamp: * sr.Write ('w'); * break; * case BiomesTypes.RiverMill: * sr.Write ('a'); * break; * case BiomesTypes.RiverMaze: * sr.Write ('$'); * break;*/ case BiomesTypes.Caves: sr.Write('O'); break; /*case BiomesTypes.CavesSwamp: * sr.Write ('C'); * break; * case BiomesTypes.CavesMill: * sr.Write ('B'); * break; * case BiomesTypes.CavesMaze: * sr.Write ('G'); * break;*/ case BiomesTypes.Swamp: sr.Write('x'); break; /*case BiomesTypes.SwampMill: * sr.Write ('y'); * break; * case BiomesTypes.SwampMaze: * sr.Write ('W'); * break;*/ case BiomesTypes.Mill: sr.Write('A'); break; /*case BiomesTypes.MillMaze: * sr.Write ('H'); * break;*/ case BiomesTypes.Maze: sr.Write('#'); break; default: sr.Write('.'); break; } /*switch (Tiles [y] [x].eastern_passage) * { * case PassageType.No: * sr.Write (" "); * break; * case PassageType.Door: * sr.Write ("-"); * break; * case PassageType.SecretDoor: * sr.Write ("~"); * break; * case PassageType.Corridor: * sr.Write ("="); * break; * default: * break; * }*/ } sr.WriteLine(); /*for (int x = 0; x < Width; x++) * { * switch (Tiles [y] [x].southern_passage) * { * case PassageType.No: * sr.Write (" "); * break; * case PassageType.Door: * sr.Write (" | "); * break; * case PassageType.SecretDoor: * sr.Write (" : "); * break; * case PassageType.Corridor: * sr.Write (" H "); * break; * default: * break; * } * } * sr.WriteLine ();*/ } sr.Close(); } }
public SearchResults Search(HexagonalTileSearchProblem Problem, uint DepthLimit) { Queue <Tuple <MapTile, uint> > Frontier; Dictionary <MapTile, MapTile> Paths; Dictionary <MapTile, bool> Explored; SearchResults r = new SearchResults(); if (Problem == null) { return(r); } Frontier = new Queue <Tuple <MapTile, uint> >(); Frontier.Enqueue(new Tuple <MapTile, uint>(Problem.Start, DepthLimit)); //Storage of the Search Tiles mapped to the Tile that Led to Their Discovery. Paths = new Dictionary <MapTile, MapTile>(); Explored = new Dictionary <MapTile, bool>((int)Problem.SearchSpace.Size); foreach (MapTile mt in Problem.SearchSpace.XYTiles()) { Explored.Add(mt, false); } /* **** SEARCH ****** */ MapTile current = null; uint currentDepth; DateTime start_time = DateTime.Now; while (Frontier.Count != 0) { if (Frontier.Count > r.SpaceComplexity) { //We have a new maxmim number of nodes. r.SpaceComplexity = Frontier.Count; } current = Frontier.Peek().Item1; currentDepth = Frontier.Dequeue().Item2; Explored[current] = true; //Set the current node as explore. r.TimeComplexity++; //We have explored another node. //SUCCESS! if (current == Problem.Goal) { r.Solved = true; break; } if (currentDepth == 0) { //We have reached the limit we are allowed to search on this branch. break; } foreach (MapTile mt in current.GetNeighbours()) { if (Frontier.FirstOrDefault(p => p.Item1 == mt) == null && Explored[mt] == false) { try { Paths.Add(mt, current); } catch (ArgumentException) { Paths[mt] = current; } Frontier.Enqueue(new Tuple <MapTile, uint>(mt, currentDepth - 1)); } } } DateTime end_time = DateTime.Now; r.TimeInMilliseconds = (int)(end_time - start_time).TotalMilliseconds; //If we found a solution, find the path we actually discovered. if (r.Solved) { r.Path = SearchHelper.GetPathFromStart(current, Paths, Problem.Start); } Log.Info(string.Format("BFS: Search Complete - Solution {0}", r.Solved ? "Found" : "Not Found")); return(r); }
public void AdjustHeightOnSides(int ht, Neighbors mask, bool top, MapTile next) { if(top && (heights == null || heights.Length == 0)) { heights = new int[]{1, 1, 1, 1}; } if(!top && (baselines == null || baselines.Length == 0)) { baselines = new int[]{0, 0, 0, 0}; } int hts = ht > 0 ? 1 : -1; while(ht != 0) { int hcl = heights[(int)Corners.Left]; int hcf = heights[(int)Corners.Front]; int hcr = heights[(int)Corners.Right]; int hcb = heights[(int)Corners.Back]; int bcl = baselines[(int)Corners.Left]; int bcf = baselines[(int)Corners.Front]; int bcr = baselines[(int)Corners.Right]; int bcb = baselines[(int)Corners.Back]; int aboveTileZIfAny = next != null ? next.z : int.MaxValue; if(top) { //raise rules: if corners are different heights, only raise the lower one; // don't raise a corner if it will cause a collision with a tile above //lower rules: if corners are different heights, only lower the higher one; // don't lower a height to or below its corresponding baseline if((mask & Neighbors.FrontLeft) != 0) { if(hts > 0 ? (hcl <= hcf && z+hcl < aboveTileZIfAny) : (hcl >= hcf && hcl > bcl+1)) { heights[(int)Corners.Left] += hts; } if(hts > 0 ? (hcf <= hcl && z+hcf < aboveTileZIfAny) : (hcf >= hcl && hcf > bcf+1)) { heights[(int)Corners.Front] += hts; } } if((mask & Neighbors.FrontRight) != 0) { if(hts > 0 ? (hcr <= hcf && z+hcr < aboveTileZIfAny) : (hcr >= hcf && hcr > bcr+1)) { heights[(int)Corners.Right] += hts; } if(hts > 0 ? (hcf <= hcr && z+hcf < aboveTileZIfAny) : (hcf >= hcr && hcf > bcf+1)) { heights[(int)Corners.Front] += hts; } } if((mask & Neighbors.BackRight) != 0) { if(hts > 0 ? (hcr <= hcb && z+hcr < aboveTileZIfAny) : (hcr >= hcb && hcr > bcr+1)) { heights[(int)Corners.Right] += hts; } if(hts > 0 ? (hcb <= hcr && z+hcb < aboveTileZIfAny) : (hcb >= hcr && hcb > bcb+1)) { heights[(int)Corners.Back] += hts; } } if((mask & Neighbors.BackLeft) != 0) { if(hts > 0 ? (hcl <= hcb && z+hcl < aboveTileZIfAny) : (hcl >= hcb && hcl > bcl+1)) { heights[(int)Corners.Left] += hts; } if(hts > 0 ? (hcb <= hcl && z+hcb < aboveTileZIfAny) : (hcb >= hcl && hcb > bcb+1)) { heights[(int)Corners.Back] += hts; } } } else { //raise rules: if corners are different heights, only raise the lower one; // don't raise a baseline to or above its corresponding height; // while all corners are raised above 0, decrement all corners by 1 and increase z by 1. //lower rules: if corners are different heights, only lower the higher one; // don't lower a corner below 0 // (later: don't lower a corner below 0 if there is a tile below;) // (later: while any corner is below 0, increment all corners by 1 and decrease z by 1) if((mask & Neighbors.FrontLeft) != 0) { if(hts > 0 ? (bcl <= bcf && bcl+1<hcl) : (bcl >= bcf && bcl > 0)) { baselines[(int)Corners.Left] += hts; } if(hts > 0 ? (bcf <= bcl && bcf+1<hcf) : (bcf >= bcl && bcf > 0)) { baselines[(int)Corners.Front] += hts; } } if((mask & Neighbors.FrontRight) != 0) { if(hts > 0 ? (bcr <= bcf && bcr+1<hcr): (bcr >= bcf && bcr > 0)) { baselines[(int)Corners.Right] += hts; } if(hts > 0 ? (bcf <= bcr && bcf+1<hcf) : (bcf >= bcr && bcf > 0)) { baselines[(int)Corners.Front] += hts; } } if((mask & Neighbors.BackRight) != 0) { if(hts > 0 ? (bcr <= bcb && bcr+1<hcr) : (bcr >= bcb && bcr > 0)) { baselines[(int)Corners.Right] += hts; } if(hts > 0 ? (bcb <= bcr && bcb+1<hcb) : (bcb >= bcr && bcb > 0)) { baselines[(int)Corners.Back] += hts; } } if((mask & Neighbors.BackLeft) != 0) { if(hts > 0 ? (bcl <= bcb && bcl+1<hcl) : (bcl >= bcb && bcl > 0)) { baselines[(int)Corners.Left] += hts; } if(hts > 0 ? (bcb <= bcl && bcb+1<hcb) : (bcb >= bcl && bcb > 0)) { baselines[(int)Corners.Back] += hts; } } while(baselines[(int)Corners.Left] > 0 && baselines[(int)Corners.Front] > 0 && baselines[(int)Corners.Right] > 0 && baselines[(int)Corners.Back] > 0) { baselines[(int)Corners.Left]--; baselines[(int)Corners.Front]--; baselines[(int)Corners.Right]--; baselines[(int)Corners.Back]--; z++; } } ht -= hts; } }
public void AddTile(MapTile tile) { this.tiles.Add(tile); }
public int IndexOf(MapTile t) { return tiles.IndexOf(t); }
public static void SaveMap() { string dataPath = Application.streamingAssetsPath; //Serialize map GameObject map = GameObject.Find("Map"); MapSerializable mapSerializable = new MapSerializable(map); foreach (Transform tileTransform in map.transform) { if (tileTransform.gameObject != map) { //Tile GameObject tileGO = tileTransform.gameObject; MapTile tile = new MapTile(tileGO); foreach (Transform tileElementTransform in tileGO.transform) { //Tile Element if (tileElementTransform.gameObject != tileGO) { String text = tileElementTransform.GetComponentInChildren <TextMesh>() != null?tileElementTransform.GetComponentInChildren <TextMesh>().text : null; TileElement tileElement = new TileElement(tileElementTransform.gameObject, "MapBuilding", text); tileElement.SetAlterable(false); tile.AddElement(tileElement); } } mapSerializable.AddTile(tile); } } int i = 1; SerializedScene serializedScene = new SerializedScene(); serializedScene.SetMap(mapSerializable); //Serialize Additional Elements GameObject additionalElementContainer = GameObject.Find("AdditionalElements"); foreach (Transform elementTransform in additionalElementContainer.transform) { if (elementTransform.gameObject != additionalElementContainer && elementTransform.GetComponentInChildren <MeshFilter>() != null && elementTransform.gameObject.activeInHierarchy) { TileElement tileElement; String text = elementTransform.GetComponentInChildren <TextMesh>() != null?elementTransform.GetComponentInChildren <TextMesh>().text : null; //ElementMenuController ElementMenuController = GameObject.Find("ElementMenuCanvas").GetComponent<ElementMenuController>(); //if (chidlrenGO.GetComponent<MeshRenderer>().material.color != null && chidlrenGO.Equals(ElementMenuController.GetSelectedElement())) // tileElement = new TileElement(chidlrenGO, "AdditionalElement", ElementMenuController.GetSelectedElement().GetComponent<MeshRenderer>().material.color, text); //else tileElement = new TileElement(elementTransform.gameObject, "AdditionalElement", text); tileElement.SetAlterable(elementTransform.GetComponent <SelectableElementController>().IsAlterable()); serializedScene.AddAdditionalElement(tileElement); ++i; } } BinaryFormatter bf = new BinaryFormatter(); //Save a file String filePath = dataPath + "/map-" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss.fff") + ".bytes"; //String filePath = "./Assets" + Scenes.GetParamForString("titleProject") + "/map-" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss.fff") + ".bytes"; FileStream stream = new FileStream(filePath, FileMode.Create); bf.Serialize(stream, serializedScene); Debug.Log("Serialization Done."); stream.Close(); //Save a BLOB //byte[] savedDatas; //using (MemoryStream ms = new MemoryStream()) //{ // bf.Serialize(ms, serializedScene); // savedDatas = ms.ToArray(); // ms.Close(); //} //Save BDD and Update binary file //DataService.UpdateProposalSaveFile(savedDatas); //Scenes.GetSelectedProposal().File = savedDatas; }
}; //,"-y"}; public void Generate() { int room_count = this.maximumRoomCount; int min_size = this.min_size; int max_size = this.max_size; map_size = (room_count * roomMargin) * max_size; map = new MapTile[map_size, map_size]; for (var x = 0; x < map_size; x++) { for (var y = 0; y < map_size; y++) { map [x, y] = new MapTile(); map [x, y].type = 0; } } rooms = new List <Room> (); this.roomMarginTemp = this.roomMargin; int collision_count = 0; string direction = "set"; string oldDirection = "set"; Room lastRoom; for (var i = 0; i < room_count; i++) { Room room = new Room(); if (rooms.Count == 0) { //first room room.x = (int)Mathf.Floor(map_size / 2f); room.y = (int)Mathf.Floor(map_size / 2f); //Random.Range(10,20); room.w = Random.Range(min_size, max_size); room.h = Random.Range(min_size, max_size); room.branch = 0; lastRoom = room; } else { int branch = 0; if (collision_count == 0) { branch = Random.Range(5, 20); //complexity } room.branch = branch; lastRoom = rooms [rooms.Count - 1]; int lri = 1; while (lastRoom.dead_end) { lastRoom = rooms [rooms.Count - lri++]; } if (direction == "set") { string newRandomDirection = directions[Random.Range(0, directions.Count)]; direction = newRandomDirection; while (direction == oldDirection) { newRandomDirection = directions[Random.Range(0, directions.Count)]; direction = newRandomDirection; } } if (direction == "y") { room.x = lastRoom.x + lastRoom.w + Random.Range(3, 5) + this.roomMargin; room.y = lastRoom.y; } else if (direction == "-y") { room.x = lastRoom.x - lastRoom.w - Random.Range(3, 5) - this.roomMargin; room.y = lastRoom.y; } else if (direction == "x") { room.y = lastRoom.y + lastRoom.h + Random.Range(3, 5) + this.roomMargin; room.x = lastRoom.x; } else if (direction == "-x") { room.y = lastRoom.y - lastRoom.h - Random.Range(3, 5) - this.roomMargin; room.x = lastRoom.x; } room.w = Random.Range(min_size, max_size); room.h = Random.Range(min_size, max_size); room.connectedTo = lastRoom; } bool doesCollide = this.DoesCollide(room, 0); if (doesCollide) { i--; collision_count += 1; if (collision_count > 3) { lastRoom.branch = 1; lastRoom.dead_end = true; collision_count = 0; } else { oldDirection = direction; direction = "set"; } } else { room.room_id = i; rooms.Add(room); oldDirection = direction; direction = "set"; } } //room making for (int i = 0; i < rooms.Count; i++) { Room room = rooms [i]; for (int x = room.x; x < room.x + room.w; x++) { for (int y = room.y; y < room.y + room.h; y++) { map [x, y].type = 1; map [x, y].room = room; } } } //corridor making for (int i = 1; i < rooms.Count; i++) { Room roomA = rooms [i]; Room roomB = rooms [i].connectedTo; if (roomB != null) { var pointA = new Room(); //start var pointB = new Room(); pointA.x = roomA.x + (int)Mathf.Floor(roomA.w / 2); pointB.x = roomB.x + (int)Mathf.Floor(roomB.w / 2); pointA.y = roomA.y + (int)Mathf.Floor(roomA.h / 2); pointB.y = roomB.y + (int)Mathf.Floor(roomB.h / 2); if (Mathf.Abs(pointA.x - pointB.x) > Mathf.Abs(pointA.y - pointB.y)) { //yatay if (roomA.h > roomB.h) { pointA.y = pointB.y; } else { pointB.y = pointA.y; } } else { //dikey if (roomA.w > roomB.w) { pointA.x = pointB.x; } else { pointB.x = pointA.x; } } while ((pointB.x != pointA.x) || (pointB.y != pointA.y)) { if (pointB.x != pointA.x) { if (pointB.x > pointA.x) { pointB.x--; } else { pointB.x++; } } else if (pointB.y != pointA.y) { if (pointB.y > pointA.y) { pointB.y--; } else { pointB.y++; } } if (map [pointB.x, pointB.y].room == null) { map [pointB.x, pointB.y].type = 3; } } } } //x crop; because map created in the middle of array and we are pushing it to bottom left edge. int row = 1; int min_crop_x = map_size; for (int x = 0; x < map_size - 1; x++) { bool x_empty = true; for (int y = 0; y < map_size - 1; y++) { if (map[x, y].type != 0) { x_empty = false; if (x < min_crop_x) { min_crop_x = x; } break; } } if (!x_empty) { for (int y = 0; y < map_size - 1; y++) { map[row, y] = map[x, y]; map[x, y] = new MapTile(); } row += 1; } } //y crop row = 1; int min_crop_y = map_size; for (int y = 0; y < map_size - 1; y++) { bool y_empty = true; for (int x = 0; x < map_size - 1; x++) { if (map[x, y].type != 0) { y_empty = false; if (y < min_crop_y) { min_crop_y = y; } break; } } if (!y_empty) { for (int x = 0; x < map_size - 1; x++) { map[x, row] = map[x, y]; map[x, y] = new MapTile(); } row += 1; } } foreach (Room room in rooms) { room.x -= min_crop_x; room.y -= min_crop_y; } //test map size int final_map_size_y = 0; for (int y = 0; y < map_size - 1; y++) { for (int x = 0; x < map_size - 1; x++) { if (map[x, y].type != 0) { final_map_size_y += 1; break; } } } int final_map_size_x = 0; for (int x = 0; x < map_size - 1; x++) { for (int y = 0; y < map_size - 1; y++) { if (map[x, y].type != 0) { final_map_size_x += 1; break; } } } final_map_size_x += 4; final_map_size_y += 4; MapTile[,] new_map = new MapTile[final_map_size_x, final_map_size_y]; for (int x = 0; x < final_map_size_x; x++) { for (int y = 0; y < final_map_size_y; y++) { new_map[x, y] = map[x, y]; } } map = new_map; map_size_x = final_map_size_x; map_size_y = final_map_size_y; //walls for (int x = 0; x < map_size_x - 1; x++) { for (int y = 0; y < map_size_y - 1; y++) { if (map [x, y].type == 0) { if (map [x + 1, y].type == 1 || map [x + 1, y].type == 3) //west { map [x, y].type = 11; map [x, y].room = map [x + 1, y].room; } if (x > 0) { if (map [x - 1, y].type == 1 || map [x - 1, y].type == 3) //east { map [x, y].type = 9; map [x, y].room = map [x - 1, y].room; } } if (map [x, y + 1].type == 1 || map [x, y + 1].type == 3) //south { map [x, y].type = 10; map [x, y].room = map [x, y + 1].room; } if (y > 0) { if (map [x, y - 1].type == 1 || map [x, y - 1].type == 3) //north { map [x, y].type = 8; map [x, y].room = map [x, y - 1].room; } } } } } //corners for (int x = 0; x < map_size_x - 1; x++) { for (int y = 0; y < map_size_y - 1; y++) { if (walls.Contains(map [x, y + 1].type) && walls.Contains(map [x + 1, y].type) && roomsandfloors.Contains(map [x + 1, y + 1].type)) //north { map [x, y].type = 4; map [x, y].room = map [x + 1, y + 1].room; } if (y > 0) { if (walls.Contains(map [x + 1, y].type) && walls.Contains(map [x, y - 1].type) && roomsandfloors.Contains(map [x + 1, y - 1].type)) //north { map [x, y].type = 5; map [x, y].room = map [x + 1, y - 1].room; } } if (x > 0) { if (walls.Contains(map [x - 1, y].type) && walls.Contains(map [x, y + 1].type) && roomsandfloors.Contains(map [x - 1, y + 1].type)) //north { map [x, y].type = 7; map [x, y].room = map [x - 1, y + 1].room; } } if (x > 0 && y > 0) { if (walls.Contains(map [x - 1, y].type) && walls.Contains(map [x, y - 1].type) && roomsandfloors.Contains(map [x - 1, y - 1].type)) //north { map [x, y].type = 6; map [x, y].room = map [x - 1, y - 1].room; } } /* door corners --- a bit problematic in this version */ if (map [x, y].type == 3) { if (map [x + 1, y].type == 1) { map [x, y + 1].type = 11; map [x, y - 1].type = 11; } else if (Dungeon.map [x - 1, y].type == 1) { map [x, y + 1].type = 9; map [x, y - 1].type = 9; } } } } //find far far away room goalRoom = rooms[rooms.Count - 1]; if (goalRoom != null) { goalRoom.x = goalRoom.x + (goalRoom.w / 2); goalRoom.y = goalRoom.y + (goalRoom.h / 2); } //starting point startRoom = rooms[0]; startRoom.x = startRoom.x + (startRoom.w / 2); startRoom.y = startRoom.y + (startRoom.h / 2); }
private void DrawEntities(Map map, Position3D center, MousePicking mousePicking, out Vector2 renderOffset) { if (center == null) { renderOffset = new Vector2(); return; } // reset the spritebatch Z m_SpriteBatch.Reset(); // set the lighting variables. m_SpriteBatch.SetLightIntensity(Lighting.IsometricLightLevel); m_SpriteBatch.SetLightDirection(Lighting.IsometricLightDirection); // get variables that describe the tiles drawn in the viewport: the first tile to draw, // the offset to that tile, and the number of tiles drawn in the x and y dimensions. Point firstTile, renderDimensions; int overDrawTilesOnSides = 3; int overDrawTilesAtTopAndBottom = 6; int overDrawAdditionalTilesOnBottom = 10; CalculateViewport(center, overDrawTilesOnSides, overDrawTilesAtTopAndBottom, out firstTile, out renderOffset, out renderDimensions); CountEntitiesRendered = 0; // Count of objects rendered for statistics and debug MouseOverList overList = new MouseOverList(mousePicking); // List of entities mouse is over. List <AEntity> deferredToRemove = new List <AEntity>(); for (int y = 0; y < renderDimensions.Y * 2 + 1 + overDrawAdditionalTilesOnBottom; y++) { Vector3 drawPosition = new Vector3(); drawPosition.X = (firstTile.X - firstTile.Y + (y % 2)) * TILE_SIZE_FLOAT_HALF + renderOffset.X; drawPosition.Y = (firstTile.X + firstTile.Y + y) * TILE_SIZE_FLOAT_HALF + renderOffset.Y; Point firstTileInRow = new Point(firstTile.X + ((y + 1) / 2), firstTile.Y + (y / 2)); for (int x = 0; x < renderDimensions.X + 1; x++) { MapTile tile = map.GetMapTile(firstTileInRow.X - x, firstTileInRow.Y + x); if (tile == null) { drawPosition.X -= TILE_SIZE_FLOAT; continue; } List <AEntity> entities = tile.Entities; bool draw = true; for (int i = 0; i < entities.Count; i++) { if (entities[i] is DeferredEntity) { deferredToRemove.Add(entities[i]); } if (!m_DrawTerrain) { if ((entities[i] is Ground) || (entities[i].Z > tile.Ground.Z)) { draw = false; } } if ((entities[i].Z >= m_DrawMaxItemAltitude || (m_DrawMaxItemAltitude != 255 && entities[i] is Item && (entities[i] as Item).ItemData.IsRoof)) && !(entities[i] is Ground)) { continue; } if (draw) { AEntityView view = entities[i].GetView(); if (view != null) { if (view.Draw(m_SpriteBatch, drawPosition, overList, map, !m_UnderSurface)) { CountEntitiesRendered++; } } } } foreach (AEntity deferred in deferredToRemove) { tile.OnExit(deferred); } deferredToRemove.Clear(); drawPosition.X -= TILE_SIZE_FLOAT; } } OverheadsView.Render(m_SpriteBatch, overList, map, m_UnderSurface); // Update the MouseOver objects mousePicking.UpdateOverEntities(overList, mousePicking.Position); // Draw the objects we just send to the spritebatch. m_SpriteBatch.GraphicsDevice.SetRenderTarget(m_RenderTargetSprites); m_SpriteBatch.GraphicsDevice.Clear(Color.Black); m_SpriteBatch.FlushSprites(true); m_SpriteBatch.GraphicsDevice.SetRenderTarget(null); }
//private void drawImage(System.Drawing.Graphics g, MapTile tile, TileType tileType, ImageAttributes imageA) //{ // ClassImage img = FindImage(baseNames[tileType] + tile.Name); // string baseUrl = tile.Url; // IDataHelper data = dataHelpers[tileType]; // if (img == null) // { // img = data.GetImage(baseUrl, tile.Name); // if (img == null) // { // img = new ClassImage(); // } // if (img.PicImage != null) // listImages.Add(img); // } // img.IsDiscard = false; // img.Left = tile.Left; // img.Top = tile.Top; // if (img.Left < -nPerWidth || img.Left > _width || img.Top > _height || img.Top < -nPerWidth) // { // return; // } // Rectangle rect = new Rectangle(img.Left, img.Top, nPerWidth, nPerWidth); // if (img.PicImage != null && g != null) // g.DrawImage(img.PicImage, rect, 0, 0, nPerWidth, nPerWidth, GraphicsUnit.Pixel, imageA); //} private void drawImage(MapTile tile, TileType tileType, ImageAttributes imageA) { ClassImage img = FindImage(baseNames[tileType] + tile.Name); string baseUrl = tile.Url; IDataHelper data = dataHelpers[tileType]; if (img == null) { img = data.GetImages(baseUrl, tile.Name); } img.IsDiscard = false; img.Left = tile.Left; img.Top = tile.Top; if (img.Left < -nPerWidth || img.Left > _width || img.Top > _height || img.Top < -nPerWidth) { return; } }
static void GenerateMapFile(int posX, int posY, int posZ, string outDirectory) { string filename = GetMapFileName(posX, posY, posZ); string[] files; string file; // The map to be filled. MapView Maps = new MapView(posX, posY, posZ); Bitmap image = MapImages[posZ]; // Go backward across all the stores; last = most recent. for (int s = stores.Length - 1; s >= 0; s--) { if (Directory.Exists(stores[s] + "\\MapJson") && Directory.Exists(stores[s] + "\\MapJson\\" + filename)) { files = Directory.GetFiles(stores[s] + "\\MapJson\\" + filename); for (int f = files.Length - 1; f >= 0; f--) { file = files[f]; Console.WriteLine("Loading " + filename + " : " + stores[s]); ReadMapFile(file, Maps); } } } if (!Maps.IsEmpty()) { if (!Directory.Exists(outDirectory)) { Directory.CreateDirectory(outDirectory); } for (int x = 0; x < SIZE_X; x++) { for (int y = 0; y < SIZE_Y; y++) { MapTile t = Maps.GetTile(x, y); if (t != null) { for (int i = 0; i < t.Items.Count; i++) { int id = t.Items[i].ID; DatItem item = DatContext.GetItem(id); if (item.HasMapColor) { image.SetPixel((posX + x) - START_X, (posY + y) - START_Y, GetMapColor(item.MapColor)); } } } } } using (FileStream fs = new FileStream(outDirectory + "\\" + filename + ".json", FileMode.Create, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { sw.Write(Maps.ToJSON()); } } } }
public void Add(MapTile mapTile) { db.MapTiles.InsertOnSubmit(mapTile); }
/// <summary> /// Makes gradient between tiles where needed /// </summary> /// <param name="t"></param> public void UpdateTileNeighborVisibility(MapTile t) { Vector2 t1, t2, t3, t4, tc; Vector3 tv1, tv2, tv3, tv4; float c1, c2 = t.VisibilityOpacity; int j; Graph.Corner c; bool b; for (int i = 0; i < t.neighbors.Count; i++)//Loop; through all neighbors { if (t.neighbors[i].VisibilityOpacity >= t.VisibilityOpacity)//Ignore neighbors with lower/same opacity continue; //Project edge corners t1 = PointToTexCoord(tv1 = t.GraphNode.edges[i].C1.PositionNormalized); t2 = PointToTexCoord(tv2 = t.GraphNode.edges[i].C2.PositionNormalized); //Compute third point j = i == 0 ? t.neighbors.Count - 1 : i - 1; if (b = t.GraphNode.edges[j].HasCorner(t.GraphNode.edges[i].C1)) c = t.GraphNode.edges[i].C1; else c = t.GraphNode.edges[i].C2; t3 = PointToTexCoord(tv3 = c.PositionNormalized + (t.GraphNode.edges[j].GetOtherCorner(c).PositionNormalized - c.PositionNormalized).normalized * 0.02f); //Compute fourth point j = i == t.neighbors.Count - 1 ? 0 : i + 1; c = t.GraphNode.edges[i].GetOtherCorner(c); t4 = PointToTexCoord(tv4 = c.PositionNormalized + (t.GraphNode.edges[j].GetOtherCorner(c).PositionNormalized - c.PositionNormalized).normalized * 0.02f); //Inflate points tc = (t1 + t2 + t3 + t4) / 4; t1 += (t1 - tc).normalized * maxTexelDistance * 2; t2 += (t2 - tc).normalized * maxTexelDistance * 2; t3 += (t3 - tc).normalized * maxTexelDistance * 2; t4 += (t4 - tc).normalized * maxTexelDistance * 2; //Get opacities c1 = t.neighbors[i].VisibilityOpacity; //Add triangles to queue triGradQueue.Add(new TriangleGrad() { p1 = t1, p2 = t2, p3 = t3, c1 = c1, c2 = c1, c3 = c2 }); if (b) triGradQueue.Add(new TriangleGrad() { p1 = t4, p2 = t3, p3 = t2, c1 = c2, c2 = c2, c3 = c1 }); else triGradQueue.Add(new TriangleGrad() { p1 = t4, p2 = t1, p3 = t3, c1 = c2, c2 = c1, c3 = c2 }); } }
public SearchResults Search(HexagonalTileSearchProblem Problem) { /* ----- SETUP ----- */ SearchResults r = new SearchResults(); if (Problem == null) { return(r); } Dictionary <MapTile, MapTile> Paths = new Dictionary <MapTile, MapTile>(); Dictionary <MapTile, bool> Explored = new Dictionary <MapTile, bool>((int)Problem.SearchSpace.Size); foreach (MapTile mt in Problem.SearchSpace.XYTiles()) { Explored.Add(mt, false); } hSortedList <double, MapTile> Available = new hSortedList <double, MapTile>(); Available.Add(0, Problem.Start); /* ----- SEARCH ----- */ /* A Star works by evaluating potential paths based on an estimate of * there overall path cost to the goal. This is computed as the existing cost * from the start to the node, based on the known cost to the current node, and the * length of the edge , plus its estimated distance to the goal. If a node has been observed * before, or is part of a path already established, the cost via the new route is compared with * that of the old, and if cheaper, will be used in placed of the old. In this fashion, the algo is * always capable of finding the best route through a graph, but has a fair amount of overhead. */ MapTile current = null; int current_cost; DateTime start_time = DateTime.Now; while (Available.Count != 0) { if (Available.Count > r.SpaceComplexity) { r.SpaceComplexity = Available.Count; } current = Available.Pop(); current_cost = SearchHelper.GetPathLengthFromStart(current, Paths, Problem.Start); r.TimeComplexity++; Explored[current] = true; //If we have recieved the destination, we have completed the search. if (current == Problem.Goal) { r.Solved = true; break; } //If we have not found the destination, catalog the available operations //from this mapTile. foreach (MapTile mt in current.GetNeighbours()) { if (Explored[mt] == false) { //We have not previously seen this location. if (!Paths.ContainsKey(mt)) { Paths.Add(mt, current); Available.Add( current_cost + 1 //All nodes have a distance of one from their neighbour + Heuristic.Calculate(mt, Problem.Goal), mt); } else { int old_cost = SearchHelper.GetPathLengthFromStart(mt, Paths, Problem.Start); MapTile oldParent = Paths[mt]; Paths[mt] = current; int new_cost = SearchHelper.GetPathLengthFromStart(mt, Paths, Problem.Start); //If the new cost to the tile is more than our previous //path to this tile, we want to keep our previous parent assignment if (new_cost > old_cost) { Paths[mt] = oldParent; } else { Available.Add( current_cost + 1 + Heuristic.Calculate(mt, Problem.Goal), mt); } } } } } DateTime end_time = DateTime.Now; r.TimeInMilliseconds = (int)(end_time - start_time).TotalMilliseconds; /* ----- BACKTRACK PATH GENERATION ----- */ if (r.Solved) { r.Path = SearchHelper.GetPathFromStart(current, Paths, Problem.Start); } return(r); }
public void OnNeighborVisibilityChanged(MapTile neighbor) { chunk.visibilityOverlay.UpdateTileVisibility(this); chunk.visibilityOverlay.UpdateTileNeighborVisibility(this); }
int Distance(MapTile a, MapTile b) { return((int)Mathf.Abs(a.x - b.x) + Mathf.Abs(a.y - b.y)); }
public void CloseMenu() { activeTile.ActiveTile(); activeTile = null; gameObject.SetActive(false); }
public Finish(Curio curio, MapTile source, MapTile destination) : base(curio, source, destination) { }
public void SetTile(MapTile tile) { this.tile = tile; }
public void AddNeighbor(MapTile t) { if (!neighbors.Contains(t)) neighbors.Add(t); }
public void Triangulate(MapTile tile) { float edgeOffset = (MapTileMetrics.outerWidth - MapTileMetrics.innerWidth) / 2; // Inner Square: Solid Color Vector3 tileOrigin = tile.transform.localPosition; AddTriangle( tileOrigin + new Vector3(edgeOffset, 0f, edgeOffset), tileOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset) ); AddTriangleColor(tile.color, tile.color, tile.color); AddTriangle( tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), tileOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), tileOrigin + MapTileMetrics.corners[3] + new Vector3(edgeOffset, 0f, edgeOffset) ); AddTriangleColor(tile.color, tile.color, tile.color); // Geometry between adjacent tiles MapTile neighbor; // Add North Quad if ((neighbor = tile.GetNeighbor(MapTileMetrics.Direction.N)) != null) { Vector3 neighborOrigin = neighbor.transform.localPosition; AddTriangle( tileOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), neighborOrigin + new Vector3(edgeOffset, 0f, edgeOffset), neighborOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset) ); AddTriangleColor(tile.color, neighbor.color, neighbor.color); AddTriangle( tileOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), neighborOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset) ); AddTriangleColor(tile.color, neighbor.color, tile.color); } // Add East Quad if ((neighbor = tile.GetNeighbor(MapTileMetrics.Direction.E)) != null) { Vector3 neighborOrigin = neighbor.transform.localPosition; AddTriangle( tileOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), neighborOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset) ); AddTriangleColor(tile.color, tile.color, neighbor.color); AddTriangle( tileOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), neighborOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), neighborOrigin + new Vector3(edgeOffset, 0f, edgeOffset) ); AddTriangleColor(tile.color, neighbor.color, neighbor.color); } // Connect Corners MapTile north = tile.GetNeighbor(MapTileMetrics.Direction.N); MapTile east = tile.GetNeighbor(MapTileMetrics.Direction.E); MapTile northEast = (north != null ? north.GetNeighbor(MapTileMetrics.Direction.E) : (east != null ? east.GetNeighbor(MapTileMetrics.Direction.N) : null)); if (north != null && east != null && northEast != null) { Vector3 northOrigin = north.transform.localPosition; Vector3 northEastOrigin = northEast.transform.localPosition; Vector3 eastOrigin = east.transform.localPosition; // For center point float elevationAvg = (tileOrigin.y + northOrigin.y + northEastOrigin.y + eastOrigin.y) / 4; Color colorAvg = 0.25f * (tile.color + north.color + northEast.color + east.color); Vector3 centerPoint = tileOrigin + MapTileMetrics.corners[1]; centerPoint.y = elevationAvg; AddTriangle( tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), northOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), centerPoint ); AddTriangleColor(tile.color, north.color, colorAvg); AddTriangle( northOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), northEastOrigin + new Vector3(edgeOffset, 0f, edgeOffset), centerPoint ); AddTriangleColor(north.color, northEast.color, colorAvg); AddTriangle( northEastOrigin + new Vector3(edgeOffset, 0f, edgeOffset), eastOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), centerPoint ); AddTriangleColor(northEast.color, east.color, colorAvg); AddTriangle( eastOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), centerPoint ); AddTriangleColor(east.color, tile.color, colorAvg); } else if (north != null && northEast != null) { Vector3 northOrigin = north.transform.localPosition; Vector3 northEastOrigin = northEast.transform.localPosition; AddTriangle( tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), northOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), northEastOrigin + new Vector3(edgeOffset, 0f, edgeOffset) ); AddTriangleColor(tile.color, north.color, northEast.color); } else if (northEast != null && east != null) { Vector3 northEastOrigin = northEast.transform.localPosition; Vector3 eastOrigin = east.transform.localPosition; AddTriangle( northEastOrigin + new Vector3(edgeOffset, 0f, edgeOffset), eastOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset), tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset) ); AddTriangleColor(northEast.color, east.color, tile.color); } else if (north != null && east != null) { Vector3 northOrigin = north.transform.localPosition; Vector3 eastOrigin = east.transform.localPosition; AddTriangle( tileOrigin + MapTileMetrics.corners[1] + new Vector3(-edgeOffset, 0f, -edgeOffset), northOrigin + MapTileMetrics.corners[2] + new Vector3(-edgeOffset, 0f, edgeOffset), eastOrigin + MapTileMetrics.corners[0] + new Vector3(edgeOffset, 0f, -edgeOffset) ); AddTriangleColor(tile.color, north.color, east.color); } }
private bool IsInGeneralDirection(MapTile currentPosition, MapTile destination, int radi) { int rowCenterFold = GameContext.Map.Rows/2; int currentRowFromCenter = Math.Abs(rowCenterFold - currentPosition.Row); int destinationRowFromCenter = Math.Abs(rowCenterFold - destination.Row); int colCenterFold = GameContext.Map.Columns/2; int currentColFromCenter = Math.Abs(colCenterFold - currentPosition.Column); int destinationColFromCenter = Math.Abs(colCenterFold - destination.Column); switch (this._direction) { case Direction.East: return currentPosition.Column < destination.Column && ((Math.Abs(currentRowFromCenter - destinationRowFromCenter)) <= radi); case Direction.West: return currentPosition.Column > destination.Column && ((Math.Abs(currentRowFromCenter - destinationRowFromCenter)) <= radi); case Direction.South: return currentPosition.Row < destination.Row && ((Math.Abs(currentColFromCenter - destinationColFromCenter)) <= radi); case Direction.North: return currentPosition.Row > destination.Row && ((Math.Abs(currentColFromCenter - destinationColFromCenter)) <= radi); default: return false; } }
private void SetBushesDoors(MapTile MT) { for (int i = MT.blocks[0].Count / 2 - 4; i < MT.blocks[0].Count / 2 + 3; i++) { for (int j = 0; j < 9; j++) { if (MT.blocks[j][i] == (int)BlockType.TopBushUD) { if ((j == 0) || (MT.blocks[j - 1][i] == (int)BlockType.Empty)) { if (MT.passages[0] == PassageType.Door) { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.Top; } else { MT.blocks[j][i] = (int)BlockType.TopBushD; } } else { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.TopBushU; } else { MT.blocks[j][i] = (int)BlockType.TopBushUD; } } } } if (MT.blocks[j][i] == (int)BlockType.IncLeftBushUD) { if (MT.passages[0] == PassageType.Door) { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.InclLeft; } else { MT.blocks[j][i] = (int)BlockType.IncLeftBushD; } } else { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.IncLeftBushU; } else { MT.blocks[j][i] = (int)BlockType.IncLeftBushUD; } } } if (MT.blocks[j][i] == (int)BlockType.IncRightBushUD) { if (MT.passages[0] == PassageType.Door) { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.InclRight; } else { MT.blocks[j][i] = (int)BlockType.IncRightBushD; } } else { if (MT.passages[2] == PassageType.Door) { MT.blocks[j][i] = (int)BlockType.IncRightBushU; } else { MT.blocks[j][i] = (int)BlockType.IncRightBushUD; } } } } } }
public Ant(MapTile currentPosition) { this.CurrentPosition = currentPosition; }
/// <summary> /// Detemines if a GmapTile contains a transition in it. /// </summary> /// <param name="gmapX">The google maps X coordinates</param> /// <param name="gmapY">The google maps Y coordinates</param> /// <param name="gmapBitmap">The bitmap we are processing</param> /// <returns>a value indicating if a tile has a transition in it. </returns> private bool CheckGmapTilesForTransitions(int gmapX, int gmapY, Bitmap gmapBitmap, int zoomLevel, Point currentAbsolutePosition) { int offset = getOffSet(zoomLevel); bool hasWater = false; bool hasLand = false; using (BmpData largeBmpData = new BmpData(gmapBitmap, 256)) CheckEdges(largeBmpData, 256, out hasWater, out hasLand); //if we have land and water on the tile, then we need to Process it normally, otherwise we can skip all of that. if (hasLand && hasWater) return true; MapGraphicsTile mapGraphicsTile = new MapGraphicsTile(); if (hasLand) mapGraphicsTile= _mapGraphicsTileSet.LandTile; else mapGraphicsTile= _mapGraphicsTileSet.WaterTile; MapTile mapTile = new MapTile(mapGraphicsTile); for (int x = currentAbsolutePosition.X * _graphicsTileSize; x < (currentAbsolutePosition.X * _graphicsTileSize) + (_graphicsTileSize * offset); x++) { for (int y = currentAbsolutePosition.Y * _graphicsTileSize; y < (currentAbsolutePosition.Y * _graphicsTileSize) + (_graphicsTileSize * offset); y++) { _gameWorld.GameMap[x,y] = mapTile; } } return false; }
/// <summary> /// Adds tile to rasterizer queue /// </summary> /// <param name="t"></param> public void UpdateTileVisibility(MapTile t) { float vv = t.VisibilityOpacity; Mesh m = t.mesh;//Get tile mesh Vector2[] v = new Vector2[m.vertexCount];//Vertices coordinates in UV space Vector2 ce = Vector2.zero; for (int i = 0; i < v.Length; i++)//Convert all vertices to UV space ce += v[i] = PointToTexCoord(m.vertices[i].normalized); ce /= v.Length;//Find center point for (int i = 0; i < v.Length; i++)//Inflate all vertices a little v[i] += (v[i] - ce).normalized * maxTexelDistance; int[] ind = m.GetIndices(0);//Get mesh indices TriangleConst c; for (int i = 0; i < ind.Length; i += 3)//For every triangle add its projected version to rasterizer queue { c = new TriangleConst(); c.c = vv; c.p1 = v[ind[i]]; c.p2 = v[ind[i + 1]]; c.p3 = v[ind[i + 2]]; triConstQueue.Add(c); } }
public void FindMoveTiles(int move, MapTile mt, Character charToMove) { moveTilePositions.Clear(); FindMoveTile(move, mt, charToMove, false); }