Exemplo n.º 1
0
        public void ExitLocationsDoNotOverwriteDoorDescriptions()
        {
            selectedExit.Width = 2;

            var exit = new Area { Type = AreaTypeConstants.Door, Descriptions = new[] { "door-like" } };
            var otherExit = new Area { Type = AreaTypeConstants.Door, Descriptions = new[] { "sliding", "like Star Trek" } };
            mockDoorGenerator.SetupSequence(g => g.Generate(9266, 90210, "temperature")).Returns(new[] { exit }).Returns(new[] { otherExit });

            mockPercentileSelector.SetupSequence(s => s.SelectFrom(TableNameConstants.ExitLocation)).Returns("on the ceiling").Returns("behind you");
            mockPercentileSelector.SetupSequence(s => s.SelectFrom(TableNameConstants.ExitDirection)).Returns("to the right").Returns("to the left");

            var exits = roomExitGenerator.Generate(9266, 90210, 42, 600, "temperature");
            Assert.That(exits.Count(), Is.EqualTo(2));

            var first = exits.First();
            var last = exits.Last();

            Assert.That(first, Is.EqualTo(exit));
            Assert.That(first.Descriptions, Contains.Item("on the ceiling"));
            Assert.That(first.Descriptions, Contains.Item("door-like"));
            Assert.That(first.Descriptions.Count(), Is.EqualTo(2));
            Assert.That(last, Is.EqualTo(otherExit));
            Assert.That(last.Descriptions, Contains.Item("behind you"));
            Assert.That(last.Descriptions, Contains.Item("sliding"));
            Assert.That(last.Descriptions, Contains.Item("like Star Trek"));
            Assert.That(last.Descriptions.Count(), Is.EqualTo(3));
        }
Exemplo n.º 2
0
    /// <summary>
    /// generates average filter on given region
    /// </summary>
    public void GenerateAverageFilterInRegion(Area region)
    {
        int x_min = region.botLeft.x;
        int z_min = region.botLeft.z;

        int x_max = region.topRight.x;
        int z_max = region.topRight.z;

        float height;
        float neighbourAverage;
        for (int x = x_min; x < x_max; x++)
        {
            for (int z = z_min; z < z_max; z++)
            {

                if (lt.globalTerrainC.IsDefined(x, z) && !globalFilterAverageC.IsDefined(x, z))
                {
                    height = lt.lm.GetCurrentHeight(x, z);
                    neighbourAverage = lt.gt.GetNeighbourAverage(x, z, 2);
                    if (neighbourAverage != 666)
                    {
                        fg.SetGlobalValue(x, z, height -
                            neighbourAverage, false, globalFilterAverageC);
                    }
                }
            }
        }
    }
Exemplo n.º 3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="SharpNav.AreaGenerator"/> class.
		/// </summary>
		/// <param name="verts">collection of Triangles.</param>
		/// <param name="triCount">The number of triangles to enumerate..</param>
		/// <param name="defaultArea">Default area.</param>
		private AreaGenerator(IEnumerable<Triangle3> verts, int triCount, Area defaultArea)
		{
			this.tris = verts;
			this.triCount = triCount;
			this.defaultArea = defaultArea;
			conditions = new List<Tuple<Func<Triangle3, bool>, Area>>();
		}
Exemplo n.º 4
0
        public IEnumerable<Area> Generate(int dungeonLevel, int partyLevel, string temperature)
        {
            var shape = percentileSelector.SelectFrom(TableNameConstants.SpecialAreaShapes);

            if (shape == AreaTypeConstants.Cave)
                return caveGenerator.Generate(dungeonLevel, partyLevel, temperature);

            var area = new Area();
            area.Width = 1;
            area.Descriptions = new[] { shape };

            var shouldReroll = false;

            do
            {
                var size = areaPercentileSelector.SelectFrom(TableNameConstants.SpecialAreaSizes);
                area.Length += size.Width + size.Length;
                shouldReroll = size.Width > 0;
            } while (shouldReroll);

            if (area.Descriptions.Contains(DescriptionConstants.Circular))
            {
                area.Contents.Pool = poolGenerator.Generate(partyLevel, temperature);
            }

            return new[] { area };
        }
Exemplo n.º 5
0
        public NinePatchImage(Texture2D texture)
        {
            _texture = texture;
            XnaColor[] data = new XnaColor[texture.Width * texture.Height];
            texture.GetData(data);
            Stretch = new Area(
                vertical: GetLine(texture, data, 0, 1, 0, 0),
                horizontal: GetLine(texture, data, 1, 0, 0, 0));
            Content = new Area(
                vertical: GetLine(texture, data, 0, 1, _texture.Width - 1, 0),
                horizontal: GetLine(texture, data, 1, 0, 0, _texture.Height - 1));

            Width = _texture.Width - 2;
            Height = _texture.Height - 2;

            _leftTop = new XnaRectangle(1, 1, Stretch.Horizontal.Start, Stretch.Vertical.Start);
            _leftCenter = new XnaRectangle(1, Stretch.Vertical.Start, Stretch.Horizontal.Start, Stretch.Vertical.Size);
            _leftBottom = new XnaRectangle(1, Stretch.Vertical.End, Stretch.Horizontal.Start, texture.Height - 1 - Stretch.Vertical.End);
            _centerTop = new XnaRectangle(Stretch.Horizontal.Start, 1, Stretch.Horizontal.Size, Stretch.Vertical.Start);
            _center = new XnaRectangle(Stretch.Horizontal.Start, Stretch.Vertical.Start, Stretch.Horizontal.Size, Stretch.Vertical.Size);
            _centerBottom = new XnaRectangle(Stretch.Horizontal.Start, Stretch.Vertical.End, Stretch.Horizontal.Size, texture.Height - 1 - Stretch.Vertical.End);
            _rightTop = new XnaRectangle(Stretch.Horizontal.End, 1, texture.Width - 1 - Stretch.Horizontal.End, Stretch.Vertical.Start);
            _rightCenter = new XnaRectangle(Stretch.Horizontal.End, Stretch.Vertical.Start, texture.Width - 1 - Stretch.Horizontal.End, Stretch.Vertical.Size);
            _rightBottom = new XnaRectangle(Stretch.Horizontal.End, Stretch.Vertical.End, texture.Width - 1 - Stretch.Horizontal.End, texture.Height - 1 - Stretch.Vertical.End);
        }
Exemplo n.º 6
0
        public override actions.Action GetAction()
        {
            CalcXYDiff();
            int xMov = 0, yMov = 0;
            while( XDif == 0 && YDif == 0)
            {
                curDest = WorldMap.GetArea(random.Next(10), random.Next(10));
                CalcXYDiff();
            }
            if( XDif < 0)
            {
                xMov = -1;
            }else if( XDif > 0 )
            {
                xMov = 1;
            }
            if (YDif < 0)
            {
                yMov = -1;
            }
            else if (YDif > 0)
            {
                yMov = 1;
            }

            actions.Move  ret = new actions.Move(Owner, WorldMap.GetArea(Owner.Location.X + xMov, Owner.Location.Y + yMov));
            return ret;
        }
        public void SetUp()
        {
            var placeholder1 = new Placeholder("area 1");
            var placeholder2 = new Placeholder("area 2");
            var widgetSpecification = new WidgetSpecification("widget");
            widgetSpecification.Insert(0, placeholder1);
            widgetSpecification.Insert(1, placeholder2);

            var area = new Area("area 1");
            var widget = new Widget("widget", new[] { area });

            var buildContext = new BuildData(Enumerable.Empty<IContextItem>());

            var builder = new Builder(RenderingInstructions.BuildForPreview(), w => widgetSpecification, null);

            var instance = widget.Build(builder, new[] { 0 }, buildContext);

            var rendererFactory = MockRepository.GenerateStub<IRendererFactory>();
            this.viewHelper = MockRepository.GenerateStub<IViewHelper>();
            var multiRenderer = new MultiRenderer(rendererFactory);

            KolaConfigurationRegistry.RegisterRenderer(multiRenderer);

            this.result = instance.Render(multiRenderer);
        }
    static void Main()
    {
        var findedAreas = new SortedSet<Area>();
        for (int row = 0; row < matrix.GetLength(0); row++)
        {
            for (int col = 0; col < matrix.GetLength(1); col++)
            {
                if (matrix[row, col] == ' ')
                {
                    GetConnectedAreaSize(row, col);
                    var area = new Area(row, col, areaSize);
                    findedAreas.Add(area);
                    areaSize = 0;
                }
            }
        }

        if (findedAreas.Any())
        {
            Console.WriteLine("Total areas found: {0}", findedAreas.Count);
            int number = 0;
            foreach (var area in findedAreas)
            {
                ++number;
                Console.WriteLine("Area #{0} at {1}", number, area.ToString());
            }
        }
    }
Exemplo n.º 9
0
        public Wander(Entity o, IWorld map)
            : base(o)
        {
            WorldMap = map;

            curDest = WorldMap.GetArea(random.Next(10), random.Next(10));
        }
Exemplo n.º 10
0
        public void ExitLocationsAndDirectionsDoNotOverwriteHallDescriptions()
        {
            selectedExit.Width = 2;

            var exit = new Area { Descriptions = new[] { "hallway-y" } };
            var otherExit = new Area { Descriptions = new[] { "dark", "dank" } };
            mockHallGenerator.SetupSequence(g => g.Generate(9266, 90210, "temperature")).Returns(new[] { exit }).Returns(new[] { otherExit });

            mockPercentileSelector.SetupSequence(s => s.SelectFrom(TableNameConstants.ExitLocation)).Returns("on the ceiling").Returns("behind you");
            mockPercentileSelector.SetupSequence(s => s.SelectFrom(TableNameConstants.ExitDirection)).Returns("to the right").Returns("to the left");

            var exits = chamberExitGenerator.Generate(9266, 90210, 42, 600, "temperature");
            Assert.That(exits.Count(), Is.EqualTo(2));

            var first = exits.First();
            var last = exits.Last();

            Assert.That(first, Is.EqualTo(exit));
            Assert.That(first.Descriptions, Contains.Item("on the ceiling"));
            Assert.That(first.Descriptions, Contains.Item("to the right"));
            Assert.That(first.Descriptions, Contains.Item("hallway-y"));
            Assert.That(first.Descriptions.Count(), Is.EqualTo(3));
            Assert.That(last, Is.EqualTo(otherExit));
            Assert.That(last.Descriptions, Contains.Item("behind you"));
            Assert.That(last.Descriptions, Contains.Item("to the left"));
            Assert.That(last.Descriptions, Contains.Item("dark"));
            Assert.That(last.Descriptions, Contains.Item("dank"));
            Assert.That(last.Descriptions.Count(), Is.EqualTo(4));
        }
Exemplo n.º 11
0
    public void GenerateMinThresholdInRegion(Area region, float minThreshold, float strength)
    {
        lastMinThreshold = minThreshold;

        int x_min = region.botLeft.x;
        int z_min = region.botLeft.z;

        int x_max = region.topRight.x;
        int z_max = region.topRight.z;

        for (int x = x_min; x < x_max; x++)
        {
            for (int z = z_min; z < z_max; z++)
            {
                if (!globalMinThresholdC.IsDefined(x, z))
                {
                    float height = lt.gt.GetHeight(x, z);

                    if (height < minThreshold)
                    {
                        fg.SetGlobalValue(x, z, -Mathf.Log(Mathf.Abs(height - minThreshold)+1, strength), false, globalMinThresholdC);
                    }
                }
            }
        }
    }
