Esempio n. 1
0
        /// <summary>
        /// Attaches the collection of behaviors to the specified <see cref="Windows.UI.Xaml.DependencyObject"/>.
        /// </summary>
        /// <param name="associatedObject">The <see cref="Windows.UI.Xaml.DependencyObject"/> to which to attach.</param>
        /// <exception cref="InvalidOperationException">The <see cref="BehaviorCollection"/> is already attached to a different <see cref="Windows.UI.Xaml.DependencyObject"/>.</exception>
        public void Attach(DependencyObject associatedObject)
        {
            if (associatedObject == this.AssociatedObject)
            {
                return;
            }

            if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                return;
            }

            if (this.AssociatedObject != null)
            {
                throw new InvalidOperationException(ResourceHelper.GetString("CannotAttachBehaviorMultipleTimesExceptionMessage"));
            }

            Debug.Assert(associatedObject != null, "The previous checks should keep us from ever setting null here.");
            this.AssociatedObject = associatedObject;

            foreach (DependencyObject item in this)
            {
                IBehavior behavior = (IBehavior)item;
                behavior.Attach(this.AssociatedObject);
            }
        }
        protected override void OnSelectedStatusChangedForTo(IBehavior child, BehaviorStatus oldStatus, BehaviorStatus status)
        {
#if SanityChecks
            if (child != SelectedChild)
            {
                l.Warn("child != SelectedChild");
                return;
            }
#endif

            switch (status)
            {
                //case BehaviorStatus.Uninitialized:
                //    break;
                //case BehaviorStatus.Initialized:
                //    break;
                case BehaviorStatus.Running:
                    // It is running as expected
                    break;
                case BehaviorStatus.Failed:
                    Fail(child.StatusMessage);
                    break;
                case BehaviorStatus.Succeeded:
                    if (Advance() == BehaviorStatus.Succeeded)
                    {
                        Succeed();
                    }
                    break;
                //case BehaviorStatus.Disposed:
                //    break;
                default:
                    l.Warn("UNEXPECTED Sequencer child state: " + child.ToString());
                    break;
            }
        }
Esempio n. 3
0
        public void Run(IEditorApplication context, IBehavior behavior)
        {
            _log = new Log(context, DriverIdent);

            try
            {
                _driverContext = new DriverContext(context, _log, DriverName, false);

                // enter your code which should be executed when starting the SCADA Editor Wizard

                _log.Message("begin test");

                _driverContext.Export(XmlSuffixBefore);

                if (_driverContext.OpenDriver(10))
                {
                    _driverContext.ModifyCommonProperties();
                    _driverContext.ModifyCOMProperties();

                    ModifyOptions();

                    _driverContext.CloseDriver();

                    _driverContext.Export(XmlSuffixAfter);
                    _driverContext.Import(XmlSuffixBefore);
                }

                _log.Message("end test");
            }
            catch (Exception ex)
            {
                _log.ExpectionMessage($"An exception has been thrown: {ex.Message}", ex);
                throw;
            }
        }
Esempio n. 4
0
 public PauseDirective(float duration, IBehavior caller)
 {
     Behavior = caller;
     this.duration = duration;
     this.pause_start = Time.time;
     Priority = 1;
 }
Esempio n. 5
0
        public void Run(IEditorApplication context, IBehavior behavior)
        {
            if (context.Workspace.ActiveProject == null)
            {
                MessageBox.Show("No project is available. Please active a project.");
                return;
            }

            try
            {
                var application = new Application();

                var pageViewModels = new List <IPageViewModel>
                {
                    new WelcomeViewModel <WelcomePage>(),
                    new SelectionListViewModel <SelectionListPage>(context.Workspace.ActiveProject)
                };

                var mainView = new MainView {
                    DataContext = new MainViewModel(pageViewModels)
                };
                application.MainWindow = mainView;
                mainView.Show();
                application.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An exception has been thrown: {ex.Message}");
                throw;
            }
        }
        /// <summary>
        ///   Creates a new <see cref="BehaviorChainConfiguration"/> from this
        ///   template.
        /// </summary>
        // TODO: Comment.
        internal BehaviorChainConfiguration CreateConfiguration(
            IBehaviorFactoryConfiguration factoryConfiguration
            )
        {
            Check.NotNull(factoryConfiguration, nameof(factoryConfiguration));

            var config = new BehaviorChainConfiguration();
            IBehaviorFactory factory = factoryConfiguration.GetFactory(_factoryProvider);

            foreach (BehaviorChainItemTemplate itemTemplate in _itemTemplates)
            {
                BehaviorKey key = itemTemplate.Key;

                if (itemTemplate.State == DefaultBehaviorState.DisabledWithoutFactory)
                {
                    config.Append(key);
                }
                else
                {
                    IBehavior instance = factory.Create(key);
                    config.Append(key, instance);

                    if (itemTemplate.State == DefaultBehaviorState.Enabled)
                    {
                        config.Enable(key);
                    }
                }
            }

            return(config);
        }
