public Cube(MapElementType type, Overlay overlay, WorldMap worldMap, Vector3Int position) : base(worldMap, position) { ElementType = type; Overlay = overlay; Solid = true; }
public void CopyFromRemote(WorldMap remoteMap, MapInfo mapInfo) { if (remoteMap == null) { Debug.Log("Didn't get world map!"); return; } width = remoteMap.world_width; height = remoteMap.world_height; worldNameEnglish = remoteMap.name_english; offset = new Vector3( (-mapInfo.block_pos_x + (remoteMap.map_x * 16)) * 48 * GameMap.tileWidth, -mapInfo.block_pos_z * GameMap.tileHeight, (mapInfo.block_pos_y - (remoteMap.map_y * 16)) * 48 * GameMap.tileWidth); worldPosition = new Vector3(mapInfo.block_pos_x, mapInfo.block_pos_y, mapInfo.block_pos_z); meshRenderer.material.SetFloat("_Scale", scale); meshRenderer.material.SetFloat("_SeaLevel", (99 * GameMap.tileHeight) + offset.y); InitArrays(); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { int index = y * width + x; elevation[x, y] = remoteMap.elevation[index]; rainfall[x, y] = remoteMap.rainfall[index]; vegetation[x, y] = remoteMap.vegetation[index]; temperature[x, y] = remoteMap.temperature[index]; evilness[x, y] = remoteMap.evilness[index]; drainage[x, y] = remoteMap.drainage[index]; volcanism[x, y] = remoteMap.volcanism[index]; savagery[x, y] = remoteMap.savagery[index]; salinity[x, y] = remoteMap.salinity[index]; } GenerateMesh(); }
public Tree(WorldMap worldMap, Vector3Int position) : base(worldMap, position) { Dimentions = new Vector3Int(1, 1, 1); SpriteSource = new Rectangle(0 * 32, 20 * 5 + 32 * 5, 32, 32); ElementType = MapElementType.Tree; }
// Setup public virtual void Setup() { worldMap = GameObject.FindGameObjectWithTag ("GameController").GetComponent<WorldMap> (); int n = 0; int spr = 0; // If needs a random name if(hasRandomName){ n = Mathf.RoundToInt(Random.Range(0,possibleNames.Length)); name = possibleNames[n]; nameTitle = possibleTitleNames[n]; } // If needs a random sprite if(hasRandomSprite){ spr = Mathf.RoundToInt(Random.Range(0,possibleSprites.Length)); gameObject.GetComponent<SpriteRenderer>().sprite = possibleSprites[spr]; color = possibleColors[spr]; // Match name to sprite if(nameMatchesSprite){ n = spr; name = possibleNames[n]; nameTitle = possibleTitleNames[n]; } } // Match name to color if(nameMatchesColor){ for(int c=0; c<=possibleColors.Length-1; c++){ if(color == possibleColors[c]){ n = c; } } name = possibleNames[n]; nameTitle = possibleTitleNames[n]; } SetSpriteColorToColor(); }
public Stone(WorldMap worldMap, Vector3Int position) : base(worldMap, position) { Dimentions = new Vector3Int(1, 1, 1); SpriteSource = new Rectangle(0 * 32, 20 * 7 + 32 * 9, 16, 16); ElementType = MapElementType.Stone; SpriteOfset = new Vector2(8, 13); Solid = false; }
// Use this for initialization void Start() { // Get the player player = GameObject.FindGameObjectWithTag ("Player").GetComponent<Player> (); worldMap = GameObject.FindGameObjectWithTag ("GameController").GetComponent<WorldMap> (); options = GameObject.FindGameObjectWithTag ("GameController").GetComponent<GameOptions> (); speed = worldMap.mapTileSize; }
public void InitHost(bool Shell, string version, WorldMap worldmap, PictureBox pctWorldMap) { Scripting.Host.ScriptGlobal.Init(Scripting.Host.ScriptHost, worldmap, pctWorldMap); Scripting.Host.ScriptHost.resources_loaded(); if (Shell) { frmShell shell = new frmShell(version, false); Scripting.Host.ScriptHost.RegisterConsole(shell.GetConsole()); shell.Show(); } }
public void bindAdjacentField(WorldMap WorldMap) { this.adjacentFieldList = new iField[8]; this.adjacentFieldList[N] = WorldMap.getField(X - 1, Y - 1); this.adjacentFieldList[NE] = WorldMap.getField(X - 1, Y); this.adjacentFieldList[E] = WorldMap.getField(X - 1, Y + 1); this.adjacentFieldList[SE] = WorldMap.getField(X, Y + 1); this.adjacentFieldList[S] = WorldMap.getField(X + 1, Y + 1); this.adjacentFieldList[SW] = WorldMap.getField(X + 1, Y); this.adjacentFieldList[W] = WorldMap.getField(X + 1, Y - 1); this.adjacentFieldList[NW] = WorldMap.getField(X, Y - 1); }
void CopyFromRemote(WorldMap remoteMap) { if (remoteMap == null) { Debug.Log("Didn't get world map!"); return; } timeHolder.realTime = new DFTime(remoteMap.cur_year, remoteMap.cur_year_tick); width = remoteMap.world_width; height = remoteMap.world_height; if(width * height > 65535) { width = Mathf.Clamp(width, 0, 255); height = Mathf.Clamp(height, 0, 255); } worldName = remoteMap.name; worldNameEnglish = remoteMap.name_english; offset = new Vector3( -remoteMap.center_x * 48 * GameMap.tileWidth, 0, remoteMap.center_y * 48 * GameMap.tileWidth); meshRenderer.material.SetFloat("_Scale", scale); meshRenderer.material.SetFloat("_SeaLevel", (99 * GameMap.tileHeight) + offset.y); InitArrays(); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { int index = y * remoteMap.world_width + x; elevation[x, y] = remoteMap.elevation[index]; rainfall[x, y] = remoteMap.rainfall[index]; vegetation[x, y] = remoteMap.vegetation[index]; temperature[x, y] = remoteMap.temperature[index]; evilness[x, y] = remoteMap.evilness[index]; drainage[x, y] = remoteMap.drainage[index]; volcanism[x, y] = remoteMap.volcanism[index]; savagery[x, y] = remoteMap.savagery[index]; salinity[x, y] = remoteMap.salinity[index]; cumulusMedium[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MEDIUM; cumulusMulti[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MULTI; cumulusNimbus[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_NIMBUS; stratusAlto[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_ALTO; stratusProper[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_PROPER; stratusNimbus[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_NIMBUS; cirrus[x, y] = remoteMap.clouds[index].cirrus; fogMist[x, y] = remoteMap.clouds[index].fog == FogType.FOG_MIST; fogNormal[x, y] = remoteMap.clouds[index].fog == FogType.FOG_NORMAL; fogThick[x, y] = remoteMap.clouds[index].fog == FogType.F0G_THICK; } GenerateMesh(); GenerateClouds(); //Debug.Log("Loaded World: " + worldNameEnglish); }
// ----- ----- ----- ctor ----- ----- ----- public WorldMapPanel(WorldMap map) { Contract.Requires(map != null); _reignMap = map; _animations = new AnimationManager<IAnimation>(); Initialize(); InitializeComponent(); InitializeOtherComponent(); }
public void SetPosition(WorldMap mainMap) { if (mainMap != null) { offset = (new Vector3(-mainMap.center_x, 0, mainMap.center_y) + embarkTileOffset) * 48 * GameMap.tileWidth; } else { offset = embarkTileOffset * 48 * GameMap.tileWidth; } transform.position = offset * scale; }
public Location init (WorldMap worldMap) { this.worldMap = worldMap; fightScreen = Vars.gameplay.getFightScreen(); enemyRender = transform.Find("EnemyImage").GetComponent<SpriteRenderer>(); questMarker = enemyRender.transform.Find("QuestMarker").gameObject; huntBtn = transform.Find("HuntBtn").GetComponent<Button>(); leaveBtn = transform.Find("LeaveBtn").GetComponent<Button>(); attackBtn = transform.Find("AttackBtn").GetComponent<Button>(); backBtn = transform.Find("BackBtn").GetComponent<Button>(); background = transform.Find("BG").GetComponent<Background>(); background.init(this); enemyRender.gameObject.SetActive(true); gameObject.SetActive(false); return this; }
/// <summary> /// Generates a renderthread and graphics related data structures /// </summary> /// <param name="whatControl">The GLControl to use for rendering</param> /// <param name="whatMap">The map to render in the control</param> public Renderer(GLControl whatControl, WorldMap whatMap, AstarInterface whatInterface) { if (whatInterface == null) throw new ArgumentNullException("whatInterface", "Cannot get selector position from non-existing interface."); AstarInterface = whatInterface; if (whatMap == null) throw new ArgumentNullException("whatMap", "Cannot render a non-existing map"); map = whatMap; if (whatControl == null) throw new ArgumentNullException("whatControl", "Cannot use a non-existing GLControl for rendering"); GLControl = whatControl; GLControl.Context.MakeCurrent(null); //Currently hardcoded camera position lock (whatMap) { camera = new Camera( new Vector3d((double)whatMap.xSizeCache / 2, (double)whatMap.ySizeCache / 2, (double)whatMap.zSizeCache / 2 + whatMap.xSizeCache + CAMERA_HEIGHT_PADDING), new Vector3d((double)whatMap.xSizeCache / 2, (double)whatMap.ySizeCache / 2, (double)whatMap.zSizeCache / 2)); } renderTask = Task.Factory.StartNew(rendererMain, TaskCreationOptions.LongRunning); }
public bool updatePlan(WorldMap worldMap, float perfectVisionRange) { // TODO: Decide whether actual is more useful here than anticipated planUpdateBudget -= (planUpdateTime / planUpdateCount); // decrement by expected time rather than actual. planUpdateResult = false; planUpdateStart = Time.unscaledTime; // add percept-getting to the plan time if(worldMap != null) { worldMap.getPercepts(this._myself, perfectVisionRange); } planUpdateResult = executePlanUpdate(); planUpdateDelta = (Time.realtimeSinceStartup - planUpdateStart); // Debug.Log("Delta: "+planUpdateDelta); planUpdateTime += planUpdateDelta; planUpdateCount++; return planUpdateResult; }
void CopyClouds(WorldMap remoteMap) { if (remoteMap == null) { Debug.Log("Didn't get world map!"); return; } for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { int index = y * remoteMap.world_width + x; cumulusMedium[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MEDIUM; cumulusMulti[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MULTI; cumulusNimbus[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_NIMBUS; stratusAlto[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_ALTO; stratusProper[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_PROPER; stratusNimbus[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_NIMBUS; cirrus[x, y] = remoteMap.clouds[index].cirrus; fogMist[x, y] = remoteMap.clouds[index].fog == FogType.FOG_MIST; fogNormal[x, y] = remoteMap.clouds[index].fog == FogType.FOG_NORMAL; fogThick[x, y] = remoteMap.clouds[index].fog == FogType.F0G_THICK; } GenerateClouds(); }
public void SendWorldMap(WorldMap map) { var x2E = new ServerPacket(0x2E); x2E.Write(map.GetBytes()); x2E.DumpPacket(); IsAtWorldMap = true; Enqueue(x2E); }
/// <summary> /// Searches a path on a given map. The map data is altered in the process and a path is set on it. /// </summary> /// <param name="whatMap">The map to search a path on</param> /// <returns>Whether a path could be found</returns> public static SearchResult searchPathOnMap(WorldMap whatMap) { if (whatMap.goal == null || whatMap.start == null) throw new ArgumentException("The provided map does either not have a start or a goal.", "whatMap"); SearchResult currentResult = SearchResult.None; //Initialize open list SortedDictionary<int, List<MapNode>> openList = new SortedDictionary<int, List<MapNode>>(); MapNode cache = whatMap.actualMap[whatMap.start.Item1][whatMap.start.Item2][whatMap.start.Item3]; cache.currentShortestPathToNode = 0; openList.Add(cache.possibleDistanceToGoal, new List<MapNode>() { cache }); //Very simple test whether it makes sense to search the map at all if (cache.currentStatus == MapNode.Status.isClosed) { currentResult |= SearchResult.MapHasAlreadyBeenSearched; cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3]; for (int i = 0; i < CIRCLE_TIMEOUT && cache != null && cache != whatMap.start; i++) { cache = cache.currentPredesessorNode; } if (cache != null) { if (cache == whatMap.start) currentResult |= SearchResult.FoundPath; else throw new Exception("Map has been altered to contain a circle as a path"); } } else { //The actual searching. Take the node with the possibly least remaining distance ( estimated ) and expand it while (openList.Any()) { cache = openList.First().Value.First(); //remove it from the open list and possibly the entire entry list if empty openList[cache.possibleDistanceToGoal].Remove(cache); if (!openList[cache.possibleDistanceToGoal].Any()) openList.Remove(cache.possibleDistanceToGoal); //Have we found the goal? if (cache == whatMap.goal) { currentResult = SearchResult.FoundPath; break; } cache.currentStatus |= MapNode.Status.isClosed; expandNode(cache, openList, whatMap); } //Create the path information on the map data ( This is an extra list for simplicity, the main data has been altered already above ) LinkedList<BlockInfo> path = new LinkedList<BlockInfo>(); if (currentResult.HasFlag(SearchResult.FoundPath)) { cache = whatMap.actualMap[whatMap.goal.Item1][whatMap.goal.Item2][whatMap.goal.Item3]; while (cache.currentPredesessorNode != null) { path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus)); cache = cache.currentPredesessorNode; } //Add the start aswell even though its predecessor is null ( obviously ) path.AddFirst(new BlockInfo(cache.x, cache.y, cache.z, cache.currentStatus)); } whatMap.path = path; } return currentResult; }
public override void Execute(Bot bot, WorldMap map) { bot.Direction = (Directions)(((int)bot.Direction + rotationIndex) % 8); bot.MoveCommandPointer(1); }
public void showUserInfoScreenAdmin(WorldMap.CachedUserInfo userInfo) { if (this.getMainTabBar().getCurrentTab() != 0) { this.getMainTabBar().changeTab(0); } this.clearControlsLeaveRightHandPanel(); this.addMainWindow(false, true); this.userInfoScreen.Size = this.mainWindowPanel.Size; this.userInfoScreen.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Top; this.userInfoScreen.clear(); this.userInfoScreen.init(userInfo); this.userInfoScreen.display(this.mainWindowPanel, 0, 0); }
public void CopyFromRemote(WorldMap remoteMap, WorldMap mainMap) { if (remoteMap == null) { Debug.Log("Didn't get world map!"); return; } width = remoteMap.world_width; height = remoteMap.world_height; worldNameEnglish = remoteMap.name_english; embarkTileOffset = new Vector3((remoteMap.map_x * 16), 0, -(remoteMap.map_y * 16)); regionOrigin = new DFCoord(remoteMap.map_x * 16, remoteMap.map_y * 16, 0); SetPosition(mainMap); InitArrays(); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { int index = y * width + x; tiles[x, y] = new RegionTile(remoteMap, index); } GenerateMesh(); }
/// <summary> /// Implement your bot here. /// </summary> /// <param name="map">The gamemap.</param> /// <param name="visiblePlayers">Players that are visible to your bot.</param> /// <returns>The action you wish to execute.</returns> internal string ExecuteTurn(Map map, IEnumerable <IPlayer> visiblePlayers) { worldMap = WorldMap.ReadMap(); if (worldMap == null || worldMap.HomePosition != PlayerInfo.HouseLocation) { worldMap = new WorldMap(); } worldMap.UpdateWorldMap(map); worldMap.HomePosition = PlayerInfo.HouseLocation; WorldMap.WriteMap(worldMap); this.astarService = new AStarAlgo(worldMap); this.ressourcePlaner = new RessourcePlaner(worldMap, PlayerInfo, astarService); this.navigationHelper = new NavigationHelper(PlayerInfo, astarService); this.manathan = new Manathan(); this.placePlaner = new PlacePlaner(map, PlayerInfo, astarService); Console.WriteLine("Cash : " + PlayerInfo.TotalResources); try { var best_ressource = ressourcePlaner.GetBestRessourcePath(); //var best_place_for_shop = placePlaner.GetBestPlacePath(TileContent.Shop); // 10000 15000 25000 50000 100000 if (PlayerInfo.Position == PlayerInfo.HouseLocation) { bool upgrade = false; switch (PlayerInfo.GetUpgradeLevel(UpgradeType.AttackPower)) { case 0: if (PlayerInfo.TotalResources >= 10000) { upgrade = true; } break; case 1: if (PlayerInfo.TotalResources >= 15000) { upgrade = true; } break; case 2: if (PlayerInfo.TotalResources >= 25000) { upgrade = true; } break; case 3: if (PlayerInfo.TotalResources >= 50000) { upgrade = true; } break; case 4: if (PlayerInfo.TotalResources >= 100000) { upgrade = true; } break; } if (upgrade) { return(AIHelper.CreateUpgradeAction(UpgradeType.AttackPower)); } } if (PlayerInfo.CarriedResources < PlayerInfo.CarryingCapacity && best_ressource != null) { if (best_ressource.Path.Count == 2) { // On est adjacent à la meilleure ressource var direction = astarService.DirectionToward(PlayerInfo.Position, best_ressource.Tile.Position); return(AIHelper.CreateCollectAction(direction)); } else if (best_ressource.Path.Count == 1) { // on est dessus var tileToGo = map.GetTile(PlayerInfo.Position.X - 1, PlayerInfo.Position.Y); var action = navigationHelper.NavigateToNextPosition(tileToGo); return(action); } else { // On est pas rendu return(navigationHelper.NavigateToNextPosition(best_ressource.Path[1])); } } else { // on doit aller à la base var home_tile = worldMap.GetTile(PlayerInfo.HouseLocation.X, PlayerInfo.HouseLocation.Y); var current_tile = worldMap.GetTile(PlayerInfo.Position.X, PlayerInfo.Position.Y); if (home_tile == null) { var path = manathan.GetManathanPath(current_tile.Position, PlayerInfo.HouseLocation); return(navigationHelper.NavigateToNextPosition(worldMap.GetTile(path[0].X, path[0].Y))); } else { var best_path_to_home = astarService.Run(current_tile, home_tile); if (best_path_to_home == null) { var path = manathan.GetManathanPath(current_tile.Position, PlayerInfo.HouseLocation); return(navigationHelper.NavigateToNextPosition(worldMap.GetTile(path[0].X, path[0].Y))); } // On est pas rendu return(navigationHelper.NavigateToNextPosition(best_path_to_home[1])); } } } catch (Exception e) { Console.WriteLine("*** Reset the map! ***"); Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine(e.InnerException); Console.WriteLine("*** inner exception ***"); Console.WriteLine(e); Console.WriteLine("*** exception ***"); worldMap = new WorldMap(); worldMap.UpdateWorldMap(map); worldMap.HomePosition = PlayerInfo.HouseLocation; WorldMap.WriteMap(worldMap); return(""); } /* * AStarAlgo astar = new AStarAlgo(map); * var result = astar.Run(PlayerInfo.Position, new Point(-4, 21)); * * * var data = StorageHelper.Read<TestClass>("Test"); * Console.WriteLine(data?.Test); * //return AIHelper.CreateMoveAction(new Point(_currentDirection, 0)); astar.DirectionToward(PlayerInfo.Position, result[0].Position); * return AIHelper.CreateMoveAction(astar.DirectionToward(PlayerInfo.Position, result[0].Position));*/ }
/// <summary> /// Places mountain tiles /// </summary> /// <param name="map">Working map</param> /// <param name="amount">Amount to place - currently unused</param> public static void DoMountains(WorldMap map, int amount) { int cutoff = 200; int cutoff2 = 160; int cutoff3 = 128; float MountainSizeDivisor = 1f / 32f; float MountainSpreadDivisor = 1f / 128f; float MountainFrequencyDivisor = 1f / 512f; float Noise1 = 1f / 4f; float Noise2 = 1f / 6f; for (int x = 1; x < map.Width - 1; x++) { for (int y = 1; y < map.Height - 1; y++) { int H = (int)Simplex.CalcPixel2D(x, y, MountainSizeDivisor); int M = (int)Simplex.CalcPixel2D(x, y, MountainFrequencyDivisor); int S = (int)Simplex.CalcPixel2D(x, y, MountainSpreadDivisor); int N1 = (int)Simplex.CalcPixel2D(x, y, Noise1); int N2 = (int)Simplex.CalcPixel2D(x, y, Noise2); if (H > cutoff && M > cutoff2 && S > cutoff3 && N1 > cutoff3 && N2 > cutoff3) { WorldMap.TileType Target = map.TileData[x, y]; if (Target != WorldMap.TileType.Ocean && Target != WorldMap.TileType.River) { map.TileData[x, y] = WorldMap.TileType.Mountain; //greatly raise actual mountain tiles map.ElevationData[x, y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x, y], 0f, 999f)), 1f / 10f); //raise tiles around them too if (map.TileData[x - 1, y] != WorldMap.TileType.Mountain) { map.ElevationData[x - 1, y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x - 1, y], 0f, 999f)), 1f / 3f); } if (map.TileData[x + 1, y] != WorldMap.TileType.Mountain) { map.ElevationData[x + 1, y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x + 1, y], 0f, 999f)), 1f / 3f); } if (map.TileData[x, y - 1] != WorldMap.TileType.Mountain) { map.ElevationData[x, y - 1] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x, y - 1], 0f, 999f)), 1f / 3f); } if (map.TileData[x, y + 1] != WorldMap.TileType.Mountain) { map.ElevationData[x, y + 1] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x, y + 1], 0f, 999f)), 1f / 3f); } } } } } /*/ * for (int i=0;i<amount;i++) * { * int X = RNG.NextInt(0, map.Width); * int Y = RNG.NextInt(0, map.Height); * WorldMap.TileType Target = map.TileData[X, Y]; * if (Target != WorldMap.TileType.Ocean && Target != WorldMap.TileType.River) * map.TileData[X, Y] = WorldMap.TileType.Mountain; * } * //*/ }
// Use this for initialization void Start() { worldMap = GameObject.FindGameObjectWithTag ("GameController").GetComponent<WorldMap> (); mapSizeX = (int)worldMap.GetMapSize().x; mapSizeY = (int)worldMap.GetMapSize().y; }
/// <summary> /// Fills the ocean - this ensures no isolated "lakes" of ocean are left after /// generating the continents. /// </summary> /// <param name="map">WorldMap to use.</param> public static void FillOcean(WorldMap map) { FloodFill(map, 1, 1, WorldMap.TileType.Unfilled, WorldMap.TileType.Ocean); }
/// <summary> /// Populates a float 2D array with distance values on a given map from given tile type /// </summary> /// <param name="map">Working map</param> /// <param name="DistanceField">Initial 2D distance field</param> /// <param name="Target">Tile to calculate distances from</param> /// <returns>Computed 2D array distance field</returns> public static float[,] DoDistanceField(WorldMap map, float[,] DistanceField, WorldMap.TileType Target) { //pass 1: set all to something stupid like 9999 except target float MAX = 9999f; float Highest = 0f; float[] neighbourhood = new float[8]; for (int x = 0; x < map.Width; x++) { for (int y = 0; y < map.Height; y++) { if (map.TileData[x, y] == Target) { DistanceField[x, y] = 0; } else { DistanceField[x, y] = MAX; } } } //pass 2 & 3: pathfind for (int x = 1; x < map.Width - 1; x++) { for (int y = 1; y < map.Height - 1; y++) { //iterate over 8 neighbours, pick the smallest, add 1 neighbourhood[0] = DistanceField[x - 1, y - 1]; neighbourhood[1] = DistanceField[x, y - 1]; neighbourhood[2] = DistanceField[x + 1, y - 1]; neighbourhood[3] = DistanceField[x - 1, y]; neighbourhood[4] = DistanceField[x + 1, y]; neighbourhood[5] = DistanceField[x - 1, y + 1]; neighbourhood[6] = DistanceField[x, y + 1]; neighbourhood[7] = DistanceField[x + 1, y + 1]; float smallest = neighbourhood.Min(); //do not make any changes if no neighbours are lower and not the default value if (smallest < MAX && smallest < DistanceField[x, y]) { DistanceField[x, y] = smallest + 1; } } } //go from the other direction now for (int x = map.Width - 2; x > 0; x--) { for (int y = map.Height - 2; y > 0; y--) { //iterate over 8 neighbours, pick the smallest, add 1 neighbourhood[0] = DistanceField[x - 1, y - 1]; neighbourhood[1] = DistanceField[x, y - 1]; neighbourhood[2] = DistanceField[x + 1, y - 1]; neighbourhood[3] = DistanceField[x - 1, y]; neighbourhood[4] = DistanceField[x + 1, y]; neighbourhood[5] = DistanceField[x - 1, y + 1]; neighbourhood[6] = DistanceField[x, y + 1]; neighbourhood[7] = DistanceField[x + 1, y + 1]; float smallest = neighbourhood.Min(); //do not make any changes if no neighbours are lower and not the default value if (smallest < MAX && smallest < DistanceField[x, y]) { //add 1 to the distance - regardless if diagonal or straight DistanceField[x, y] = smallest + 1; //find the furthest value - use it for scaling down to highest being 1.0f and lowest being 0.0f if (Highest < smallest + 1) { Highest = smallest + 1; } } } } //pass 4: normalisation if (Highest != 0) { for (int x = 1; x < map.Width - 1; x++) { for (int y = 1; y < map.Height - 1; y++) { DistanceField[x, y] /= Highest; } } } return(DistanceField); }
/// <summary> /// Creates a single random river /// </summary> /// <param name="map">WorldMap to use</param> public static List <Point> DoRiver(WorldMap map) { int x = 0; int y = 0; List <Point> visited = new List <Point>(); x = RNG.NextInt(map.Width); y = RNG.NextInt(map.Height); int oldx = 0; int oldy = 0; map.TileData[x, y] = WorldMap.TileType.River; int overflow = 0; while (overflow < 1024) { overflow++; int next = PointRiver(map, x, y); oldx = x; oldy = y; switch (next) { case 3: { x--; break; } case 2: { y++; break; } case 1: { x++; break; } default: { y--; break; } } if (visited.Contains(new Point(x, y))) { x = oldx; y = oldy; next = ClosestOcean(map, x, y); switch (next) { case 3: { x--; break; } case 2: { y++; break; } case 1: { x++; break; } default: { y--; break; } } } //stop if we reached edge of the map if (x < 0 || x >= map.Width || y < 0 || y > map.Height) { break; } //stop if we reached the ocean if (map.TileData[x, y] == WorldMap.TileType.Ocean) { break; } visited.Add(new Point(x, y)); map.TileData[x, y] = WorldMap.TileType.River; } foreach (Point p in visited) { map.ElevationData[p.X, p.Y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[x, y], 0f, 999f)), 6f); if (map.TileData[p.X - 1, p.Y] != WorldMap.TileType.River) { map.ElevationData[p.X - 1, p.Y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[p.X - 1, p.Y], 0f, 999f)), 2f); } if (map.TileData[p.X + 1, p.Y] != WorldMap.TileType.River) { map.ElevationData[p.X + 1, p.Y] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[p.X + 1, p.Y], 0f, 999f)), 2f); } if (map.TileData[p.X, p.Y - 1] != WorldMap.TileType.River) { map.ElevationData[p.X, p.Y - 1] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[p.X, p.Y - 1], 0f, 999f)), 2f); } if (map.TileData[p.X, p.Y + 1] != WorldMap.TileType.River) { map.ElevationData[p.X, p.Y + 1] = (float)Math.Pow((MathHelper.Clamp(map.ElevationData[p.X, p.Y + 1], 0f, 999f)), 2f); } } return(visited); }
/// <summary> /// Performs a single update. /// </summary> /// <exception cref="System.Exception"></exception> void PerformSingleUpdate() { //pause df here, so it doesn't try to resume while we're working. networkClient.suspend_game(); //everything that controls DF. #region DF Control if (mapResetRequested.Pop()) { mapResetCall.execute(); } if (digCommandCall != null) { while (netDigCommands.Count > 0) { digCommandCall.execute(netDigCommands.Dequeue()); } } if (pauseCommandCall != null) { while (pauseCommands.Count > 0) { pauseCommandCall.execute(pauseCommands.Dequeue()); } } if (keyboardEventCall != null) { KeyboardEvent dfEvent; while (keyPresses.TryDequeue(out dfEvent)) { keyboardEventCall.execute(dfEvent); } } #endregion #region DF Read if (fetchMap) { if (mapInfoCall != null) { MapInfo mapInfo; mapInfoCall.execute(null, out mapInfo); if (mapInfo == null) { if (netMapInfo != null) { lock (mapInfoLock) { embarkMapPosition = new DFCoord(-1, -1, -1); embarkMapSize = new DFCoord(0, 0, 0); MapDataStore.InitMainMap(embarkMapSize.x * 16, embarkMapSize.y * 16, embarkMapSize.z); } } } else { if ((netMapInfo == null) || mapInfo.block_pos_x != netMapInfo.block_pos_x || mapInfo.block_pos_y != netMapInfo.block_pos_y || mapInfo.block_pos_z != netMapInfo.block_pos_z || mapInfo.block_size_x != netMapInfo.block_size_x || mapInfo.block_size_y != netMapInfo.block_size_y || mapInfo.block_size_z != netMapInfo.block_size_z) { lock (mapInfoLock) { embarkMapPosition = new DFCoord(mapInfo.block_pos_x, mapInfo.block_pos_y, mapInfo.block_pos_z); embarkMapSize = new DFCoord(mapInfo.block_size_x, mapInfo.block_size_y, mapInfo.block_size_z); MapDataStore.InitMainMap(EmbarkMapSize.x * 16, EmbarkMapSize.y * 16, EmbarkMapSize.z); mapResetCall.execute(); } } } netMapInfo = mapInfo; } if (viewInfoCall != null) { ViewInfo viewInfo; viewInfoCall.execute(null, out viewInfo); netViewInfo.Set(viewInfo); } } if (fetchScreen) { if (copyScreenCall != null) { ScreenCapture screenCapture; copyScreenCall.execute(null, out screenCapture); netScreenCapture.Set(screenCapture); } } if (fetchUnits) { if (unitListCall != null) { UnitList unitList; unitListCall.execute(null, out unitList); netUnitList.Set(unitList); } } if (fetchWorldMap) { if (worldMapCenterCall != null) { WorldMap tempWorldMap; worldMapCenterCall.execute(null, out tempWorldMap); if (tempWorldMap != null) { DFTime = new DFTime(tempWorldMap.cur_year, tempWorldMap.cur_year_tick); } if (netWorldMapCenter == null || (tempWorldMap != null && (netWorldMapCenter.center_x != tempWorldMap.center_x || netWorldMapCenter.center_y != tempWorldMap.center_y))) { if (worldMapCall != null) { WorldMap worldMap; worldMapCall.execute(null, out worldMap); netWorldMap.Set(worldMap); } netWorldMapCenter = tempWorldMap; worldMapMoved.Set(); if (regionMapCall != null) { RegionMaps regionMaps; regionMapCall.execute(null, out regionMaps); netRegionMaps.Set(regionMaps); } nextRegionUpdate = DateTime.Now.AddSeconds(0.2); //add another region map update after this one, to get delayed regions.s } } if (nextRegionUpdate < DateTime.Now) { if (regionMapCall != null) { RegionMaps regionMaps; regionMapCall.execute(null, out regionMaps); netRegionMaps.Set(regionMaps); } nextRegionUpdate = DateTime.MaxValue; } } if (pauseCommandCall != null) { SingleBool status; pauseStatusCall.execute(null, out status); if (status != null) { _dfPauseState = status.Value; } } // since enqueueing results can block, we do it after we've unsuspended df BlockList resultList = null; if (fetchMap) { if (EmbarkMapSize.x > 0 && EmbarkMapSize.y > 0 && EmbarkMapSize.z > 0 && _needNewBlocks) { BlockCoord.Range?requestRangeUpdate = requestRegion.Pop(); if (requestRangeUpdate != null) { blockRequest.min_x = requestRangeUpdate.Value.Min.x; blockRequest.min_y = requestRangeUpdate.Value.Min.y; blockRequest.min_z = requestRangeUpdate.Value.Min.z; blockRequest.max_x = requestRangeUpdate.Value.Max.x; blockRequest.max_y = requestRangeUpdate.Value.Max.y; blockRequest.max_z = requestRangeUpdate.Value.Max.z; } if (blockListCall != null) { blockListCall.execute(blockRequest, out resultList); } } } #endregion //All communication with DF should be before this. networkClient.resume_game(); if (resultList != null) { foreach (MapBlock mapBlock in resultList.map_blocks) { pendingBlocks.Enqueue(mapBlock); } } }
public TransitSystem(WorldMap worldMap) { this.worldMap = worldMap; Stations = new List <Station>(); Debug.Log("I am a transit system!"); }
void UpdateRegionPositions(WorldMap map) { if (!GameSettings.Instance.rendering.drawDistantTerrain) return; foreach (var item in DetailRegions) { RegionMaker region = item.Value; region.SetPosition(map); } }
private void OnEnable( ) { obj = ( WorldMap )target; map = obj.map; openLocation = null; }
public World(WorldMap map) : this(map.Width, map.Height) { Map = map; }
public abstract void Populate(WorldMap w, Chunk c);
public void CreateWorldMap() { WorldMap = new WorldMap(this); }
private void onPlayerJoinEvent(object sender, PlayerJoinEventArgs e) { lblCurrentZone.Text = WorldMap.GetMapDisplayName(e.mapID); }
void UpdateRegionPositions(WorldMap map) { foreach (var item in DetailRegions) { RegionMaker region = item.Value; region.SetPosition(map); } }
// TO change -> change the Vector3 to Vector3 public Vector3Int GetCellPositionFromMouseInput() { Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); return(WorldMap.WorldToCell(mousePosition)); }
public void SetWorldMap(WorldMap worldMap) { map = worldMap; buildings = map.buildingsList; }
/// <summary> /// Loads the specified file name. /// </summary> /// <param name="fileName">Name of the file.</param> /// <returns>The map.</returns> /// <exception cref="FileFormatException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> private WorldMap Load(string fileName) { string workingFolder = Path.GetDirectoryName(fileName); OpenFile(fileName); // File version Reader.ReadUInt32(); // Initialize InitializeRoot(); if (Reader.ReadByte() != NodeTags.StartTag) { throw new FileFormatException("Could not find start node."); } //if (!ParseNode(Root)) // throw new FileFormatException("Could not parse root node."); // TODO: This should probably throw an exception if the return is 'false'(?) ParseNode(Root); Node node = GetRootNode(); if (!ReadProperty(node, out MapStreamReader mapPropertyReader)) { throw new FileFormatException("Could not parse root node properties."); } // First byte of OTB is 0 // TODO: Use propertyReader.Skip(byte.size); - byte.size is unknown mapPropertyReader.ReadByte(); MapMetadata metadata = mapPropertyReader.ReadMetadata(); if (metadata == null) { throw new FileFormatException("Could not read OTBM metadata."); } WorldMap map = new WorldMap { Width = metadata.Width, Height = metadata.Height }; node = node.Child; if ((MapNodeType)node.Type != MapNodeType.MapData) { throw new FileFormatException("Could not find map data node."); } if (!ReadProperty(node, out mapPropertyReader)) { throw new FileFormatException("Could not parse OTBM attribute."); } while (mapPropertyReader.PeekChar() != -1) { MapAttribute attribute = (MapAttribute)mapPropertyReader.ReadByte(); switch (attribute) { case MapAttribute.Description: map.Description = mapPropertyReader.ReadString(); break; case MapAttribute.ExtSpawnFile: string spawnFile = mapPropertyReader.ReadString(); map.SpawnFile = Path.Combine(workingFolder, spawnFile); break; case MapAttribute.ExtHouseFile: string houseFile = mapPropertyReader.ReadString(); map.HouseFile = Path.Combine(workingFolder, houseFile); break; default: throw new ArgumentException($"OTBM attribute '{attribute}' is not supported."); } } Node childNode = node.Child; while (childNode != null) { MapNodeType nodeType = (MapNodeType)childNode.Type; switch (nodeType) { case MapNodeType.Tiles: if (!ParseTiles(childNode, out IDictionary <IVector3, ITile> tiles)) { throw new FileFormatException("Could not parse tiles."); } map.Tiles.AddRange(tiles); break; case MapNodeType.Towns: if (!TryParseTowns(childNode, out IDictionary <uint, ITown> towns)) { throw new FileFormatException("Could not parse towns."); } map.Towns.AddRange(towns); break; case MapNodeType.Waypoints: if (!TryParseWaypoints(childNode, out IDictionary <string, IWaypoint> waypoints)) { throw new FileFormatException("Could not parse waypoints."); } map.Waypoints.AddRange(waypoints); break; default: throw new ArgumentOutOfRangeException(nameof(nodeType), nodeType, "OTBM node type is not supported."); } childNode = childNode.Next; } return(map); }
private void SetResourcePrefabs(int aIForNPCSeed) { LimitedMinedResourceInfo[] hexTypeToLimitedMinedResourceInfo = new LimitedMinedResourceInfo[(int)WorldMap.HexType.AllResources]; foreach (LimitedMinedResourceInfo resourceInfo in limitedMinedResourceInfoList.resourceInfos) { WorldMap.HexType hexType = WorldMap.GameResourceTypeToHexType(resourceInfo.gameResourceType); hexTypeToLimitedMinedResourceInfo[(int)hexType] = resourceInfo; } int currentAIForNPCOffset = aIForNPCSeed; for (int x = 0; x < cellColumns; ++x) { for (int y = 0; y < cellRows; ++y) { WorldMap.HexCell hexCell = worldMap.worldAreaInfo.area[x, y]; if (WorldMap.IsResourceOnlyType(hexCell.hexType)) { GameResourceType gameResourceType = WorldMap.HexTypeToGameResourceType(hexCell.hexType); GameObject resourceDeposit = Instantiate(resourceDepositPrefab, worldMap.GetHexPosition(new Vector2Int(x, y)), Quaternion.identity, resourcesTransform); ResourceSprite resourceSprite = resourceDeposit.GetComponent <ResourceSprite>(); resourceSprite.InitWithGameResourceType(gameResourceType); ResourceDeposit resourceDepositScript = resourceDeposit.GetComponent <ResourceDeposit>(); LimitedMinedResourceInfo limitedMinedResourceInfo = hexTypeToLimitedMinedResourceInfo[(int)hexCell.hexType]; float resourceAmount = limitedMinedResourceInfo.minAmount + Mathf.Pow(hexCell.resourceAmount / maxPossibleResourceValuePerCell, limitedMinedResourceInfo.power) * (limitedMinedResourceInfo.maxAmount - limitedMinedResourceInfo.minAmount); resourceDepositScript.SetResourceType(gameResourceType, resourceAmount); hexCell.indexInResourceArray = (short)worldMap.resourceDepositArray.Count; worldMap.worldAreaInfo.area[x, y] = hexCell; worldMap.resourceDepositArray.Add(resourceDepositScript); worldMap.resourceDepositIndicesArray.Add(new Vector2Int(x, y)); } else if (hexCell.hexType == WorldMap.HexType.Mountain) { GameObject mountain = Instantiate(mountainPrefab, worldMap.GetHexPosition(new Vector2Int(x, y)), Quaternion.identity, mountainsTransform); EnvironmentHeightParameter environmentHeightParameter = mountain.GetComponent <EnvironmentHeightParameter>(); environmentHeightParameter.InitHeight(hexCell.resourceAmount / maxPossibleResourceValuePerCell); } else if (hexCell.hexType == WorldMap.HexType.Crater) { GameObject crater = Instantiate(craterPrefab, worldMap.GetHexPosition(new Vector2Int(x, y)), Quaternion.identity, cratersTransform); EnvironmentHeightParameter environmentHeightParameter = crater.GetComponent <EnvironmentHeightParameter>(); environmentHeightParameter.InitHeight(hexCell.resourceAmount / maxPossibleResourceValuePerCell); } else if (hexCell.hexType == WorldMap.HexType.ColonyMainBase) { GameObject mainBaseLocation = Instantiate(mainBaseLocationPrefab, worldMap.GetHexPosition(new Vector2Int(x, y)), Quaternion.identity, mainBaseLocationsTransform); ColonyTeritory colonyTeritory = mainBaseLocation.GetComponent <ColonyTeritory>(); Vector3[] positions = worldMap.GetHexRings(worldMap.GetHexPosition(new Vector2Int(x, y)), 1, colonyRaduis); bool isPlayer = worldMap.colonyMainBaseArray.Count == 0; colonyTeritory.InitAvailableHexes(new List <Vector3>(positions), isPlayer); if (!isPlayer) { AIForNPC aIForNPC = mainBaseLocation.GetComponent <AIForNPC>(); aIForNPC.worldMap = worldMap; aIForNPC.freezer = freezer; aIForNPC.colonyRaduis = colonyRaduis; aIForNPC.seed = currentAIForNPCOffset; aIForNPC.enabled = true; ++currentAIForNPCOffset; } hexCell.indexInColonyMainBaseArray = (short)worldMap.colonyMainBaseArray.Count; worldMap.worldAreaInfo.area[x, y] = hexCell; worldMap.colonyMainBaseArray.Add(mainBaseLocation); worldMap.colonyMainBaseIndicesArray.Add(new Vector2Int(x, y)); } } } }
public override void Handle() => WorldMap.AddOrUpdate(AddOrUpdateTile, AddOrUpdateObject, RemovedObjects);
public void Init(ScriptHost.ScriptHost Host, WorldMap WM, PictureBox Pct) { this.Host = Host; this.WM = WM; this.PctWM = Pct; Rand = new Random(); }
public override string Move(ICharacter comp, ICharacter player, WorldMap map) { return(base.Move(comp, player, map)); }
/// <summary> /// Checks all neighbour nodes whether this node provides a shorter ( or new, thats trivially shorter ) path to it /// and update the data on the map accordingly /// </summary> /// <param name="whatNode">The node to expand</param> /// <param name="openList">A link to the current open list. As this function is just for code readability, this is plainly forwarded</param> /// <param name="whatMap">The map that is currently searched on</param> private static void expandNode(MapNode whatNode, SortedDictionary<int, List<MapNode>> openList, WorldMap whatMap) { foreach (Tuple<MapNode, int> reachableOpenNode in whatMap.getNeighbours(whatNode)) { if (reachableOpenNode.Item1.currentShortestPathToNode == null || reachableOpenNode.Item1.currentShortestPathToNode > whatNode.currentShortestPathToNode + reachableOpenNode.Item2) { if (reachableOpenNode.Item1.currentStatus.HasFlag(MapNode.Status.isClosed)) throw new Exception("Node is closed but currently known path is not the shortest. If the algorithm is working properly, this is impossible. This could be due to rounding errors but still hasn't been confirmed, so no further check is implemented."); //Remove the node from the open list because it needs to be put in another sublist. Remove current sublist if empty if (reachableOpenNode.Item1.currentShortestPathToNode != null) { openList[reachableOpenNode.Item1.possibleDistanceToGoal].Remove(reachableOpenNode.Item1); if (!openList[reachableOpenNode.Item1.possibleDistanceToGoal].Any()) openList.Remove(reachableOpenNode.Item1.possibleDistanceToGoal); } //Set the data on the updated node reachableOpenNode.Item1.currentPredesessorNode = whatNode; reachableOpenNode.Item1.currentShortestPathToNode = whatNode.currentShortestPathToNode + reachableOpenNode.Item2; //Put the node in the correct sublist. Create a new sublist if it doesnt already exist if (!openList.ContainsKey(reachableOpenNode.Item1.possibleDistanceToGoal)) openList.Add(reachableOpenNode.Item1.possibleDistanceToGoal, new List<MapNode>()); openList[reachableOpenNode.Item1.possibleDistanceToGoal].Add(reachableOpenNode.Item1); } } }
public void InitSelector(WorldMapManager managet) { worldMapManager = managet; this.currentMap = managet.currWorldMap; }
private void buildWorld() { if(mapRenderer != null) { mapRenderer.purge(); } worldMap = new WorldMap(worldWidth,worldHeight,buildingCount); List<Agent> population = worldMap.populateWorld(initLivingCount,initCorpseCount,initUndeadCount); mapRenderer.WorldMap = (worldMap); mapRenderer.instantiateWorld(); ActionArbiter.Instance.WorldMap = (worldMap); if(overlayUpdater != null) { overlayUpdater.map = worldMap; } if(spawnPlayerAgent) { spawnAgent(Agent.AgentType.HUMAN_PLAYER); mapRenderer.instantiateObjects(worldMap.placeWorldObject(WorldObject.ObjectType.EXTRACT_POINT)); } }
public override List <Hex> ValidTargets(WorldMap wm, Hex h) { return(justHeroValid(wm, h)); }
void CopyFromRemote(WorldMap remoteMap) { if (remoteMap == null) { Debug.Log("Didn't get world map!"); return; } if (!GameSettings.Instance.rendering.drawDistantTerrain) return; width = remoteMap.world_width; height = remoteMap.world_height; worldName = remoteMap.name; worldNameEnglish = remoteMap.name_english; offset = new Vector3( ((-remoteMap.center_x * 48) - 0.5f) * GameMap.tileWidth, 0, ((remoteMap.center_y * 48) + 0.5f) * GameMap.tileWidth); terrainMat.SetFloat("_Scale", scale); terrainMat.SetFloat("_SeaLevel", (99 * GameMap.tileHeight) + offset.y); InitArrays(); for (int x = 0; x < width; x++) for (int y = 0; y < height; y++) { int index = y * remoteMap.world_width + x; elevation[x, y] = remoteMap.elevation[index]; if (remoteMap.water_elevation != null && remoteMap.water_elevation.Count > index) water_elevation[x, y] = remoteMap.water_elevation[index]; else water_elevation[x, y] = 99; rainfall[x, y] = remoteMap.rainfall[index]; vegetation[x, y] = remoteMap.vegetation[index]; temperature[x, y] = remoteMap.temperature[index]; evilness[x, y] = remoteMap.evilness[index]; drainage[x, y] = remoteMap.drainage[index]; volcanism[x, y] = remoteMap.volcanism[index]; savagery[x, y] = remoteMap.savagery[index]; salinity[x, y] = remoteMap.salinity[index]; if (GameSettings.Instance.rendering.drawClouds) { cumulusMedium[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MEDIUM; cumulusMulti[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_MULTI; cumulusNimbus[x, y] = remoteMap.clouds[index].cumulus == CumulusType.CUMULUS_NIMBUS; stratusAlto[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_ALTO; stratusProper[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_PROPER; stratusNimbus[x, y] = remoteMap.clouds[index].stratus == StratusType.STRATUS_NIMBUS; cirrus[x, y] = remoteMap.clouds[index].cirrus; fogMist[x, y] = remoteMap.clouds[index].fog == FogType.FOG_MIST; fogNormal[x, y] = remoteMap.clouds[index].fog == FogType.FOG_NORMAL; fogThick[x, y] = remoteMap.clouds[index].fog == FogType.F0G_THICK; } } GenerateMesh(); if (GameSettings.Instance.rendering.drawClouds) GenerateClouds(); //Debug.Log("Loaded World: " + worldNameEnglish); }
public DirtCube(Overlay overlay, WorldMap worldMap, Vector3Int position) : base(MapElementType.Dirt, overlay, worldMap, position) { SpriteSource = new Rectangle(8*32, 20 * 2 + 32 * 1, 32, 32); }
public override WorldMap GetMap(GameManager gm) { WorldMap map = SaveManager.LoadLevel(GameManager.l, "crypt", gm); return(map); }
public void DoImportMap(string filename, out int processedmaps, out int processedspawners) { int i; string[] strArrays; processedmaps = 0; processedspawners = 0; int num = 0; int num1 = 0; if (filename == null || filename.Length <= 0) { return; } if (!File.Exists(filename)) { if (Directory.Exists(filename)) { string[] files = null; try { files = Directory.GetFiles(filename, "*.map"); } catch { } if (files != null && (int)files.Length > 0) { strArrays = files; for (i = 0; i < (int)strArrays.Length; i++) { this.DoImportMap(strArrays[i], out processedmaps, out processedspawners); num = num + processedmaps; num1 = num1 + processedspawners; } } string[] directories = null; try { directories = Directory.GetDirectories(filename); } catch { } if (directories != null && (int)directories.Length > 0) { strArrays = directories; for (i = 0; i < (int)strArrays.Length; i++) { this.DoImportMap(strArrays[i], out processedmaps, out processedspawners); num = num + processedmaps; num1 = num1 + processedspawners; } } processedmaps = num; processedspawners = num1; } return; } string fileName = Path.GetFileName(filename); int num2 = 0; int num3 = 0; int num4 = 0; int num5 = -1; try { using (StreamReader streamReader = new StreamReader(filename)) { while (true) { string str = streamReader.ReadLine(); string str1 = str; if (str == null) { break; } num4++; string str2 = str1.Trim(); char[] chrArray = new char[] { ' ' }; string[] strArrays1 = str2.Split(chrArray); if ((int)strArrays1.Length == 2 && strArrays1[0].ToLower() == "overridemap") { try { num5 = int.Parse(strArrays1[1]); } catch { } } if ((int)strArrays1.Length > 0 && strArrays1[0] == "*") { bool flag = false; int num6 = 0; int num7 = 0; int num8 = 0; int num9 = 0; int num10 = 0; int num11 = 0; int num12 = 0; int num13 = 0; int num14 = 0; string[] strArrays2 = null; if ((int)strArrays1.Length == 11 || (int)strArrays1.Length == 12) { string str3 = strArrays1[1]; chrArray = new char[] { ':' }; strArrays2 = str3.Split(chrArray); if ((int)strArrays1.Length == 11) { try { num6 = int.Parse(strArrays1[2]); num7 = int.Parse(strArrays1[3]); num8 = int.Parse(strArrays1[4]); num9 = int.Parse(strArrays1[5]); num10 = int.Parse(strArrays1[6]); num11 = int.Parse(strArrays1[7]); num12 = int.Parse(strArrays1[8]); num13 = int.Parse(strArrays1[9]); num14 = int.Parse(strArrays1[10]); } catch { flag = true; } } else if ((int)strArrays1.Length == 12) { try { num6 = int.Parse(strArrays1[2]); num7 = int.Parse(strArrays1[3]); num8 = int.Parse(strArrays1[4]); num9 = int.Parse(strArrays1[5]); num10 = int.Parse(strArrays1[6]); num11 = int.Parse(strArrays1[7]); num12 = int.Parse(strArrays1[8]); num13 = int.Parse(strArrays1[9]); int.Parse(strArrays1[10]); num14 = int.Parse(strArrays1[11]); } catch { flag = true; } } } else { flag = true; } if (flag || strArrays2 == null || (int)strArrays2.Length <= 0) { num3++; } else { if (num5 >= 0) { num9 = num5; } WorldMap worldMap = WorldMap.Internal; i = num9; switch (i) { case 0: { worldMap = WorldMap.Felucca; break; } case 1: { worldMap = WorldMap.Felucca; break; } case 2: { worldMap = WorldMap.Trammel; break; } case 3: { worldMap = WorldMap.Ilshenar; break; } case 4: { worldMap = WorldMap.Malas; break; } case 5: { try { worldMap = WorldMap.Tokuno; break; } catch { break; } break; } } if (worldMap != WorldMap.Internal) { Guid guid = Guid.NewGuid(); SpawnPoint spawnPoint = new SpawnPoint(guid, worldMap, (short)num6, (short)num7, (short)(num13 * 2), (short)(num13 * 2)) { SpawnName = string.Format("{0}#{1}", fileName, num2), SpawnHomeRange = num12, CentreZ = (short)num8, SpawnMinDelay = (double)num10, SpawnMaxDelay = (double)num11, SpawnMaxCount = num14 }; Type type = SpawnEditor.FindRunUOType("BaseVendor"); bool flag1 = false; for (int j = 0; j < (int)strArrays2.Length; j++) { Type type1 = SpawnEditor.FindRunUOType(strArrays2[j]); if (type1 != null && type != null && (type1 == type || type1.IsSubclassOf(type))) { flag1 = true; } spawnPoint.SpawnObjects.Add(new SpawnObject(strArrays2[j], num14)); } spawnPoint.IsSelected = false; if (flag1) { spawnPoint.SpawnSpawnRange = 0; } SpawnPointNode spawnPointNode = new SpawnPointNode(spawnPoint); this._Editor.tvwSpawnPoints.Nodes.Add(spawnPointNode); num2++; if (num9 == 0) { worldMap = WorldMap.Trammel; guid = Guid.NewGuid(); spawnPoint = new SpawnPoint(guid, worldMap, (short)num6, (short)num7, (short)(num13 * 2), (short)(num13 * 2)) { SpawnName = string.Format("{0}#{1}", fileName, num2), SpawnHomeRange = num12, CentreZ = (short)num8, SpawnMinDelay = (double)num10, SpawnMaxDelay = (double)num11, SpawnMaxCount = num14 }; for (int k = 0; k < (int)strArrays2.Length; k++) { spawnPoint.SpawnObjects.Add(new SpawnObject(strArrays2[k], num14)); } spawnPoint.IsSelected = false; if (flag1) { spawnPoint.SpawnSpawnRange = 0; } spawnPointNode = new SpawnPointNode(spawnPoint); this._Editor.tvwSpawnPoints.Nodes.Add(spawnPointNode); num2++; } } else { num3++; } } } } streamReader.Close(); } } catch { } processedmaps = 1; processedspawners = num2; }
public void setWorldMap(WorldMap newWorldMap) { _myWorld = newWorldMap; configureCamera(); }
// Start is called before the first frame update void Start() { worldMap = GameObject.FindGameObjectWithTag("WorldMap").GetComponent <WorldMap>(); cursor = GameObject.FindGameObjectWithTag("Cursor").GetComponent <Cursor>(); }
public RegionTile(WorldMap remoteMap, int index) { elevation = remoteMap.elevation[index]; if (remoteMap.water_elevation != null && remoteMap.water_elevation.Count > index) water_elevation = remoteMap.water_elevation[index]; else water_elevation = 99; rainfall = remoteMap.rainfall[index]; vegetation = remoteMap.vegetation[index]; temperature = remoteMap.temperature[index]; evilness = remoteMap.evilness[index]; drainage = remoteMap.drainage[index]; volcanism = remoteMap.volcanism[index]; savagery = remoteMap.savagery[index]; salinity = remoteMap.salinity[index]; if (remoteMap.river_tiles != null && remoteMap.river_tiles.Count > index) rivers = remoteMap.river_tiles[index]; }
// Use this for initialization void Start() { effector = GameObject.FindGameObjectWithTag("Effector").GetComponent <Effector> (); wMap = Camera.main.GetComponent <WorldMap> (); }
public void SetPosition(WorldMap mainMap) { if (mainMap != null) { offset = (new Vector3(-mainMap.center_x, 0, mainMap.center_y) + embarkTileOffset) * 48 * GameMap.tileWidth; } else { offset = embarkTileOffset * 48 * GameMap.tileWidth; } offset += new Vector3(-0.5f, 0, 0.5f) * GameMap.tileWidth; transform.position = offset; transform.localScale = new Vector3(scale, scale, scale); }
public void Update(GameTime gameTime, KeyboardState lastKeyState, MouseState lastMouseState, bool chatting) { MouseState mouseState = Mouse.GetState(); bool playerTeam = MainPlayer.PlayerTeam.Name == "Red Team"; if (online) { foreach (KeyValuePair <int, Player> entry in PlayerIndex.ToArray()) { if (!chatting) { entry.Value.Update(gameTime, lastKeyState, lastMouseState, DrawBlockOutline, entry.Value == MainPlayer); } else { entry.Value.Update(gameTime, lastKeyState, lastMouseState, DrawBlockOutline, false); } } } foreach (KeyValuePair <int, Mob> entry in MobIndex.ToArray()) { entry.Value.Update(gameTime, WorldMap); } foreach (KeyValuePair <int, ItemDrop> entry in DropIndex.ToArray()) { entry.Value.Update(gameTime, WorldMap, MainPlayer.Items, new Vector2(MainPlayer.X + MainPlayer.BoundWidth, MainPlayer.Y + MainPlayer.BoundHeight), playerTeam); } foreach (KeyValuePair <int, FallingBlock> entry in FallingBlockIndex.ToArray()) { FallingBlock fallingBlock = entry.Value; fallingBlock.Update(gameTime, WorldMap); if (fallingBlock.CanDestroy) { Universal.TryDictRemove(FallingBlockIndex, entry.Key); } } if (ServerMode == GameMode.TeamDeathmatch || ServerMode == GameMode.CaptureTheFlag) { RedTent.Update(gameTime, WorldMap, MainPlayer.Items, MainPlayer.Position, playerTeam); BlueTent.Update(gameTime, WorldMap, MainPlayer.Items, MainPlayer.Position, playerTeam); } foreach (GameObject gameObject in objectList.ToArray()) { gameObject.Update(gameTime); if (gameObject.Dead) { objectList.Remove(gameObject); } } int blockX = (camera.CX + mouseState.X) / 16; int blockY = (camera.CY + mouseState.Y) / 16; Item selectedItem = MainPlayer.SelectedItem; if (MainPlayer.Motion != Vector2.Zero || mouseState.LeftButton != lastMouseState.LeftButton || mouseState.RightButton != lastMouseState.RightButton || blockX != lastBlockX || blockY != lastBlockY) { DrawBlockOutline = false; if (blockX >= 0 && blockX < WorldMap.Width && blockY >= 0 && blockY < WorldMap.Height && Vector2.Distance(new Vector2(MainPlayer.X + MainPlayer.BoundWidth, MainPlayer.Y + MainPlayer.BoundHeight / 2), new Vector2(camera.CX + mouseState.X, camera.CY + mouseState.Y)) <= Universal.TILE_SIZE * Universal.PLACE_DISTANCE) { if (mouseState.RightButton == ButtonState.Pressed && WorldMap.Tiles[0, blockX, blockY].ID >= 0) { DrawBlockOutline = true; } else if (selectedItem.Type == ItemType.Block && mouseState.RightButton == ButtonState.Released && WorldMap.Tiles[0, blockX, blockY].ID == -1) { if (blockX >= 0 && blockX < WorldMap.Width) { if (blockY - 1 >= 0 && WorldMap.Tiles[0, blockX, blockY - 1].ID >= 0) { DrawBlockOutline = true; } if (blockY + 1 < WorldMap.Height && WorldMap.Tiles[0, blockX, blockY + 1].ID >= 0) { DrawBlockOutline = true; } } if (blockY >= 0 && blockY < WorldMap.Height) { if (blockX - 1 >= 0 && WorldMap.Tiles[0, blockX - 1, blockY].ID >= 0) { DrawBlockOutline = true; } if (blockX + 1 < WorldMap.Width && WorldMap.Tiles[0, blockX + 1, blockY].ID >= 0) { DrawBlockOutline = true; } } if (blockX == 0 || blockX == WorldMap.Width - 1 || blockY == 0 || blockY == WorldMap.Height - 1) { DrawBlockOutline = true; } } } } if (network != null && (mouseState.RightButton != lastMouseState.RightButton || blockX != lastBlockX || blockY != lastBlockY)) { network.SendHitBlock(DrawBlockOutline, mouseState.X, mouseState.Y); } lastBlockX = blockX; lastBlockY = blockY; if (!MainPlayer.RespawnInterval.IsRunning) { camera.Position = MainPlayer.Position; } if (camera.X < Universal.SCREEN_WIDTH / 2) { camera.X = Universal.SCREEN_WIDTH / 2; } else if (camera.X > WorldMap.Width * Universal.TILE_SIZE - Universal.SCREEN_WIDTH / 2) { camera.X = WorldMap.Width * Universal.TILE_SIZE - Universal.SCREEN_WIDTH / 2; } if (camera.Y < Universal.SCREEN_HEIGHT / 2) { camera.Y = Universal.SCREEN_HEIGHT / 2; } else if (camera.Y > WorldMap.Height * Universal.TILE_SIZE - Universal.SCREEN_HEIGHT / 2) { camera.Y = WorldMap.Height * Universal.TILE_SIZE - Universal.SCREEN_HEIGHT / 2; } WorldMap.CheckRender(); }
public async Task Run(GameContext context, BaseWorkerWindow vm, Action <string> statusUpdater, CancellationToken cancellationToken) { using (NDC.Push("Mapper Worker")) { await Task.Delay(1); var map = new WorldMap(context); var stride = (int)Math.Ceiling(484D / SubScanBounds.Width); var scans = (int)Math.Ceiling(484D / SubScanBounds.Height); var linear = Phase; ProcessedTiles = RecognizedTiles = FailedTiles = 0; TotalTiles = 484 * 484 / Period; TileInfo[][] mapData = null; var clog = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "logs", "map.json"); var ilog = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "logs", "tiles"); var jss = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; if (!Directory.Exists(Path.GetDirectoryName(clog))) { Directory.CreateDirectory(clog); } if (!Directory.Exists(ilog)) { Directory.CreateDirectory(ilog); } if (File.Exists(clog)) { try { mapData = JsonConvert.DeserializeObject <TileInfo[][]>(File.ReadAllText(clog), jss); } catch { } } if (mapData == null || mapData.Length != 492) { mapData = new TileInfo[492][]; } for (var i = 0; i < mapData.Length; i++) { if (mapData[i] == null || mapData[i].Length != 492) { mapData[i] = new TileInfo[492]; } } while (!cancellationToken.IsCancellationRequested) { if (linear > stride * scans) { break; } var cx = 8 + (linear % stride) * SubScanBounds.Width - SubScanBounds.X; var cy = 8 + (linear / stride) * SubScanBounds.Height - SubScanBounds.Y; statusUpdater($"Mapping at {cx},{cy} ({linear})"); if (!map.IsScreenActive()) { await Task.Delay(500, cancellationToken); if (!map.IsScreenActive()) { Logger.Fatal("World map screen not detected! Bailing out."); throw new InvalidOperationException("Not on the world map screen"); } } var needTiles = 0; for (var xx = SubScanBounds.Left; xx < SubScanBounds.Right; xx++) { for (var yy = SubScanBounds.Top; yy < SubScanBounds.Bottom; yy++) { if (xx + cx < 8 || xx + cx > 492 || yy + cy < 8 || yy + cy > 492) { continue; } ProcessedTiles++; if (mapData[cx + xx][cy + yy] == null) { needTiles++; } } } cancellationToken.ThrowIfCancellationRequested(); if (needTiles > 0) { statusUpdater($"Mapping {needTiles} tiles at {cx},{cy} ({linear})"); await map.GoTo(cx, cy, cancellationToken); for (var xx = SubScanBounds.Left; xx < SubScanBounds.Right; xx++) { for (var yy = SubScanBounds.Top; yy < SubScanBounds.Bottom; yy++) { if (xx + cx < 8 || xx + cx > 492 || yy + cy < 8 || yy + cy > 492) { continue; } mapData[cx + xx][cy + yy] = await map.SelectTile(xx, yy, Path.Combine(ilog, $"tile{cx + xx},{cy + yy}"), cancellationToken); if (mapData[cx + xx][cy + yy] != null) { mapData[cx + xx][cy + yy].CenterPoint = new Point(cx + xx, cy + yy); RecognizedTiles++; } else { FailedTiles++; } } } File.WriteAllText(clog, JsonConvert.SerializeObject(mapData, jss)); } linear += Period; } } }
internal Bot() { worldMap = new WorldMap(); }
static IEnumerator GenerateCoroutine(int sizeX, int sizeY, float seed, int minSpawnPoints, WorldFinishedEvent callback) { WorldMap world; // Repeat until we generate a valid world while (true) { world = new WorldMap { mapDict = new Dictionary <Vector2Int, TileType>() }; int tilesPerFrame = 100; int tilesDoneSinceFrame = 0; Dictionary <Vector2Int, float> heightmap = GenerateHeightMap(sizeX, sizeY, seed); // Loop through every tile defined by the size, fill it with grass and maybe add a plant for (int y = 0; y < sizeY; y++) { for (int x = 0; x < sizeX; x++) { Vector2Int currentPosition = new Vector2Int(x, y); TileType newTileType; // Assign ground material based on height if (heightmap[currentPosition] > waterLevel) { if (UnityEngine.Random.value < forestProbability) { newTileType = TileTypeLibrary.GetTileType(ForestTileId); } else if (UnityEngine.Random.value < farmProbability) { newTileType = TileTypeLibrary.GetTileType(FarmTileId); } else { newTileType = TileTypeLibrary.GetTileType(PlainsTileId); } } else { newTileType = TileTypeLibrary.GetTileType(WaterTileId); } world.mapDict.Add(currentPosition, newTileType); tilesDoneSinceFrame++; if (tilesDoneSinceFrame >= tilesPerFrame) { tilesDoneSinceFrame = 0; yield return(null); } } } if (!WorldIsValid(world, minSpawnPoints)) { yield return(new WaitForSeconds(0.1f)); seed = Random.value * 1000; continue; } break; } callback(world); }
public override void Undo(WorldMap w) { u.h = prev; }