Exemplo n.º 12
0
		public AreaRegion(Area area, MathMLElement element, float x, float y)
		{
			this.Area = area;
			this.Element = element;
			this.X = x;
			this.Y = y;
		}
        public Color[,] Render(Size resolution, Area viewPort)
        {
            _log.InfoFormat("Starting to render ({0:N0}x{1:N0})", resolution.Width, resolution.Height);

            viewPort.LogViewport();

            var output = new Color[resolution.Width, resolution.Height];

            _log.Debug("Rendering points");

            var allPointsWithEscapeTimes =
                resolution
                .GetAllPoints()
                .AsParallel()
                .WithDegreeOfParallelism(GlobalArguments.DegreesOfParallelism)
                .Select(p => Tuple.Create(p, PickColor(FindEscapeTime(viewPort.GetNumberFromPoint(resolution, p)))))
                .AsEnumerable();

            foreach (var result in allPointsWithEscapeTimes)
            {
                output[result.Item1.X, result.Item1.Y] = result.Item2;
            }

            return output;
        }
Exemplo n.º 14
0
 public static Area DoAllowedAreaSelectors( Rect rect, Area areaIn,
                                            AllowedAreaMode mode = AllowedAreaMode.Humanlike, float lrMargin = 0 )
 {
     Area areaIO = areaIn;
     DoAllowedAreaSelectors( rect, ref areaIO, mode, lrMargin );
     return areaIO;
 }
Exemplo n.º 15
0
 // RimWorld.AreaAllowedGUI
 private static void DoAreaSelector( Rect rect, ref Area areaAllowed, Area area )
 {
     rect = rect.ContractedBy( 1f );
     GUI.DrawTexture( rect, area == null ? BaseContent.GreyTex : area.ColorTexture );
     Text.Anchor = TextAnchor.MiddleLeft;
     string text = AreaUtility.AreaAllowedLabel_Area( area );
     Rect rect2 = rect;
     rect2.xMin += 3f;
     rect2.yMin += 2f;
     Widgets.Label( rect2, text );
     if ( areaAllowed == area )
     {
         Widgets.DrawBox( rect, 2 );
     }
     if ( Mouse.IsOver( rect ) )
     {
         if ( area != null )
         {
             area.MarkForDraw();
         }
         if ( Input.GetMouseButton( 0 ) &&
              areaAllowed != area )
         {
             areaAllowed = area;
             SoundDefOf.DesignateDragStandardChanged.PlayOneShotOnCamera();
         }
     }
     TooltipHandler.TipRegion( rect, text );
 }
Exemplo n.º 16
0
        private Area GetSpecialDoor(Area specialDoor)
        {
            var newDoor = areaPercentileSelector.SelectFrom(TableNameConstants.DoorTypes);

            while (newDoor.Type == AreaTypeConstants.Special)
            {
                newDoor = areaPercentileSelector.SelectFrom(TableNameConstants.DoorTypes);
            }

            var specialBonus = specialDoor.Length;

            if (specialDoor.Descriptions.Contains(DescriptionConstants.MagicallyReinforced) && newDoor.Descriptions.Contains(DescriptionConstants.Wooden) == false)
                specialBonus = specialDoor.Width;

            if (newDoor.Length > 0)
            {
                newDoor.Length += specialBonus;

                if (specialDoor.Descriptions.Contains(DescriptionConstants.MagicallyReinforced))
                    newDoor.Length = specialBonus;
            }

            if (newDoor.Width > 0)
            {
                newDoor.Width += specialBonus;

                if (specialDoor.Descriptions.Contains(DescriptionConstants.MagicallyReinforced))
                    newDoor.Width = specialBonus;
            }

            newDoor.Descriptions = newDoor.Descriptions.Union(specialDoor.Descriptions);

            return newDoor;
        }
Exemplo n.º 17
0
        public void DoNotApplyDoorLocationToRoomDoors()
        {
            var areaFromHall = new Area();
            areaFromHall.Type = "area type";
            areaFromHall.Width = 1;

            mockAreaPercentileSelector.Setup(s => s.SelectFrom(TableNameConstants.DungeonAreaFromDoor)).Returns(areaFromHall);

            var mockAreaGenerator = new Mock<AreaGenerator>();
            mockAreaGeneratorFactory.Setup(f => f.HasSpecificGenerator("area type")).Returns(true);
            mockAreaGeneratorFactory.Setup(f => f.Build("area type")).Returns(mockAreaGenerator.Object);

            var specificArea = new Area();
            var otherSpecificArea = new Area { Type = AreaTypeConstants.Door };
            otherSpecificArea.Descriptions = new[] { "strong", "wood" };

            mockAreaGenerator.Setup(g => g.Generate(9266, 90210, "temperature")).Returns(new[] { specificArea, otherSpecificArea });

            var areas = dungeonGenerator.GenerateFromDoor(9266, 90210, "temperature");
            Assert.That(areas, Contains.Item(specificArea));
            Assert.That(areas, Contains.Item(otherSpecificArea));
            Assert.That(areas.Count(), Is.EqualTo(2));

            var last = areas.Last();
            Assert.That(last, Is.EqualTo(otherSpecificArea));
            Assert.That(otherSpecificArea.Descriptions, Contains.Item("strong"));
            Assert.That(otherSpecificArea.Descriptions, Contains.Item("wood"));
            Assert.That(otherSpecificArea.Descriptions.Count(), Is.EqualTo(2));
        }
Exemplo n.º 18
0
 public MoveLoop(Entity o, Area[] d, IWorld map)
     : base(o)
 {
     WorldMap = map;
     Destination = d;
     curDest = 0;
 }
Exemplo n.º 19
0
		/**
		 * private ctor used for fit'ing
		 */
		private HorizontalArea(Area[] content, Area source) : base(content, source)
		{
			// calulate bounding box
			BoundingBox box = BoundingBox.New();
			foreach(Area a in content) box.Append(a.BoundingBox);
			this.box = box;
		}
Exemplo n.º 20
0
 public void AreaRange_Range_Zero()
 {
     Area<string> Area = new Area<string>("a", 0);
      Assert.AreEqual("a", Area.Id);
      Assert.AreEqual(0m, Area.Start);
      Assert.AreEqual(0.1m, Area.End);
 }
Exemplo n.º 21
0
 public void AreaRange_ToString_AreaFullRange1()
 {
     Area<string> a = new Area<string>("a", "10", "19");
      Assert.AreEqual<decimal>(0.1m, a.Start);
      Assert.AreEqual<decimal>(0.2m, a.End);
      Assert.AreEqual(a.ToString(), "1");
 }
        ObjectModMeta DeleteAreaAuthorization(Area obj)
        {
            var meta = SetModDetailsOnPrincipalAndStopModIfNegativeReputationAndReturnObjectModMeta(obj);

            if (obj.Type == CfType.Province)
            {
                //-- Would be good to move this out of the method? W.I.F.??
                if (!currentUser.IsGodUser) { throw new AccessViolationException("DeleteArea: Only god users can delete provinces."); }
            }

            if (meta.CQR > 7 && !currentUser.IsInRole("ModAdmin"))
            {
                throw new AccessViolationException("DeleteArea: Only Admin Moderators can delete places with CQR higher than 7");
            }
            else if (meta.CQR > 1 && !currentUser.IsInRole("ModAdmin,ModSenior"))
            {
                throw new AccessViolationException("DeleteArea: Only Senior Moderators can delete places with CQR higher than 1");
            }
            else if (!currentUser.IsInRole("ModAdmin,ModSenior,ModCommunity"))
            {
                throw new AccessViolationException("DeleteArea: You must be Moderator to delete places");
            }

            return meta;
        }
Exemplo n.º 23
0
        public override void Up()
        {
            var ccb = new Area
            {
                Nome = "CCB",
                Ativo = true,
                Abreviacao = "CCB",
                Parent = null,
                Segura = false
            }.Persistir();

            var administrador = new Perfil
            {
                Nome = "Administrador",
                Ativo = true
            }.Persistir();

            new Usuario
            {
                Area = ccb,
                Perfil = administrador,
                Senha = new HashString().Do("pwd123"),
                Login = "******",
                Nome = "Administrador do sistema",
                Email = "*****@*****.**",
                Ativo = true,
                Expira = false
            }.Persistir();
        }
 public void SetArea(Area area)
 {
     var adjs =
         from a in area.Adjacent
         where a.Province == area.Province
         select a;
     this.SuspendLayout();
     {
         int btm = 35;
         foreach (var a in adjs)
         {
             btm += 23;
             var button = new Button {
                 Text = a.Name,
                 Dock = DockStyle.Top,
                 Tag = a
             };
             button.Click += this.ButtonClick;
             this.Controls.Add(button);
         }
         this.Controls.Remove(_label);
         this.Controls.Add(_label);
         this.ClientSize = new Size(this.ClientSize.Width, btm);
     }
     this.ResumeLayout();
 }
Exemplo n.º 25
0
    public int Import(string UPICode, string AreaName, string Description, int RegionId)
    {
        try
        {
            if (CheckExistedArea(AreaName) == false)
            {
                Area o = new Area();
                o.UpiCode = UPICode;
                o.AreaName = AreaName;
                o.Description = Description;
                o.RegionId = RegionId;
                db.Areas.InsertOnSubmit(o);
                db.SubmitChanges();
                return o.Id;
            }

            var area = (from a in db.Areas where a.AreaName == AreaName select a).SingleOrDefault();

            if (area != null) return area.Id;

            return -1;
        }
        catch
        {
            return -1;
        }
    }
Exemplo n.º 26
0
        public void PointToNumberToPointTest()
        {
            const int xRange = 500;
            const int yRange = 500;

            var resolution = new Size(xRange * 2, yRange * 2);

            const int xLower = -1 * xRange;
            const int xUpper = xRange;
            const int yLower = -1 * yRange;
            const int yUpper = yRange;

            var area = new Area(new InclusiveRange(xLower, xUpper), new InclusiveRange(yLower, yUpper));
            for (int x = xLower; x < xUpper; x++)
            {
                for (int y = yLower; y < yUpper; y++)
                {
                    var point = new Point(x, y);

                    var calculatedNumber = area.GetNumberFromPoint(resolution, point);
                    var calculatedPoint = area.GetPointFromNumber(resolution, calculatedNumber);

                    Assert.AreEqual(point, calculatedPoint);
                }
            }
        }
Exemplo n.º 27
0
        public Area ReloadWithSeat(Area area, out IEnumerable<IArrangeSeatRule> availableOrganizations)
        {
            var result = _areaRepository.Get(area.Id);
            var exists = _areaRepository.GetOrganizationSeatingArea(area.Id).ToDictionary(o => o.Object);

            var all = new List<IArrangeSeatRule>();

            var defaultTargetSeat = result.Seats.FirstOrDefault();

            foreach (var item in ((Campaign)result.Campaign).Organizations)
            {
              
                if (exists.ContainsKey(item))
                {
                    all.Add(exists[item]);
                }
                else
                {
                    var o = defaultTargetSeat == null ? null : _entityFactory.Create<OrganizationSeatingArea>(new Dictionary<string, object> { { "Area", result }, { "Object", item }, { "TargetSeat", defaultTargetSeat } });
                    if (o != null)
                    {
                        _areaRepository.MakePersistent(o);
                        all.Add(o);
                    }
                }
            }

            availableOrganizations = all.ToRebuildPriorityList<IArrangeSeatRule, IArrangeSeatRule>(true, null);
            return result;
        }