Esempio n. 7
0
        public void UpdateBehavior(GameTime g)
        {
            //Simply loop through the list of behaviors, looking for the
            //last behavior which wants to activate. Order matters, so
            //behaviors at the end of the list will always override
            //behaviors before it

            for (int i = 0; i < behaviors.Length; i++)
            {
                if (behaviors[i].ShouldTakeControl())
                {
                    currentBehavior = behaviors[i];
                }
            }

            if (currentBehavior != null && !currentBehavior.Equals(lastBehavior))
            {
                //If we have just changed behaviors, allow the new behavior to run
                //initialization logic
                currentBehavior.Begin();
            }

            if (currentBehavior != null)
            {
                currentBehavior.Act(g);
            }

            lastBehavior = currentBehavior;
        }
Esempio n. 8
0
        private IBehavior HydrateBehavior(string id, bool edit)
        {
            IBehavior behavior = null;
            // find the mapped setting if any
            Settings mappedSetting = LayoutSettings
                                     .Where(setting => setting.PanelID.EqualsIgnoreCase(id))
                                     .FirstOrDefault();

            if (mappedSetting != null)
            {
                behavior = LoadBehaviorControl(mappedSetting.BehaviorControl, edit);
                if (behavior != null &&
                    !string.IsNullOrEmpty(mappedSetting.BehaviorDataRaw))
                {
                    var data = TryHydrateData(behavior.GetType(), mappedSetting.BehaviorDataRaw);

                    // Although we're using generics to have strongly typed Data properties,
                    // Generics unfortunately doesn't support contra-variance for downcasting
                    // the defined template for T in IBehavior<T> eventhough the T will always
                    // a type inherited from IData, we therefore resort to reflection
                    var dataProperty = behavior
                                       .GetType()
                                       .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                       .Where(prop => prop.Name.EqualsIgnoreCase("Data"))
                                       .FirstOrDefault();
                    if (dataProperty != null)
                    {
                        dataProperty.SetValue(behavior, data, new object[] { });
                    }
                }
            }

            return(behavior);
        }
Esempio n. 9
0
 public IBehaviors RemoveBehavior(IBehavior aBehavior)
 {
     CheckArg.Behavior(aBehavior);
     aBehavior.LinkBehaviors(null);
     fList.Remove(aBehavior);
     return(this);
 }
Esempio n. 10
0
        /// <summary>
        /// Called when the <paramref name="child"/> has terminated.
        /// </summary>
        /// <param name="child">The child that has terminated.</param>
        /// <param name="status">The status the <paramref name="child"/> terminated with.</param>
        private void OnChildTerminated(IBehavior child, Status status)
        {
            //Remove from active list.
            child.Terminated -= OnChildTerminated;
            _activeChildren.Remove(child);

            //Check if either policy is reached.
            switch (status)
            {
            case Status.Success:
            {
                _successfulChildren.Add(child);
                if (ValidatePolicy(SuccessPolicy, _successfulChildren))
                {
                    Terminate(Status.Success);
                }

                break;
            }

            case Status.Failure:
            {
                _failedChildren.Add(child);
                if (ValidatePolicy(FailurePolicy, _failedChildren))
                {
                    Terminate(Status.Failure);
                }

                break;
            }
            }
        }
