/// <summary> /// Returns a component of the specified type if it is attached to the entity. /// </summary> public TComponent GetComponent <TComponent>(IEntityRecord entity) where TComponent : class, IComponent { TComponent component = default(TComponent); return(GetComponent(entity, component)); }
void OnEntered(IEntityRecord entity) { if (Entered != null) { Entered(this, new EntityEventArgs(entity)); } }
void OnRemoved(IEntityRecord entity) { if (Removed != null) { Removed(this, new EntityEventArgs(entity)); } }
public bool Remove(IEntityRecord record, IComponent component) { if (record == null || component == null) { return(false); } if (component.Record != null && !component.Record.Equals(record)) { return(false); } var componentWasRemoved = false; var components = GetComponentsForRecord(record); lock (_locker) { if (components.Count > 0) { var key = component.GetType(); if (components.ContainsKey(key)) { componentWasRemoved = components.Remove(key); } } if (component.Record != null) { component.Record = null; } } return(componentWasRemoved); }
public bool Add(IEntityRecord record, IComponent component) { lock (_locker) { var components = GetComponentsForRecord(record); if (component != null) { var previousRecord = component.Record; if (previousRecord != null) { if (!previousRecord.Equals(record)) { Remove(previousRecord, component); } } var key = component.GetType(); if (!components.ContainsKey(key)) { components.Add(key, component); } if (component.Record == null || !component.Record.Equals(record)) { component.Record = record; } } } return(true); }
public bool Remove(IEntityRecord record) { if (record == null) { return(false); } bool recordDeleted = false; var components = GetComponentsForRecord(record); lock (_locker) { if (components != null && components.Count > 0) { var values = components.Values; for (int i = 0; i < values.Count - 1; i++) { var component = values.ElementAt(i); Remove(record, component); } } recordDeleted = _records.Remove(record); } return(recordDeleted); }
/// <summary> /// Returns a component of the specified type if it is attached to the entity. /// </summary> public TComponent GetComponent <TComponent>(IEntityRecord entity, TComponent component) where TComponent : class, IComponent { if (entity == null) { return(default(TComponent)); } IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); TComponent result = default(TComponent); if (components != null && components.Count > 0) { Type componentType = null; if (component != null) { componentType = component.GetType(); } else { componentType = typeof(TComponent); } if (components.ContainsKey(componentType)) { result = (TComponent)components[componentType]; } } return(result); }
/// <summary> /// Unregisters an entity and returns `true` if it was successfully dropped. /// </summary> public bool Drop(IEntityRecord entity) { if (entity == null) { return(false); } bool entityWasDropped = false; IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); lock (_keyhole) { if (components != null && components.Count > 0) { ICollection <IComponent> values = components.Values; for (int i = values.Count - 1; i >= 0; i--) { IComponent component = values.ElementAt(i); Remove(entity, component); } } entityWasDropped = _records.Remove(entity); } if (entityWasDropped) { OnRemoved(entity); } return(entityWasDropped); }
/// <summary> /// Goes through all discovered dependencies and injects them one by one. /// </summary> void InjectDependencies() { if (Record == null) { return; } foreach (KeyValuePair <FieldInfo, RequireComponentAttribute> pair in _dependencies) { FieldInfo field = pair.Key; RequireComponentAttribute dependency = pair.Value; if (!dependency.Automatically) { continue; } /// Determines which entity the dependency should be grabbed from. IEntityRecord record = (dependency.FromRecordNamed != null) ? /// The dependency will **not** be injected if the specified entity /// is not registered at the time. Entity.Find(dependency.FromRecordNamed, Record.Registry) : Record; if (record == null) { continue; } /// Immediately attempt injecting the component. InjectDependency(field, record, allowingDerivedTypes: dependency.AllowDerivedTypes); } }
public static IEntityRecord CreateChild(this IEntityRecord parent, string name) { IEntityRecord record = Entity.Create(name); record.Parent = record; return(record); }
public override Decision Decide(IEntityRecord opponent) { Decision trick = Decision.Undecided; Outcome outcome = Outcome.Unknown; int retries = 0; int maxRetries = 5; while (outcome == Outcome.Unknown || outcome == Outcome.Loss) { // pick any hand and use it to see how opponent would react // > note that it must have some amount of influence to be considered a real decision trick = Decision.Next(1); Decision reaction = new Decision(); foreach (Behavior behavior in opponent.GetComponents().OfType<Behavior>()) { reaction += behavior.React(Record, trick); } outcome = trick.DetermineOutcome(reaction); if (retries++ > maxRetries) { break; } } // > note that we do not use Decision.Counter on the reaction that resulted in a win, because // it was actually the trick hand that caused the win return Decision.Distribute( trick.MostInfluencedHand, Influence); }
public static IEntityRecord CreateChild(this IEntityRecord parent, params IComponent[] components) { IEntityRecord record = Entity.Create(components); record.Parent = record; return(record); }
public static IEntityRecord CreateChild(this IEntityRecord parent, string name, IEntityRecordCollection registry) { IEntityRecord record = Entity.Create(name, registry); record.Parent = record; return(record); }
/// <summary> /// Attempts to inject a component into a field, and adds the component to the specified entity. /// </summary> /// <remarks> /// Note that the dependency will remain, even if it becomes dettached from its entity. /// </remarks> void InjectDependency(FieldInfo field, IEntityRecord record, bool allowingDerivedTypes) { if (field == null || record == null) { return; } Type componentType = field.FieldType; IComponent dependency = record.Registry.GetComponent(record, componentType, allowingDerivedTypes); if (dependency == null) { dependency = Create(componentType); if (dependency == null) { return; } record.Add(dependency); } if (dependency != null) { field.SetValue(this, dependency); } }
public static IEntityRecord CreateChild(this IEntityRecord parent, string name, IEntityRecordCollection registry, params IComponent[] components) { IEntityRecord record = Entity.Create(name, registry, components); record.Parent = record; return(record); }
/// <summary> /// If `allowingDerivedTypes` is `true`, returns any component that is either a subclass of, or is, the specified type if it is attached to the entity. /// </summary> public IComponent GetComponent(IEntityRecord entity, Type componentType, bool allowingDerivedTypes) { if (entity == null || componentType == null) { return(null); } IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); IComponent result = null; if (components != null && components.Count > 0) { foreach (IComponent otherComponent in components.Values) { if ((allowingDerivedTypes && otherComponent.GetType().IsSubclassOf(componentType)) || otherComponent.GetType() == componentType) { result = otherComponent; break; } } } return(result); }
public void Breathe(IEntityRecord target) { if (target.HasComponent <Combustible>()) { Console.WriteLine("Firebreathe !!!"); target.GetComponent <Combustible>().Combust(); } }
/// <summary> /// Returns all the components that are attached to the entity. /// </summary> public IEnumerable <IComponent> GetComponents(IEntityRecord entity) { IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); return(components != null ? components.Values : null); }
/// <summary> /// Gets all components currently attached to this entity. /// </summary> public static IEnumerable <IComponent> GetComponents(this IEntityRecord entity) { if (entity.Registry != null) { return(entity.Registry.GetComponents(entity)); } return(null); }
/// <summary> /// Dettaches a component from this entity. /// </summary> public static bool Remove(this IEntityRecord entity, IComponent component) { if (entity.Registry != null) { return(entity.Registry.Remove(entity, component)); } return(false); }
/// <summary> /// Unregisters this entity from its registry. /// </summary> public static bool Drop(this IEntityRecord entity) { if (entity.Registry != null) { return(entity.Registry.Drop(entity)); } return(false); }
/// <summary> /// Attaches the specified component to an entity. /// /// If a component of the same type is already attached to the entity, then nothing happens /// and the method returns false. /// </summary> public bool Add(IEntityRecord entity, IComponent component) { bool componentSuccessfullyAttached = false; bool entityWasAlreadyRegistered = true; lock (_keyhole) { if (component != null) { IEntityRecord previousRecord = component.Record; if (previousRecord != null) { if (!previousRecord.Equals(entity)) { Remove(previousRecord, component); } } } IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); if (components == null) { components = new Dictionary <Type, IComponent>(1); entityWasAlreadyRegistered = false; _records[entity] = components; } if (component != null) { Type key = component.GetType(); if (!entityWasAlreadyRegistered || !components.ContainsKey(key)) { components.Add(key, component); if (component.Record == null || !component.Record.Equals(entity)) { component.Record = entity; } PrepareComponentForSynchronization(component); componentSuccessfullyAttached = true; } } } if (!entityWasAlreadyRegistered) { OnEntered(entity); } return(componentSuccessfullyAttached); }
/// <summary> /// If `allowingDerivedTypes` is `true`, returns any component that is either a subclass of, or is, the specified type if it is attached to this entity. /// </summary> public static TComponent GetComponent <TComponent>(this IEntityRecord entity, TComponent component, bool allowingDerivedTypes) where TComponent : class, IComponent { if (entity.Registry != null) { return(entity.Registry.GetComponent(entity, component, allowingDerivedTypes)); } return(default(TComponent)); }
public bool Equals(IEntityRecord other) { if (other == null) { return(false); } /// Which is used to determine equality between entities. return(GetHashCode() == other.GetHashCode()); }
/// ###Component retrieval /// <summary> /// Returns a component of the specified type if it is attached to this entity. /// </summary> public static TComponent GetComponent <TComponent>(this IEntityRecord entity) where TComponent : class, IComponent { if (entity.Registry != null) { return(entity.Registry.GetComponent <TComponent>(entity)); } return(default(TComponent)); }
public override Decision React(IEntityRecord opponent, Decision decision) { Decision counter = Decision.Win(decision, Influence); Hand choices = counter.MostInfluencedHand | decision.MostInfluencedHand; return Decision.Next( choices, Influence * 2); }
//ConcurrentDictionary<LinkKey, double> links = new ConcurrentDictionary<LinkKey, double>(); //ConcurrentDictionary<int, double> ranks = new ConcurrentDictionary<int, double>(); //ConcurrentDictionary<int, ConcurrentBag<int>> leaderGroups = new ConcurrentDictionary<int, ConcurrentBag<int>>(); // leader & followers public Application( IOptions <Config> config, ILogger <Application> logger, IEntityRecord entityRecord, IEnumerator <IEntityRecord> entityRecordEnumerator) { _config = config.Value; _logger = logger; _entityRecord = entityRecord; _entityRecordEnumerator = entityRecordEnumerator; }
public static IEntityRecord CreateFromDefinition(string definition, string name, params IComponent[] components) { IEntityRecord entity = _definitions.Make(definition, Create(name)); foreach (IComponent component in components) { entity.Add(component); } return(entity); }
/// <summary> /// Creates and registers a new entity in the specified registry. The specified components will also be attached to it. /// </summary> public static IEntityRecord Create(string name, IEntityRecordCollection registry, params IComponent[] components) { IEntityRecord record = Create(name, registry); foreach (IComponent component in components) { record.Add(component); } return(record); }
public static IEntityRecord CreateFromDefinition(string definition, params IComponent[] components) { IEntityRecord entity = CreateFromDefinition(definition); foreach (IComponent component in components) { entity.Add(component); } return(entity); }
public override Decision Decide(IEntityRecord opponent) { Decision decision = Decision.Undecided; History opponentHistory = opponent.GetComponent<History>(); if (opponentHistory != null) { decision = opponentHistory.MostRecentDecision; } return Decision.Distribute( decision.MostInfluencedHand, Influence); }
/// <summary> /// Pull an entity toward this portal. /// </summary> void Pull(IEntityRecord entity) { Transformable2D transform = entity.GetComponent<Transformable2D>(); HasVelocity velocity = entity.GetComponent<HasVelocity>(); float distance = _transform.DistanceTo(transform); float strength = Strength * (InfluenceRadius / distance); Vector2 directionTowardsPortal = Vector2.Normalize(_transform.Position - transform.Position); Vector2 movement = directionTowardsPortal * strength; velocity.Velocity += movement; }
public override Decision React(IEntityRecord opponent, Decision decision) { Decision reaction = Decision.Undecided; History opponentHistory = opponent.GetComponent<History>(); if (opponentHistory != null) { reaction = opponentHistory.PreviousDecision; } return Decision.Distribute( reaction.MostInfluencedHand, Influence); }
IDictionary <Type, IComponent> GetComponentsForRecord(IEntityRecord record) { IDictionary <Type, IComponent> components = null; lock (_keyhole) { if (_records.ContainsKey(record)) { components = _records[record]; } } return(components); }
/// <summary> /// Consume an entity and then do something. /// </summary> void Consume(IEntityRecord entity, Vector2 original, Vector2 target, Action then) { Transformable2D transform = entity.GetComponent<Transformable2D>(); TimeSpan duration = TimeSpan.FromSeconds(0.2); TaskManager.Main .WaitUntil( elapsed => { var t = elapsed / duration.TotalSeconds; var step = Easing.EaseIn(t, EasingType.Cubic); transform.Scale = Vector2.Lerp(original, target, step); return t >= 1; }) .Then(then); }
/// <summary> /// Returns a component of the specified type if it is attached to the entity. /// </summary> public IComponent GetComponent(IEntityRecord entity, Type componentType) { if (entity == null || componentType == null) { return(null); } IDictionary <Type, IComponent> components = GetComponentsForRecord(entity); IComponent result = null; if (components != null && components.Count > 0) { if (components.ContainsKey(componentType)) { result = components[componentType]; } } return(result); }
void CreateSquad(SpriteBatch spriteBatch) { Entity.Define("squad-unit", typeof(Health)); Texture unitTexture = Texture.FromFile("Content/Graphics/unit.png"); _squadLeader = CreateSquadUnit("leader", _dungeon, new Vector2(unitTexture.Width * (DungeonColumns / 2), 0)); _squadLeader.Add( new SquadLeader() { MovementInPixels = unitTexture.Width }); IEntityRecord squadUnitLeft = CreateSquadUnit("left", _squadLeader, new Vector2(-unitTexture.Width, -unitTexture.Width)); IEntityRecord squadUnitRight = CreateSquadUnit("right", _squadLeader, new Vector2(unitTexture.Width, -unitTexture.Width)); IEntityRecord squadUnitMiddle = CreateSquadUnit("middle", _squadLeader, new Vector2(0, -unitTexture.Width)); spriteBatch.Add(_squadLeader.GetComponent<Sprite>()); spriteBatch.Add(squadUnitLeft.GetComponent<Sprite>()); spriteBatch.Add(squadUnitRight.GetComponent<Sprite>()); spriteBatch.Add(squadUnitMiddle.GetComponent<Sprite>()); }
void CreateSharedEntities() { _world = Entity.Create(Entities.Shared.World, new Transformable2D()); Entity.Create(Entities.Shared.Tasks, new TaskManager()); Entity.Create(Entities.Shared.Sprites, new SpriteBatch()); }
void CreateTheDungeon(SpriteBatch spriteBatch) { _dungeon = Entity.Create(Entities.Game.Dungeon, new Transformable2D() { Position = new Vector2( -(GameContext.Bounds.Width / 2), -(GameContext.Bounds.Height / 2)) }); SpriteGridSettings gridSettings = new SpriteGridSettings() { SpriteBatch = spriteBatch, Columns = DungeonColumns, Rows = DungeonRows }; gridSettings.Layer = 0; Entity.Create(Entities.Game.DungeonFloor, new Transformable2D() { Parent = _dungeon.GetComponent<Transformable2D>() }, new SpriteGrid(gridSettings) { Texture = Texture.FromFile("Content/Graphics/floor.png") } ); string dungeonWallsMap = "11111011111" + "10000000001" + "10000000001" + "10000000001" + "10001000001" + "10001000001" + "10111110001" + "10001100001" + "10002000001" + "10000000001" + "10000000011" + "10000021111" + "10000000011" + "10000000001" + "10000000021" + "11000000011"; gridSettings.Layer = 1; Entity.Create(Entities.Game.DungeonWalls, new Transformable2D() { Parent = _dungeon.GetComponent<Transformable2D>() }, new MappedSpriteGrid(gridSettings, dungeonWallsMap) { Textures = new Texture[] { Texture.FromFile("Content/Graphics/wall.png"), // #1 Texture.FromFile("Content/Graphics/wall-broken.png") // #2 } } ); string dungeonEnemiesMap = "00000000000" + "00001111000" + "00000100000" + "00000000000" + "00010000000" + "00000010000" + "01000000000" + "01100010000" + "00000100000" + "00011100000" + "00000000000" + "00000000000" + "00000001100" + "00000000000" + "00000000000" + "00000000000"; Entity.Create(Entities.Game.DungeonEnemies, new Transformable2D() { Parent = _dungeon.GetComponent<Transformable2D>() }, new MappedSpriteGrid(gridSettings, dungeonEnemiesMap) { Texture = Texture.FromFile("Content/Graphics/enemy.png") } ); }
/// <summary> /// Attempts to inject a component into a field, and adds the component to the specified entity. /// </summary> /// <remarks> /// > Note that the dependency will remain, even if it becomes dettached from its entity. /// </remarks> void InjectDependency(FieldInfo field, IEntityRecord record, bool allowingDerivedTypes) { if (field == null || record == null) { return; } Type componentType = field.FieldType; IComponent dependency = record.Registry.GetComponent(record, componentType, allowingDerivedTypes); if (dependency == null) { dependency = Create(componentType); record.Add(dependency); } if (dependency != null) { field.SetValue(this, dependency); } }
public SensorEventArgs(IEntityRecord record) { Other = record; }
/// <summary> /// Reacts on an opponent's decision by always picking a losing hand. /// </summary> public override Decision React(IEntityRecord opponent, Decision decision) { return Decision.Loss( decision, Influence); }
bool Select(string entityName) { _selectedEntity = Entity.Find(entityName); WriteInfo(String.Format("{0} selected: {1}", OutputSymbol, _selectedEntity == null ? "nothing" : _selectedEntity.ToString())); if (_selectedEntity != null) { return true; } return false; }
bool Remove(string entityName) { if (!string.IsNullOrEmpty(entityName)) { if (_selectedEntity != null && _selectedEntity.Name.Equals(entityName)) { _selectedEntity = null; } if (Entity.Drop(entityName)) { return true; } else { WriteWarning(String.Format("{0} that entity was not removed", OutputSymbol)); } } else { if (_selectedEntity != null) { return Remove(_selectedEntity.Name); } } return false; }
IEntityRecord CreateSquadUnit(string name, IEntityRecord parent, Vector2 formationPosition) { IEntityRecord squadUnit = Entity.CreateFromDefinition("squad-unit", String.Format("{0}~{1}", Entities.Game.Squad, name), new Transformable2D() { Parent = parent.GetComponent<Transformable2D>(), Position = formationPosition }, new Sprite() { Layer = 2, Texture = Texture.FromFile("Content/Graphics/unit.png") }); return squadUnit; }
/// <summary> /// Make entity appear at destination after being consumed by portal. /// </summary> void Eject(IEntityRecord entity, Vector2 original, Vector2 target) { if (!_entitiesBeingTeleported.Contains(entity)) { return; } Transformable2D transform = entity.GetComponent<Transformable2D>(); TimeSpan duration = TimeSpan.FromSeconds(0.2); transform.Position = Destination.Position; TaskManager.Main .WaitUntil( elapsed => { var t = elapsed / duration.TotalSeconds; var step = Easing.EaseOut(t, EasingType.Cubic); transform.Scale = Vector2.Lerp(original, target, step); return t >= 1; }) .Then( () => { transform.Scale = target; _entitiesBeingTeleported.Remove(entity); }); }
private void OnHit(IEntityRecord entity) { if (EntityHit != null) EntityHit(this, new SensorEventArgs(entity)); }
public EntityEventArgs(IEntityRecord entity) { Record = entity; }
public ComponentStateEventArgs(IEntityRecord entity) : base(entity) { }
public abstract Decision Decide(IEntityRecord opponent);
public abstract Decision React(IEntityRecord opponent, Decision decision);
public void Annotate(IEntityRecord entity, string annotation) { Annotations.Add(annotation, entity); }
static string GetInspectableEntityName(IEntityRecord entity) { return String.Format("{0}{1}", entity.Name, EntityNamingSuffix); }
public ComponentStateEventArgs(IEntityRecord entity, IEntityRecord previousEntity) : base(entity) { PreviousRecord = previousEntity; }
/// <summary> /// Teleport entity to portal destination. /// </summary> void Teleport(IEntityRecord entity) { if (_entitiesBeingTeleported.Contains(entity)) { return; } _entitiesBeingTeleported.Add(entity); Transformable2D transform = entity.GetComponent<Transformable2D>(); Vector2 originalScale = new Vector2(transform.Scale.X); Vector2 targetScale = Vector2.Zero; Consume(entity, originalScale, targetScale, () => { Eject(entity, targetScale, originalScale); }); }