Exemplo n.º 28
0
        public virtual JsonResult Crear(Area entidad)
        {
            var jsonResponse = new JsonResponse { Success = false };

            if (ModelState.IsValid)
            {
                try
                {
                    entidad.UsuarioCreacion = UsuarioActual.IdUsuario.ToString();
                    entidad.UsuarioModificacion = UsuarioActual.IdUsuario.ToString();
                    AreaBL.Instancia.Add(entidad);

                    jsonResponse.Success = true;
                    jsonResponse.Message = "Se Proceso con éxito";
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("Mensaje: {0} Trace: {1}", ex.Message, ex.StackTrace));
                    jsonResponse.Message = "Ocurrio un error, por favor intente de nuevo o más tarde.";
                }
            }
            else
            {
                jsonResponse.Message = "Por favor ingrese todos los campos requeridos";
            }
            return Json(jsonResponse, JsonRequestBehavior.AllowGet);
        }
 public bool InitRoutine(Area area)
 {
     this.area = area;
     ArrayList possibleRoutines = new ArrayList();
      		if (canWalk){
         possibleRoutines.Add(new GenericWanderAction(gameObject, area.wanderWaypointParent));
     }
     if (canSitOnChair && area.chairParent != null){
         possibleRoutines.Add(new GenericSitAction(gameObject, "chair", "sit_chair", area.chairParent));
     }
     if (canEat && area.chairParent != null){
         possibleRoutines.Add(new GenericSitAction(gameObject, "chair", "eat", area.chairParent));
     }
     if (canSitOnLounger && area.loungerParent != null){
         possibleRoutines.Add(new GenericSitAction(gameObject, "lounger", "sit_lounger", area.loungerParent));
     }
     if (canSitOnDeckChair && area.deckChairParent != null){
         possibleRoutines.Add(new GenericSitAction(gameObject, "deck_chair", "sit_deck_chair", area.deckChairParent));
     }
     if (canDance && area.name.Equals("Disco")){
     //	possibleRoutines.Add(new GenericDanceAction());
     }
     if (possibleRoutines.Count == 0){
         routine = new GenericSelfDestructAction(gameObject);
         return false;
     } else {
         routine = (Action)possibleRoutines[Random.Range(0, possibleRoutines.Count)];
         //Debug.Log("Chosen routine: " + routine + " for " + name);
         return true;
     }
 }
Exemplo n.º 30
0
 public void AreaRange_Range_NineRepeated()
 {
     Area<string> Area = new Area<string>("a", 99999999999L);
      Assert.AreEqual("a", Area.Id);
      Assert.AreEqual(0.99999999999m, Area.Start);
      Assert.AreEqual(1m, Area.End);
 }
Exemplo n.º 31
0
        public void We_Can_Activate_Previously_Not_Active_Group()
        {
            // arrange
            var userId = Guid.NewGuid();
            var dbUser = new User()
            {
                Id     = userId,
                Groups = new List <Group>()
            };

            var groupOneId = Guid.NewGuid();
            var groupOne   = new Group()
            {
                Id       = groupOneId,
                IsActive = true
            };

            var newAreaId = Guid.NewGuid();
            var newArea   = new Area()
            {
                Id        = newAreaId,
                Latitude  = 10,
                Longitude = 10,
                Radius    = RadiusRangeEnum.FiftyMeters,
                IsActive  = false,
                Groups    = new List <Group>()
                {
                    groupOne
                }
            };

            var secondNewAreaId = Guid.NewGuid();
            var secondNewArea   = new Area()
            {
                Id        = secondNewAreaId,
                Latitude  = 10,
                Longitude = 10,
                Radius    = RadiusRangeEnum.FiveHundredMeters,
                IsActive  = false,
                Groups    = new List <Group>()
                {
                    groupOne
                }
            };

            groupOne.Areas = new List <Area>()
            {
                newArea, secondNewArea
            };

            var populatedDatabase = new FakeLikkleDbContext()
            {
                Areas = new FakeDbSet <Area>()
                {
                    newArea, secondNewArea
                },
                Groups = new FakeDbSet <Group>()
                {
                    groupOne
                },
                Users = new FakeDbSet <User>()
                {
                    dbUser
                }
            }
            .Seed();

            this._mockedLikkleUoW.Setup(uow => uow.AreaRepository).Returns(new AreaRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.GroupRepository).Returns(new GroupRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.UserRepository).Returns(new UserRepository(populatedDatabase));

            // act
            this._groupService.ActivateGroup(groupOneId, userId);

            // assert
            Assert.IsTrue(groupOne.IsActive);
            Assert.IsTrue(newArea.IsActive);
            Assert.IsTrue(secondNewArea.IsActive);
            Assert.IsTrue(dbUser.Groups.Any());
            Assert.IsTrue(dbUser.Groups.Any(gr => gr.Id == groupOneId));
        }
Exemplo n.º 32
0
 public void Init()
 {
     _area = Create();
 }
Exemplo n.º 33
0
 public WorkSurface(int x, int y, int width, int height)
 {
     area    = new Area(x, y, width, height);
     windows = new LinkedList <WorkWindow>();
 }
Exemplo n.º 34
0
        public void LengthTimesLengthEqualsArea()
        {
            Area area = Length.FromMeters(10) * Length.FromMeters(2);

            Assert.Equal(area, Area.FromSquareMeters(20));
        }
Exemplo n.º 35
0
        public void LengthTimesAreaEqualsVolume()
        {
            Volume volume = Length.FromMeters(3) * Area.FromSquareMeters(9);

            Assert.Equal(volume, Volume.FromCubicMeters(27));
        }
Exemplo n.º 36
0
        public void AreaTimesLengthEqualsVolume()
        {
            Volume volume = Area.FromSquareMeters(10) * Length.FromMeters(3);

            Assert.Equal(volume, Volume.FromCubicMeters(30));
        }
Exemplo n.º 37
0
        public void We_Can_Insert_New_Group()
        {
            // arrange
            var userId = Guid.NewGuid();
            var dbUser = new User()
            {
                Id = userId,
                AutomaticSubscriptionSettings = null
            };

            var newAreaId = Guid.NewGuid();
            var newArea   = new Area()
            {
                Id        = newAreaId,
                Latitude  = 10,
                Longitude = 10,
                Radius    = RadiusRangeEnum.FiftyMeters
            };

            var populatedDatabase = new FakeLikkleDbContext()
            {
                Users = new FakeDbSet <User>()
                {
                    dbUser
                },
                Areas = new FakeDbSet <Area>()
                {
                    newArea
                }
            }
            .Seed();

            this._mockedLikkleUoW.Setup(uow => uow.UserRepository).Returns(new UserRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.AreaRepository).Returns(new AreaRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.TagRepository).Returns(new TagRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.GroupRepository).Returns(new GroupRepository(populatedDatabase));

            var newGroupRequest = new StandaloneGroupRequestDto()
            {
                Name   = "New group",
                TagIds = new List <Guid>()
                {
                    Guid.Parse("caf77dee-a94f-49cb-b51f-e0c0e1067541"), Guid.Parse("bd456f08-f137-4382-8358-d52772c2dfc8")
                },
                AreaIds = new List <Guid>()
                {
                    newAreaId
                },
                UserId = userId
            };

            // act
            var newGroupId = this._groupService.InsertNewGroup(newGroupRequest);

            // assert
            Assert.IsTrue(newGroupId != Guid.Empty);

            var newlyCreatedGroup = this._groupService.GetGroupById(newGroupId);

            Assert.IsNotNull(newlyCreatedGroup);
        }
Exemplo n.º 38
0
        public void We_Can_Get_List_Of_Previously_Created_Groups_When_At_A_Place_With_Previous_Activity()
        {
            // arrange
            var userId = Guid.NewGuid();
            var dbUser = new User()
            {
                Id = userId,
                AutomaticSubscriptionSettings = null
            };

            var groupOneId = Guid.NewGuid();
            var groupOne   = new Group()
            {
                Id       = groupOneId,
                Name     = "Group one",
                IsActive = false
            };

            var groupTwoId = Guid.NewGuid();
            var groupTwo   = new Group()
            {
                Id       = groupTwoId,
                Name     = "Group two",
                IsActive = true
            };

            var groupThreeId = Guid.NewGuid();
            var groupThree   = new Group()
            {
                Id       = groupThreeId,
                Name     = "Group three",
                IsActive = false
            };

            dbUser.HistoryGroups = new List <HistoryGroup>()
            {
                new HistoryGroup()
                {
                    DateTimeGroupWasSubscribed = DateTime.UtcNow.AddDays(-2),
                    GroupId = groupOneId,
                    GroupThatWasPreviouslySubscribed = groupOne,
                    Id     = Guid.NewGuid(),
                    UserId = userId,
                    UserWhoSubscribedGroup = dbUser
                },
                new HistoryGroup()
                {
                    DateTimeGroupWasSubscribed = DateTime.UtcNow.AddDays(-2),
                    GroupId = groupThreeId,
                    GroupThatWasPreviouslySubscribed = groupThree,
                    Id     = Guid.NewGuid(),
                    UserId = userId,
                    UserWhoSubscribedGroup = dbUser
                }
            };

            groupOne.Users = new List <User>()
            {
                dbUser
            };
            groupTwo.Users = new List <User>()
            {
                dbUser
            };
            groupThree.Users = new List <User>()
            {
                dbUser
            };

            var areaOneId = Guid.NewGuid();
            var areaOne   = new Area()
            {
                Id        = areaOneId,
                Latitude  = 10.0000000,
                Longitude = 10.0000000,
                Radius    = RadiusRangeEnum.FiftyMeters,
                IsActive  = true,
                Groups    = new List <Group>()
                {
                    groupOne, groupTwo
                }
            };

            var areaTwoId = Guid.NewGuid();
            var areaTwo   = new Area()
            {
                Id        = areaTwoId,
                Latitude  = 10.0000001,
                Longitude = 10.0000001,
                Radius    = RadiusRangeEnum.HunderdAndFiftyMeters,
                IsActive  = true,
                Groups    = new List <Group>()
                {
                    groupOne, groupTwo, groupThree
                }
            };

            groupOne.Areas = new List <Area>()
            {
                areaOne, areaTwo
            };
            groupTwo.Areas = new List <Area>()
            {
                areaOne, areaTwo
            };
            groupThree.Areas = new List <Area>()
            {
                areaTwo
            };

            var populatedDatabase = new FakeLikkleDbContext()
            {
                Users = new FakeDbSet <User>()
                {
                    dbUser
                },
                Areas = new FakeDbSet <Area>()
                {
                    areaOne, areaTwo
                },
                Groups = new FakeDbSet <Group>()
                {
                    groupOne, groupTwo, groupThree
                }
            }
            .Seed();

            this._mockedLikkleUoW.Setup(uow => uow.UserRepository).Returns(new UserRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.AreaRepository).Returns(new AreaRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.TagRepository).Returns(new TagRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.GroupRepository).Returns(new GroupRepository(populatedDatabase));

            // act
            var result = this._groupService.GetGroupCreationType(10, 10, userId);

            // assert
            Assert.IsNotNull(result);
            Assert.IsNotNull(result.PrevousGroupsList);
            Assert.AreEqual(result.CreationType, CreateGroupActionTypeEnum.ListOfPreviouslyCreatedOrSubscribedGroups);
            Assert.AreEqual(2, result.PrevousGroupsList.Count());
        }