Esempio n. 11
0
        private IBehavior GetBehavior()
        {
            foreach (var behavior in Behaviors)
            {
                if (behavior == _currentBehavior)
                {
                    if (behavior.CanContinue())
                    {
                        return(behavior);
                    }

                    behavior.OnEnd();
                    _currentBehavior = null;
                }

                if (behavior.ShouldStart())
                {
                    if (_currentBehavior == null || Behaviors.IndexOf(_currentBehavior) > Behaviors.IndexOf(behavior))
                    {
                        _currentBehavior?.OnEnd();
                        return(behavior);
                    }
                }
            }

            return(null);
        }
Esempio n. 12
0
        public void ShouldRaiseIfMethodIsNullWhenAddMethod()
        {
            BaseBehavior baseBehavior = new BaseBehavior();
            IBehavior    behavior     = baseBehavior.CreateDelegated();

            behavior.Send("methodAt:put:", "aMethod", null);
        }
Esempio n. 13
0
        public void ShouldCreateCachedExecutionPlan()
        {
            var stringWriter = new StringWriter();

            var behaviors = new IBehavior[]
            {
                new StageFork("stagefork1", stringWriter),
                new Behavior1("behavior1", stringWriter),
                new Stage1("stage1", stringWriter),
                new Behavior2("behavior2", stringWriter),
                new Stage2("stage2", stringWriter),
                new Terminator("terminator", stringWriter),
            };

            var expressions = new List <Expression>();

            behaviors.CreatePipelineExecutionExpression(expressions);

#if NET5_0_OR_GREATER
            // System.Threading.Tasks.Task has changed to System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult] in .net5
            // This ifdef is to make sure the new type is only validated for .net5 or greater.
            var scenario = "net5";
#else
            var scenario = string.Empty;
#endif

            Approver.Verify(expressions.PrettyPrint(), scenario: scenario);
        }
Esempio n. 14
0
        public void WithAfterExecuteWithActionOnExtensionWithInitializer_Behavior_ShouldAddBehaviorToLastExecutable()
        {
            IBehavior <ICustomExtension> behavior = null;
            Action <IBehaviorAware <ICustomExtension>, object> contextInitializer = null;

            var extension = A.Fake <IExecutable <ICustomExtension> >();

            A.CallTo(() => extension.Add(A <IBehavior <ICustomExtension> > ._)).Invokes((IBehavior <ICustomExtension> b) => behavior = b);

            A.CallTo(() => this.executableFactory.CreateExecutable(
                         A <Expression <Func <object> > > ._,
                         A <Expression <Action <ICustomExtension, object> > > ._,
                         A <Action <IBehaviorAware <ICustomExtension>, object> > ._))
            .Invokes((Expression <Func <object> > func, Expression <Action <ICustomExtension, object> > action, Action <IBehaviorAware <ICustomExtension>, object> ctx) => contextInitializer = ctx)
            .Returns(A.Fake <IExecutable <ICustomExtension> >());

            var context = new object();

            this.testee.Execute(() => context, (e, o) => e.Dispose()).With(o => new TestableBehavior(o));

            contextInitializer(extension, context);

            behavior.Should().NotBeNull();
            behavior.As <TestableBehavior>().Context.Should().Be(context);
        }
Esempio n. 15
0
        public Publisher(IPublisherBehavior publisher, params IBehavior <IPublisherMessageBatching>[] behaviors)
        {
            _behavior = AggregateBehavior <IPublisherMessageBatching> .Create(new PublisherBehaviorWrapper(publisher),
                                                                              behaviors);

            _observers = new HashSet <IObserver <IPublisherMessageBatching> >();
        }
Esempio n. 16
0
        internal void Load(IAttributeLoader attributeLoader, string xmlFile)
        {
            XmlDocument xml = new XmlDocument();

            xml.Load(xmlFile);

            XmlNode behaviorNode = xml.GetElementsByTagName("behaviors")[0];

            foreach (XmlNode node in behaviorNode.ChildNodes)
            {
                Type      t     = System.Type.GetType(typeof(IBehavior).Namespace + "." + node.Name);
                object[]  param = new object[] { this };
                IBehavior b     = Activator.CreateInstance(t, param) as IBehavior;

                AddBehavior(b);
            }

            XmlNode attributeNode = xml.GetElementsByTagName("attributes")[0];

            foreach (XmlNode node in attributeNode.ChildNodes)
            {
                if (node.Attributes != null) // used to handle comment nodes
                {
                    if (!HasAttribute(node.Attributes["key"].Value))
                    {
                        continue;
                    }

                    dynamic value = extractValue(attributeLoader, node);
                    this[node.Attributes["key"].Value] = value;
                }
            }
        }
