Ejemplo n.º 1
0
        public void SingleSolution()
        {
            CurrentState state = new CurrentState();
            IDecision[] decisions = new IDecision[] {
                new MoveToFridge(state),
                new KillFridgeGuardian(state),
                new OpenFridgeDecision(state),
                new GetBananaFromFridge(state)
            };

            Planner planner = new Planner(StateOffset.Heuristic);
            for (int i = 0; i < decisions.Length; i++) {
                planner.AddDecision(decisions[i]);
            }

            StateOffset goal = new StateOffset();
            goal.Set("HasBanana", true);

            Queue<IDecision> plan = planner.CreatePlan(goal);

            Assert.Greater(plan.Count, 0);
            Assert.AreSame(decisions[0], plan.Dequeue()); // MoveToFridge
            Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGuardian
            Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGUardian
            Assert.AreSame(decisions[1], plan.Dequeue()); // KillFridgeGuardian
            Assert.AreSame(decisions[2], plan.Dequeue()); // OpenFridge
            Assert.AreSame(decisions[3], plan.Dequeue()); // GetBananaFromFridge
        }
Ejemplo n.º 2
0
 private CurrentState(Method method, CurrentState oldState)
 {
     this.Assembly = oldState.Assembly;
     this.assemblySuppressed = oldState.assemblySuppressed;
     this.Type = oldState.Type;
     this.typeSuppressed = oldState.typeSuppressed;
     this.Method = method;
     this.methodSuppressed = null;
 }
Ejemplo n.º 3
0
 public CurrentState(TypeNode type, CurrentState oldState)
 {
     this.Type = type;
     this.Method = null;
     this.typeSuppressed = null;
     this.methodSuppressed = null;
     this.Assembly = oldState.Assembly;
     this.assemblySuppressed = oldState.assemblySuppressed;
 }
Ejemplo n.º 4
0
        public Koopa(Vector2 initialPosition, CurrentState type)
            : base(new Vector2(initialPosition.X, initialPosition.Y))
        {
            Texture2D koopaTexture = Textures.GetTexture(Textures.Texture.koopa);

            walking = new Animation(koopaTexture, new Rectangle(0, 0 + (24 * World.WorldType), 16, 24), 2, timeBetweenAnimation, 0);
            hopping = new Animation(koopaTexture, new Rectangle(48, 0 + (24 * World.WorldType), 16, 24), 2, timeBetweenAnimation, 0);
            velocity.X = -walkingSpeed;

            state = type;
        }
Ejemplo n.º 5
0
    public virtual void Initialize(GameObject _newCamPoint, GameObject _triggerObj)
    {
        isGoingHome = false;
        currentCamPoint = _newCamPoint;

        ResetDayTimers ();
        direction = RandomDirection ();
        StartCoroutine (ExitBuilding (_triggerObj.GetComponent<Collider>(), true));

        currentState = CurrentState.CS_Sleeping;
    }
Ejemplo n.º 6
0
        public Spikey(Vector2 initialPosition, CurrentState type)
            : base(initialPosition)
        {
            walking = new Animation(Textures.GetTexture(Textures.Texture.spikey), new Rectangle(0, 0, 16, 16), 2, timeBetweenAnimation, 0);
            thrown = new Animation(Textures.GetTexture(Textures.Texture.spikey), new Rectangle(32, 0, 16, 16), 2, timeBetweenAnimation, 0);

            state = type;

            if (state == CurrentState.walking)
                velocity.X = walkingSpeed;
            else
                velocity.Y = thrownSpeed;
        }
Ejemplo n.º 7
0
		void DebugManager_OnProcessStateChanged(object sender, DebuggerEventArgs e) {
			var oldState = currentState;
			currentState = new CurrentState();
			var dbg = (DnDebugger)sender;
			switch (DebugManager.Instance.ProcessState) {
			case DebuggerProcessState.Starting:
				savedEvalState = null;
				break;

			case DebuggerProcessState.Continuing:
				if (dbg.IsEvaluating && savedEvalState == null)
					savedEvalState = oldState;
				break;

			case DebuggerProcessState.Running:
				if (!dbg.IsEvaluating)
					ClearStackFrameLines();
				break;

			case DebuggerProcessState.Stopped:
				if (dbg.IsEvaluating)
					break;

				// Don't update the selected thread if we just evaluated something
				if (UpdateState(savedEvalState)) {
					currentState.Thread = DebugManager.Instance.Debugger.Current.Thread;
					SelectedFrameNumber = 0;
				}
				else
					currentState = savedEvalState;
				savedEvalState = null;

				foreach (var textView in MainWindow.Instance.AllVisibleTextViews)
					UpdateStackFrameLines(textView, false);
				break;

			case DebuggerProcessState.Terminated:
				savedEvalState = null;
				ClearStackFrameLines();
				break;

			default:
				throw new InvalidOperationException();
			}

			if (StackFramesUpdated != null)
				StackFramesUpdated(this, new StackFramesUpdatedEventArgs(dbg));
		}
Ejemplo n.º 8
0
        public void serialPingServers(BackgroundWorker worker,
                                        DoWorkEventArgs e,
                                        int[] speeds
            )
        {
            while (!worker.CancellationPending)
            {
                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                options.DontFragment = true;
                string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках
                CurrentState state = new CurrentState();
                byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках
                int timeout = speeds[2]; // сделать изменяемым в настройках
                double count = serverList.Count;
                double i = 0;
                int progress;
                foreach (serverControl server in serverList)
                {
                    System.Threading.Thread.Sleep(speeds[0]);
                    if (worker.CancellationPending)
                    {
                        break;
                    }
                    i++;
                    progress = (int)Math.Round((i / count) * 100);

                    string host = server.objectAddress; // сделать изменяемым в настройках
                    PingReply reply = pingSender.Send(host, timeout, buffer, options);
                    if (reply.Status == IPStatus.Success)
                    {
                        state.address = server.objectAddress;
                        state.isOnline = true;
                        worker.ReportProgress(progress, state);
                    }
                    else
                    {
                        state.address = server.objectAddress;
                        state.isOnline = false;
                        worker.ReportProgress(progress, state);
                    }
                }
                if (!workState)
                    System.Threading.Thread.Sleep(1000);
                System.Threading.Thread.Sleep(speeds[1]);
            }
            e.Cancel = true;
        }