Exemplo n.º 39
0
        public static void RenderSubstitution(Color color, Time evt, LMPlayer playerIn, LMPlayer playerOut, bool selected,
                                              bool isExpanded, IDrawingToolkit tk, IContext context, Area backgroundArea,
                                              Area cellArea, CellState state)
        {
            Point  selectPoint, textPoint, imagePoint, circlePoint;
            Point  inPoint, imgPoint, outPoint, timePoint;
            double textWidth;

            if (subsImage == null)
            {
                subsImage = App.Current.ResourcesLocator.LoadIcon(Icons.Subs);
            }
            tk.Context = context;
            tk.Begin();

            RenderTimelineEventBase(color, null, selected, null, tk, context, backgroundArea, cellArea, state,
                                    out selectPoint, out textPoint, out imagePoint, out circlePoint, out textWidth);
            inPoint  = textPoint;
            imgPoint = new Point(textPoint.X + Sizes.ListImageWidth + Sizes.ListRowSeparator, textPoint.Y);
            outPoint = new Point(imgPoint.X + 20 + Sizes.ListRowSeparator, imgPoint.Y);
            RenderPlayer(tk, playerIn, inPoint);
            tk.DrawImage(imgPoint, 20, cellArea.Height, subsImage, ScaleMode.AspectFit);
            RenderPlayer(tk, playerOut, outPoint);

            timePoint        = new Point(outPoint.X + Sizes.ListImageWidth + Sizes.ListRowSeparator, textPoint.Y);
            tk.FontSize      = 10;
            tk.FontWeight    = FontWeight.Normal;
            tk.StrokeColor   = App.Current.Style.TextBase;
            tk.FontAlignment = FontAlignment.Left;
            tk.DrawText(timePoint, 100, cellArea.Height, evt.ToSecondsString());
            RenderSeparationLine(tk, context, backgroundArea);
            tk.End();
        }
Exemplo n.º 40
0
        public void We_Get_Choice_Screen_When_Creating_A_group_In_Existing_Active_Area()
        {
            // arrange
            var userId = Guid.NewGuid();
            var dbUser = new User()
            {
                Id = userId,
                AutomaticSubscriptionSettings = null
            };

            var groupOneId = Guid.NewGuid();
            var groupOne   = new Group()
            {
                Id       = groupOneId,
                IsActive = true
            };

            var groupTwoId = Guid.NewGuid();
            var groupTwo   = new Group()
            {
                Id       = groupTwoId,
                IsActive = true
            };

            var newAreaId = Guid.NewGuid();
            var newArea   = new Area()
            {
                Id        = newAreaId,
                Latitude  = 10,
                Longitude = 10,
                Radius    = RadiusRangeEnum.FiftyMeters,
                IsActive  = true,
                Groups    = new List <Group>()
                {
                    groupOne, groupTwo
                }
            };

            groupOne.Areas = new List <Area>()
            {
                newArea
            };
            groupTwo.Areas = new List <Area>()
            {
                newArea
            };

            var populatedDatabase = new FakeLikkleDbContext()
            {
                Users = new FakeDbSet <User>()
                {
                    dbUser
                },
                Areas = new FakeDbSet <Area>()
                {
                    newArea
                },
                Groups = new FakeDbSet <Group>()
                {
                    groupOne, groupTwo
                }
            }
            .Seed();

            this._mockedLikkleUoW.Setup(uow => uow.UserRepository).Returns(new UserRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.AreaRepository).Returns(new AreaRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.TagRepository).Returns(new TagRepository(populatedDatabase));
            this._mockedLikkleUoW.Setup(uow => uow.GroupRepository).Returns(new GroupRepository(populatedDatabase));

            // act
            var result = this._groupService.GetGroupCreationType(10, 10, userId);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(result.CreationType, CreateGroupActionTypeEnum.ChoiceScreen);
        }
Exemplo n.º 41
0
        public static void RenderAnalysisCategory(EventTypeTimelineVM vm, int count, bool isExpanded, IDrawingToolkit tk,
                                                  IContext context, Area backgroundArea, Area cellArea, CellState state)
        {
            Point textP = new Point(Sizes.ListTextOffset, cellArea.Start.Y);

            tk.Context = context;
            tk.Begin();
            RenderBackgroundAndText(isExpanded, tk, backgroundArea, textP, cellArea.Width - textP.X, vm.EventTypeVM.Name);
            RenderCount(isExpanded, vm.EventTypeVM.Color, count, tk, backgroundArea, cellArea);
            RenderSeparationLine(tk, context, backgroundArea);
            if (!(vm.Model is SubstitutionEventType))
            {
                RenderPlayButton(tk, cellArea, vm.VisibleChildrenCount == 0, state);
            }
            tk.End();
        }
Exemplo n.º 42
0
        public static void Render(object item, LMProject project, int count, bool isExpanded, IDrawingToolkit tk,
                                  IContext context, Area backgroundArea, Area cellArea, CellState state)
        {
            //Get the offset to properly calulate if needs tooltip or redraw
            offsetX = backgroundArea.Right - cellArea.Right;
            offsetY = cellArea.Top - backgroundArea.Top;

            bool playing = (item as IPlayable)?.Playing ?? false;

            // HACK: to be remove when all treeviews are migrated to user VM's
            if (item is TimelineEventVM)
            {
                item = ((TimelineEventVM)item).Model;
            }
            else if (item is EventTypeTimelineVM)
            {
                var vm = item as EventTypeTimelineVM;
                RenderAnalysisCategory(vm, count, isExpanded, tk,
                                       context, backgroundArea, cellArea, state);
                return;
            }
            else if (item is PlaylistElementVM)
            {
                item = ((PlaylistElementVM)item).Model;
            }
            else if (item is PlaylistVM)
            {
                item = ((PlaylistVM)item).Model;
            }
            else if (item is PlayerVM)
            {
                item = ((PlayerVM)item).Model;
            }
            else if (item is PlayerTimelineVM)
            {
                item = ((PlayerTimelineVM)item).Model;
            }

            // FIXME: This first if case must be deleted when presentations is migrated to MVVMC
            if (item is EventType)
            {
                RenderAnalysisCategory(item as EventType, count, isExpanded, tk,
                                       context, backgroundArea, cellArea);
            }
            else if (item is SubstitutionEvent)
            {
                SubstitutionEvent s = item as SubstitutionEvent;
                RenderSubstitution(s.Color, s.EventTime, s.In, s.Out, playing, isExpanded, tk, context,
                                   backgroundArea, cellArea, state);
            }
            else if (item is TimelineEvent)
            {
                LMTimelineEvent p = item as LMTimelineEvent;
                // always add local first.
                RenderPlay(p.Color, p.Miniature, p.Players, p.Teams, playing, p.Description, count, isExpanded, tk,
                           context, backgroundArea, cellArea, state);
            }
            else if (item is Player)
            {
                RenderPlayer(item as LMPlayer, count, isExpanded, tk, context, backgroundArea, cellArea);
            }
            else if (item is Playlist)
            {
                RenderPlaylist(item as Playlist, count, isExpanded, tk, context, backgroundArea, cellArea, state);
            }
            else if (item is PlaylistPlayElement)
            {
                PlaylistPlayElement p = item as PlaylistPlayElement;
                RenderPlay(p.Play.EventType.Color, p.Miniature, null, null, playing, p.Description, count, isExpanded, tk,
                           context, backgroundArea, cellArea, state);
            }
            else if (item is IPlaylistElement)
            {
                IPlaylistElement p = item as IPlaylistElement;
                RenderPlay(App.Current.Style.ThemeContrastDisabled, p.Miniature, null, null, playing, p.Description,
                           count, isExpanded, tk, context, backgroundArea, cellArea, state);
            }
            else
            {
                Log.Error("No renderer for type " + item?.GetType());
            }
        }
Exemplo n.º 43
0
        public static void RenderSeparationLine(IDrawingToolkit tk, IContext context, Area backgroundArea)
        {
            double x1, x2, y;

            x1             = backgroundArea.Start.X;
            x2             = x1 + backgroundArea.Width;
            y              = backgroundArea.Start.Y + backgroundArea.Height;
            tk.LineWidth   = 1;
            tk.StrokeColor = App.Current.Style.ThemeContrastDisabled;
            tk.DrawLine(new Point(x1, y), new Point(x2, y));
        }
Exemplo n.º 44
0
        // FIXME: This method might be deleted when presentations is migrated to MVVMC
        public static void RenderAnalysisCategory(EventType cat, int count, bool isExpanded, IDrawingToolkit tk,
                                                  IContext context, Area backgroundArea, Area cellArea)
        {
            Point textP = new Point(Sizes.ListTextOffset, cellArea.Start.Y);

            tk.Context = context;
            tk.Begin();
            RenderBackgroundAndText(isExpanded, tk, backgroundArea, textP, cellArea.Width - textP.X, cat.Name);
            RenderCount(isExpanded, cat.Color, count, tk, backgroundArea, cellArea);
            RenderSeparationLine(tk, context, backgroundArea);
            tk.End();
        }