Esempio n. 17
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
                                        JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            object deserialized = serializer.Deserialize(reader);

            NonblockingWrapperBehavior obsoleteBehavior = deserialized as NonblockingWrapperBehavior;

            if (obsoleteBehavior == null)
            {
                return(deserialized);
            }
            else
            {
                IBehavior properBehavior             = obsoleteBehavior.Data.Behavior;
                IBackgroundBehaviorData blockingData = properBehavior.Data as IBackgroundBehaviorData;
                if (blockingData != null)
                {
                    blockingData.IsBlocking = obsoleteBehavior.Data.IsBlocking;
                }

                return(properBehavior);
            }
        }
Esempio n. 18
0
        public void EnableUndo_EnablesUndoSetValueBehavior()
        {
            UserVM vm = CreateUserVMWithItems();

            var department = vm.GetValue(x => x.Groups);

            var relevantProperties = new[] {
                department.GetProperty(x => x.AllItems),
                department.GetProperty(x => x.SelectedItems)
            };

            foreach (var property in relevantProperties)
            {
                bool found = false;
                for (IBehavior b = property.Behaviors; b != null; b = b.Successor)
                {
                    if (b.GetType().Name.Contains("UndoSetValueBehavior") ||
                        b.GetType().Name.Contains("UndoCollectionModifcationBehavior"))
                    {
                        found = true;
                        break;
                    }
                }
                Assert.IsTrue(found);
            }
        }
Esempio n. 19
0
        public void SwitchToEditMode(LayoutPanel panel)
        {
            // re-initialize
            IBehavior editBehavior = HydrateBehavior(panel.ID, true);

            SwitchToEditMode(panel, editBehavior);
        }