Ejemplo n.º 9
0
        public override void Update(GameTime gameTime)
        {
            walking.Update(gameTime);
            thrown.Update(gameTime);

            if (velocity.X < 0)
                effects = SpriteEffects.None;
            else
                effects = SpriteEffects.FlipHorizontally;

            if (state == CurrentState.thrown && isOnSolidTile)
            {
                state = CurrentState.walking;
                velocity.X = walkingSpeed;
            }
            base.Update(gameTime);
        }
Ejemplo n.º 10
0
        private Planner BasicPlanner()
        {
            CurrentState state = new CurrentState();
            IDecision[] decisions = new IDecision[] {
                new MoveToFridge(state),
                new KillFridgeGuardian(state),
                new OpenFridgeDecision(state),
                new GetBananaFromFridge(state)
            };

            Planner planner = new Planner(StateOffset.Heuristic);
            for (int i = 0; i < decisions.Length; i++) {
                planner.AddDecision(decisions[i]);
            }

            return planner;
        }
Ejemplo n.º 11
0
        public void CountWords(
            System.ComponentModel.BackgroundWorker worker,
            System.ComponentModel.DoWorkEventArgs e)
        {
            CurrentState state = new CurrentState();
            string line = "";
            int elapsedTime = 20;
            DateTime lastReportDateTime = DateTime.Now;

            if (CompareString == null || CompareString == string.Empty) {
                throw new Exception("CompareString not specified.");
            }

            try {
                using (System.IO.StreamReader stream = new System.IO.StreamReader(SourceFile)) {
                    while (!stream.EndOfStream) {
                        if (worker.CancellationPending) {
                            e.Cancel = true;
                            break;
                        }
                        else {
                            line = stream.ReadLine();
                            WordCount += CountInString(line, CompareString);
                            LinesCounted += 1;

                            int compare = DateTime.Compare(
                                DateTime.Now, lastReportDateTime.AddMilliseconds(elapsedTime));
                            if (compare > 0) {
                                state.LinesCounted = LinesCounted;
                                state.WordsMatched = WordCount;
                                worker.ReportProgress(0, state);
                                lastReportDateTime = DateTime.Now;
                            }
                        }
                    }

                    state.LinesCounted = LinesCounted;
                    state.WordsMatched = WordCount;
                    worker.ReportProgress(0, state);
                }
            }
            catch (Exception exc) {
                throw exc;
            }
        }
Ejemplo n.º 12
0
        public void parallelPingServers(System.ComponentModel.BackgroundWorker worker,
                                        System.ComponentModel.DoWorkEventArgs e,
                                        int[] speeds,
                                        ARSMonitor.serverControl server
            )
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // сделать размер буфера изменяемым в настройках
            CurrentState state = new CurrentState();
            byte[] buffer = Encoding.ASCII.GetBytes(data); // сделать изменяемым в настройках
            int timeout = 120; // сделать изменяемым в настройках
            double count = serverList.Count;
            double i = 0;
            int progress;
            i++;
            progress = (int)Math.Round((i / count) * 100);
            //elements.Find(el => el.Child == server);
            string host = server.objectAddress; // сделать изменяемым в настройках

            while (!worker.CancellationPending)
            {
                PingReply reply = pingSender.Send(host, timeout, buffer, options);
                if (reply.Status == IPStatus.Success)
                {
                    state.address = server.objectAddress;
                    state.isOnline = true;
                    /*while (worker.IsBusy)
                        System.Threading.Thread.Sleep(100);*/
                    worker.ReportProgress(progress, state);
                }
                else
                {
                    state.address = server.objectAddress;
                    state.isOnline = false;
                    worker.ReportProgress(progress, state);
                }
                if (!workState)
                    System.Threading.Thread.Sleep(1000);

                System.Threading.Thread.Sleep(speeds[1]);
            }
            e.Cancel = true;
        }
Ejemplo n.º 13
0
 //wait(reset), BigBottom, Alarm, LittleBottom, Postpone(10 bigbottom), WelcomeBack
 private void BigBottom()
 {
     currentState = CurrentState.BigBottom;
     soundPlayer.Stop();
     //BigBottom状态,计时50分钟,大按钮消失,leave按钮enable,postpone和finish button unabled,GotitButton显示got it
     StartButton.Visibility = Visibility.Hidden;
     TimeBlock.Visibility = Visibility.Visible;
     GotitButton.Visibility = Visibility.Visible;
     PostponeButton.Visibility = Visibility.Visible;
     LeaveButton.Visibility = Visibility.Visible;
     GotitButton.IsEnabled = false;
     PostponeButton.IsEnabled = false;
     LeaveButton.IsEnabled = true;
     TipBlock.Text = "Your Bottom is getting bigger!";
     TipBlock.Visibility = Visibility.Visible;
     timeTicks = 0;
     TimeBlock.Text = "0:0";
     timer.Start();
 }
Ejemplo n.º 14
0
        public void GoalNodeNeighborIterator()
        {
            CurrentState state = new CurrentState();
            List<IDecision> decisions = new List<IDecision>() {
                new MoveToFridge(state),
                new KillFridgeGuardian(state),
                new OpenFridgeDecision(state),
                new GetBananaFromFridge(state)
            };

            StateOffset goal = new StateOffset();
            //goal.SetStateValue("HasBanana", true, false);
            GoalNode end = new GoalNode(goal, decisions);

            int i = decisions.Count - 1;
            foreach (GoalNode neighbor in end.GetNeighbors()) {
                Console.WriteLine(end.GetEdge(neighbor));
                //Assert.AreSame(decisions[i--], end.GetEdge(neighbor));
            }
        }