Exemplo n.º 45
0
        public static Monster Create(MonsterTemplate template, Area map)
        {
            if (template.CastSpeed == 0)
            {
                template.CastSpeed = 2000;
            }

            if (template.AttackSpeed == 0)
            {
                template.AttackSpeed = 1000;
            }

            if (template.MovementSpeed == 0)
            {
                template.MovementSpeed = 2000;
            }

            if (template.Level <= 0)
            {
                template.Level = 1;
            }

            var obj = new Monster
            {
                Template       = template,
                CastTimer      = new GameServerTimer(TimeSpan.FromMilliseconds(1 + template.CastSpeed)),
                BashTimer      = new GameServerTimer(TimeSpan.FromMilliseconds(1 + template.AttackSpeed)),
                WalkTimer      = new GameServerTimer(TimeSpan.FromMilliseconds(1 + template.MovementSpeed)),
                CastEnabled    = template.MaximumMP > 0,
                TaggedAislings = new HashSet <int>()
            };

            if (obj.Template.Grow)
            {
                obj.Template.Level++;
            }

            var mod  = (obj.Template.Level + 1) * 0.01;
            var rate = mod * 250 * obj.Template.Level;
            var exp  = obj.Template.Level * rate / 1;
            var hp   = mod + 50 + obj.Template.Level * (obj.Template.Level + 40);
            var mp   = hp / 3;
            var dmg  = hp / 1 * mod * 1;

            obj.Template.MaximumHP = (int)hp;
            obj.Template.MaximumMP = (int)mp;

            var stat = RandomEnumValue <PrimaryStat>();

            obj._Str = 3;
            obj._Int = 3;
            obj._Wis = 3;
            obj._Con = 3;
            obj._Dex = 3;

            switch (stat)
            {
            case PrimaryStat.STR:
                obj._Str += (byte)(obj.Template.Level * 0.5 * 2);
                break;

            case PrimaryStat.INT:
                obj._Int += (byte)(obj.Template.Level * 0.5 * 2);
                break;

            case PrimaryStat.WIS:
                obj._Wis += (byte)(obj.Template.Level * 0.5 * 2);
                break;

            case PrimaryStat.CON:
                obj._Con += (byte)(obj.Template.Level * 0.5 * 2);
                break;

            case PrimaryStat.DEX:
                obj._Dex += (byte)(obj.Template.Level * 0.5 * 2);
                break;
            }

            obj.MajorAttribute = stat;

            obj.BonusAc = (int)(70 - obj.Template.Level * 0.5 / 1.0);

            if (obj.BonusAc < -70)
            {
                obj.BonusAc = -70;
            }

            obj.DefenseElement = ElementManager.Element.None;
            obj.OffenseElement = ElementManager.Element.None;

            if (obj.Template.ElementType == ElementQualifer.Random)
            {
                obj.DefenseElement = RandomEnumValue <ElementManager.Element>();
                obj.OffenseElement = RandomEnumValue <ElementManager.Element>();
            }
            else if (obj.Template.ElementType == ElementQualifer.Defined)
            {
                obj.DefenseElement = template?.DefenseElement == ElementManager.Element.None
                    ? RandomEnumValue <ElementManager.Element>()
                    : template.DefenseElement;
                obj.OffenseElement = template?.OffenseElement == ElementManager.Element.None
                    ? RandomEnumValue <ElementManager.Element>()
                    : template.OffenseElement;
            }

            obj.BonusMr = (byte)(10 * (template.Level / 20));

            if (obj.BonusMr > ServerContextBase.Config.BaseMR)
            {
                obj.BonusMr = ServerContextBase.Config.BaseMR;
            }

            if ((template.PathQualifer & PathQualifer.Wander) == PathQualifer.Wander)
            {
                obj.WalkEnabled = true;
            }
            else if ((template.PathQualifer & PathQualifer.Fixed) == PathQualifer.Fixed)
            {
                obj.WalkEnabled = false;
            }
            else if ((template.PathQualifer & PathQualifer.Patrol) == PathQualifer.Patrol)
            {
                obj.WalkEnabled = true;
            }

            if (template.MoodType.HasFlag(MoodQualifer.Aggressive))
            {
                obj.Aggressive = true;
            }
            else if (template.MoodType.HasFlag(MoodQualifer.Unpredicable))
            {
                lock (Generator.Random)
                {
                    obj.Aggressive = Generator.Random.Next(1, 101) > 50;
                }
            }
            else
            {
                obj.Aggressive = false;
            }

            if (template.SpawnType == SpawnQualifer.Random)
            {
                var x = Generator.Random.Next(1, map.Cols);
                var y = Generator.Random.Next(1, map.Rows);

                obj.XPos = x;
                obj.YPos = y;

                if (map.IsWall(x, y))
                {
                    return(null);
                }
            }
            else if (template.SpawnType == SpawnQualifer.Defined)
            {
                obj.XPos = template.DefinedX;
                obj.YPos = template.DefinedY;
            }

            lock (Generator.Random)
            {
                obj.Serial = GenerateNumber();
            }

            obj.CurrentMapId  = map.ID;
            obj.CurrentHp     = template.MaximumHP;
            obj.CurrentMp     = template.MaximumMP;
            obj._MaximumHp    = template.MaximumHP;
            obj._MaximumMp    = template.MaximumMP;
            obj.AbandonedDate = DateTime.UtcNow;

            lock (Generator.Random)
            {
                obj.Image = template.ImageVarience
                            > 0
                    ? (ushort)Generator.Random.Next(template.Image, template.Image + template.ImageVarience)
                    : template.Image;
            }

            obj.Scripts = ScriptManager.Load <MonsterScript>(template.ScriptName, obj, map);

            if (obj.Template.LootType.HasFlag(LootQualifer.Table))
            {
                obj.LootManager  = new LootDropper();
                obj.LootTable    = new LootTable(template.Name);
                obj.UpgradeTable = new LootTable("Probabilities");

                foreach (var drop in obj.Template.Drops)
                {
                    if (drop.Equals("random", StringComparison.OrdinalIgnoreCase))
                    {
                        lock (Generator.Random)
                        {
                            var available = ServerContextBase.GlobalItemTemplateCache.Select(i => i.Value)
                                            .Where(i => Math.Abs(i.LevelRequired - obj.Template.Level) <= 10).ToList();
                            if (available.Count > 0)
                            {
                                obj.LootTable.Add(available[GenerateNumber() % available.Count]);
                            }
                        }
                    }
                    else
                    {
                        if (ServerContextBase.GlobalItemTemplateCache.ContainsKey(drop))
                        {
                            obj.LootTable.Add(ServerContextBase.GlobalItemTemplateCache[drop]);
                        }
                    }
                }

                obj.UpgradeTable.Add(new Common());
                obj.UpgradeTable.Add(new Uncommon());
                obj.UpgradeTable.Add(new Rare());
                obj.UpgradeTable.Add(new Epic());
                obj.UpgradeTable.Add(new Legendary());
                obj.UpgradeTable.Add(new Mythical());
                obj.UpgradeTable.Add(new Godly());
                obj.UpgradeTable.Add(new Forsaken());
            }

            return(obj);
        }
Exemplo n.º 46
0
        static void RenderCount(bool isExpanded, Color color, int count, IDrawingToolkit tk, Area backgroundArea, Area cellArea)
        {
            double   countX1, countX2, countY, countYC;
            Point    arrowY;
            ISurface arrow;

            countX1 = cellArea.Start.X + Sizes.ListRowSeparator * 2 + Sizes.ListCountRadio;
            countX2 = countX1 + Sizes.ListCountWidth;
            countYC = backgroundArea.Start.Y + backgroundArea.Height / 2;
            countY  = countYC - Sizes.ListCountRadio;
            if (count > 0)
            {
                if (!isExpanded)
                {
                    if (ArrowRight == null)
                    {
                        ArrowRight = App.Current.DrawingToolkit.CreateSurfaceFromIcon(Icons.ListArrowRightPath, false);
                    }
                    arrow = ArrowRight;
                }
                else
                {
                    if (ArrowDown == null)
                    {
                        ArrowDown = App.Current.DrawingToolkit.CreateSurfaceFromIcon(Icons.ListArrowDownPath, false);
                    }
                    arrow = ArrowDown;
                }
                arrowY = new Point(cellArea.Start.X + 1, cellArea.Start.Y + cellArea.Height / 2 - arrow.Height / 2);
                tk.DrawSurface(arrowY, Sizes.ListArrowRightWidth, Sizes.ListArrowRightHeight, arrow, ScaleMode.AspectFit);
            }

            tk.LineWidth = 0;
            tk.FillColor = color;
            tk.DrawCircle(new Point(countX1, countYC), Sizes.ListCountRadio);
            tk.DrawCircle(new Point(countX2, countYC), Sizes.ListCountRadio);
            tk.DrawRectangle(new Point(countX1, countY), Sizes.ListCountWidth, 2 * Sizes.ListCountRadio);
            tk.StrokeColor   = App.Current.Style.ThemeBase;
            tk.FontAlignment = FontAlignment.Center;
            tk.FontWeight    = FontWeight.Bold;
            tk.FontSize      = 14;
            tk.DrawText(new Point(countX1, countY), Sizes.ListCountWidth,
                        2 * Sizes.ListCountRadio, count.ToString());
        }
Exemplo n.º 47
0
        public int CheckBreakBefore(Area area)
        {
            if (!(area is ColumnArea))
            {
                switch (properties.GetProperty("break-before").GetEnum())
                {
                case BreakBefore.PAGE:
                    return(Status.FORCE_PAGE_BREAK);

                case BreakBefore.ODD_PAGE:
                    return(Status.FORCE_PAGE_BREAK_ODD);

                case BreakBefore.EVEN_PAGE:
                    return(Status.FORCE_PAGE_BREAK_EVEN);

                case BreakBefore.COLUMN:
                    return(Status.FORCE_COLUMN_BREAK);

                default:
                    return(Status.OK);
                }
            }
            else
            {
                ColumnArea colArea = (ColumnArea)area;
                switch (properties.GetProperty("break-before").GetEnum())
                {
                case BreakBefore.PAGE:
                    if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1))
                    {
                        return(Status.OK);
                    }
                    else
                    {
                        return(Status.FORCE_PAGE_BREAK);
                    }

                case BreakBefore.ODD_PAGE:
                    if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1) &&
                        (colArea.getPage().getNumber() % 2 != 0))
                    {
                        return(Status.OK);
                    }
                    else
                    {
                        return(Status.FORCE_PAGE_BREAK_ODD);
                    }

                case BreakBefore.EVEN_PAGE:
                    if (!colArea.hasChildren() && (colArea.getColumnIndex() == 1) &&
                        (colArea.getPage().getNumber() % 2 == 0))
                    {
                        return(Status.OK);
                    }
                    else
                    {
                        return(Status.FORCE_PAGE_BREAK_EVEN);
                    }

                case BreakBefore.COLUMN:
                    if (!area.hasChildren())
                    {
                        return(Status.OK);
                    }
                    else
                    {
                        return(Status.FORCE_COLUMN_BREAK);
                    }

                default:
                    return(Status.OK);
                }
            }
        }
Exemplo n.º 48
0
 private Area ChangeDefence(Area oldDefence)
 {
     return((oldDefence == Area.HookKick) ? Area.HookPunch : Area.HookKick);
 }
Exemplo n.º 49
0
 public static List <Area> obtenerTuplasArea()
 {
     return(Area.listDatos());
 }
