public ObjectDirectory(string name) { this.id = 0; this.name = name; this.objectDirectories = new ObjectDirectories(); this.mapObjects = new MapObjects(); }
protected override void Initialize() { var generator = ObjectGenerator.GetGenerator(); var wires = ObjectGenerator.GetWires(generator); var consumers = ObjectGenerator.GetConsumers(wires); var elecritians = ObjectGenerator.GetElectritians(); var dispatherStation = ObjectGenerator.GetDispatherStation(); foreach (var el in wires) { MapObjects.Add(el); } foreach (var el in consumers) { MapObjects.Add(el); } foreach (var el in elecritians) { MapObjects.Add(el); } MapObjects.Add(generator); MapObjects.Add(dispatherStation); }
public void NextTick() { foreach (var baseMapObject in MapObjects) { baseMapObject.NextTick(); } for (var i = 0; i < Interactables.Count; i++) { for (var j = i + 1; j < Interactables.Count; j++) { if (i == j) { continue; } if (Interactables[i].IsIntersect(Interactables[j])) { Interactables[i].Intersect(Interactables[j]); Interactables[j].Intersect(Interactables[i]); } } } var objectToRemove = MapObjects.Where(a => a.ObjectState == MapObjectState.RemovalCandidate).ToList(); foreach (var mapObject in objectToRemove) { RemoveMapObject(mapObject); } }
public async Task <IActionResult> PutMapObjects([FromRoute] int id, [FromBody] MapObjects mapObjects) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != mapObjects.Id) { return(BadRequest()); } _context.Entry(mapObjects).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MapObjectsExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
//convert float heoght map to int objects map private MapObjects[][] heightConversion(float[][] mat) { int l = size / 16; int increment = 0; MapObjects[][] matInt = new MapObjects[size / l][]; for (int i = 0; i < size - 1; i += l) { matInt[i / l] = new MapObjects[size / l]; for (int j = 0; j < size - 1; j += l) { float control = (mat[i][j] + mat[i + 1][j] + mat[i + 1][j + 1] + mat[i][j + 1]) / l; increment = 0; while (increment < hb.size) { if (control > hb.data[increment++]) { matInt[i / l][j / l] = (MapObjects)increment; } } if (i / l > 2 && j / l > 2 && matInt[i / l - 1][j / l - 1] == MapObjects.marsh) { matInt[i / l - 1][j / l - 1] = chooseCoastOrientation( matInt[i / l - 1][j / l - 2], matInt[i / l - 1][j / l], matInt[i / l][j / l - 1], matInt[i / l - 2][j / l - 1], matInt[i / l][j / l - 2], matInt[i / l - 2][j / l - 2], matInt[i / l][j / l], matInt[i / l - 2][j / l] ); } } } mat = null; return(matInt); }
public JsonResult DeliverWithinDays(string days) { var deliveries = DateFilter.getDeliveriesWithinDays(company.Deliveries.ToList(), Convert.ToInt32(days)); var routes = DateFilter.getRoutesWithinDays(company.Routes.ToList(), Convert.ToInt32(days)); Response.StatusCode = (int)HttpStatusCode.OK; List <ShipperSingleDeliveryMapViewModel> delsWithAddress = new List <ShipperSingleDeliveryMapViewModel>(); foreach (Delivery delivery in deliveries) { ShipperSingleDeliveryMapViewModel model = new ShipperSingleDeliveryMapViewModel(); model.Client = delivery.Client; model.addressString = DirectionsService.getStringFromAddress(delivery.Client.Address); model.ID = delivery.ID; string clientName = delivery.Client.FirstName + " " + delivery.Client.LastName; string currentStatus = StatusExtension.DisplayName(delivery.DeliveryStatus.Status); string deliverByDate = delivery.DeliverBy.Value.Date.ToString(); string deliverByString = deliverByDate.Substring(0, deliverByDate.IndexOf(" ")); model.clientName = clientName; model.currentStatus = currentStatus; model.deliverBy = deliverByString; delsWithAddress.Add(model); } MapObjects result = new MapObjects(deliveries, routes, delsWithAddress, company); return(Json(result)); }
public void RefreshMapUnits() { var mapUnits = objectTileMap.GetComponentsInChildren <GameUnit>(); if (mapUnits.Any()) { foreach (var unit in mapUnits) { // Add the unit to our list of units and objects on this map if (!MapUnits.Contains(unit)) { MapUnits.Add(unit); } if (!MapObjects.Contains(unit)) { MapObjects.Add(unit); } // And make sure it's Map X/Y coordinates are corred in our grid var unitPosition = objectTileMap.WorldToCell(unit.transform.position); var gridPosition = objectTileMap.CellToWorld(unitPosition); unit.transform.position = gridPosition; TranslateUnityXYToMapXY(unitPosition, out var unitMapX, out var unitMapY); unit.MapX = unitMapX; unit.MapY = unitMapY; } } }
public IActionResult Index() { var deliveries = DateFilter.getDeliveriesWithinDays(company.Deliveries.ToList(), 2); var depots = company.PickUpLocations.ToList(); List <ShipperSingleDeliveryMapViewModel> delsWithAddress = new List <ShipperSingleDeliveryMapViewModel>(); foreach (Delivery delivery in deliveries) { ShipperSingleDeliveryMapViewModel model = new ShipperSingleDeliveryMapViewModel(); model.Client = delivery.Client; model.addressString = DirectionsService.getStringFromAddress(delivery.Client.Address); model.ID = delivery.ID; string clientName = delivery.Client.FirstName + " " + delivery.Client.LastName; string currentStatus = StatusExtension.DisplayName(delivery.DeliveryStatus.Status); string deliverByDate = delivery.DeliverBy.Value.Date.ToString(); string deliverByString = deliverByDate.Substring(0, deliverByDate.IndexOf(" ")); model.clientName = clientName; model.currentStatus = currentStatus; model.deliverBy = deliverByString; delsWithAddress.Add(model); } MapObjects objects = new MapObjects(deliveries, depots, company.Routes.ToList(), delsWithAddress, company); return(View(objects)); }
// Этот метод вызывается регулярно, поэтому тут все действия, которые будут повторяться public override void Update(long elapsedMilliseconds) { var actors = MapObjects.GetAll <Actor>(); Console.WriteLine($"Got {actors.Count} actors\n"); // Для каждого актёра проверяем условия и назначаем новую активность если нужно foreach (var actor in actors) { // Есть ли активность bool isActivity = actor.Activity != null; // Если активность дороги домой bool goHome = isActivity ? actor.Activity is MovementActivityHome : false; // Если ли активность ожидания bool goWait = isActivity ? actor.Activity is WaitingActivityHome : false; Console.WriteLine($"Flags: {isActivity} {goHome} {goWait}"); if (!isActivity) { // Назначить актору путь до дома Console.WriteLine("Said actor go home\n"); actor.Activity = new MovementActivityHome(); } } }
/// <summary> /// Update the Saveability of every MapObject in this map, setting /// instance entities to be Saveability.Children. /// </summary> /// <param name="map"></param> /// <returns>A copy of the input Map with its MapObjects' Saveability /// updated, in preparation for writing to disk as a string.</returns> public override Map Collapse() { var collapsed = new QuakeMap(this); collapsed.MapObjects.Clear(); int worldspawnIndex = MapObjects.FindIndex(o => o.Definition.ClassName == "worldspawn"); MapObject worldspawn = MapObjects[worldspawnIndex]; collapsed.MapObjects.Add(worldspawn); for (int i = 0; i < MapObjects.Count; i++) { if (i != worldspawnIndex) { List <MapObject> collapsedObject = MapObjects[i].Collapse(); foreach (MapObject co in collapsedObject) { if (co.Definition.ClassName == "worldspawn") { worldspawn.Renderables.AddRange(co.Renderables); } else { collapsed.MapObjects.Add(co); } } } } return(collapsed); }
public async Task MethodWithDelayAsync(int milliseconds) { await Task.Delay(milliseconds); endResearch = true; MapObjects.Remove(objRes); Console.WriteLine("Исследование закончилось 😎😎😎😎"); // ищем ближайщий объект int minIndex = 0; double min = 0; int i = 0; var objOnMap = MapObjects.GetAll <ObjResearch>(); foreach (var minDist in objOnMap) { if (min == 0) { min = TestModule.Distance(submarine, minDist); i++; continue; } if (min > TestModule.Distance(submarine, minDist)) { min = TestModule.Distance(submarine, minDist); minIndex = i; } i++; } objRes = objOnMap[minIndex]; }
public CollectionsViewModel() { Status = TaskStatuses.Success; const double Radius = 10; Collections.Add(new OverpassCollection(new[] { "toilets" }, Radius) { Title = "Toilets", ImageSource = "em173", MakeIconFunc = _ => BitmapCache.GetBitmap("em173.png"), MaxVisibleCount = 100 }); Collections.Add(new OverpassCollection(new[] { "recycling" }, Radius) { Title = "Recycling", ImageSource = "em157", MakeIconFunc = _ => BitmapCache.GetBitmap("em157.png"), MaxVisibleCount = 100 }); var root = new MapObjectCollection() { Title = "Root", MaxVisibleCount = 10 }; root.Add(Collections.ToList()); Collections.Add(root); MapObjects.Add(root); }
public void CanGetAScore() { var map = new MapObjects[7, 7]; map[2, 4] = MapObjects.Wall; map[2, 5] = MapObjects.Wall; map[2, 6] = MapObjects.Wall; map[3, 0] = MapObjects.Wall; map[3, 1] = MapObjects.Wall; map[3, 2] = MapObjects.Wall; map[3, 3] = MapObjects.FreeSquare; map[3, 4] = MapObjects.Wall; map[3, 5] = MapObjects.FreeSquare; map[4, 0] = MapObjects.Wall; map[4, 1] = MapObjects.FreeSquare; map[4, 2] = MapObjects.FreeSquare; map[4, 3] = MapObjects.Motorcycle; map[4, 4] = MapObjects.FreeSquare; map[4, 5] = MapObjects.FreeSquare; map[5, 0] = MapObjects.Wall; map[5, 1] = MapObjects.FreeSquare; map[5, 2] = MapObjects.FreeSquare; map[5, 3] = MapObjects.Wall; map[5, 4] = MapObjects.FreeSquare; map[5, 5] = MapObjects.FreeSquare; // sanity check Assert.Equal(map[4, 3], MapObjects.Motorcycle); var result1 = PathEvaluator.GetScore(new Vector2D(4, 2), map); var result2 = PathEvaluator.GetScore(new Vector2D(3, 3), map); var result3 = PathEvaluator.GetScore(new Vector2D(4, 4), map); var result4 = PathEvaluator.GetScore(new Vector2D(5, 3), map); }
protected override void Initialize() { controller = new Controller(); // Создание координат полигона. var polygonCoordinates = new Coordinate[] { new Coordinate(4817367, 6144314), new Coordinate(4817367, 6267072), new Coordinate(4950673, 6267072), new Coordinate(4950673, 6144314), new Coordinate(4817367, 6144314) }; // Создание стандартного полигона по ранее созданным координатам. controller.tempList.Add(new Temperature(new LinearRing(polygonCoordinates))); var polygonCoordinates2 = new Coordinate[] { new Coordinate(4950673, 6144314), new Coordinate(4950673, 6267072), new Coordinate(5040869, 6267072), new Coordinate(5040869, 6144314), new Coordinate(4950673, 6144314) }; // Создание стандартного полигона по ранее созданным координатам. controller.tempList.Add(new Temperature(new LinearRing(polygonCoordinates2))); MapObjects.Add(controller.tempList[0]); MapObjects.Add(controller.tempList[1]); }
protected override void Initialize() { controller = new Controller(); // Создание координат полигона. var polygonCoordinates = new Coordinate[] { new Coordinate(4817367, 6144314), new Coordinate(4817367, 6267072), new Coordinate(4950673, 6267072), new Coordinate(4950673, 6144314), new Coordinate(4817367, 6144314) }; // Создание стандартного полигона по ранее созданным координатам. Territory territory = new Territory(new LinearRing(polygonCoordinates)); Dog dog = new Dog(controller.generateCoordinate(territory)); Human human = new Human(controller.generateCoordinate(territory)); Enemy enemy = new Enemy(controller.generateCoordinate(territory)); territory.dogs.Add(dog); territory.human = human; territory.enemys.Add(enemy); controller.territories.Add(territory); MapObjects.Add(territory); MapObjects.Add(dog); MapObjects.Add(enemy); MapObjects.Add(human); }
private async void OnSizeChanged(Object sender, SizeChangedEventArgs args) { var latitudeTiles = (UInt16)Math.Max(1, Math.Ceiling(args.NewSize.Height / 400) - 1); var longitudeTiles = (UInt16)Math.Max(1, Math.Ceiling(args.NewSize.Width / 400) - 1); if (MapObjects == null) { MapObjects = new MapObjects <MapPhoto, MapCluster>(Map, longitudeTiles, latitudeTiles); MapObjects.ObjectTapped += OnObjectTapped; MapObjects.ClusterTapped += OnClusterTapped; MapControlEventSampler = new MapControlEventSampler(Map, TimeSpan.FromMilliseconds(2000)); MapControlEventSampler.MapViewChanged += OnMapViewChanged; if (PrimaryMenu.SelectedIndex == 1) { var mapViewSettings = App.Model.MapView.Get(); if (mapViewSettings != null) { await Context.StartProgressiveSearchAsync(mapViewSettings, PhotoTag.Public); } } } else { MapObjects.Apply(longitudeTiles, latitudeTiles); } }
private void GenerateMapObjects(string region) { //Variables for generating monsters //Move these somehwere?? int minMonsters = 6; int maxMonsters = 10; string[] latlon; Random rnd = new Random(); MapObjects newObject; Monsters mon; int numMonsters = rnd.Next(minMonsters, maxMonsters); for (int i = 0; i < numMonsters; i++) { newObject = new MapObjects(); newObject.Region = region; newObject.Type = "monster"; newObject.TimeStamp = DateTime.UtcNow; //Choose monster type mon = _context.Monsters.OrderBy(r => Guid.NewGuid()).Take(1).First(); newObject.Attributes = mon.Attributes; //Generate random location from region latlon = region.Split(','); newObject.Lat = Convert.ToDecimal(latlon[0]); newObject.Lon = Convert.ToDecimal(latlon[1]); newObject.Lat += Decimal.Divide(rnd.Next(1, 10), 1000) - .005m; newObject.Lon += Decimal.Divide(rnd.Next(1, 10), 1000) - .005m; _context.MapObjects.Add(newObject); } _context.SaveChanges(); }
protected override void Initialize() { //тут будут жить звери var wildLandCoordinates = new[] { new Coordinate(_leftX, _downY), new Coordinate(_leftX, _upY), new Coordinate(_rightX, _upY), new Coordinate(_rightX, _downY), new Coordinate(_leftX, _downY), }; _wildLand = new Polygon(new LinearRing(wildLandCoordinates)); MapObjects.Add(_wildLand); //Спаун оленей foreach (var coordinate in GenerateCoordinatesAnimal(200)) { MapObjects.Add(new Deer(coordinate, _deerSeed)); } //Спаун волков foreach (var coordinate in GenerateCoordinatesAnimal(300)) { MapObjects.Add(new Wolf(coordinate, _wolfSpeed)); } }
public override void Update(long elapsedMilliseconds) { var deers = MapObjects.GetAll <Deer>(); var wolves = MapObjects.GetAll <Wolf>(); foreach (var deer in deers) { //проверяю чтобы олени не вышли из полигона if (deer.Coordinate.X < _leftX - _barier || deer.Coordinate.Y < _downY - _barier) { deer._speed = _deerSeed; } else if (deer.Coordinate.X > _rightX - _barier || deer.Coordinate.Y > _upY - _barier) { deer._speed = -_deerSeed; } deer.MoveUpRight(); } foreach (var wolf in wolves) { var nearestDeer = deers.Aggregate((deer1, deer2) => PointExtension.Distance((Point)wolf, (Point)deer1) < PointExtension.Distance((Point)wolf, (Point)deer2) ? deer1 : deer2); wolf.MoveUpRight(new Coordinate(nearestDeer.X, nearestDeer.Y)); //Ищем ближайшего волка var minDistance = double.MaxValue; foreach (var _wolf in wolves.Where(_wolf => (PointExtension.Distance((Point)wolf, (Point)_wolf) < minDistance) && (PointExtension.Distance((Point)wolf, (Point)_wolf) > 0))) { minDistance = (PointExtension.Distance((Point)wolf, (Point)_wolf)); } if (minDistance < 250) { if (wolf._flagPack == false) { Console.WriteLine(minDistance); wolf.WolfInThePack(); wolf._flagPack = true; } } else { wolf._speed = _wolfSpeed; wolf._flagPack = false; } if (!wolf.CanEat(nearestDeer)) { continue; } MapObjects.Remove(nearestDeer); deers.Remove(nearestDeer); var newDeerCoordinate = GenerateCoordinatesAnimal(1)[0]; MapObjects.Add(new Deer(newDeerCoordinate, 10)); } }
public void Draw(GameTime gameTime, SpriteBatch spriteBatch) { float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds; //Draw backgrounds Rectangle screenRectangle = new Rectangle(0, 0, _width * Tile.DefaultWidth, _height * Tile.DefaultHeight); BoundingBox screenBox = screenRectangle.MakeBoundingBox(); foreach (BackgroundTexture texture in _backgroundTextures) { Rectangle destination = new Rectangle(texture.Point.X * Tile.DefaultWidth - ScrollOffset, texture.Point.Y * Tile.DefaultHeight, texture.Width, texture.Height); BoundingBox destinationBoundingBox = destination.MakeBoundingBox(); if (destinationBoundingBox.Intersects(screenBox)) { //we can see it! spriteBatch.Draw(texture.Texture, destination, Color.White); } } //Draw tiles for (int i = 0; i < ViewWidth + 1; i++) { for (int j = 0; j < Height; j++) { if (i + ScrollOffset / Tile.DefaultWidth < 0) { continue; } Tile tile = _tiles[j, i + ScrollOffset / Tile.DefaultWidth]; if (tile == null) { continue; } if (!tile.IsAlive) { continue; } //Vector2 pos = new Vector2(Tile.DefaultWidth * i - (ScrollOffset % Tile.DefaultWidth), Tile.DefaultHeight * j); //Rectangle dest = new Rectangle((int)pos.X, (int)pos.Y, Tile.DefaultWidth, Tile.DefaultHeight); //spriteBatch.Draw(tile.Texture, dest, Color.White); tile.Draw(gameTime, spriteBatch); } } //Draw player ActivePlayer.Draw(gameTime, spriteBatch); //Draw Objects MapObjects.Draw(gameTime, spriteBatch); //Draw Particle Effects _particleEffects.Draw(gameTime, spriteBatch); }
public void RemoveMapUnit(IGameMapObject mapObject) { if (MapObjects.Contains(mapObject)) { MapObjects.Remove(mapObject); mapObject.WorldPosition = new Vector3(-100, -100, -100); } }
// Этот метод будет вызван один раз при запуске, соответственно тут вся инициализация protected override void Initialize() { State state = new State() { Hunger = 100, // Интервал можно задать через объекты LocalTime HomeTime = new TimeInterval(new LocalTime(20, 0), new LocalTime(18, 23)), }; // Создаём акторов for (int i = 0; i < 2; i++) { Console.WriteLine($"Creating actor {i + 1}"); // Делаем для каждого точку дома и точку работы в квадрате заданного радиуса от точки спавна state.Home = new Point(x + offset, y + offset); state.Job = new Point(x + offset, y + offset); Console.WriteLine($"Home at {state.Home.X}, {state.Home.Y}; " + $"Job at {state.Job.X}, {state.Job.Y}"); // Создаём актора с заданным состоянием // Так как в конструкторе актора состояние копируется, // можно использовать один и тот же объект состояния для инициализации, // при этом каждый актор получит отдельный объект, не связанный с другими Actor actor = new Actor(x, y, state); // Добавляем актора в объекты карты MapObjects.Add(actor); var firstCoordinate = new Coordinate(x, y); var secondCoordinate = new Coordinate(state.Home.X, state.Home.Y); Console.WriteLine($"Coor {firstCoordinate} and {secondCoordinate}"); Console.WriteLine("Building path..."); MapObjects.Add(new Highlighted(new Geometry[] { PathsFinding.GetPath(firstCoordinate, secondCoordinate, "Walking").Result })); Console.WriteLine("Path was builded"); } // Получаем список акторов на карте и выводим их количество var actors = MapObjects.GetAll <Actor>(); Console.WriteLine($"Added {actors.Count} actors"); foreach (var actor in actors) { Console.WriteLine($"Actor on ({actor.Coordinate.X}, {actor.Coordinate.Y})\n" + $"\tHome at {actor.State.Home.X}, {actor.State.Home.Y}\n"); } }
protected override void Initialize() { //Добавление созданных объектов в общий список, доступный всем модулям. Объекты из данного списка отображаются на карте. MapObjects.Add(new Airport(china, 20)); MapObjects.Add(new Airport(moscow, 13)); MapObjects.Add(new Airport(iraq, 9)); MapObjects.Add(new Airport(afganistan, 7)); MapObjects.Add(new Airport(usa, 17)); allAirports = MapObjects.GetAll <Airport>(); }
//Движение самолетов в их пункты назначения-аэропорты и их удаление при достижении пункта назначения public void Fly() { foreach (var airplane in MapObjects.GetAll <Airplane>()) { int flew = airplane.MoveToAirport(); if (flew != -1) { RemoveAirplane(airplane); } } }
//Создание самолетов в аэропорте, если они там существуют public void CreateAirplanes() { foreach (var airport in allAirports) { if (airport.Count != 0) { CreateAirplane(airport.FlyOff(allAirplanes.Count, allAirports[new Random().Next(0, 5)])); allAirplanes = MapObjects.GetAll <Airplane>(); } } }
public async Task <IActionResult> PostMapObjects([FromBody] MapObjects mapObjects) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _context.MapObjects.Add(mapObjects); await _context.SaveChangesAsync(); return(CreatedAtAction("GetMapObjects", new { id = mapObjects.Id }, mapObjects)); }
private static int Score(MapObjects input) { switch (input) { case MapObjects.FreeSquare: return(ScoreFree); case MapObjects.Unknown: return(ScoreUnknown); default: return(0); } }
protected override void Initialize() { //Добавление созданных объектов в общий список, доступный всем модулям. Объекты из данного списка отображаются на карте. //тут добавить Human1, Human2, Human3, Human4, Animal1, Animal2, Animal3, Animal4 с разными хар-ами. Все они объекты класса VitalFunctions MapObjects.Add(new VitalFunctions(new Coordinate(4956032, 6225636), 1, 100, false, 43, "Human", new Coordinate(4956332, 6225936))); MapObjects.Add(new VitalFunctions(new Coordinate(4956030, 6225750), 1, 98, false, 50, "Human", new Coordinate(4956332, 6225936))); MapObjects.Add(new VitalFunctions(new Coordinate(4956600, 6225750), 1, 95, false, 50, "Human", new Coordinate(4956332, 6225936))); MapObjects.Add(new VitalFunctions(new Coordinate(4955900, 6225855), 1, 97, false, 43, "Animal", new Coordinate(4955800, 6226000))); MapObjects.Add(new VitalFunctions(new Coordinate(4955930, 6225845), 1, 90, false, 50, "Animal", new Coordinate(4955800, 6226000))); MapObjects.Add(new VitalFunctions(new Coordinate(4956000, 6226000), 1, 99, false, 50, "Animal", new Coordinate(4955500, 6225750))); MapObjects.Add(new VitalFunctions(new Coordinate(4955500, 6226200), 1, 89, false, 40, "Human", new Coordinate(4955800, 6225950))); MapObjects.Add(new VitalFunctions(new Coordinate(4955901, 6225901), 1, 91, false, 50, "Human", new Coordinate(4956332, 6225936))); }
protected override void Initialize() { // добавляем регион подводной лодки и подлодку MapObjects.Add(new Region(_leftX, _rightX, _upY, _downY).polygon); MapObjects.Add(new Submarine(new Coordinate(-14000000, -7000000), 5000)); // создаем таймер на создание объектов для исследование каждые 5с Init(); //Получим объект подлодки и объекта для исследования objRes = MapObjects.GetAll <ObjResearch>()[0]; submarine = MapObjects.GetAll <Submarine>()[0]; }
// private void Map_Click(object sender, MouseEventArgs e) { // label2.Text = e.X.ToString(); um neue MapObjekte erstellen zu können //label4.Text = e.Y.ToString(); '' if (Player.Lifepoints < 1) { MessageBox.Show($"Du bist tot. Um neu zu beginnen, musst du das Programm neustarten. du hattest {Player.Money}$"); Player.Money = 0; LoadPlayerDataOnScreen(); } MapObjects.GetMapObject(e.X, e.Y); LoadPlayerDataOnScreen(); }
public void RemoveMapObject(BaseMapObject obj) { MapObjects.Remove(obj); if (obj is IInteractable interactable) { Interactables.Remove(interactable); } if (obj is User user) { Users.Remove(user); } }
/// <summary> /// Gets a collection of map objects that have the given parent /// </summary> /// <param name="parent">The parent to find map objects for</param> /// <returns>A collection of map objects with the given parent</returns> public static MapObjects GetMapObjects(long parent) { MapObjects toReturn = new MapObjects(); MapObject temp = null; DataTable dt = null; SqlCommand cmd = new SqlCommand(); string query = "SELECT * FROM [MapObject] WHERE Parent = @Parent"; cmd.CommandType = CommandType.Text; cmd.CommandText = query; cmd.Parameters.Add(new SqlParameter("@Parent", SqlDbType.BigInt)).Value = parent; dt = DatabaseHelper.ExecuteQuery(GetConnectionString(), cmd); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { temp = new MapObject(); temp.ID = DatabaseHelper.GetValidValueFromObject(dr["ID"], (long)0); temp.Name = DatabaseHelper.GetValidValueFromObject(dr["Name"], string.Empty); if (dr["Structure"] != DBNull.Value) { temp.TileMap = TileMap.CreateTileMapFromByteArray((byte[])dr["Structure"]); } else { temp.TileMap = null; } toReturn.Add(temp); } } return toReturn; }
/// <summary> /// Deletes from the database any Map Object that is no longer in this list, then calls insertupdate on each object /// </summary> /// <param name="os">The list of map objects to have in the database</param> /// <param name="parent">The parent of the map objects</param> private static void InsertUpdateMapObjects(MapObjects os, long parent) { MapObjects curr = GetMapObjects(parent); if (curr != null && curr.Count > 0 && os != null) { foreach (MapObject o in curr) { if (os.FindByID(o.ID) == null) { DeleteMapObject(o.ID); } } } foreach (MapObject o in os) { InsertUpdateMapObject(o, parent); } }