Ejemplo n.º 15
0
	void Awake()
	{
		//iniate audio source and cache variables
		if(GetComponent<AudioSource>() == null)
		{
			c_Audio = gameObject.AddComponent<AudioSource>();
		}
		else
		{
			c_Audio = GetComponent<AudioSource>();
		}
		
		brain = GetComponent<AIStateManager>();
		previousState = brain.currentState;
		previousPanic = brain.panic;
		
		//set the pitch correctly
		c_Audio.pitch = basePitch;
		c_Audio.pitch = c_Audio.pitch + Random.Range( -randomPitch, randomPitch);
		
	}
Ejemplo n.º 16
0
        public ICommand GetCommand()
        {
            //Check which state we are in
            switch (currentState)
            {
                    //If we are at the initial welcome for the new character, just change the state and move on
                case CurrentState.InitialWelcome:
                    currentState = CurrentState.EnteringPasswordFirst;
                    break;
                    //We need to get the first out of two password entries and make sure it's legal.
                case CurrentState.EnteringPasswordFirst:
                    {
                        GetPassword(PasswordPhase.FirstPassword);
                        break;
                    }
                case CurrentState.EnteringPasswordSecond:
                    {
                        GetPassword(PasswordPhase.SecondPassword);
                        break;
                    }
            }

            return new NoOpCommand();
        }
Ejemplo n.º 17
0
        public override void Execute()
        {
            watch = new Stopwatch();
            Console.WriteLine("Beginning execution for Bi-directional");
            Console.WriteLine("Initial State: ");
            CurrentState.Format();
            watch.Start();

            FrontOpenSet.Enqueue(CurrentState);
            BackOpenSet.Enqueue(new State(GlobalVar.GOAL));
            while (FrontOpenSet.Count > 0 || BackOpenSet.Count > 0)
            {
                //pop from queue for each direction
                var front = FrontOpenSet.Dequeue();
                var back  = BackOpenSet.Dequeue();

                if (FrontClosedSet.ContainsKey(front.Key) == false)
                {
                    FrontClosedSet.Add(front.Key, front);
                }
                if (BackClosedSet.ContainsKey(back.Key) == false)
                {
                    BackClosedSet.Add(back.Key, back);
                }

                //check if either is at it's respective goal positions, just in case they don't ever intersect
                if (front.IsEqualToGoal())
                {
                    watch.Stop();

                    Console.WriteLine("Found goal through front open set, no intersection");
                    SolutionFound(front);
                    break;
                }
                if (back.IsEqualToGoal(CurrentState.StateArray))
                {
                    watch.Stop();

                    Console.WriteLine("Found goal through back open set, no intersection");
                    SolutionFound(back);
                    break;
                }


                var fChildren = front.BuildChildren();
                var bChildren = back.BuildChildren();

                foreach (var child in fChildren)
                {
                    if (FrontClosedSet.ContainsKey(child.Key))
                    {
                        continue;
                    }

                    FrontOpenSet.Enqueue(child);

                    if (!frontparents.ContainsKey(child.Key))
                    {
                        frontparents.Add(child.Key, front);
                    }
                }

                foreach (var child in bChildren)
                {
                    if (BackClosedSet.ContainsKey(child.Key))
                    {
                        continue;
                    }

                    BackOpenSet.Enqueue(child);

                    if (!backparents.ContainsKey(child.Key))
                    {
                        backparents.Add(child.Key, back);
                    }
                }


                //chech if either is in the closed set of each direction
                if (BackClosedSet.ContainsKey(front.Key))
                {
                    Console.WriteLine("Found Solution");
                    SolutionFound(front);
                    //found solution
                    break;
                }

                if (FrontClosedSet.ContainsKey(back.Key))
                {
                    Console.WriteLine("Found Solution");
                    SolutionFound(back);
                    //found solution
                    break;
                }

                if (BackOpenSet.Count == 0 && FrontOpenSet.Count == 0)
                {
                    throw new Exception("no solution");
                }
            }
            watch.Stop();
            Console.WriteLine("Elapsed time: {0} ms", watch.Elapsed.Milliseconds);
        }
Ejemplo n.º 18
0
    protected virtual void WaitForGreenLight()
    {
        currentState = CurrentState.CS_WaitingToCross;

        if(currentCrossWalk.currentCWState == CrossWalk.CrosswalkState.CWS_Green && currentState == CurrentState.CS_WaitingToCross)
        {
            isCrossing = true;
            StartCoroutine(CrossStreet(currentCrossWalk.gameObject));
            CancelInvoke("WaitForGreenLight");
        }
    }
Ejemplo n.º 19
0
 public void OnTileRightClicked(object sender, object args)
 {
     CurrentState.OnTileRightClicked();
 }
Ejemplo n.º 20
0
 private void OnEndTurnButtonPressed(object sender, object args)
 {
     CurrentState.OnEndTurnButtonPressed();
 }
Ejemplo n.º 21
0
 public void OnAbilityButtonPressed(object sender, object args)
 {
     CurrentAbility = ((Events.OnAbilityButtonPressed)args).Ability;
     CurrentState.OnAbilityButtonPressed();
 }
Ejemplo n.º 22
0
 private void btnStop_Click(object sender, EventArgs e) {
     _currentState = CurrentState.Paused;
 }
Ejemplo n.º 23
0
        public override void VisitClass(Class Class)
        {
            if (Class == null) return;

            var savedState = this.currentState;

            this.currentState = savedState.Derive(Class);

            try
            {
                this.CheckClass(Class);

                CheckForWrapperImplementationsForInheritedInterfaceImplementations(Class);
            }
            finally
            {
                this.currentState = savedState;
            }

            base.VisitClass(Class);
        }