Exemplo n.º 50
0
        private static void FillTollAreaTable(string dbLocation)
        {
            var         dBOperations = new DBOperations(dbLocation);
            List <Area> tollAreaList = new List <Area>();

            #region Izmir - Aydin

            Area newTollArea = new Area {
                areaID = 1, areaName = "Işıkkent", areaLatitude = 38.349817, areaLongitude = 27.233494, isBooth = true
            };
            tollAreaList.Add(newTollArea);
            Area newTollArea2 = new Area {
                areaID = 1.1, areaName = "Işıkkent Gate", areaLatitude = 38.348549, areaLongitude = 27.233526, isBooth = false
            };
            tollAreaList.Add(newTollArea2);
            Area newTollArea3 = new Area {
                areaID = 1.2, areaName = "Tahtalıçay Gate 1", areaLatitude = 38.280364, areaLongitude = 27.224707, isBooth = false
            };
            tollAreaList.Add(newTollArea3);
            Area newTollArea4 = new Area {
                areaID = 2, areaName = "Tahtalıçay", areaLatitude = 38.272664, areaLongitude = 27.217156, isBooth = true
            };
            tollAreaList.Add(newTollArea4);
            Area newTollArea5 = new Area {
                areaID = 2.1, areaName = "Tahtalıçay Gate 2", areaLatitude = 38.262033, areaLongitude = 27.221531, isBooth = false
            };
            tollAreaList.Add(newTollArea5);
            Area newTollArea6 = new Area {
                areaID = 2.2, areaName = "Torbalı Gate 1", areaLatitude = 38.181769, areaLongitude = 27.311198, isBooth = false
            };
            tollAreaList.Add(newTollArea6);
            Area newTollArea7 = new Area {
                areaID = 3, areaName = "Torbalı", areaLatitude = 38.194008, areaLongitude = 27.337692, isBooth = true
            };
            tollAreaList.Add(newTollArea7);
            Area newTollArea8 = new Area {
                areaID = 3.1, areaName = "Torbalı Gate 2", areaLatitude = 38.169250, areaLongitude = 27.314788, isBooth = false
            };
            tollAreaList.Add(newTollArea8);
            Area newTollArea9 = new Area {
                areaID = 3.2, areaName = "Belevi Gate 1", areaLatitude = 38.026104, areaLongitude = 27.440117, isBooth = false
            };
            tollAreaList.Add(newTollArea9);
            Area newTollArea10 = new Area {
                areaID = 4, areaName = "Belevi", areaLatitude = 38.029083, areaLongitude = 27.449236, isBooth = true
            };
            tollAreaList.Add(newTollArea10);
            Area newTollArea11 = new Area {
                areaID = 4.1, areaName = "Belevi Gate 2", areaLatitude = 38.018769, areaLongitude = 27.454438, isBooth = false
            };
            tollAreaList.Add(newTollArea11);
            Area newTollArea12 = new Area {
                areaID = 4.2, areaName = "Germencik Gate 1", areaLatitude = 37.885426, areaLongitude = 27.574535, isBooth = false
            };
            tollAreaList.Add(newTollArea12);
            Area newTollArea13 = new Area {
                areaID = 5, areaName = "Germencik", areaLatitude = 37.878217, areaLongitude = 27.578042, isBooth = true
            };
            tollAreaList.Add(newTollArea13);
            Area newTollArea14 = new Area {
                areaID = 5.1, areaName = "Germencik Gate 2", areaLatitude = 37.881230, areaLongitude = 27.590210, isBooth = false
            };
            tollAreaList.Add(newTollArea14);
            Area newTollArea15 = new Area {
                areaID = 5.2, areaName = "Aydın Kuzey Gate", areaLatitude = 37.862656, areaLongitude = 27.777258, isBooth = false
            };
            tollAreaList.Add(newTollArea15);
            Area newTollArea16 = new Area {
                areaID = 6, areaName = "Aydın Kuzey", areaLatitude = 37.860439, areaLongitude = 27.788492, isBooth = true
            };
            tollAreaList.Add(newTollArea16);

            #endregion
            #region İzmir - Çeşme
            Area newTollArea18 = new Area {
                areaID = 7, areaName = "Seferihisar", areaLatitude = 38.363192, areaLongitude = 26.864297, isBooth = true
            };
            tollAreaList.Add(newTollArea18);
            Area newTollArea19 = new Area {
                areaID = 7.2, areaName = "Seferihisar Gate 1", areaLatitude = 38.365347, areaLongitude = 26.866310, isBooth = false
            };
            tollAreaList.Add(newTollArea19);
            Area newTollArea20 = new Area {
                areaID = 7.3, areaName = "Urla Gate 1", areaLatitude = 38.319070, areaLongitude = 26.789697, isBooth = false
            };
            tollAreaList.Add(newTollArea20);
            Area newTollArea21 = new Area {
                areaID = 8, areaName = "Urla", areaLatitude = 38.322789, areaLongitude = 26.781961, isBooth = true
            };
            tollAreaList.Add(newTollArea21);
            Area newTollArea22 = new Area {
                areaID = 8.1, areaName = "Urla Gate 2", areaLatitude = 38.316125, areaLongitude = 26.778991, isBooth = false
            };
            tollAreaList.Add(newTollArea22);
            Area newTollArea23 = new Area {
                areaID = 8.2, areaName = "Karaburun Gate 1", areaLatitude = 38.295224, areaLongitude = 26.696702, isBooth = false
            };
            tollAreaList.Add(newTollArea23);
            Area newTollArea24 = new Area {
                areaID = 9, areaName = "Karaburun", areaLatitude = 38.303045, areaLongitude = 26.686012, isBooth = true
            };
            tollAreaList.Add(newTollArea24);
            Area newTollArea25 = new Area {
                areaID = 9.1, areaName = "Karaburun Gate 2", areaLatitude = 38.296799, areaLongitude = 26.682553, isBooth = false
            };
            tollAreaList.Add(newTollArea25);
            Area newTollArea26 = new Area {
                areaID = 9.2, areaName = "Zeytinler Gate 1", areaLatitude = 38.280887, areaLongitude = 26.570717, isBooth = false
            };
            tollAreaList.Add(newTollArea26);
            Area newTollArea27 = new Area {
                areaID = 10, areaName = "Zeytinler", areaLatitude = 38.285034, areaLongitude = 26.564107, isBooth = true
            };
            tollAreaList.Add(newTollArea27);
            Area newTollArea28 = new Area {
                areaID = 10.1, areaName = "Zeytinler Gate 2", areaLatitude = 38.280462, areaLongitude = 26.558759, isBooth = false
            };
            tollAreaList.Add(newTollArea28);
            Area newTollArea29 = new Area {
                areaID = 10.2, areaName = "Alaçatı Gate 1", areaLatitude = 38.278265, areaLongitude = 26.389298, isBooth = false
            };
            tollAreaList.Add(newTollArea29);
            Area newTollArea30 = new Area {
                areaID = 11, areaName = "Alaçatı", areaLatitude = 38.280511, areaLongitude = 26.382368, isBooth = true
            };
            tollAreaList.Add(newTollArea30);
            Area newTollArea31 = new Area {
                areaID = 11.1, areaName = "Alaçatı Gate 2", areaLatitude = 38.276998, areaLongitude = 26.377074, isBooth = false
            };
            tollAreaList.Add(newTollArea31);
            Area newTollArea32 = new Area {
                areaID = 11.2, areaName = "Çeşme Gate", areaLatitude = 38.294980, areaLongitude = 26.310653, isBooth = false
            };
            tollAreaList.Add(newTollArea32);
            Area newTollArea33 = new Area {
                areaID = 12, areaName = "Çeşme", areaLatitude = 38.295994, areaLongitude = 26.310317, isBooth = true
            };
            tollAreaList.Add(newTollArea33);
            #endregion
            dBOperations.InsertAll(tollAreaList, typeof(Area));
        }
Exemplo n.º 51
0
        internal FArea(Area t)
        {
            TheArea = t;

            InitializeComponent();
        }
Exemplo n.º 52
0
        private void ExecuteRestore()
        {
            MessageBoxResult messageBoxResult = MessageBox.Show("Are you sure to Restore", "Restore", MessageBoxButton.YesNo, MessageBoxImage.Warning);

            if (messageBoxResult == MessageBoxResult.Yes)
            {
                using (var unitofWork = new UnitOfWork(new MahalluDBContext())) {
                    unitofWork.Residences.RemoveRange(unitofWork.Residences.GetAll());
                    unitofWork.ResidenceMembers.RemoveRange(unitofWork.ResidenceMembers.GetAll());
                    unitofWork.Areas.RemoveRange(unitofWork.Areas.GetAll());
                    unitofWork.ExpenseCategories.RemoveRange(unitofWork.ExpenseCategories.GetAll());
                    unitofWork.IncomeCategories.RemoveRange(unitofWork.IncomeCategories.GetAll());
                    unitofWork.CashSources.RemoveRange(unitofWork.CashSources.GetAll());
                    //unitofWork.Expenses.RemoveRange(unitofWork.Expenses.GetAll());
                    //unitofWork.ExpenseDetails.RemoveRange(unitofWork.ExpenseDetails.GetAll());
                    //unitofWork.Contributions.RemoveRange(unitofWork.Contributions.GetAll());
                    //unitofWork.ContributionDetails.RemoveRange(unitofWork.ContributionDetails.GetAll());
                    //unitofWork.MarriageCertificates.RemoveRange(unitofWork.MarriageCertificates.GetAll());
                    unitofWork.Complete();

                    string[] directories   = Directory.GetDirectories(BackupAndRestoreLocation);
                    string   directoryPath = backupAndRestoreLocation + @"\MMBackup";
                    if (Directory.Exists(directoryPath))
                    {
                        string filePath = directoryPath + @"\Residences.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]  fields    = backupData[i].Split(new char[] { ',' });
                                Residence residence = new Residence();
                                residence.Number = fields[0];
                                residence.Name   = fields[1];
                                residence.Area   = fields[2];
                                unitofWork.Residences.Add(residence);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\ResidenceMembers.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]        fields          = backupData[i].Split(new char[] { ',' });
                                Residence       residence       = unitofWork.Residences.GetAll().Where(x => x.Number == fields[0]).FirstOrDefault();
                                ResidenceMember residenceMember = new ResidenceMember();
                                residenceMember.Residence_Id   = residence.Id;
                                residenceMember.MemberName     = fields[1];
                                residenceMember.DOB            = Convert.ToDateTime(fields[2]);
                                residenceMember.Job            = fields[3];
                                residenceMember.Mobile         = fields[4];
                                residenceMember.Abroad         = Convert.ToBoolean(fields[5]);
                                residenceMember.Country        = fields[6];
                                residenceMember.IsGuardian     = Convert.ToBoolean(fields[7]);
                                residenceMember.Gender         = fields[8];
                                residenceMember.MarriageStatus = fields[9];
                                residenceMember.Qualification  = fields[10];
                                residenceMember.Remarks        = fields[11];
                                unitofWork.ResidenceMembers.Add(residenceMember);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\Areas.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[] fields = backupData[i].Split(new char[] { ',' });
                                Area     area   = new Area();
                                area.Name = fields[0];
                                unitofWork.Areas.Add(area);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\ContributionDetail.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]           fields             = backupData[i].Split(new char[] { ',' });
                                ContributionDetail contributionDetail = new ContributionDetail();

                                unitofWork.ContributionDetails.Add(contributionDetail);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\CashSources.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]   fields     = backupData[i].Split(new char[] { ',' });
                                CashSource cashSource = new CashSource();
                                cashSource.SourceName = fields[0];
                                cashSource.Amount     = Convert.ToDecimal(fields[1]);
                                unitofWork.CashSources.Add(cashSource);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\ExpenseCategories.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]        fields          = backupData[i].Split(new char[] { ',' });
                                ExpenseCategory expenseCategory = new ExpenseCategory();
                                expenseCategory.Name            = fields[0];
                                expenseCategory.DetailsRequired = Convert.ToBoolean(fields[1]);
                                unitofWork.ExpenseCategories.Add(expenseCategory);
                            }
                        }
                        unitofWork.Complete();

                        filePath = directoryPath + @"\IncomeCategories.csv";
                        if (File.Exists(filePath))
                        {
                            String[] backupData = File.ReadAllLines(filePath);
                            for (int i = 1; i < backupData.Length; i++)
                            {
                                string[]       fields         = backupData[i].Split(new char[] { ',' });
                                IncomeCategory incomeCategory = new IncomeCategory();
                                incomeCategory.Name            = fields[0];
                                incomeCategory.DetailsRequired = Convert.ToBoolean(fields[1]);
                                unitofWork.IncomeCategories.Add(incomeCategory);
                            }
                        }
                        unitofWork.Complete();

                        MessageBox.Show("Restore is completed successfully..!");
                    }
                    else
                    {
                        MessageBox.Show(backupAndRestoreLocation + " doesn't contain back up directory as MMBackup");
                    }
                }
            }
        }
Exemplo n.º 53
0
 public override Status Layout(Area area)
 {
     return(Layout(area, null));
 }
