/// <summary> /// Dispatch an action /// </summary> /// <param name="action"></param> public async Task Dispatch(IAction <TActionType> action) { await Task.Factory.StartNew(() => { var targetReducer = _reducers.GetValueOrDefault(action.Type, null); if (targetReducer.IsDefault()) { _errorHandler(States.LastOrDefault().Key, action, new Exception($"Failed to find a reducer for action type: {action.Type}")); throw new ReducerMatchException <TActionType>(action.Type); } TState updatedState; try { // Update the state updatedState = targetReducer(CurrentState, action); } catch (Exception e) { _errorHandler(States.LastOrDefault().Key, action, e); throw; } // Run updated state through middleware updatedState = _middleware(updatedState); // Add new state to list of states States = States.Add(new KeyValuePair <TState, DateTime>(updatedState, DateTime.Now)).TakeLast(StatesCountLimit).ToImmutableList(); // Set the current state CurrentState = States.Last().Key; EventHandler(this, CurrentState); }); }
public object GetState(Type type) { using (Logger.BeginScope(nameof(GetState))) { var typeName = type.FullName; Logger.LogDebug($"{DebugName}: {nameof(this.GetState)} typeName: {typeName}"); if (!States.TryGetValue(typeName, out var state)) { Logger.LogDebug($"{DebugName}: Creating State of type: {typeName}"); state = (IState)Activator.CreateInstance(type); States.Add(typeName, state); } else { Logger.LogDebug($"{DebugName}: State exists: {state.Guid}"); } return(state); } }
public fmCOrderManageDocSM() { StateExecution = new State(this, fmIOrderManageDocStatus.Execution); IState StateAcceptMaker = new State(this, fmIOrderManageDocStatus.AcceptMaker); IState StateAcceptPlanDepartment = new State(this, fmIOrderManageDocStatus.AcceptPlanDepartment); IState StateAcceptAccountDepartment = new State(this, fmIOrderManageDocStatus.AcceptAccountDepartment); IState StateRejected = new State(this, fmIOrderManageDocStatus.Rejected); StateExecution.Transitions.Add(new Transition(StateAcceptMaker, "Утвердить", 1)); StateExecution.Transitions.Add(new Transition(StateRejected, "Отклонить", 2)); StateAcceptMaker.Transitions.Add(new Transition(StateExecution, "Доработать", 1)); StateAcceptMaker.Transitions.Add(new Transition(StateAcceptPlanDepartment, "Утвердить", 2)); StateAcceptMaker.Transitions.Add(new Transition(StateRejected, "Отклонить", 3)); StateAcceptPlanDepartment.Transitions.Add(new Transition(StateAcceptAccountDepartment, "Утвердить", 1)); StateAcceptPlanDepartment.Transitions.Add(new Transition(StateAcceptMaker, "Вернуть", 2)); States.Add(StateExecution); States.Add(StateAcceptMaker); States.Add(StateAcceptPlanDepartment); States.Add(StateAcceptAccountDepartment); States.Add(StateRejected); }
protected override void AddStates() { path = new List <Node>(); EntityState idle = new EntityState(new SpriteAnimation(Assets.Worker, 1, 5, true, 160)); idle.OnStateEnd += delegate { PickState(); }; EntityState wander = new EntityState(new SpriteAnimation(Assets.Worker_Walk, 4, 8, true, 160)); wander.OnStateBegin += delegate { Velocity = new Vector2(RNGMachine.Instance.Generator.Next(-16, 17), RNGMachine.Instance.Generator.Next(-16, 17)); }; wander.OnStateUpdate += Wander_OnUpdate; wander.OnStateEnd += delegate { Velocity = Vector2.Zero; SetState("Idle"); }; EntityState tracingPath = new EntityState(new SpriteAnimation(Assets.Worker_Walk, 4, 8, true)); tracingPath.OnStateUpdate += delegate { TracePath(); }; tracingPath.OnStateEnd += delegate { Velocity = Vector2.Zero; SetState("Idle"); }; States.Add("Idle", idle); States.Add("Wander", wander); States.Add("TracingPath", tracingPath); }
/// <summary> /// Adds the state. /// </summary> /// <param name="id"> The id. </param> /// <param name="state"> The state. </param> /// <param name="line"> </param> /// <param name="shape"> </param> /// <param name="nodosEstado"> </param> public void AddState(int id, string state, string line, string shape, int nodosEstado) { var s = new State { Id = id, Name = state, Line = line, Shape = shape }; if (s.IsInternalState()) { Logger.Debug(string.Format("Adding State {0}", state)); States.Add(nodosEstado + id, new State { Id = nodosEstado + id, Name = string.Format("PendientePublicar {0}", state), Line = line, Shape = shape }); Logger.Debug(string.Format("Adding State {0}", state)); States.Add(id, s); } else { Logger.Debug(string.Format("Adding State {0}", state)); States.Add(id, s); } }
private void CreateState() { if (!CanCreateState()) { return; } StateModel state = new StateModel { StateName = "", NamedColor = NamedColor.All.FirstOrDefault(x => x.Name == "Gray"), }; States.Add(state); if (!IsNewCategory) { state.CategoryID = Category.CategoryID; IsUpdated = true; } SaveChanges(); }
/// <summary> /// Creates a state by a given unique id. /// </summary> /// <param name="stateId">The unique state id.</param> /// <param name="isStartState">True, if the new state is the starting state.</param> /// <param name="isAcceptState">True, if the new state is an accepting state.</param> /// <returns>The newly created state.</returns> public IState CreateState(string stateId, bool isStartState = false, bool isAcceptState = false) { if (stateId == null) { throw new ArgumentNullException(nameof(stateId), "The state id can not be null!"); } var state = GetState(stateId); if (state != null) { throw new Exception("A state with this id already exists!"); } state = InstantiateState(stateId, isStartState, isAcceptState); if (States.Add(state)) { OnStateAdd?.Invoke(this, new StateEventArgs(state)); } return(state); }
protected override void SetDeath(Unit killer) { Health = 0; States.Add((byte)CreatureState.Dead); // Death State PacketOut Out = new PacketOut((byte)Opcodes.F_OBJECT_DEATH, 12); Out.WriteUInt16(Oid); Out.WriteByte(1); Out.WriteByte(0); Out.WriteUInt16(killer.IsPet() ? killer.GetPet().Owner.Oid : killer.Oid); Out.Fill(0, 6); DispatchPacket(Out, true); AbtInterface.Cancel(true); ScrInterface.OnDie(this); BuffInterface.RemoveBuffsOnDeath(); EvtInterface.Notify(EventName.OnDie, this, killer); AiInterface.ProcessCombatEnd(); EvtInterface.AddEvent(RezUnit, 10000, 1); // Clear the object in 10 seconds. if (_ownerUILinked) { SendPetRemove(true); IPetCareerInterface petInterface = Owner.CrrInterface as IPetCareerInterface; petInterface?.Notify_PetDown(); _ownerUILinked = false; } }
/// <summary> /// Constructor /// </summary> /// <param name="dev">The spice device</param> public SpiceDefinitions(SpiceDevice dev, SpiceSetup setup) { // Get the variable string var = setup.StatesVariable; string code; Count = 0; // Open the definitions file using (StreamReader sr = new StreamReader(Path.Combine(dev.Folder, dev.Def))) code = sr.ReadToEnd(); // Find all the states Regex r = new Regex($@"#define\s*(?<name>\w+)\s*{setup.StatesVariable}\s*\+\s*(?<offset>\d+)"); var ms = r.Matches(code); foreach (Match m in ms) { int offset = Convert.ToInt32(m.Groups["offset"].Value); States.Add(new Tuple <int, string>(offset, m.Groups["name"].Value)); StateNames.Add(m.Groups["name"].Value); Count = Math.Max(Count, offset + 1); } }
/// <summary> /// Creates a new finite automata with the given parameters. /// </summary> /// <param name="alphabet">The alphabet of the new automata.</param> /// <param name="states">The list of states of the new automata.</param> /// <param name="startState">The start state of the new automata.</param> /// <param name="transitions">The list of transitions of the new automata.</param> /// <param name="acceptingStates">The list of accepting transitions of the new automata.</param> public FiniteAutomata(IAlphabet alphabet, IEnumerable <IState> states, IState startState, IEnumerable <IStateTransition> transitions, IEnumerable <IState> acceptingStates) { if (states == null) { throw new ArgumentNullException(nameof(states), "The state list can not be null!"); } if (startState == null) { throw new ArgumentNullException(nameof(startState), "The start state can not be null!"); } if (transitions == null) { throw new ArgumentNullException(nameof(transitions), "The transition list can not be null!"); } if (acceptingStates == null) { throw new ArgumentNullException(nameof(acceptingStates), "The accepting state list can not be null!"); } Alphabet = alphabet ?? throw new ArgumentNullException(nameof(alphabet), "The alphabet can not be null!"); startState.IsStartState = true; States.UnionWith(states); States.Add(startState); foreach (var state in acceptingStates) { state.IsAcceptState = true; } Transitions.UnionWith(transitions); }
public OrderCreateModel(string id, string number, UserListModel customer, DateTime createdDate, IEnumerable <OrderDetailModel> details, DeliveryPlaceOptions deliveryPlace, DateTime?deliveryPredicateAt, DateTime?deliveryAt, StateOptions state, string comment) : this() { Id = id; Number = number; Customer = customer; CreatedDate = createdDate.ToRelativeDate(); Details = details; DeliveryPlaceId = ((int)deliveryPlace).ToString(); DeliveryPredicateAt = deliveryPredicateAt; DeliveryAt = deliveryAt; StateId = ((int)state).ToString(); Comment = comment; foreach (DeliveryPlaceOptions options in Enum.GetValues(typeof(DeliveryPlaceOptions))) { Places.Add ( new EnumModel ( ((int)options).ToString(), options.ToString().Replace("_", " ") ) ); } foreach (StateOptions options in Enum.GetValues(typeof(StateOptions))) { States.Add ( new EnumModel ( ((int)options).ToString(), options.ToString().Replace("_", " ") ) ); } }
private Node getOrCreateNodeClosure(Node nodeFrom, List <Node> stateList) { var closure = States.FirstOrDefault(n => n.verifyIfStatesIsEqual(stateList)); if (closure == null) { bool isFinal = false; // É final ? if (stateList.FirstOrDefault(n => n.End) != null) { isFinal = true; } var newClosure = new Closure(nodeFrom, stateList, String.Format("S{0}", _closureCount++)); States.Add(newClosure); NewStates.Add(newClosure); var newNode = new Node(_nodeCount++, newClosure.Name, false, isFinal); _nodes.Add(newNode); return(newNode); } return(_nodes.First(q => q.Value == closure.Name)); }
/// <summary> /// 引数の状態を更新しカレント状態とする /// </summary> /// <param name="newState"></param> private static void AddNewState(State newState) { //次の状態を取得 State nextState = CurrentState?.NextState; //次の状態があれば、排除する if (nextState != null) { EliminateStates(nextState); } /***状態を新しく更新***/ CurrentState.NextState = newState; //現在の状態のRedo = 次の状態のUndo //は同じもの!!! CurrentState.NextCommand = newState.PrevCommand; //現在の状態は次の状態の前の状態にあたる newState.PrevState = CurrentState; States.Add(newState); //次の状態をカレント状態とする CurrentStateIndex = States.IndexOf(newState); }
private void ReadElementChildNodes(XmlElement animationMapElement) { foreach (var node in animationMapElement.ChildNodes) { var element = node as XmlElement; if (element == null) { continue; } if (element.Name == ANIMATION_STATE) { AnimationStateReader stateReader = new AnimationStateReader(element); stateReader.Read(); AnimationState state = new AnimationState( stateReader.StateName, stateReader.StepActions, AnimationStateLoopType.Cycle); States.Add(stateReader.StateName, state); } } }
public void PanelInitialize(FSMSystem fsmSystem, bool autoGUISetActive, AbstractFSMState state) { AutoGUISetActive = autoGUISetActive; if (FsmSystem != null) { if (FsmSystem != fsmSystem) { log.Error(_Logger.User.Msaw, "Trying to register panel in more than one states that are in different FsmSystems. This is currently not tested and shouldn't be done."); } } FsmSystem = fsmSystem; if (States == null) { States = new List <AbstractFSMState>(); } States.Add(state); State = state; //GUIPanel = this.GetComponent<UIPanel>(); //if (GUIPanel != null && AutoGUISetActive == true) //{ SetPanelActive(false); //} OnInitialize(); }
public VertexPointTool() { _vertices = new ConcurrentDictionary <VertexSolid, VertexList>(); States.Add(new WrapperDraggableState(GetDraggables)); _boxState = new BoxDraggableState(this) { RenderBoxText = false, BoxColour = Color.Orange, FillColour = Color.FromArgb(64, Color.DodgerBlue) }; _boxState.DragStarted += (sender, args) => { if (!KeyboardState.Ctrl) { DeselectAll(); } }; States.Add(_boxState); _showPoints = VisiblePoints.All; }
public ClaimTrxsStateMachine(IObjectSpace objectSpace) : base(objectSpace) { startState = new DevExpress.ExpressApp.StateMachine.NonPersistent.State(this, "Not Applicable", ApprovalStatuses.Not_Applicable); IState Required_Approval = new DevExpress.ExpressApp.StateMachine.NonPersistent.State(this, "Required Approval", ApprovalStatuses.Required_Approval); IState Approved = new DevExpress.ExpressApp.StateMachine.NonPersistent.State(this, "Approved", ApprovalStatuses.Approved); IState Rejected = new DevExpress.ExpressApp.StateMachine.NonPersistent.State(this, "Rejected", ApprovalStatuses.Rejected); //startState.Transitions.Add(new Transition(Required_Approval)); Required_Approval.Transitions.Add(new Transition(Required_Approval)); Required_Approval.Transitions.Add(new Transition(Rejected)); Required_Approval.Transitions.Add(new Transition(Approved)); //States.Add(startState); States.Add(Required_Approval); States.Add(Approved); States.Add(Rejected); StateAppearance NAAppearance = new StateAppearance(startState); NAAppearance.TargetItems = "ApprovalStatus"; //NAAppearance.Enabled = false; NAAppearance.FontColor = System.Drawing.Color.Red; StateAppearance RequiredAppearance = new StateAppearance(Required_Approval); RequiredAppearance.TargetItems = "ApprovalStatus"; RequiredAppearance.FontColor = System.Drawing.Color.Red; StateAppearance completedAppearance = new StateAppearance(Approved); completedAppearance.TargetItems = "*"; completedAppearance.FontColor = System.Drawing.Color.Green; StateAppearance RejectedAppearance = new StateAppearance(Rejected); RejectedAppearance.TargetItems = "*"; RejectedAppearance.FontColor = System.Drawing.Color.Red; }
public VertexScaleTool() { _vertices = new Dictionary <VertexSolid, VertexList>(); States.Add(new WrapperDraggableState(GetDraggables)); _boxState = new BoxDraggableState(this) { RenderBoxText = false, BoxColour = Color.Orange, FillColour = Color.FromArgb(64, Color.DodgerBlue) }; _boxState.DragStarted += (sender, args) => { if (!KeyboardState.Ctrl) { DeselectAll(); } }; States.Add(_boxState); _origin = new ScaleOrigin(this); }
public void AddTransition(Transition <T> t) { Transitions.Add(t); States.Add(t.FromState); States.Add(t.ToState); }
/// <summary> /// 添加状态节点 /// </summary> /// <param name="state"></param> public void AddState(State state) { States.Add(state.Name, state); Tags.Add(state.Name); state.Initiate(this); }
public TimeMachineState(object initialState) : this() { States = States.Add(initialState); }
private void AddState(StateItemViewModel state) { state.PropertyChanged += (o, ea) => PropertyChanged?.Invoke(this, ea); state.StateChanged += (o, ea) => LastState = States.LastOrDefault(p => p.Value.IsDone).Value; States.Add(state.Name, state); }
public bool AddState(State newState, ParsingOperation op) { var addedToStates = false; var addedToCompletedViterbi = false; State oldState; var oldOrNewState = false; var isCompleted = newState.IsCompleted(); //step 1: check in states dictionary //if does not exist, add. otherwise, merge. if (!StatesDictionary.TryGetValue(newState, out oldState)) { StatesDictionary.Add(newState, newState); newState.EndColumn = this; States.Add(newState); addedToStates = true; } else { if (op != ParsingOperation.Scan) { //the state is already present, modulo the stack. we need to share stacks: Merge(oldState, newState); //merging into the old state. oldOrNewState = true; //inner probability of completed, but not predicted, item changes upon merge //(see stolcke 1995) if (oldState.Node != null && op == ParsingOperation.Complete) { oldState.Node.LogProbability = Grammar.GetProbabilitySumOfTwoLogProbabilities(oldState.Node.LogProbability, newState.Node.LogProbability); if (oldState.Node.LogProbability < 0) { throw new Exception( string.Format( "case2: impossible probability resulted from summation of two log probabilities {0},", oldState.Node.LogProbability)); } } } else { throw new Exception("scan - identical states - not supposed to happen?!?"); } } //step 2: if completed, check in completed dictionary. //if does not exist, add. otherwise, replace with old state. if (isCompleted) { var stateTocheck = oldOrNewState ? oldState : newState; State oldStateViterbi; if (!StateViterbiCompletedDictionary.TryGetValue(stateTocheck, out oldStateViterbi)) { StateViterbiCompletedDictionary.Add(stateTocheck, stateTocheck); addedToCompletedViterbi = true; } else { if (stateTocheck.Node.LogProbability < oldStateViterbi.Node.LogProbability) { oldStateViterbi.Node = stateTocheck.Node; if (oldStateViterbi.Node.LogProbability < 0) { throw new LogException( string.Format( "columnarrr! NODE log probability lower than 0: {0}, reductor state: {1}", oldStateViterbi.Node.LogProbability, oldStateViterbi)); } if (debug) { Console.WriteLine("state {0} has higher probability than state {1}. ", stateTocheck.StateNumber, oldStateViterbi.StateNumber); } } } } var finalAdd = false; //step 3: determine whether the state needs to be added to the agendas. if (!isCompleted && addedToStates) { ActionableNonCompleteStates.Enqueue(newState); var term = newState.NextProductionTerm(); //check if the next nonterminal leads to an expansion of null production, if yes, insert it to the //completed rules. //initially just check if the next nonterminal is nullable production if (grammar.nullableProductions.ContainsKey(term)) { //spontaneous dot shift. EpsilonComplete(newState); } finalAdd = true; } else if (isCompleted && addedToCompletedViterbi) { //note: it is possible that a new state has been added to the state dictionary //but it is not added to the viterbi completed state dictionary. //in such a case, do not push the item to the agenda. //with the same LHS side if (!ActionableCompleteStates.ContainsKey(newState)) { ActionableCompleteStates[newState] = new Queue <State>(); } ActionableCompleteStates[newState].Enqueue(newState); finalAdd = true; } return(finalAdd); }
/// <summary> /// Advance the game by one turn /// </summary> public void Step() { if (IsGameOver) { return; } //Check for win condition if (States.Count == Rules.TurnLimit || m_currentState.Teams.Any(t => t.FlagCaptures == Rules.FlagLimit)) { var winningTeam = m_currentState.Teams.OrderByDescending(t => t.FlagCaptures).ThenByDescending(t => t.Kills).FirstOrDefault(); if (States.Count == Rules.TurnLimit) { GameEndReason = "Turn limit reached"; } else if (m_currentState.Teams.Any(t => t.FlagCaptures == Rules.FlagLimit)) { GameEndReason = string.Format("AI {0} ({1}) reached the flag capture limit", winningTeam.Name, winningTeam.Id); } m_currentState.Events.Add(GameEndReason); WinningTeam = winningTeam.Id; return; } IDictionary <int, Ship> masterShips = m_currentState.Teams.SelectMany(t => t.Ships).ToDictionary(s => s.Id); IDictionary <int, Team> masterTeams = m_currentState.Teams.ToDictionary(t => t.Id); IDictionary <int, CtfGameState> updates = new Dictionary <int, CtfGameState>(); HashSet <int> deadProjectiles = new HashSet <int>(); //Resolve collisions foreach (var team in masterTeams.Values) { foreach (var projectile in team.Projectiles) { if (deadProjectiles.Contains(projectile.Id)) { //Check if this projectile was previously hit by another projectile continue; } //Remove projectiles that go out of bounts if (projectile.Position.Length() > Rules.ArenaRadius) { deadProjectiles.Add(projectile.Id); continue; } foreach (var enemyTeam in masterTeams.Values) { if (team.Id == enemyTeam.Id) { continue; } foreach (var enemyShip in enemyTeam.Ships) { if (enemyShip.Bounds.Intersects(projectile.Bounds)) { string killLog = string.Format("{0}'s ship ({1}) was killed by {2}'s ship ({3})", enemyTeam.Name, enemyShip.Id, team.Name, masterShips[projectile.FiredBy].Id); m_currentState.Events.Add(killLog); //Ship hit deadProjectiles.Add(projectile.Id); enemyShip.Position = SpawnPositions[enemyShip.Id]; team.Kills++; //Reset flag position if the killed ship was holding a flag foreach (var t in masterTeams.Values) { if (t.Flag.HeldBy == enemyShip.Id) { string dropLog = string.Format("{0}'s flag was dropped by {1}'s ship ({2}) after it was killed", masterTeams[t.Flag.Owner].Name, enemyTeam.Name, enemyShip.Id); m_currentState.Events.Add(dropLog); t.Flag.HeldBy = null; t.Flag.Position = SpawnPositions[team.Flag.Id]; } } continue; } } if (deadProjectiles.Contains(projectile.Id)) { continue; } foreach (var enemyProjectile in enemyTeam.Projectiles) { //check projectile vs projectile if (enemyProjectile.Bounds.Intersects(projectile.Bounds)) { string collideLog = string.Format("{0}'s projectile ({1}) collided with {2}'s projectile ({3})", team.Name, projectile.Id, enemyTeam.Name, enemyProjectile.Id); m_currentState.Events.Add(collideLog); deadProjectiles.Add(enemyProjectile.Id); deadProjectiles.Add(projectile.Id); continue; } } if (deadProjectiles.Contains(projectile.Id)) { continue; } } if (deadProjectiles.Contains(projectile.Id)) { continue; } } //Remove dead projectiles team.Projectiles = team.Projectiles.Where(p => !deadProjectiles.Contains(p.Id)).ToList(); } //Check flag captures foreach (var team in masterTeams.Values) { //If the team's flag is captured... if (team.Flag.HeldBy != null) { var holder = masterShips[team.Flag.HeldBy.Value]; team.Flag.Position = holder.Position; var holderTeam = masterTeams[holder.Owner]; //If the flag's captor has brought the flag back to their team's base and their flag is there... if (holderTeam.Flag.HeldBy == null && holderTeam.Flag.Bounds.Intersects(team.Flag.Bounds)) { string capLog = string.Format("{0}'s flag has been captured by {1}'s ship ({2})", team.Name, holderTeam.Name, holder.Id); m_currentState.Events.Add(capLog); //Flag is captured! holderTeam.FlagCaptures++; //Reset flag team.Flag.HeldBy = null; team.Flag.Position = SpawnPositions[team.Flag.Id]; } } else { //If team's flag isn't captured... foreach (var enemyTeam in masterTeams.Values) { if (enemyTeam.Id == team.Id) { continue; } //Check if any enemy ships are intersecting it foreach (var ship in enemyTeam.Ships) { //Enemy pickup flag if (ship.Bounds.Intersects(team.Flag.Bounds)) { string pickupLog = string.Format("{0}'s flag has been taken by {1}'s ship ({2})", team.Name, enemyTeam.Name, ship.Id); m_currentState.Events.Add(pickupLog); team.Flag.HeldBy = ship.Id; break; } } if (team.Flag.HeldBy != null) { break; } } } } //AI Act foreach (var ai in m_ais) { var aiStateCopy = m_currentState.Clone(); try { //Pass game state to each AI ai.Value.Update(aiStateCopy, aiStateCopy.Teams.First(t => t.Id == ai.Key), aiStateCopy.Teams.Where(t => t.Id != ai.Key).ToList()); } catch { } updates[ai.Key] = aiStateCopy; } //Apply updates foreach (var update in updates) { var aiStateCopy = update.Value; var aiId = update.Key; var team = aiStateCopy.Teams.FirstOrDefault(t => t.Id == aiId); if (team != null) { if (team.Ships != null) { foreach (var updatedShip in team.Ships) { Ship masterShip = null; if (masterShips.TryGetValue(updatedShip.Id, out masterShip)) { if (masterShip.Owner == aiId) { //Copy across updates from cloned state masterShip.SetLabel(updatedShip.Label); masterShip.SetThrust(updatedShip.Thrust); masterShip.SetTorque(updatedShip.Torque); if (updatedShip.IsFiring) { masterShip.Fire(); } else { masterShip.StopFiring(); } } } } } } } //Step firing foreach (var ship in masterShips.Values) { if (ship.IsFiring) { int lastFireTurn = m_lastFireTurns[ship.Id]; //Check the firing isn't on cooldown if (m_currentState.TurnNumber - lastFireTurn > Rules.FireCooldown) { m_lastFireTurns[ship.Id] = m_currentState.TurnNumber; var team = masterTeams[ship.Owner]; //Fire a projectile in the direction the ship is facing team.Projectiles.Add(new Projectile() { Bounds = new BoundingCircle(ship.Position, Rules.ProjectileRadius), FiredBy = ship.Id, Owner = team.Id, Velocity = Vector2.FromPolar(Rules.ProjectileVelocity, ship.Rotation) }); } } } //Step physics m_currentState = Step(m_currentState); States.Add(m_currentState); }
private void CreateDspObjects() { Debug.Console(2, "Creating DSP Objects"); var props = JsonConvert.DeserializeObject <TesiraDspPropertiesConfig>(_dc.Properties.ToString()); if (props == null) { return; } Debug.Console(2, this, "Props Exists"); Debug.Console(2, this, "Here's the props string\n {0}", _dc.Properties.ToString()); Faders.Clear(); Presets.Clear(); Dialers.Clear(); States.Clear(); Switchers.Clear(); ControlPointList.Clear(); Meters.Clear(); RoomCombiners.Clear(); if (props.FaderControlBlocks != null) { Debug.Console(2, this, "levelControlBlocks is not null - There are {0} of them", props.FaderControlBlocks.Count()); foreach (var block in props.FaderControlBlocks) { var key = block.Key; Debug.Console(2, this, "LevelControlBlock Key - {0}", key); var value = block.Value; Faders.Add(key, new TesiraDspFaderControl(key, value, this)); Debug.Console(2, this, "Added LevelControlPoint {0} LevelTag: {1} MuteTag: {2}", key, value.LevelInstanceTag, value.MuteInstanceTag); if (block.Value.Enabled) { //Add ControlPoint to the list for the watchdog ControlPointList.Add(Faders[key]); } } } if (props.SwitcherControlBlocks != null) { Debug.Console(2, this, "switcherControlBlocks is not null - There are {0} of them", props.FaderControlBlocks.Count()); foreach (var block in props.SwitcherControlBlocks) { var key = block.Key; Debug.Console(2, this, "SwitcherControlBlock Key - {0}", key); var value = block.Value; Switchers.Add(key, new TesiraDspSwitcher(key, value, this)); Debug.Console(2, this, "Added TesiraSwitcher {0} InstanceTag {1}", key, value.SwitcherInstanceTag); if (block.Value.Enabled) { //Add ControlPoint to the list for the watchdog ControlPointList.Add(Switchers[key]); } } } if (props.DialerControlBlocks != null) { Debug.Console(2, this, "DialerControlBlocks is not null - There are {0} of them", props.DialerControlBlocks.Count()); foreach (var block in props.DialerControlBlocks) { var key = block.Key; Debug.Console(2, this, "LevelControlBlock Key - {0}", key); var value = block.Value; Dialers.Add(key, new TesiraDspDialer(key, value, this)); Debug.Console(2, this, "Added DspDialer {0} ControlStatusTag: {1} DialerTag: {2}", key, value.ControlStatusInstanceTag, value.DialerInstanceTag); if (block.Value.Enabled) { ControlPointList.Add(Dialers[key]); } } } if (props.StateControlBlocks != null) { Debug.Console(2, this, "stateControlBlocks is not null - There are {0} of them", props.StateControlBlocks.Count()); foreach (var block in props.StateControlBlocks) { var key = block.Key; var value = block.Value; States.Add(key, new TesiraDspStateControl(key, value, this)); Debug.Console(2, this, "Added DspState {0} InstanceTag: {1}", key, value.StateInstanceTag); if (block.Value.Enabled) { ControlPointList.Add(States[key]); } } } if (props.Presets != null) { foreach (var preset in props.Presets) { var value = preset.Value; var key = preset.Key; Presets.Add(key, value); Debug.Console(2, this, "Added Preset {0} {1}", value.Label, value.PresetName); } } if (props.MeterControlBlocks != null) { foreach (var meter in props.MeterControlBlocks) { var key = meter.Key; var value = meter.Value; Meters.Add(key, new TesiraDspMeter(key, value, this)); Debug.Console(2, this, "Adding Meter {0} InstanceTag: {1}", key, value.MeterInstanceTag); if (value.Enabled) { ControlPointList.Add(Meters[key]); } } } if (props.CrosspointStateControlBlocks != null) { foreach (var mixer in props.CrosspointStateControlBlocks) { var key = mixer.Key; var value = mixer.Value; CrosspointStates.Add(key, new TesiraDspCrosspointState(key, value, this)); Debug.Console(2, this, "Adding Mixer {0} InstanceTag: {1}", key, value.MatrixInstanceTag); if (value.Enabled) { ControlPointList.Add(CrosspointStates[key]); } } } if (props.RoomCombinerControlBlocks == null) { return; } foreach (var roomCombiner in props.RoomCombinerControlBlocks) { var key = roomCombiner.Key; var value = roomCombiner.Value; RoomCombiners.Add(key, new TesiraDspRoomCombiner(key, value, this)); Debug.Console(2, this, "Adding Mixer {0} InstanceTag: {1}", key, value.RoomCombinerInstanceTag); if (value.Enabled) { ControlPointList.Add(RoomCombiners[key]); } } //Keep me at the end of this method! DeviceManager.AddDevice(new TesiraDspDeviceInfo(String.Format("{0}--DeviceInfo", Key), String.Format("{0}--DeviceInfo", Name, Presets), this, Presets)); }
public void AddState(State state) { States.Add(state); }
public void AddState(string name, IState State) { States.Add(name, State); }
public override void OnLoad() { InteractType = Spawn.Proto.InteractType; SetFaction(Spawn.Faction != 0 ? Spawn.Faction : Spawn.Proto.Faction); ItmInterface.Load(CreatureService.GetCreatureItems(Spawn.Entry)); if (Spawn.Proto.MinLevel > Spawn.Proto.MaxLevel) { Spawn.Proto.MinLevel = Spawn.Proto.MaxLevel; } if (Spawn.Proto.MaxLevel <= Spawn.Proto.MinLevel) { Spawn.Proto.MaxLevel = Spawn.Proto.MinLevel; } if (Spawn.Proto.MaxLevel == 0) { Spawn.Proto.MaxLevel = 1; } if (Spawn.Proto.MinLevel == 0) { Spawn.Proto.MinLevel = 1; } if (Spawn.Level != 0) { if (Spawn.Level > 2) { Level = (byte)StaticRandom.Instance.Next(Spawn.Level - 1, Spawn.Level + 1); } else { Level = (byte)StaticRandom.Instance.Next(Spawn.Level, Spawn.Level + 1); } } else { Level = (byte)StaticRandom.Instance.Next(Spawn.Proto.MinLevel, Spawn.Proto.MaxLevel + 1); } SetCreatureStats(); Health = TotalHealth; X = Zone.CalculPin((uint)Spawn.WorldX, true); Y = Zone.CalculPin((uint)Spawn.WorldY, false); Z = (ushort)Spawn.WorldZ; // TODO : Bad Height Formula /*int HeightMap = HeightMapMgr.GetHeight(Zone.ZoneId, X, Y); * if (Z < HeightMap) * { * Log.Error("Creature", "["+Spawn.Entry+"] Invalid Height : Min=" + HeightMap + ",Z=" + Z); * return; * }*/ Heading = (ushort)Spawn.WorldO; WorldPosition.X = Spawn.WorldX; WorldPosition.Y = Spawn.WorldY; WorldPosition.Z = Spawn.WorldZ; SetOffset((ushort)(Spawn.WorldX >> 12), (ushort)(Spawn.WorldY >> 12)); ScrInterface.AddScript(Spawn.Proto.ScriptName); SaveSpawnData(); LoadInterfaces(); AiInterface.SetBrain(new DummyBrain(this)); States.Add(0x12); States.Add((byte)CreatureState.UnkOmnipresent); Speed = 350; StsInterface.Speed = 350; MvtInterface.SetBaseSpeed(Speed); MvtInterface.FollowReacquisitionInterval = 100; IsActive = true; }
/// <summary> /// Add a new state to the statemachine /// </summary> /// <param name="id"></param> /// <param name="state"></param> public void Add(K id, State <K, T> state) { States.Add(id, state); state.Init(id, this, Parent); }
public NFA Construction() { Token token = tokens.ElementAt(indexToken); State rootState = new State(indexState.ToString()); States.Add(rootState); Transition rootTransition = new Transition(null, epsilon, rootState); NFA rootNFA = new NFA(rootTransition, rootTransition); Transitions.Add(rootTransition); switch (token.TypeToken) { case Token.Type.CONCATENATION_SIGN: indexToken++; indexState++; NFA n1C = Construction(); indexToken++; indexState++; NFA n2C = Construction(); n1C.Initial.From = rootNFA.Acceptance.To; n2C.Initial.From = n1C.Acceptance.To; rootTransition.From = rootNFA.Initial.From; rootTransition.To = n1C.Initial.From; rootNFA.Acceptance = n2C.Acceptance; break; case Token.Type.DISJUNCTION_SIGN: indexState++; State s1D = new State(indexState.ToString()); States.Add(s1D); Transition t1D = new Transition(rootState, epsilon, s1D); Transitions.Add(t1D); indexToken++; indexState++; NFA n2D = Construction(); n2D.Initial.From = t1D.To; indexState++; State s3D = new State(indexState.ToString()); States.Add(s3D); Transition t3D = new Transition(rootState, epsilon, s3D); Transitions.Add(t3D); indexToken++; indexState++; NFA n4D = Construction(); n4D.Initial.From = t3D.To; indexState++; State s5D = new State(indexState.ToString()); States.Add(s5D); Transition t25D = new Transition(n2D.Acceptance.To, epsilon, s5D); Transitions.Add(t25D); Transition t45D = new Transition(n4D.Acceptance.To, epsilon, s5D); Transitions.Add(t45D); rootNFA.Initial.To = rootState; rootNFA.Acceptance = new Transition(null, epsilon, t45D.To); break; case Token.Type.ASTERISK_SIGN: indexState++; State s1A = new State(indexState.ToString()); States.Add(s1A); Transition t1A = new Transition(rootState, epsilon, s1A); Transitions.Add(t1A); indexToken++; indexState++; NFA n2A = Construction(); n2A.Initial.From = t1A.To; Transition t21A = new Transition(n2A.Acceptance.To, epsilon, s1A); Transitions.Add(t21A); indexState++; State s3A = new State(indexState.ToString()); States.Add(s3A); Transition t23A = new Transition(n2A.Acceptance.To, epsilon, s3A); Transitions.Add(t23A); Transition t03A = new Transition(rootState, epsilon, s3A); Transitions.Add(t03A); rootNFA.Initial.To = rootState; rootNFA.Acceptance = new Transition(null, epsilon, t03A.To); break; case Token.Type.ID: case Token.Type.NUMBER: case Token.Type.STR: case Token.Type.SYMBOL: case Token.Type.LINE_BREAK: case Token.Type.SINGLE_QUOTE: case Token.Type.DOUBLE_QUOTE: case Token.Type.TABULATION: case Token.Type.EPSILON: rootTransition.Token = token; if (Terminals.Find(t => t.Value == token.Value) == null) { Terminals.Add(token); } // Console.WriteLine(" -> " + rootTransition.Token.Value + " -> " + rootTransition.To.StateName); break; } return(rootNFA); }