Ejemplo n.º 24
0
 private void Robot_OnWallOnLeft()
 {
     LogCall();
     CurrentState.OnWallOnLeft();
 }
Ejemplo n.º 25
0
 private void Robot_OnLineAppears()
 {
     LogCall();
     CurrentState.OnLineAppears();
 }
Ejemplo n.º 26
0
 public void ProcessReservationResponsePacket(MultiplayerSessionReservation reservation)
 {
     Reservation = reservation;
     CurrentState.NegotiateReservation(this);
 }
Ejemplo n.º 27
0
 private void Robot_OnNoWallOnRight()
 {
     LogCall();
     CurrentState.OnNoWallOnRight();
 }
Ejemplo n.º 28
0
 public void RequestSessionReservation(PlayerSettings playerSettings, AuthenticationContext authenticationContext)
 {
     PlayerSettings        = playerSettings;
     AuthenticationContext = authenticationContext;
     CurrentState.NegotiateReservation(this);
 }
Ejemplo n.º 29
0
 public void Connect(string ipAddress, int port)
 {
     IpAddress  = ipAddress;
     ServerPort = port;
     CurrentState.NegotiateReservation(this);
 }
Ejemplo n.º 30
0
 public void JoinSession()
 {
     CurrentState.JoinSession(this);
 }
Ejemplo n.º 31
0
 private void LoadFile() {
     initButtonsForProcess();
     _currentState = CurrentState.InProcces;
     int readBytes = DEFAULT_BUFFER_SIZE;
     try {
         while (_file.Peek() >= 0 && readBytes >= DEFAULT_BUFFER_SIZE) {
             readBytes = _file.Read(_buff, 0, DEFAULT_BUFFER_SIZE);
             if (readBytes < DEFAULT_BUFFER_SIZE)
                 _strBuff.Append(_buff, 0, readBytes);
             else
                 _strBuff.Append(_buff);
             Application.DoEvents();
             if (!isInProcces())
                 break;
             _loaded += readBytes;
             _loadedValue = Convert.ToInt32(_loaded/_step);
             _loadedValue = (_loadedValue > progressBar.Maximum) ? progressBar.Maximum : _loadedValue;
             progressBar.Value = _loadedValue;
             txtLoaded.Text = (_loaded/1000).ToString("f3");
             Refresh();
         }
     }
     catch (IOException ex) {
         setCancelled();
         Messenger.ShowError(MsgsBase.Res.File_IO_error_ex, ex);
     }
     catch (OutOfMemoryException ex) {
         setCancelled();
         Messenger.ShowError(MsgsBase.Res.Error_Out_of_memory_ex, ex);
     }
     catch (Exception ex) {
         setCancelled();
         Messenger.ShowError(MsgsBase.Res.Undefined_error_ex, ex);
     }
     finally {
         if (_file != null)
             _file.Close();
     }
     initButtonsForPause();
     if (_currentState == CurrentState.Canceled) {
         this.DialogResult = DialogResult.Cancel;
         _strBuff = new StringBuilder(0);
         Close();
         return;
     }
     else if (_currentState == CurrentState.Accepted || isInProcces()) {
         this.DialogResult = DialogResult.OK;
         Close();
         return;
     }
 }
Ejemplo n.º 32
0
 private void Robot_OnBeaconClose(int id)
 {
     Log(new RobotEventLogEntry($"Robot_OnBeaconClose({id})"));
     CurrentState.OnBeaconClose(id);
 }
Ejemplo n.º 33
0
 private void OpenFileForm_Closing(object sender, CancelEventArgs e) {
     _currentState = CurrentState.Canceled;
     e.Cancel = false;
 }
Ejemplo n.º 34
0
 public void Action()
 {
     CurrentState.Action();
 }
Ejemplo n.º 35
0
        public override void VisitAssembly(AssemblyNode assembly)
        {
            this.currentState = new CurrentState(assembly);

            if (ContractNodes.IsAlreadyRewritten(assembly))
            {
                this.HandleError(new Error(1029, "Cannot extract contracts from rewritten assembly '" + assembly.Name + "'.", assembly.SourceContext));
                return;
            }

            base.VisitAssembly(assembly);
        }
Ejemplo n.º 36
0
 public void InsertQuarter()
 {
     CurrentState.InsertQuarter();
 }