Exemplo n.º 54
0
        public override void Update(GameTime gameTime)
        {
            // Nur wenn Komponente aktiviert wurde.
            if (!Enabled)
            {
                return;
            }

            // Nur berechnen, falls eine Welt aktiv ist.
            if (World == null)
            {
                return;
            }

            List <Action> transfers = new List <Action>();

            foreach (var area in World.Areas)
            {
                // Schleife über alle sich aktiv bewegenden Spiel-Elemente
                foreach (var character in area.Items.OfType <Character>().ToArray())
                {
                    // Tote Charactere ignorieren
                    if (character is IAttackable && (character as IAttackable).Hitpoints <= 0)
                    {
                        continue;
                    }

                    // KI Update
                    if (character.Ai != null && Mode != SimulationMode.Client)
                    {
                        character.Ai.Update(area, gameTime);
                    }

                    // Neuberechnung der Character-Position.
                    character.move += character.Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

                    // Attacker identifizieren
                    IAttacker attacker = null;
                    if (character is IAttacker)
                    {
                        attacker = (IAttacker)character;
                        attacker.AttackableItems.Clear();

                        // Recovery-Time aktualisieren
                        attacker.Recovery -= gameTime.ElapsedGameTime;
                        if (attacker.Recovery < TimeSpan.Zero)
                        {
                            attacker.Recovery = TimeSpan.Zero;
                        }
                    }

                    // Interactor identifizieren
                    IInteractor interactor = null;
                    if (character is IInteractor)
                    {
                        interactor = (IInteractor)character;
                        interactor.InteractableItems.Clear();
                    }

                    // Kollisionsprüfung mit allen restlichen Items.
                    foreach (var item in area.Items)
                    {
                        // Kollision mit sich selbst ausschließen
                        if (item == character)
                        {
                            continue;
                        }

                        // Distanz berechnen
                        Vector2 distance = (item.Position + item.move) - (character.Position + character.move);

                        // Ermittlung der angreifbaren Items.
                        if (attacker != null &&
                            item is IAttackable &&
                            distance.Length() - attacker.AttackRange - item.Radius < 0f)
                        {
                            attacker.AttackableItems.Add(item as IAttackable);
                        }

                        // Ermittlung der interagierbaren Items.
                        if (interactor != null &&
                            item is IInteractable &&
                            distance.Length() - interactor.InteractionRange - item.Radius < 0f)
                        {
                            interactor.InteractableItems.Add(item as IInteractable);
                        }

                        // Überschneidung berechnen & darauf reagieren
                        float overlap = item.Radius + character.Radius - distance.Length();
                        if (overlap > 0f)
                        {
                            Vector2 resolution = distance * (overlap / distance.Length());
                            if (item.Fixed && !character.Fixed)
                            {
                                // Item fixiert
                                character.move -= resolution;
                            }
                            else if (!item.Fixed && character.Fixed)
                            {
                                // Character fixiert
                                item.move += resolution;
                            }
                            else if (!item.Fixed && !character.Fixed)
                            {
                                // keiner fixiert
                                float totalMass = item.Mass + character.Mass;
                                character.move -= resolution * (item.Mass / totalMass);
                                item.move      += resolution * (character.Mass / totalMass);
                            }

                            // Kombination aus Collectable und Iventory
                            if (item is ICollectable && character is IInventory)
                            {
                                ICollectable collectable = item as ICollectable;

                                //  -> Character sammelt Item ein
                                if (Mode != SimulationMode.Client)
                                {
                                    transfers.Add(() =>
                                    {
                                        if (area.Items.Contains(item))
                                        {
                                            area.Items.Remove(item);
                                        }

                                        IInventory inventory = character as IInventory;
                                        if (!inventory.Inventory.Contains(item))
                                        {
                                            inventory.Inventory.Add(item);
                                            item.Position = Vector2.Zero;
                                        }
                                    });
                                }

                                // Event aufrufen
                                if (collectable.OnCollect != null)
                                {
                                    collectable.OnCollect(this, item);
                                }
                            }
                        }
                    }
                }

                // Kollision mit blockierten Zellen
                foreach (var item in area.Items.ToArray())
                {
                    bool collision = false;
                    int  loops     = 0;

                    // Standard-Update für das Item
                    if (item.Update != null)
                    {
                        item.Update(game, area, item, gameTime);
                    }

                    do
                    {
                        // Grenzbereiche für die zu überprüfenden Zellen ermitteln
                        Vector2 position = item.Position + item.move;
                        int     minCellX = (int)(position.X - item.Radius);
                        int     maxCellX = (int)(position.X + item.Radius);
                        int     minCellY = (int)(position.Y - item.Radius);
                        int     maxCellY = (int)(position.Y + item.Radius);

                        collision = false;
                        float minImpact = 2f;
                        int   minAxis   = 0;

                        // Schleife über alle betroffenen Zellen zur Ermittlung der ersten Kollision
                        for (int x = minCellX; x <= maxCellX; x++)
                        {
                            for (int y = minCellY; y <= maxCellY; y++)
                            {
                                // Zellen ignorieren die den Spieler nicht blockieren
                                if (!area.IsCellBlocked(x, y))
                                {
                                    continue;
                                }

                                // Zellen ignorieren die vom Spieler nicht berührt werden
                                if (position.X - item.Radius > x + 1 ||
                                    position.X + item.Radius < x ||
                                    position.Y - item.Radius > y + 1 ||
                                    position.Y + item.Radius < y)
                                {
                                    continue;
                                }

                                collision = true;

                                // Kollisionszeitpunkt auf X-Achse ermitteln
                                float diffX = float.MaxValue;
                                if (item.move.X > 0)
                                {
                                    diffX = position.X + item.Radius - x + gap;
                                }
                                if (item.move.X < 0)
                                {
                                    diffX = position.X - item.Radius - (x + 1) - gap;
                                }
                                float impactX = 1f - (diffX / item.move.X);

                                // Kollisionszeitpunkt auf Y-Achse ermitteln
                                float diffY = float.MaxValue;
                                if (item.move.Y > 0)
                                {
                                    diffY = position.Y + item.Radius - y + gap;
                                }
                                if (item.move.Y < 0)
                                {
                                    diffY = position.Y - item.Radius - (y + 1) - gap;
                                }
                                float impactY = 1f - (diffY / item.move.Y);

                                // Relevante Achse ermitteln
                                // Ergibt sich aus dem spätesten Kollisionszeitpunkt
                                int   axis   = 0;
                                float impact = 0;
                                if (impactX > impactY)
                                {
                                    axis   = 1;
                                    impact = impactX;
                                }
                                else
                                {
                                    axis   = 2;
                                    impact = impactY;
                                }

                                // Ist diese Kollision eher als die bisher erkannten
                                if (impact < minImpact)
                                {
                                    minImpact = impact;
                                    minAxis   = axis;
                                }
                            }
                        }

                        // Im Falle einer Kollision in diesem Schleifendurchlauf...
                        if (collision)
                        {
                            // X-Anteil ab dem Kollisionszeitpunkt kürzen
                            if (minAxis == 1)
                            {
                                item.move *= new Vector2(minImpact, 1f);
                            }

                            // Y-Anteil ab dem Kollisionszeitpunkt kürzen
                            if (minAxis == 2)
                            {
                                item.move *= new Vector2(1f, minImpact);
                            }
                        }
                        loops++;
                    }while(collision && loops < 2);

                    // Finaler Move-Vektor auf die Position anwenden.
                    item.Position += item.move;
                    item.move      = Vector2.Zero;

                    // Portal anwenden (nur Player)
                    if (area.Portals != null && item is Player)
                    {
                        Player player   = item as Player;
                        bool   inPortal = false;

                        foreach (var portal in area.Portals)
                        {
                            if (item.Position.X > portal.Box.Left &&
                                item.Position.X <= portal.Box.Right &&
                                item.Position.Y > portal.Box.Top &&
                                item.Position.Y <= portal.Box.Bottom)
                            {
                                inPortal = true;
                                if (player.InPortal)
                                {
                                    continue;
                                }

                                // Ziel-Area und Portal finden
                                Area   destinationArea   = World.Areas.First(a => a.Name.Equals(portal.DestinationArea));
                                Portal destinationPortal = destinationArea.Portals.First(p => p.DestinationArea.Equals(area.Name));

                                // Neue Position des Spielers finden
                                Vector2 position = new Vector2(
                                    destinationPortal.Box.X + (destinationPortal.Box.Width / 2f),
                                    destinationPortal.Box.Y + (destinationPortal.Box.Height / 2f));

                                // Transfer in andere Area vorbereiten
                                if (Mode != SimulationMode.Client)
                                {
                                    transfers.Add(() =>
                                    {
                                        if (area.Items.Contains(item))
                                        {
                                            area.Items.Remove(item);
                                        }

                                        if (!destinationArea.Items.Contains(item))
                                        {
                                            destinationArea.Items.Add(item);
                                            item.Position = position;
                                        }
                                    });
                                }
                            }
                        }

                        player.InPortal = inPortal;
                    }

                    // Interaktionen durchführen
                    if (item is IInteractor)
                    {
                        IInteractor interactor = item as IInteractor;
                        if (interactor.InteractSignal)
                        {
                            // Alle Items in der Nähe aufrufen
                            foreach (var interactable in interactor.InteractableItems)
                            {
                                if (interactable.OnInteract != null)
                                {
                                    interactable.OnInteract(this, interactor, interactable);
                                }
                            }
                        }
                        interactor.InteractSignal = false;
                    }

                    // Angriff durchführen
                    if (item is IAttacker)
                    {
                        IAttacker attacker = item as IAttacker;
                        if (attacker.AttackSignal && attacker.Recovery <= TimeSpan.Zero)
                        {
                            // Alle Items in der Nähe schlagen
                            foreach (var attackable in attacker.AttackableItems)
                            {
                                attackable.Hitpoints -= attacker.AttackValue;
                                if (attackable.OnHit != null)
                                {
                                    attackable.OnHit(this, attacker, attackable);
                                }
                            }

                            // Schlagerholung anstoßen
                            attacker.Recovery = attacker.TotalRecovery;
                        }
                        attacker.AttackSignal = false;
                    }
                }
            }

            // Transfers durchführen
            if (Mode != SimulationMode.Client)
            {
                foreach (var transfer in transfers)
                {
                    transfer();
                }
            }
        }
Exemplo n.º 55
0
        public static Force FromPressureByArea(Pressure p, Area area)
        {
            double newtons = p.Pascals * area.SquareMeters;

            return(new Force(newtons));
        }
Exemplo n.º 56
0
        public void Test1()
        {
            /////////////////////////////////////////////
            /// Venue part
            ///

            Venue[] _venue = new Venue[]
            {
                new Venue("Venue1_d", "Venue1_n", "", ""),
                new Venue("Venue2_d", "Venue2_n", "", "")
            };
            foreach (Venue v in _venue)
            {
                Assert.AreEqual(0, _business.CreateVenue(v));
            }

            // check unique name
            Venue v3 = new Venue("Venue3_d", "Venue1_n", "", "");

            Assert.AreNotEqual(0, _business.CreateVenue(v3));

            // set not unique name
            _venue[1].Name = "Venue1_n";
            Assert.AreNotEqual(0, _business.UpdateVenue(_venue[1]));

            // set unique name
            _venue[1].Name = "Venue1_n_update";
            Assert.AreEqual(0, _business.UpdateVenue(_venue[1]));


            /////////////////////////////////////////////
            /// Layout part
            ///

            Layout[] _layout = new Layout[]
            {
                new Layout(_venue[0].Id, "Layout1_d", "Layout1_name"),
                new Layout(_venue[0].Id, "Layout2_d", "Layout2_name"),
                new Layout(_venue[1].Id, "Layout2_d", "Layout2_name")
            };
            foreach (Layout l in _layout)
            {
                Assert.AreEqual(0, _business.CreateLayout(l));
            }

            // layout name should me unique in venue
            Layout l4 = new Layout(_venue[0].Id, "Layout4_d", "Layout1_name");

            Assert.AreNotEqual(0, _business.CreateLayout(l4));

            // event can't be created without any seats;
            Event _e = new Event("Event1_name", "Event1_desc", _layout[0].Id, DateTime.Today.AddDays(2));

            Assert.AreNotEqual(0, _business.CreateEvent(_e));


            /////////////////////////////////////////////
            /// Area part
            ///

            Area[] _area = new Area[]
            {
                new Area(_layout[0].Id, "Area1_d", 1, 1),
                new Area(_layout[0].Id, "Area2_d", 2, 2),
                new Area(_layout[0].Id, "Area3_d", 3, 3),
                new Area(_layout[1].Id, "Area4_d", 4, 4),
            };
            foreach (Area a in _area)
            {
                Assert.AreEqual(0, _business.CreateArea(a));

                for (int i = 0; i < 6; i++)
                {
                    Seat _seat = new Seat(a.Id, i, i);
                    Assert.AreEqual(0, _business.CreateSeat(_seat));
                }

                // row and number should be unique for area;
                Seat _s = new Seat(a.Id, 2, 2);
                Assert.AreNotEqual(0, _business.CreateSeat(_s));
            }

            // area description should be unique in layout
            Area a5 = new Area(_layout[0].Id, "Area2_d", 5, 5);

            Assert.AreNotEqual(0, _business.CreateArea(a5));


            Event[] _event = new Event[]
            {
                new Event("Event1_name", "Event1_desc", _layout[0].Id, DateTime.Today.AddDays(2)),
                new Event("Event2_name", "Event2_desc", _layout[0].Id, DateTime.Today.AddDays(3)),
                new Event("Event3_name", "Event3_desc", _layout[1].Id, DateTime.Today.AddDays(4)),
            };
            foreach (Event e in _event)
            {
                Assert.AreEqual(0, _business.CreateEvent(e));
            }

            Assert.AreEqual(0, _business.DeleteEvent(_event[2].Id));

            _event[0].Description = "Event1_desc_update";
            _event[0].Name        = "Event1_name_update";
            _event[0].StartDate   = DateTime.Today.AddDays(5);
            Assert.AreEqual(0, _business.UpdateEvent(_event[0]));
        }