Esempio n. 20
0
        public void Start(IProject context, IBehavior behavior)
        {
            _context = context;

            try
            {
                _variable = _context.VariableCollection["AddInCounter"];

                context.StandbyToServerChanging += Context_StandbyToServerChanging;
                context.ServerToStandbyChanging += ContextOnServerToStandbyChanging;


                switch (context.ProjectNetworkType)
                {
                case ProjectNetworkType.Server:
                case ProjectNetworkType.Mainstation:
                    _runBackgroundWorker = true;
                    _backgroundWorker.RunWorkerAsync();
                    break;
                }

                MessageBox.Show("The service ist started in mode: " + context.ProjectNetworkType);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Esempio n. 21
0
 public static void Behavior([ValidatedNotNull] IBehavior aBehavior)
 {
     if (aBehavior == null)
     {
         throw new ActorException("behavior can't be null");
     }
 }
Esempio n. 22
0
        public EnumerableBehavior(IBehavior behavior, IBehavior superclass, Machine machine)
            : base(behavior, superclass, machine, typeof(IEnumerable))
        {
            string dosource = @"
            do: aBlock
            | enumerator |

            enumerator := self !GetEnumerator.

            [enumerator !MoveNext] whileTrue:
            [ aBlock value: enumerator !Current ]
            ";
            string selectsource = @"
            select: aBlock
            | enumerator list |

            enumerator := self !GetEnumerator.
            list := @System.Collections.ArrayList !new.

            [enumerator !MoveNext] whileTrue:
            [ | item |
              item := enumerator !Current.
            (aBlock value: item) ifTrue:  [ list add: item ]
            ].
            ^list
            ";

            Parser parser = new Parser(dosource);
            this.DefineInstanceMethod(parser.CompileInstanceMethod(this));
            parser = new Parser(selectsource);
            this.DefineInstanceMethod(parser.CompileInstanceMethod(this));
            this.DefineInstanceMethod(new FunctionalMethod("includes:", this, this.IncludesMethod));
        }
Esempio n. 23
0
 public NonblockingWrapperBehavior(IBehavior behavior, bool isBlocking, string name = "")
 {
     Data            = new EntityData();
     Data.Behavior   = behavior;
     Data.IsBlocking = isBlocking;
     Data.Name       = name;
 }
Esempio n. 24
0
 public Asteroid(Vector position, float r, IBehavior behavior, bool isChild = false) : base(behavior)
 {
     IsChild  = isChild;
     Speed    = isChild? GetRandomNotZeroVector(-3, 3) : GetRandomNotZeroVector(-2, 2);
     Position = isChild? position + GetRandomNotZeroVector(-1, 1): position;
     this.r   = r;
 }
Esempio n. 25
0
        public void WithAfterExecuteWithActionOnExtensionWithInitializer_Behavior_ShouldAddBehaviorToLastExecutable()
        {
            IBehavior <ICustomExtension> behavior = null;
            Action <IBehaviorAware <ICustomExtension>, object> contextInitializer = null;

            var extension = new Mock <IExecutable <ICustomExtension> >();

            extension.Setup(x => x.Add(It.IsAny <IBehavior <ICustomExtension> >())).Callback <IBehavior <ICustomExtension> >(
                b => behavior = b);

            this.executableFactory.Setup(
                f =>
                f.CreateExecutable(It.IsAny <Expression <Func <object> > >(), It.IsAny <Expression <Action <ICustomExtension, object> > >(), It.IsAny <Action <IBehaviorAware <ICustomExtension>, object> >()))
            .Callback <Expression <Func <object> >, Expression <Action <ICustomExtension, object> >, Action <IBehaviorAware <ICustomExtension>, object> >(
                (func, action, ctx) => contextInitializer = ctx).Returns(Mock.Of <IExecutable <ICustomExtension> >);

            var context = new object();

            this.testee.Execute(() => context, (e, o) => e.Dispose()).With(o => new TestableBehavior(o));

            contextInitializer(extension.Object, context);

            behavior.Should().NotBeNull();
            behavior.As <TestableBehavior>().Context.Should().Be(context);
        }
Esempio n. 26
0
        /// <summary>
        /// Method which is executed on starting the SCADA Editor Wizard
        /// </summary>
        /// <param name="context">SCADA editor application object</param>
        /// <param name="behavior">For future use</param>
        public void Run(IEditorApplication context, IBehavior behavior)
        {
            if (context.Workspace.ActiveProject == null)
            {
                MessageBox.Show(string.Format("There is no active project available." + Environment.NewLine +
                                              "Please load a project into the workspace!")
                                , "Wizard with WPF GUI");
                return;
            }

            try
            {
                var pageViewModels = new List <IPageViewModel>
                {
                    new WelcomeViewModel <WelcomePage>(),
                    new SelectionListViewModel <SelectionListPage>(context.Workspace.ActiveProject)
                };

                var mainViewModel = new MainViewModel(pageViewModels);
                var mainView      = new MainView
                {
                    DataContext = mainViewModel
                };

                var application = new Application();
                application.MainWindow = mainView;
                mainView.Show();
                application.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An exception has been thrown: {ex.Message}", "Wizard with WPF GUI");
                throw;
            }
        }
Esempio n. 27
0
        public void ShouldRaiseIfSelectorIsNullWhenLookup()
        {
            BaseBehavior baseBehavior = new BaseBehavior();
            IBehavior    behavior     = baseBehavior.CreateDelegated();

            behavior.Send("lookup:", null);
        }
Esempio n. 28
0
 public static IBehavior <TResult> CombineLatest <TSource1, TSource2, TResult>(
     this IBehavior <TSource1> self,
     IBehavior <TSource2> other,
     Func <TSource1, TSource2, TResult> selector)
 {
     return(new CombineLatestBehavior <TSource1, TSource2, TResult>(self, other, selector));
 }
Esempio n. 29
0
        private void StartChild(IBehavior child)
        {
            child.Start();
            //IPolledStatus polledChild = child as IPolledStatus;

            //if (polledChild == null)
            //{
            //}
            //else
            //{
                
            //    RecurranceParameters rp = null;
            //    var hasRP = child as IHasStatusRecurranceParameters;
            //    if (hasRP != null)
            //    {
            //        rp = hasRP.StatusRecurranceParameters;
            //    }

            //    if (rp == null)
            //    {
            //        if (!DefaultInterval.HasValue)
            //        {
            //            throw new Exception("Children must have RecurranceParameters, or DefaultInterval must be set.");
            //        }
            //        else
            //        {
            //            rp = new RecurranceParameters() { Interval = DefaultInterval.Value };
            //        }
            //    }

            //    var poller = new StatusPoller(child, rp);
            //    poller.IsEnabled = true;
            //}
        }
Esempio n. 30
0
        public IComponent CreateChild(IBehavior mainBehavior)
        {
            var child = CreateChild();

            child.AppendBehavior(mainBehavior);
            return(child);
        }
Esempio n. 31
0
        // OLD - use Default RP instead?
        ///// <summary>
        ///// If null, throw an exception when trying to run a child with no IHasStatusRecurranceParameters
        ///// </summary>
        //TimeSpan? DefaultInterval = null;

        protected override void OnChildStatusChanged(IBehavior child, BehaviorStatus oldStatus, BehaviorStatus newStatus)
        {
            if (child.IsFinished)
            {
                var finishedChildrenCopy = finishedChildren;
                if (finishedChildrenCopy != null)
                {
                    finishedChildrenCopy.Add(child);
                }
                this.children.Remove(child);

#if LOG_TASK_FINISHED
                l.Info("Task finished: " + child.ToString());
#endif
            }
            
            switch (newStatus)
            {
                case BehaviorStatus.Uninitialized:
                    break;
                case BehaviorStatus.Initialized:
                    break;
                case BehaviorStatus.Running:
                    break;
                case BehaviorStatus.Failed:
                    break;
                case BehaviorStatus.Succeeded:
                    break;
                case BehaviorStatus.Disposed:
                    break;
                default:
                    break;
            }
        }        
Esempio n. 32
0
 public IBehaviors AddBehavior(IBehavior aBehavior)
 {
     CheckArg.Behavior(aBehavior);
     aBehavior.LinkBehaviors(this);
     fList.Add(aBehavior);
     return(this);
 }
Esempio n. 33
0
        public SwitchBehavior(IBehavior <IBehavior <T> > behavior)
        {
            _behavior = behavior;
            IObservable <IObservable <T> > obs = _behavior;

            _switchedObservable = obs.Switch();
        }
Esempio n. 34
0
        public void ShouldRaiseIfSelectorIsNullWhenAddMethod()
        {
            BaseBehavior baseBehavior = new BaseBehavior();
            IBehavior    behavior     = baseBehavior.CreateDelegated();

            behavior.Send("methodAt:put:", null, new MockMethod());
        }
Esempio n. 35
0
        /// <summary>
        /// Suspends the <paramref name="behavior"/>.
        /// </summary>
        public void SuspendBehaviour(IBehavior behavior)
        {
            _activeBehaviors.Remove(behavior);
            _suspendedBehaviors.Add(behavior);

            behavior.Terminated += OnSuspendedBehaviourTerminated;
        }
        public void Start(IProject context, IBehavior behavior)
        {
            var configurator = new NLogConfigurator();

            configurator.Configure();

            try
            {
                List <string> newOnlineVariables = new List <string>();

                // iterate through all variables in the current project and select all variables which are marked as "External Visible"
                foreach (var item in context.VariableCollection)
                {
                    if ((bool)item.GetDynamicProperty("ExternVisible"))
                    {
                        newOnlineVariables.Add(item.Name);
                    }
                }

                if (newOnlineVariables.Any())
                {
                    _variableSubscription.Start(context, newOnlineVariables);
                }
                else
                {
                    Logger.Info("No Variables in the project " + context.Name + " were marked as \"External Visible\"");
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
            }
        }
Esempio n. 37
0
 public NativeObjectBehavior(IBehavior behavior, IBehavior superclass, Machine machine)
     : base(behavior, superclass, machine, typeof(object))
 {
     this.DefineInstanceMethod(new FunctionalMethod("isNil", this, this.IsNil));
     this.DefineInstanceMethod(new FunctionalMethod("isNotNil", this, this.IsNotNil));
     this.DefineInstanceMethod(new FunctionalMethod("ifNil:", this, this.IfNil));
     this.DefineInstanceMethod(new FunctionalMethod("ifNotNil:", this, this.IfNotNil));
 }
Esempio n. 38
0
 public bool AddBehavior(int position, IBehavior behavior)
 {
     if (position < 0 || position > this.Behaviors.Length)
         return false;
     if (behavior == null)
         return false;
     return true;
 }
Esempio n. 39
0
        /// <summary>
        /// Registers the behavior.
        /// </summary>
        /// <param name="behavior">The behavior.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="behavior"/> is <c>null</c>.</exception>
        public void RegisterBehavior(IBehavior behavior)
        {
            Argument.IsNotNull("behavior", behavior);

            //_behaviors.Add(behavior);

            BehaviorLoaded.SafeInvoke(this, new BehaviorEventArgs(behavior));
        }
Esempio n. 40
0
        /// <summary>
        /// Unregisters the behavior.
        /// </summary>
        /// <param name="behavior">The behavior.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="behavior"/> is <c>null</c>.</exception>
        public void UnregisterBehavior(IBehavior behavior)
        {
            Argument.IsNotNull("behavior", behavior);

            //_behaviors.Remove(behavior);

            BehaviorUnloaded.SafeInvoke(this, new BehaviorEventArgs(behavior));
        }
Esempio n. 41
0
        public BaseClassDescription(IBehavior behavior, IBehavior superclass, Machine machine, string varnames)
            : base(behavior, superclass, machine)
        {
            IEnumerable<string> names = AsNames(varnames);

            foreach (string name in names)
                this.DefineInstanceVariable(name);
        }
Esempio n. 42
0
 public Method CompileInstanceMethod(string text, IBehavior cls)
 {
     ModelParser parser = new ModelParser(text);
     var methodmodel = parser.ParseMethod();
     Method method = new Method(cls, methodmodel.Selector, text);
     BytecodeCompiler compiler = new BytecodeCompiler(method);
     compiler.CompileMethod(methodmodel);
     return method;
 }
Esempio n. 43
0
        public static IMetaClass CreateMetaClass(IBehavior superclass, Machine machine)
        {
            IMetaClass metasuperclass = null;

            if (superclass != null)
                metasuperclass = superclass.MetaClass;

            return new BaseMetaClass(machine.MetaClassClass, metasuperclass, machine, string.Empty);
        }
 public Blob(string name, int health, int damage, IBehavior behaviorType, IAttack attackType)
 {
     this.Name = name;
     this.Health = health;
     this.Damage = damage;
     this.BehaviorType = behaviorType;
     this.AttackType = attackType;
     this.IsAlive = true;
 }
Esempio n. 45
0
 public Blob(string name, int health, int damage, IBehavior behavior, IAttack attack)
 {
     this.Name = name;
     this.Health = health;
     this.Damage = damage;
     this.Behavior = behavior;
     this.Attack = Attack;
     this.InitialDamage = damage;
     this.InitialHealth = health;
 }
        public override void CopyInto(IBehavior newObject)
        {
            var projectileFiring = newObject as BasicProjectileFiringBehavior;

            Debug.Assert(projectileFiring != null, "BasicProjectileFiringBehavior is null in CopyInto");

            projectileFiring.TimeBetweenShots = TimeBetweenShots;

            base.CopyInto(newObject);
        }
        public override void CopyInto(IBehavior newObject)
        {
            var behavior = newObject as ParticleEffectDeathBehavior;

            Debug.Assert(behavior != null);

            behavior.ParticleEffectName = ParticleEffectName;

            base.CopyInto(newObject);
        }
Esempio n. 48
0
 public Blob(int damage, int health, string name, IBehavior behavior, IAttack attackType)
 {
     this.Damage = damage;
     this.Health = health;
     this.Name = name;
     this.Behavior = behavior;
     this.AttackType = attackType;
     this.InitialDamage = damage;
     this.initialHealth = health;
     this.IsAlive = true;
 }
        public override void CopyInto(IBehavior newObject)
        {
            var behavior = newObject as BaseProjectileMovementBehavior;

            Debug.Assert(behavior != null, "BaseProjectileMovementBehavior was null in CopyInto");

            behavior.MoveSpeed = MoveSpeed;
            behavior.InitialDirection = InitialDirection;

            base.CopyInto(newObject);
        }
Esempio n. 50
0
File: Blob.cs Progetto: krasi070/OOP
 public Blob(string name, int health, int damage, IAttack attackType, IBehavior behaviorType)
 {
     this.Name = name;
     this.Health = health;
     this.InitialHealth = this.Health;
     this.Damage = damage;
     this.InitialDamage = this.Damage;
     this.AttackType = attackType;
     this.BehaviorType = behaviorType;
     this.HasUsedBehavior = false;
 }
        public override void CopyInto(IBehavior newObject)
        {
            var behavior = newObject as LinearProjectileMovementBehavior;

            Debug.Assert(behavior != null, "LinearProjectileMovementBehavior was null in CopyInto");

            behavior.Angle = Angle;
            behavior.ActionFiring = false;

            base.CopyInto(newObject);
        }
Esempio n. 52
0
 public Blob(string name, int health, int damage, IBehavior behavior, IAttack attack)
 {
     this.Name = name;
     this.Health = health;
     this.Damage = damage;
     this.Behavior = behavior;
     this.Attack = attack;
     this.BehaviorIsTriggered = false;
     this.BehaviorTriggeredInBattle = false;
     this.InitialBlobHealth = health;
     this.InitialBlobDamage = damage;
 }
Esempio n. 53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Blob"/> class.
 /// </summary>
 /// <param name="name">The name of the blob.</param>
 /// <param name="health">The initial health value of the blob.</param>
 /// <param name="damage">The initial damage value of the blob.</param>
 /// <param name="attack">The Attack object of the blob.</param>
 /// <param name="behavior">The behavior object of the blob.</param>
 public Blob(string name, int health, int damage, IAttack attack, IBehavior behavior) 
     : base(name)
 {
     this.initialHealth = health;
     this.initialDamage = damage;
     this.Health = this.initialHealth;
     this.Damage = this.initialDamage;
     this.attack = attack;
     this.behavior = behavior;
     this.attack.SetOwner(this);
     this.behavior.SetOwner(this);
 }
Esempio n. 54
0
        public BaseBehavior(IBehavior behavior, IBehavior superclass, Machine machine)
            : base(behavior, behavior == null ? 0 : behavior.NoInstanceVariables)
        {
            if (machine == null)
            {
                throw new ArgumentNullException("machine");
            }

            this.superclass = superclass;
            this.machine = machine;
            this.scope = machine.CurrentEnvironment;
        }
Esempio n. 55
0
 public BlockBehavior(IBehavior behavior, IBehavior superclass, Machine machine)
     : base(behavior, superclass, machine, typeof(Block))
 {
     string assertcode = @"
     assert
     self value ifFalse: [@AjTalk.Exceptions.AssertError new raise].
     ^true
     ";
     Parser parser = new Parser(assertcode);
     this.DefineInstanceMethod(parser.CompileInstanceMethod(this));
     ////this.DefineInstanceMethod(new FunctionalMethod("assert", this, this.AssertMethod));
 }
 public Blob(string name, int health, int damage, IAttack attack, IBehavior behavior)
 {
     this.Name = name;
     this.Health = health;
     this.Damage = damage;
     this.Attack = attack;
     this.Behavior = behavior;
     this.TurnsCounter = defaultTurnsCounter;
     this.defaultHealth = health;
     this.defaultDamage = damage;
     this.IsAlive = true;
 }
		private void UpdateBehavior(DependencyObject host, IBehavior behavior)
		{
			if(behavior.IsApplicable())
			{
				behavior.Update();
			}
			else
			{
				host.ClearValue(_property);

				behavior.Detach();
			}
		}
Esempio n. 58
0
 public Blob(string name, int health, int damage, IBehavior behavior, ISpell spell)
 {
     this.Behavior = behavior;
     this.BlobSpell = spell;
     this.InitialHealthValidation(health);
     this.InitialDamageValidation(damage);
     this.InitialHealth = health;
     this.InitialDamage = damage;
     this.Name = name;
     this.Health = this.InitialHealth;
     this.Damage = this.InitialDamage;
     this.RoundDelay = ValidationControl.BlobRoundDelay;
 }
Esempio n. 59
0
        public BaseClass(IBehavior behavior, string name, IBehavior superclass, Machine machine, string varnames)
            : base(behavior, superclass, machine, varnames)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            this.name = name;

            this.isBehavior = name == "Behavior";
            this.isClassDescription = name == "ClassDescription";
        }
Esempio n. 60
0
 public Blob(
     string name,
     int health,
     int attackDamage,
     IBehavior behavior,
     IAttack attack) 
     : base(name)
 {
     this.Name = name;
     this.Health = health;
     this.AttackDamage = attackDamage;
     this.Behavior = behavior;
     this.AttackType = attack;
 }