Ejemplo n.º 37
0
        public static List <KeyValuePair <int, string> > getModesList(CurrentState cs)
        {
            log.Info("getModesList Called");

            if (cs.firmware == MainV2.Firmwares.PX4)
            {
                /*
                 * union px4_custom_mode {
                 * struct {
                 * uint16_t reserved;
                 * uint8_t main_mode;
                 * uint8_t sub_mode;
                 * };
                 * uint32_t data;
                 * float data_float;
                 * };
                 */


                var temp = new List <KeyValuePair <int, string> >()
                {
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_MANUAL << 16, "Manual"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_ACRO << 16, "Acro"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_STABILIZED << 16,
                                                   "Stabalized"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_RATTITUDE << 16,
                                                   "Rattitude"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_ALTCTL << 16,
                                                   "Altitude Control"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_POSCTL << 16,
                                                   "Position Control"),
                    new KeyValuePair <int, string>((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_OFFBOARD << 16,
                                                   "Offboard Control"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_READY << 24, "Auto: Ready"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF << 24, "Auto: Takeoff"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_LOITER << 24, "Loiter"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_MISSION << 24, "Auto"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_RTL << 24, "RTL"),
                    new KeyValuePair <int, string>(
                        ((int)PX4_CUSTOM_MAIN_MODE.PX4_CUSTOM_MAIN_MODE_AUTO << 16) +
                        (int)PX4_CUSTOM_SUB_MODE_AUTO.PX4_CUSTOM_SUB_MODE_AUTO_LAND << 24, "Auto: Landing")
                };

                return(temp);
            }
            else if (cs.firmware == MainV2.Firmwares.ArduPlane)
            {
                var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1",
                                                                                               cs.firmware.ToString());
                flightModes.Add(new KeyValuePair <int, string>(16, "INITIALISING"));

                flightModes.Add(new KeyValuePair <int, string>(17, "QStabilize"));
                flightModes.Add(new KeyValuePair <int, string>(18, "QHover"));
                flightModes.Add(new KeyValuePair <int, string>(19, "QLoiter"));
                flightModes.Add(new KeyValuePair <int, string>(20, "QLand"));
                flightModes.Add(new KeyValuePair <int, string>(21, "QRTL"));

                return(flightModes);
            }
            else if (cs.firmware == MainV2.Firmwares.Ateryx)
            {
                var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1",
                                                                                               cs.firmware.ToString()); //same as apm
                return(flightModes);
            }
            else if (cs.firmware == MainV2.Firmwares.ArduCopter2)
            {
                var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("FLTMODE1",
                                                                                               cs.firmware.ToString());
                return(flightModes);
            }
            else if (cs.firmware == MainV2.Firmwares.ArduRover)
            {
                var flightModes = Utilities.ParameterMetaDataRepository.GetParameterOptionsInt("MODE1",
                                                                                               cs.firmware.ToString());
                return(flightModes);
            }
            else if (cs.firmware == MainV2.Firmwares.ArduTracker)
            {
                var temp = new List <KeyValuePair <int, string> >();
                temp.Add(new KeyValuePair <int, string>(0, "MANUAL"));
                temp.Add(new KeyValuePair <int, string>(1, "STOP"));
                temp.Add(new KeyValuePair <int, string>(2, "SCAN"));
                temp.Add(new KeyValuePair <int, string>(3, "SERVO_TEST"));
                temp.Add(new KeyValuePair <int, string>(10, "AUTO"));
                temp.Add(new KeyValuePair <int, string>(16, "INITIALISING"));

                return(temp);
            }

            return(null);
        }
Ejemplo n.º 38
0
 public void EjectQuarter()
 {
     CurrentState.EjectQuarter();
 }
Ejemplo n.º 39
0
 public void OnEscapeButtonPressed(object sender, object args)
 {
     CurrentAbility = null;
     CurrentState.OnEscapeButtonPressed();
 }
Ejemplo n.º 40
0
 public void TurnCrank()
 {
     CurrentState.TurnCrank();
     CurrentState.Dispense();
 }
Ejemplo n.º 41
0
    protected virtual IEnumerator Talking()
    {
        yield return new WaitForSeconds (talkingTime);

        currentState = CurrentState.CS_Walking;

        yield return null;
    }
Ejemplo n.º 42
0
        //check on the type of the current state
        public bool IsInState(State <entity_type> s)
        {
            bool answ = (s.GetType() == CurrentState.GetType());

            return(answ);
        }
Ejemplo n.º 43
0
    private IEnumerator CrossStreet(GameObject _crossingTrigger)
    {
        yield return new WaitForSeconds (UnityEngine.Random.Range(0.35f, 0.55f));

        currentState = CurrentState.CS_Crossing;

        GameObject newCamPoint =  _crossingTrigger.GetComponent<CornerTrigger> ().GetCitizenCamerapoint (currentCamPoint);
        currentCamPoint = newCamPoint;
        transform.eulerAngles = new Vector3 (transform.eulerAngles.x, newCamPoint.transform.eulerAngles.y, newCamPoint.transform.eulerAngles.z);

        //Vector3 targetVec = transform.forward * _crossingTrigger.GetComponent<CornerTrigger> ().distanceToCross;

        while(isCrossing)
        {
            transform.position += (_crossingTrigger.transform.forward * moveSpeed * Time.deltaTime);
            yield return null;
        }

        direction = RandomDirection ();
        currentState = CurrentState.CS_Walking;

        yield return null;
    }