Exemplo n.º 57
0
        void RenderPlaylistElement(PlaylistElementVM vm, IDrawingToolkit tk, IContext context, Area backgroundArea, Area cellArea, CellState state)
        {
            tk.Context = context;
            tk.Begin();
            Point textPoint = new Point(backgroundArea.Left + LEFT_OFFSET + (2 * SPACING) + COLOR_RECTANGLE_WIDTH +
                                        MINIATURE_WIDTH + SPACING, cellArea.Start.Y);
            double textWidth = (cellArea.Right - RIGTH_OFFSET - EYE_IMAGE_WIDTH - SPACING) - textPoint.X;

            RenderBackground(tk, backgroundArea, App.Current.Style.ThemeBase);
            RenderSelection(tk, context, backgroundArea, cellArea, state, true);
            RenderPrelit(vm.Playing, tk, context, backgroundArea, cellArea, state);
            RenderChildText(tk, textPoint, (int)textWidth, (int)cellArea.Height, vm.Description, App.Current.Style.TextBase);
            RenderColorStrip(tk, backgroundArea, App.Current.Style.TextBase);
            Point p = new Point(backgroundArea.Left + LEFT_OFFSET + COLOR_RECTANGLE_WIDTH + SPACING, cellArea.Start.Y + VERTICAL_OFFSET);

            RenderImage(tk, p, vm.Miniature, MINIATURE_WIDTH, MINIATURE_HEIGHT);
            RenderEye(tk, backgroundArea, cellArea, vm.Playing);
            tk.End();
        }
Exemplo n.º 58
0
        public async Task New_NPC(string areaName, int amount = 1, string profession = "Child", int level = 0)
        {
            if (IsGMLevel(4).Result)
            {
                //areaName = Area.AreaDataExist(areaName);
                if (areaName != null)
                {
                    NPC[] npcs = new NPC[amount];
                    for (int i = 0; i < amount; i++)
                    {
                        npcs[i] = NPC.NewNPC(level, profession, null);
                    }

                    Area   area         = Area.LoadFromName(areaName);
                    string populationId = area.GetPopulation(Neitsillia.Areas.AreaExtentions.Population.Type.Population)._id;

                    EmbedBuilder noti = new EmbedBuilder();
                    noti.WithTitle($"{area.name} Population");
                    amount = 0;
                    if (npcs != null && npcs.Length > 0)
                    {
                        foreach (NPC n in npcs)
                        {
                            if (n != null)
                            {
                                if (n.profession == Neitsillia.ReferenceData.Profession.Child)
                                {
                                    if (area.parent == null)
                                    {
                                        n.origin = area.name;
                                    }
                                    else
                                    {
                                        n.origin = area.parent;
                                    }
                                    n.displayName = n.name + " Of " + n.origin;
                                }
                                else
                                {
                                    n.displayName = n.name;
                                }
                                PopulationHandler.Add(populationId, n);
                                amount++;
                            }
                        }
                    }

                    if (amount != 0)
                    {
                        await ReplyAsync("NPCs created");
                    }
                    else
                    {
                        await ReplyAsync("No new NPC were created");
                    }
                }
                else
                {
                    await DUtils.Replydb(Context, "Area not found.");
                }
            }
        }
Exemplo n.º 59
0
    protected void btnImportTemp_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""", Server.MapPath("~/UserFile/Data_2016.xls"));
        //string query = String.Format("select * from [{0}$]", "Area");
        string           query       = String.Format("select * from [{0}$]", "Nam_2016");
        SecurityBSO      securityBSO = new SecurityBSO();
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString);
        DataSet          dataSet     = new DataSet();

        dataAdapter.Fill(dataSet);

        DataTable         myTable = dataSet.Tables[0];
        EnterpriseService comBSO  = new EnterpriseService();

        foreach (DataRow drow in myTable.Rows)
        {
            ReportTemp2014 temp = new ReportTemp2014();
            Enterprise     area = new Enterprise();
            area.Title = drow["Title"].ToString();
            temp.Title = area.Title;
            if (drow["Address"] != null)
            {
                area.Address = drow["Address"].ToString();
                temp.Address = area.Address;
            }

            area.OrganizationId = Convert.ToInt32(drow["OrgId"]);
            temp.OrgId          = area.OrganizationId;
            Organization org = new OrganizationService().FindByKey(area.OrganizationId);

            if (drow["AreaName"] != null && drow["AreaName"].ToString() != "")
            {
                temp.AreaName = drow["AreaName"].ToString();
                if (drow["AreaName"].ToString() == "Công nghiệp")
                {
                    area.AreaId = 5;
                }
                else
                if (drow["AreaName"].ToString() == "Nông nghiệp")
                {
                    area.AreaId = 3;
                }
                else
                if (drow["AreaName"].ToString() == "Công trình xây dựng")
                {
                    area.AreaId = 6;
                }
                else
                {
                    area.AreaId = 1;
                }
                temp.AreaId = area.AreaId;
            }
            if (drow["SubAreaName"] != null && drow["SubAreaName"].ToString() != "")
            {
                DataTable dtSub = new AreaService().getAreaByName(drow["SubAreaName"].ToString());
                if (dtSub != null && dtSub.Rows.Count > 0)
                {
                    area.SubAreaId = Convert.ToInt32(dtSub.Rows[0]["Id"]);
                    temp.SubAreaId = area.SubAreaId;
                }
                else
                {
                    Area sub = new Area();
                    sub.AreaName  = drow["SubAreaName"].ToString();
                    sub.ParentId  = area.AreaId;
                    sub.IsStatus  = 1;
                    sub.SortOrder = 0;
                    int subId = new AreaService().Insert(sub);
                    temp.SubAreaId = subId;
                    area.SubAreaId = subId;
                }
                area.Info        = drow["SubAreaName"].ToString();
                temp.SubAreaName = drow["SubAreaName"].ToString();
            }

            area.ProvinceId    = Convert.ToInt32(drow["ProvinceId"]);
            area.ManProvinceId = Convert.ToInt32(drow["ManProvinceId"]);
            int eId = comBSO.Insert(area);//Them doanh  nghiep

            if (eId > 0)
            {
                temp.EnterpriseId = eId;
                if (drow["Dien_kWh"] != null && drow["Dien_kWh"].ToString().Trim() != "")
                {
                    temp.Dien_kWh = drow["Dien_kWh"].ToString();
                }

                if (drow["Than_Tan"] != null && drow["Than_Tan"].ToString().Trim() != "")
                {
                    temp.Than_Tan = drow["Than_Tan"].ToString();
                }

                if (drow["DO_Tan"] != null && drow["DO_Tan"].ToString().Trim() != "")
                {
                    temp.DO_Tan = drow["DO_Tan"].ToString();
                }
                if (drow["DO_lit"] != null && drow["DO_lit"].ToString().Trim() != "")
                {
                    temp.DO_lit = drow["DO_lit"].ToString();
                }

                if (drow["FO_Tan"] != null && drow["FO_Tan"].ToString().Trim() != "")
                {
                    temp.FO_Tan = drow["FO_Tan"].ToString();
                }
                if (drow["FO_lit"] != null && drow["FO_lit"].ToString().Trim() != "")
                {
                    temp.FO_lit = drow["FO_Tan"].ToString();
                }

                if (drow["Xang_Tan"] != null && drow["Xang_Tan"].ToString().Trim() != "")
                {
                    temp.Xang_Tan = drow["Xang_Tan"].ToString();
                }
                if (drow["Xang_lit"] != null && drow["Xang_lit"].ToString().Trim() != "")
                {
                    temp.Xang_lit = drow["Xang_lit"].ToString();
                }

                if (drow["Gas_Tan"] != null && drow["Gas_Tan"].ToString().Trim() != "")
                {
                    temp.Gas_Tan = drow["Gas_Tan"].ToString();
                }

                if (drow["Khi_m3"] != null && drow["Khi_m3"].ToString().Trim() != "")
                {
                    temp.Khi_M3 = drow["Khi_m3"].ToString();
                }

                if (drow["LPG_Tan"] != null && drow["LPG_Tan"].ToString().Trim() != "")
                {
                    temp.LPG_Tan = drow["LPG_Tan"].ToString();
                }
                if (drow["NLPL_Tan"] != null && drow["NLPL_Tan"].ToString().Trim() != "")
                {
                    temp.NLPL_Tan = drow["NLPL_Tan"].ToString();
                }

                if (drow["Khac_tan"] != null && drow["Khac_tan"].ToString().Trim() != "")
                {
                    temp.KhacSoDo = drow["Khac_tan"].ToString();
                }

                if (drow["Note"] != null && drow["Note"].ToString().Trim() != "")
                {
                    temp.Note = drow["Note"].ToString();
                }


                EnterpriseYearService eYService = new EnterpriseYearService();
                EnterpriseYear        ey        = new EnterpriseYear();
                ey.EnterpriseId = eId;

                if (drow["No_TOE"] != null && drow["No_TOE"].ToString().Trim() != "" && Convert.ToDecimal(drow["No_TOE"]) > 0)
                {
                    ey.No_TOE   = Convert.ToDecimal(drow["No_TOE"]);
                    temp.No_TOE = ey.No_TOE;
                    temp.Year   = 2016;
                    int retTemp = new ReportTemp2014Service().Insert(temp);//Them bao cao tam
                    ey.IsDelete = false;
                    ey.Year     = temp.Year;
                    eYService.Insert(ey);//Them nam bao cao
                }
                //Tao tai khoan doanh nghiep

                Utils         objUtil       = new Utils();
                MemberService memberService = new MemberService();
                int           STT           = 0;

                STT = new EnterpriseService().GetNoAccount(area.OrganizationId);

                STT++;
                ePower.DE.Domain.Member member = new ePower.DE.Domain.Member();
                member.EnterpriseId = eId;
                member.IsDelete     = false;
                member.AccountName  = "dn." + Utils.UCS2Convert(org.Title).Replace(" ", "").Replace("-", "").ToLower() + "." + STT.ToString("000");
                member.Password     = securityBSO.EncPwd("123456");
                memberService.Insert(member);
            }
        }
    }
Exemplo n.º 60
0
 public List <Obra> buscarObraPorArea(Area area)
 {
     return
 }