Ejemplo n.º 44
0
        public override void VisitMethod(Method method)
        {
            if (method == null) return;
            
            // closures used from methods are visited from the method from which they are referenced
            if (HelperMethods.IsCompilerGenerated(method)) return;

            var savedState = this.currentState;
            try
            {
                this.currentState = savedState.Derive(method);
                if (this.contractNodes.IsObjectInvariantMethod(method))
                {
                    return;
                }

                // Check Abbreviators

                if (ContractNodes.IsAbbreviatorMethod(method))
                {
                    if (method.IsVirtual)
                    {
                        this.HandleError(
                            new Error(1064,
                                "Contract abbreviator method '" + method.FullName +
                                "' cannot be virtual or implement an interface method.'",
                                HelperMethods.SourceContextOfMethod(method)));
                    }

                    if (!HelperMethods.IsVoidType(method.ReturnType))
                    {
                        this.HandleError(
                            new Error(1060,
                                "Contract abbreviator method '" + method.FullName + "' must have void return type.'",
                                HelperMethods.SourceContextOfMethod(method)));
                    }

                    if (method.Contract != null)
                    {
#if false
            if (IsNonTrivial(method.Contract.ContractInitializer))
            {
              this.HandleError(new Error(1061, "Contract abbreviator validator method '" + method.FullName + "' may not use closures.'",
                HelperMethods.SourceContextOfMethod(method)));
            }
#endif
                        if (method.Contract.HasLegacyValidations)
                        {
                            this.HandleError(
                                new Error(1062,
                                    "Contract abbreviator '" + method.FullName +
                                    "' cannot contain if-then-throw contracts or validator calls. Only regular contracts and abbreviator calls are allowed.",
                                    HelperMethods.SourceContextOfMethod(method)));
                        }

                        if (method.Contract.EnsuresCount + method.Contract.RequiresCount == 0)
                        {
                            this.HandleError(
                                new Warning(1063, "No contracts recognized in contract abbreviator '" + method.FullName + "'.",
                                    HelperMethods.SourceContextOfMethod(method)));
                        }
                    }
                    else
                    {
                        // no contracts
                        this.HandleError(
                            new Warning(1063, "No contracts recognized in contract abbreviator '" + method.FullName + "'.",
                                HelperMethods.SourceContextOfMethod(method)));
                    }

                    // abbreviator code must be completely visible to all callers as it is effectively inlined there.
                    this.visibilityChecker.CheckRequires(method.Contract);
                    this.visibilityChecker.CheckAbbreviatorEnsures(method.Contract);

                    return; // no further checks as we check the rest in use-site methods.
                }

                // Check Contracts contents and visibility

                this.CheckMethodContract(method.Contract);

                // Check purity

                this.purityChecker.Check(method);

                // Check Method Body

                this.methodBodyChecker.Check(method);

                SourceContext sourceContext = HelperMethods.SourceContextOfMethod(method);
                
                Method firstRootMethod = null;

                var methodDeclaringType = method.DeclaringType;

                Contract.Assume(methodDeclaringType != null);
                
                TypeNode classForWhichThisIsContractMethod = HelperMethods.IsContractTypeForSomeOtherType(methodDeclaringType, this.contractNodes);

                foreach (var rootMethod in RootMethodsForRequires(method))
                {
                    Contract.Assume(rootMethod != null);

                    if (classForWhichThisIsContractMethod != null)
                    {
                        if (method.Contract == null) continue;

                        if (rootMethod.DeclaringType != classForWhichThisIsContractMethod)
                        {
                            this.HandleError(
                                new Warning(1076,
                                    string.Format(
                                        "Contract class {2} cannot define contract for method {0} as its original definition is not in type {1}. Define the contract on type {3} instead.",
                                        rootMethod.FullName, classForWhichThisIsContractMethod, methodDeclaringType.FullName,
                                        rootMethod.DeclaringType), 
                                    sourceContext));

                            continue;
                        }

                        if (!rootMethod.IsAbstract)
                        {
                            this.HandleError(
                                new Error(1077,
                                    string.Format(
                                        "Contract class {1} cannot define contract for non-abstract method {0}. Define the contract on {0} instead.",
                                        rootMethod.FullName, methodDeclaringType.FullName), 
                                    sourceContext));

                            continue;
                        }

                        // contract class methods can only override/implement the methods of their original type
                        continue;
                    }

                    if (!allowPreconditionsInOverrides)
                    {
                        // Overrides cannot add preconditions unless this is "the" contract method for an abstract method

                        if (method.Contract != null && method.Contract.Requires != null)
                        {
                            foreach (RequiresPlain req in method.Contract.Requires)
                            {
                                if (req == null) continue;

                                if (!this.explicitUserValidations || !req.IsFromValidation)
                                {
                                    SourceContext sc = req.SourceContext;
                                    if (rootMethod.DeclaringType is Interface)
                                    {
                                        this.HandleError(
                                            new Warning(1033,
                                                string.Format( "Method '{0}' implements interface method '{1}', thus cannot add Requires.", method.FullName, rootMethod.FullName), 
                                                sc));
                                    }
                                    else
                                    {
                                        this.HandleError(
                                            new Warning(1032,
                                                string.Format("Method '{0}' overrides '{1}', thus cannot add Requires.", method.FullName, rootMethod.FullName), 
                                                sc));
                                    }

                                    return; // only one error per method
                                }
                            }
                        }

                        // Multiple root methods with contracts

                        // check that none of them have contracts
                        if (firstRootMethod == null)
                        {
                            firstRootMethod = rootMethod;
                        }
                        else
                        {
                            bool someContracts = HasPlainRequires(GetMethodWithContractFor(rootMethod)) ||
                                                 HasPlainRequires(GetMethodWithContractFor(firstRootMethod));
                            if (someContracts)
                            {
                                // found 2 that are in conflict and at least one of them has contracts
                                this.HandleError(new Warning(1035,
                                    String.Format(
                                        "Method '{0}' cannot implement/override two methods '{1}' and '{2}', where one has Requires.",
                                        method.FullName, firstRootMethod.FullName, rootMethod.FullName), sourceContext));

                                return; // only one error per method
                            }
                        }
                    }

                    // if (classForWhichThisIsContractMethod != null) continue; // skip rest of checks in this iteration

                    // Check that validations are present if necessary

                    if (this.explicitUserValidations && !HasValidations(method.Contract))
                    {
                        var rootMethodContract = GetMethodWithContractFor(rootMethod).Contract;
                        if (rootMethodContract != null)
                        {
                            for (int i = 0; i < rootMethodContract.RequiresCount; i++)
                            {
                                var req = (RequiresPlain) rootMethodContract.Requires[i];
                                if (req == null) continue;

                                if (!req.IsWithException) continue;
                                
                                var operation = (rootMethod.DeclaringType is Interface) ? "implements" : "overrides";
                                
                                if (req.SourceConditionText != null && req.ExceptionType.Name != null)
                                {
                                    this.HandleError(new Warning(1055,
                                        String.Format(
                                            "Method '{0}' should contain custom argument validation for 'Requires<{3}>({2})' as it {4} '{1}' which suggests it does. If you don't want to use custom argument validation in this assembly, change the assembly mode to 'Standard Contract Requires'.",
                                            method.FullName,
                                            rootMethod.FullName,
                                            req.SourceConditionText,
                                            req.ExceptionType.Name.Name,
                                            operation),
                                        sourceContext));
                                }
                                else
                                {
                                    this.HandleError(new Warning(1055,
                                        String.Format(
                                            "Method '{0}' should contain custom argument validation as it {2} '{1}' which suggests it does. If you don't want to use custom argument validation in this assembly, change the assembly mode to 'Standard Contract Requires'.",
                                            method.FullName,
                                            rootMethod.FullName,
                                            operation),
                                        sourceContext));

                                    return; // avoid dups
                                }
                            }
                        }
                    }
                }

                // Check that OOB types have no legacy requires (can't inherit them anyway, so should be Requires<E>)

                if (classForWhichThisIsContractMethod != null)
                {
                    if (HasValidations(method.Contract))
                    {
                        this.HandleError(new Error(1078,
                            string.Format(
                                "Method '{0}' annotating type '{1}' should use Requires<E> instead of custom validation.",
                                method.FullName,
                                classForWhichThisIsContractMethod.FullName),
                            sourceContext));
                    }

                    // skip rest of checks
                    return;
                }

                // Explicit parameter validations should not use Requires<E>

                if (this.explicitUserValidations && method.Contract != null)
                {
                    for (int i = 0; i < method.Contract.RequiresCount; i++)
                    {
                        var req = (RequiresPlain) method.Contract.Requires[i];
                        if (req == null) continue;

                        if (req.IsFromValidation) continue;
                        
                        if (!req.IsWithException) continue;
                        
                        // found Requires<E>
                        this.HandleError(new Error(1058,
                            String.Format(
                                "Method '{0}' should not have Requires<E> contract when assembly mode is set to 'Custom Parameter Validation'. Either change it to a legacy if-then-throw validation or change the assembly mode to 'Standard Contract Requires'.",
                                method.FullName), req.SourceContext));
                        
                        return; // avoid duplicate errors.
                    }
                }

                // non-user validation assembly

                if (!this.explicitUserValidations && HasValidations(method.Contract))
                {
                    if (firstRootMethod != null)
                    {
                        this.HandleError(new Warning(1056,
                            String.Format(
                                "Method '{0}' has custom parameter validation but assembly mode is not set to support this. It will be ignored (but base method contract may be inherited).",
                                method.FullName), sourceContext));
                    }
                    else
                    {
                        this.HandleError(new Warning(1057,
                            String.Format(
                                "Method '{0}' has custom parameter validation but assembly mode is not set to support this. It will be treated as Requires<E>.",
                                method.FullName), sourceContext));
                    }
                }

                // Check Validators

                if (ContractNodes.IsValidatorMethod(method))
                {
                    if (method.IsVirtual)
                    {
                        this.HandleError(new Error(1059,
                            "Contract argument validator method '" + method.FullName +
                            "' cannot be virtual or implement an interface method.'",
                            HelperMethods.SourceContextOfMethod(method)));
                    }

                    if (!HelperMethods.IsVoidType(method.ReturnType))
                    {
                        this.HandleError(new Error(1050,
                            "Contract argument validator method '" + method.FullName + "' must have void return type.'",
                            HelperMethods.SourceContextOfMethod(method)));
                    }

                    if (method.Contract != null)
                    {
#if false
            if (IsNonTrivial(method.Contract.ContractInitializer))
            {
              this.HandleError(new Error(1051, "Contract argument validator method '" + method.FullName + "' may not use closures.'",
                HelperMethods.SourceContextOfMethod(method)));
            }
#endif
                        if (!method.Contract.HasLegacyValidations)
                        {
                            this.HandleError(new Warning(1053,
                                "No validation code recognized in contract argument validator '" + method.FullName +
                                "'.",
                                HelperMethods.SourceContextOfMethod(method)));
                        }

                        if (HasNonValidationContract(method.Contract))
                        {
                            this.HandleError(new Error(1054,
                                "Contract argument validator '" + method.FullName +
                                "' cannot contain ordinary contracts. Only if-then-throw or validator calls are allowed.",
                                HelperMethods.SourceContextOfMethod(method)));
                        }
                    }
                    else
                    {
                        // no validations
                        this.HandleError(new Warning(1053,
                            "No validation code recognized in contract argument validator '" + method.FullName + "'.",
                            HelperMethods.SourceContextOfMethod(method)));
                    }
                }
            }
            finally
            {
                this.currentState = savedState;
            }
        }
Ejemplo n.º 45
0
    public virtual bool StartTalking()
    {
        if(currentState == CurrentState.CS_Walking)
        {
            currentState = CurrentState.CS_Talking;
            StartCoroutine(Talking ());
            return true;
        }

        return false;
    }
Ejemplo n.º 46
0
 public override void Update()
 {
     // only needs to update current state
     CurrentState.Update();
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Returns whether a specific key is currently released up.
 /// </summary>
 /// <param name="key">Key to check</param>
 /// <returns>True on released up</returns>
 public Boolean IsKeyUp(Keys key)
 {
     return(CurrentState.IsKeyUp(key));
 }
Ejemplo n.º 48
0
 public override bool IsMovingDown()
 {
     return(CurrentState.IsKeyDown(Keys.A));
 }
Ejemplo n.º 49
0
 private void setCancelled() {
     _currentState = CurrentState.Canceled;
 }
 public void Update()
 {
     GlobalState?.Execute(_owner);
     CurrentState?.Execute(_owner);
 }
Ejemplo n.º 51
0
 private void btnOk_Click(object sender, EventArgs e) {
     _currentState = CurrentState.Accepted;
 }
Ejemplo n.º 52
0
        ////=============================================================================
        //// Private Method
        ////
        ////=============================================================================

        /// <summary>
        /// 再描画する
        /// </summary>
        private void Refresh()
        {
            CurrentState.Draw(this);
        }
Ejemplo n.º 53
0
        public static void MapLogs(string[] logs)
        {
            foreach (var logfile in logs)
            {
                if (File.Exists(logfile + ".jpg"))
                    continue;

                double minx = 99999;
                double maxx = -99999;
                double miny = 99999;
                double maxy = -99999;

                List<PointLatLngAlt> locs = new List<PointLatLngAlt>();
                try
                {
                    if (logfile.ToLower().EndsWith(".tlog"))
                    {
                        MAVLinkInterface mine = new MAVLinkInterface();


                        using (mine.logplaybackfile = new BinaryReader(File.Open(logfile, FileMode.Open, FileAccess.Read, FileShare.Read)))
                        {
                            mine.logreadmode = true;

                            CurrentState cs = new CurrentState();

                            while (mine.logplaybackfile.BaseStream.Position < mine.logplaybackfile.BaseStream.Length)
                            {
                                byte[] packet = mine.readPacket();

                                if (packet.Length < 5)
                                    continue;

                                try
                                {
                                    if (MainV2.speechEngine != null)
                                        MainV2.speechEngine.SpeakAsyncCancelAll();
                                }
                                catch { }

                                if (packet[5] == (byte)MAVLink.MAVLINK_MSG_ID.GLOBAL_POSITION_INT)
                                {
                                    var loc = packet.ByteArrayToStructure<MAVLink.mavlink_global_position_int_t>(6);

                                    if (loc.lat == 0 || loc.lon == 0)
                                        continue;

                                    locs.Add(new PointLatLngAlt(loc.lat / 10000000.0f, loc.lon / 10000000.0f));

                                    minx = Math.Min(minx, loc.lon / 10000000.0f);
                                    maxx = Math.Max(maxx, loc.lon / 10000000.0f);
                                    miny = Math.Min(miny, loc.lat / 10000000.0f);
                                    maxy = Math.Max(maxy, loc.lat / 10000000.0f);
                                }
                            }
                        }

                    }
                    else if (logfile.ToLower().EndsWith(".bin") || logfile.ToLower().EndsWith(".log"))
                    {
                        bool bin = logfile.ToLower().EndsWith(".bin");

                        using (var st = File.OpenRead(logfile))
                        {
                            using (StreamReader sr = new StreamReader(st))
                            {
                                while (sr.BaseStream.Position < sr.BaseStream.Length)
                                {
                                    string line = "";

                                    if (bin)
                                    {
                                        line = BinaryLog.ReadMessage(sr.BaseStream);
                                    }
                                    else
                                    {
                                        line = sr.ReadLine();
                                    }

                                    if (line.StartsWith("FMT"))
                                    {
                                        DFLog.FMTLine(line);
                                    }
                                    else if (line.StartsWith("GPS"))
                                    {
                                        var item = DFLog.GetDFItemFromLine(line, 0);

                                        var lat = double.Parse(item.items[DFLog.FindMessageOffset(item.msgtype, "Lat")]);
                                        var lon = double.Parse(item.items[DFLog.FindMessageOffset(item.msgtype, "Lng")]);

                                        if (lat == 0 || lon == 0)
                                            continue;

                                        locs.Add(new PointLatLngAlt(lat, lon));

                                        minx = Math.Min(minx, lon);
                                        maxx = Math.Max(maxx, lon);
                                        miny = Math.Min(miny, lat);
                                        maxy = Math.Max(maxy, lat);
                                    }
                                }
                            }
                        }
                    }


                    if (locs.Count > 10)
                    {
                        // add a bit of buffer
                        var area = RectLatLng.FromLTRB(minx - 0.001, maxy + 0.001, maxx + 0.001, miny - 0.001);
                        var map = GetMap(area);

                        var grap = Graphics.FromImage(map);

                        PointF lastpoint = new PointF();

                        foreach (var loc in locs)
                        {
                            PointF newpoint = GetPixel(area, loc, map.Size);

                            if (!lastpoint.IsEmpty)
                                grap.DrawLine(Pens.Red, lastpoint, newpoint);

                            lastpoint = newpoint;
                        }

                        map.Save(logfile + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                        map.Dispose();

                        map = null;
                    }
                    else
                    {
                        var map = new Bitmap(100, 100);

                        var grap = Graphics.FromImage(map);

                        grap.DrawString("No gps data", SystemFonts.DefaultFont, Brushes.Red, 0, 0, StringFormat.GenericDefault);

                        map.Save(logfile + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                        map.Dispose();

                        map = null;
                    }
                }
                catch { continue; }
            }
        }
Ejemplo n.º 54
0
 public override int GetHashCode()
 {
     return(17 + 31 * CurrentState.GetHashCode() + 31 * Token.GetHashCode());
 }
Ejemplo n.º 55
0
        public override void VisitTypeNode(TypeNode typeNode)
        {
            if (typeNode == null) return;

            var savedState = this.currentState;
            this.currentState = savedState.Derive(typeNode);
            
            try
            {
                GatherInvariantMethods(typeNode.Members);

                this.CheckTypeNode(typeNode);

                base.VisitTypeNode(typeNode);

                this.invariantCallChecker.VisitMemberList(typeNode.Members);
            }
            finally
            {
                this.currentState = savedState;
            }
        }
Ejemplo n.º 56
0
 public void PrintMyStatus()
 {
     Console.WriteLine("state= " + CurrentState.ToString());
     Console.WriteLine("lever_position=" + CurrentLeverPosition.ToString());
 }
Ejemplo n.º 57
0
 public MoveGenerator(CurrentState initialState)
 {
     m_currentState    = initialState.CurrentBoard;
     m_playerCharacter = initialState.NextMove;
 }
 public bool HandleMessage(Telegram telegram)
 {
     return(CurrentState?.OnMessage(_owner, telegram) == true ||
            GlobalState?.OnMessage(_owner, telegram) == true);
 }
Ejemplo n.º 59
0
        private void Open()
        {
            Console.WriteLine($"In State Machine Class : Open");

            CurrentState.Init();
        }
 public void ExecuteCurrentState()
 {
     CurrentState.Execute(this);
 }