Ejemplo n.º 1
0
		public void HandleWithMouse(Mouse mouse)
		{
			Position = mouse.Position;
			if (mouse.GetButtonState(Button) == State &&
				ScreenSpace.Current.Viewport.Contains(mouse.Position))
				Invoke();
		}
Ejemplo n.º 2
0
 public EditorOpenTkViewport(Window window, Mouse mouse)
 {
     Window = window;
     this.mouse = mouse;
     screenSpace = new Camera2DScreenSpace(window);
     Settings.Current.LimitFramerate = 60;
 }
Ejemplo n.º 3
0
        public Menu InvokeContextMenu(Condition condition)
        {
            var mouse = new Mouse();
            mouse.RightClick(this);

            return new Window(AutomationElement.RootElement, "Desktop").Find<Menu>(condition);
        }
Ejemplo n.º 4
0
 internal InputManager()
 {
     #if !WINDOWS_PHONE
     Players = new PlayerInputCollection();
     Mouse = new Mouse();
     #endif
 }
Ejemplo n.º 5
0
Archivo: main.cs Proyecto: KDE/qyoto
    public static int Main(string[] args)
    {
        Q_INIT_RESOURCE("mice");
        new QApplication(args);

        scene = new QGraphicsScene();
        scene.SetSceneRect(-300, -300, 600, 600);
        scene.itemIndexMethod = QGraphicsScene.ItemIndexMethod.NoIndex;

        for (int i = 0; i < MouseCount; ++i) {
            Mouse mouse = new Mouse();
            mouse.SetPos(Math.Sin((i * 6.28) / MouseCount) * 200,
                          Math.Cos((i * 6.28) / MouseCount) * 200);
            scene.AddItem(mouse);
        }

        QGraphicsView view = new QGraphicsView(scene);
        view.SetRenderHint(QPainter.RenderHint.Antialiasing);
        view.BackgroundBrush = new QBrush(new QPixmap(":/images/cheese.jpg"));
        view.CacheMode = (int) QGraphicsView.CacheModeFlag.CacheBackground;
        view.dragMode = QGraphicsView.DragMode.ScrollHandDrag;
        view.WindowTitle = QT_TRANSLATE_NOOP("QGraphicsView", "Colliding Mice");
        view.Resize(400, 300);
        view.Show();

        return QApplication.Exec();
    }
Ejemplo n.º 6
0
    public override void OnStart()
    {
        base.OnStart();

        sound = gameObject.RequireComponent<CSound>();
        doorButtonMesh = gameObject.RequireComponent<CMeshRenderer>();

        if (doorName != null && doorName.Length > 0)
        {
            door = GameObject.GetGameObjectByName(doorName);
            if (requiresSurveillancePlayer)
                doorButtonMesh.GetMaterial().SetColor(SharpMocha.YELLOW);
            else
                doorButtonMesh.GetMaterial().SetColor(SharpMocha.CORNFLOWER_BLUE);
        }
        else
        {
            isButtonRed = true; // it is a default locked button
        }
        doorButtonColor = doorButtonMesh.GetMaterial().GetColor();

        playerMouse = GetScript<Mouse>(Common.GetStealthPlayerMouse() );
        player = Common.GetStealthPlayer();
        playerScript = Common.GetStealthPlayerScript();
        ocuConsole = GetScript<OcuConsoleScreen>(Common.GetSurveillancePlayerConsoleScreen());
    }
Ejemplo n.º 7
0
 public Menu(Screen screen, Mouse mouse)
 {
     _screen = screen;
     _mouse = mouse;
     _subjectBarStatus = MenuState.MENU_CLOSED;
     _objectBarStatus = MenuState.MENU_CLOSED;
 }
Ejemplo n.º 8
0
        public GwenInput(InputManager inputManager)
        {
            this.inputManager = inputManager;

            canvas = null;
            mouseX = 0;
            mouseY = 0;
            m_AltGr = false;

            mouse = inputManager.Mouse;
            if (mouse != null)
            {
                mouse.MouseMove += ProcessMouseMove;
                mouse.MouseDrag += ProcessMouseDrag;
                mouse.MouseButtonPress += ProcessMouseButtonPressed;
                mouse.MouseButtonRelease += ProcessMouseButtonReleased;
                mouse.MouseWheelMove += ProcessMouseWheel;
            }

            keyboard = inputManager.Keyboard;
            if (keyboard != null)
            {
                keyboard.KeyPress += ProcessKeyDown;
                keyboard.KeyRelease += ProcessKeyUp;
                keyboard.KeyText += ProcessText;
            }
        }
Ejemplo n.º 9
0
 public InputCommands(Keyboard keyboard, Mouse mouse, Touch touch, GamePad gamePad)
 {
     this.keyboard = keyboard;
     this.mouse = mouse;
     this.touch = touch;
     this.gamePad = gamePad;
 }
Ejemplo n.º 10
0
		public void HandleWithMouse(Mouse mouse)
		{
			if (Position == mouse.Position)
				return;
			Position = mouse.Position;
			if (ScreenSpace.Current.Viewport.Contains(mouse.Position))
				Invoke();
		}
Ejemplo n.º 11
0
	// Use this for initialization
	public void Start () {
		//Debug.Log ("START FROM ABILITY");
		caster = this.transform.parent.gameObject;
		//Debug.Log (caster);
		mouseS = GameObject.Find("Main Camera").GetComponent<Mouse> ();
		aMan = GameObject.Find("AbilityManager").GetComponent<AbilityManager> ();
		guiScript = GameObject.Find ("SpawnGUI").GetComponent<UserInterfaceGUI> ();
	}
Ejemplo n.º 12
0
 public bool AddMouse(Mouse m)
 {
     if (mice.Contains(m)) {
         return false;
     } else {
         mice.Add(m);
         return true;
     }
 }
Ejemplo n.º 13
0
        public MessageBoxScreen(string message, Texture2D mouseText)
        {
            IsPopup = true;

            TransitionOnTime = TimeSpan.FromSeconds(0.2);
            TransitionOffTime = TimeSpan.FromSeconds(0.2);

            mouse = new Mouse(mouseText);
        }
Ejemplo n.º 14
0
        public GameCore()
        {
            _renderEngine = new RenderEngine();
            _input = new DirectInput();
            _keyboard = new Keyboard(_input);
            _mouse = new Mouse(_input);

            Initialize();
        }
Ejemplo n.º 15
0
		public void HandleWithMouse(Mouse mouse)
		{
			bool wasJustStartedPressing = lastState == State.Pressing;
			State currentState = mouse.GetButtonState(Button);
			var isNowReleased = currentState == State.Releasing;
			lastState = currentState;
			if (isNowReleased && wasJustStartedPressing)
				Invoke();
		}
Ejemplo n.º 16
0
 public SelectedEventArgs(int position, Mouse mouse, int count, double x,double y,ChessPiece chess)
 {
     this.Position = position;
     this.Mouse = mouse;
     this.Count = count;
     this.Chess = chess;
     this.X = x;
     this.Y = y;
 }
Ejemplo n.º 17
0
        public bool Initiliase(IntPtr windowHandle)
        {
            this.input = MOIS.InputManager.CreateInputSystem((uint)windowHandle.ToInt32());

            //Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
            this.keyboard = (Keyboard)input.CreateInputObject(MOIS.Type.OISKeyboard, true);
            this.mouse = (Mouse)input.CreateInputObject(MOIS.Type.OISMouse, true);
            return true;
        }
Ejemplo n.º 18
0
		public void HandleWithMouse(Mouse mouse)
		{
			if (Position == mouse.Position)
				return;
			var isButton = mouse.GetButtonState(Button) == State;
			Position = mouse.Position;
			if (isButton && ScreenSpace.Current.Viewport.Contains(mouse.Position))
				Invoke();
		}
Ejemplo n.º 19
0
        static void DoStartup()
        {
            ParamList pl = new ParamList();
            Form1 form = new Form1();
            form.Show();
            pl.Insert("WINDOW", form.Handle.ToString());

            //Default mode is foreground exclusive..but, we want to show mouse - so nonexclusive
            pl.Insert("w32_mouse", "DISCL_FOREGROUND");
            pl.Insert("w32_mouse", "DISCL_NONEXCLUSIVE");

            //This never returns null.. it will raise an exception on errors
            g_InputManager = InputManager.CreateInputSystem(pl);

            uint v = InputManager.VersionNumber;
            Console.WriteLine("OIS Version: " + (v >> 16) + "." + ((v >> 8) & 0x000000FF) + "." + (v & 0x000000FF)
                + "\n\tRelease Name: " //+ InputManager.VersionName
                + "\n\tPlatform: " + g_InputManager.InputSystemName()
                + "\n\tNumber of Mice: " + g_InputManager.GetNumberOfDevices(MOIS.Type.OISMouse)
                + "\n\tNumber of Keyboards: " + g_InputManager.GetNumberOfDevices(MOIS.Type.OISKeyboard)
                + "\n\tNumber of Joys/Pads = " + g_InputManager.GetNumberOfDevices(MOIS.Type.OISJoyStick));

            //List all devices
            DeviceList list = g_InputManager.ListFreeDevices();
            foreach (KeyValuePair<MOIS.Type, string> pair in list)
                Console.WriteLine("\n\tDevice: " + g_DeviceType[(int)pair.Key] + " Vendor: " + pair.Value);

            g_kb = (Keyboard)g_InputManager.CreateInputObject(MOIS.Type.OISKeyboard, true);
            g_kb.KeyPressed += new KeyListener.KeyPressedHandler(KeyPressed);
            g_kb.KeyReleased += new KeyListener.KeyReleasedHandler(KeyReleased);

            g_m = (Mouse)g_InputManager.CreateInputObject(MOIS.Type.OISMouse, true);
            g_m.MouseMoved += new MouseListener.MouseMovedHandler(MouseMoved);
            g_m.MousePressed += new MouseListener.MousePressedHandler(MousePressed);
            g_m.MouseReleased += new MouseListener.MouseReleasedHandler(MouseReleased);

            MouseState_NativePtr ms = g_m.MouseState;
            ms.width = form.Width;
            ms.height = form.Height;

            //This demo only uses at max 4 joys
            int numSticks = g_InputManager.GetNumberOfDevices(MOIS.Type.OISJoyStick);
            if (numSticks > 4) numSticks = 4;

            g_joys = new JoyStick[numSticks];

            for (int i = 0; i < numSticks; ++i)
            {
                g_joys[i] = (JoyStick)g_InputManager.CreateInputObject(MOIS.Type.OISJoyStick, true);
                g_joys[i].AxisMoved += new JoyStickListener.AxisMovedHandler(AxisMoved);
                g_joys[i].ButtonPressed += new JoyStickListener.ButtonPressedHandler(JoyButtonPressed);
                g_joys[i].ButtonReleased += new JoyStickListener.ButtonReleasedHandler(JoyButtonReleased);
                g_joys[i].PovMoved += new JoyStickListener.PovMovedHandler(PovMoved);
                g_joys[i].Vector3Moved += new JoyStickListener.Vector3MovedHandler(Vector3Moved);
            }
        }
Ejemplo n.º 20
0
 public static void Init(Form mainWindow)
 {
     var dinput = new DirectInput();
     _keyboard = new Keyboard(dinput);
     _keyboard.Acquire();
     _mouse = new Mouse(dinput);
     _mouse.Acquire();
     dinput.Dispose();
     dinput = null;
 }
Ejemplo n.º 21
0
 public IntroLayer()
 {
     m_mouse = new Mouse();
     KeyboardEnabled = true;
     TouchEnabled = true;
     AccelerometerEnabled = true;
     AnchorPoint = new CCPoint(0, 0);
     m_mouse.SetJson(GetPath("walker_magic.json"));
     ScheduleUpdate();
 }
Ejemplo n.º 22
0
		public void HandleWithMouse(Mouse mouse)
		{
			if (mouse.GetButtonState(Button) == State.Pressing)
				StartPosition = mouse.Position;
			Position = mouse.Position;
			if (!CheckHoverState(mouse))
				Elapsed = 0.0f;
			else if (IsHovering())
				Invoke();
		}
Ejemplo n.º 23
0
 /// <summary>
 /// Initialzes the Game.
 /// </summary>
 /// <param name="sceneManager">The Mogre SceneManager.</param>
 /// <param name="camera">The game CameraMan for the MouseControl.</param>
 /// <param name="mWindow">The RednerWindow for sending the width and height of the window.</param>
 /// <param name="mouse">The Mogre Mouse for GUI.</param>
 /// <param name="keyboard">The Mogre Keyboard for GUI.</param>
 /// <returns>Returns initializes Game singleton instance.</returns>
 private Game(SceneManager sceneManager, CameraMan camera, RenderWindow mWindow, Mouse mouse, Keyboard keyboard)
 {
     sceneMgr = sceneManager;
     gameObjectMgr = GameObjectManager.GetInstance();
     gameGUI = new MyGUI((int)mWindow.Width, (int)mWindow.Height, mouse, keyboard);
     mouseControl = MouseControl.GetInstance(camera, (int)mWindow.Width, (int)mWindow.Height);
     paused = true;
     soundPlayer = new SoundPlayer(mWindow);
     mission = new Mission();
 }
Ejemplo n.º 24
0
		public void HandleWithMouse(Mouse mouse)
		{
			int currentScrollValueDifference = mouse.ScrollWheelValue - LastScrollWheelValue;
			LastScrollWheelValue = mouse.ScrollWheelValue;
			if(!ScreenSpace.Current.Viewport.Contains(mouse.Position))
				return;
			ZoomAmount = currentScrollValueDifference * 0.1f;
			if (ZoomAmount != 0)
				Invoke();
		}
Ejemplo n.º 25
0
		public void HandleWithMouse(Mouse mouse)
		{
			if (StartArea.Contains(mouse.Position) && mouse.GetButtonState(Button) == State.Pressing)
				StartDragPosition = mouse.Position;
			else if (StartDragPosition != Vector2D.Unused &&
				mouse.GetButtonState(Button) != State.Released)
				if (StartDragPosition.DistanceTo(mouse.Position) > PositionEpsilon)
					Invoke();
				else
					StartDragPosition = Vector2D.Unused;
		}
Ejemplo n.º 26
0
 public static void Destroy()
 {
     if (_keyboard != null) {
         _keyboard.Dispose();
         _keyboard = null;
     }
     if (_mouse != null) {
         _mouse.Dispose();
         _mouse = null;
     }
 }
Ejemplo n.º 27
0
 // TODO: Zapper with "Wild Gun Man" - The Gang Mode is not working !
 public ZapperConnecter(IntPtr handle, int winPosX, int winPosY, int videoW, int videoH)
 {
     this.scanlinesCount = 240;
     this.videoW = videoW;
     this.videoH = videoH;
     this.winPosX = winPosX;
     this.winPosY = winPosY;
     DirectInput di = new DirectInput();
     mouse = new Mouse(di);
     mouse.SetCooperativeLevel(handle, CooperativeLevel.Nonexclusive | CooperativeLevel.Foreground);
 }
Ejemplo n.º 28
0
        public Input()
        {
            _directInput = new DirectInput();

            try
            {
                Result result;

                _keyboard = new Keyboard(_directInput);

                IntPtr handle = Engine.GameEngine.Window;

                if ((result = _keyboard.SetCooperativeLevel(handle, CooperativeLevel.Nonexclusive | CooperativeLevel.Background)) != ResultCode.Success)
                {
                    Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(result.Description,
                        result.Name, "keyboard cooperation"));
                }

                _mouse = new Mouse(_directInput);

                if ((result = _mouse.SetCooperativeLevel(handle, CooperativeLevel.Foreground | CooperativeLevel.Nonexclusive)) != ResultCode.Success)
                {
                    Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(result.Description,
                        result.Name, "mouse cooperation"));
                }

                if ((result = _keyboard.Acquire()) != ResultCode.Success)
                {
                    Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(result.Description,
                        result.Name, "keyboard acquire"));
                }

                if ((result = _mouse.Acquire()) != ResultCode.Success)
                {
                    Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(result.Description,
                        result.Name, "mouse acquire"));
                }

                Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData("worked", "worked", "worked"));
            }
            catch (DirectInputException e)
            {
                Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(e.Message, e.Source, e.StackTrace));
            }
            catch (Exception e)
            {
                Engine.GameEngine.Exception.Exceptions.Add(new ExceptionData(e.Message, e.Source, e.StackTrace));
            }
            finally
            {
                Dispose();
            }
        }
Ejemplo n.º 29
0
		public void HandleWithMouse(Mouse mouse)
		{
			if (LastPosition.DistanceTo(mouse.Position) < PositionEpsilon)
			{
				if (IsHovering())
					Invoke();
			}
			else
			{
				LastPosition = mouse.Position;
				Elapsed = 0.0f;
			}
		}
Ejemplo n.º 30
0
        public static void Close()
        {
            if (m_mouse != null)
            {
                m_mouse.Dispose();
                m_mouse = null;
            }

            if (m_directInput != null)
            {
                m_directInput.Dispose();
                m_directInput = null;
            }
        }
Ejemplo n.º 31
0
        protected void MouseInput()
        {
            MouseState mState = Mouse.GetState();

            ship.Position = new Vector3(-mState.X, -mState.Y, ship.Position.Z);
        }
Ejemplo n.º 32
0
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

            // TODO: Add your update logic here
            MouseState mouseState = Mouse.GetState();

            foreach (Button button in buttons)
            {
                button.Update(gameTime, mouseState);

                if (button.IsMouseClick)
                {
                    string         filepath;
                    IPathAlgorithm a;

                    switch (button.Tag)
                    {
                    case "RegenerateGrid":
                        grid.RandomlyGenerateGrid();
                        grid.AlgorithmResults.Reset();
                        break;

                    case "SaveToFile":
                        filepath = DialogBoxes.SaveDialogBox.ShowDialog();
                        if (!string.IsNullOrWhiteSpace(filepath))
                        {
                            grid.WriteToFile(filepath);
                        }
                        break;

                    case "LoadFromFile":
                        filepath = DialogBoxes.LoadDialogBox.ShowDialog();
                        if (!string.IsNullOrWhiteSpace(filepath))
                        {
                            grid.LoadFromFile(filepath);
                            grid.AlgorithmResults.Reset();
                        }
                        break;

                    case "RunAStar":
                        grid.ClearCellValues();
                        using (DialogBoxes.SelectAlgorithmForm frm = new DialogBoxes.SelectAlgorithmForm(grid.Cells, grid.Start, grid.Goal))
                        {
                            frm.ShowDialog();
                            if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                            {
                                a = frm.PathAlgorithm;
                                grid.AlgorithmResults.Reset();
                                grid.AlgorithmResults = a.RunAlgorithm();
                                if (grid.AlgorithmResults.Success)
                                {
                                    grid.AlgorithmResults.StartAnimation();
                                }
                                else
                                {
                                    System.Windows.Forms.MessageBox.Show("No path found");
                                }
                            }
                        }

                        //a = new AStarPathAlgorithm(grid.Cells, grid.Start, grid.Goal);
                        //if (a.RunAlgorithm())
                        //{
                        //    grid.AlgorithmRunDetails = a.GetDetails();
                        //    grid.AlgorithmRunDetails.StartAnimation();
                        //}
                        //else
                        //{
                        //    grid.AlgorithmRunDetails.Reset();
                        //    System.Windows.Forms.MessageBox.Show("No path found");
                        //}
                        break;

                    //case "RunWeightedAStar":
                    //    using (DialogBoxes.WeightedAStartSelectForm frm = new DialogBoxes.WeightedAStartSelectForm())
                    //    {
                    //        frm.ShowDialog();
                    //        if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                    //        {
                    //            string h = frm.Heuristic;
                    //            decimal w = frm.Weight;
                    //            runHeuristic(h, w);
                    //        }
                    //    }
                    //    break;
                    //case "RunUniformCostSearch":
                    //    grid.ClearCellValues();
                    //    a = new Algorithms.UniformCostSearchPathAlgorithm(grid.Cells, grid.Start, grid.Goal);
                    //    if (a.RunAlgorithm())
                    //    {
                    //        grid.AlgorithmRunDetails = a.GetDetails();
                    //        grid.AlgorithmRunDetails.StartAnimation();
                    //    }
                    //    else
                    //    {
                    //        grid.AlgorithmRunDetails.Reset();
                    //        System.Windows.Forms.MessageBox.Show("No path found");
                    //    }
                    //    break;
                    case "SelectStartGoal":
                        using (DialogBoxes.StartGoalPairSelectForm frm = new DialogBoxes.StartGoalPairSelectForm(grid.StartGoalPairIndex, grid.StartGoalPairs))
                        {
                            frm.ShowDialog();
                            if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                            {
                                grid.StartGoalPairIndex = frm.StartGoalPairIndex;
                                grid.ClearCellValues();
                                grid.AlgorithmResults.Reset();
                            }
                        }
                        break;
                        //case "SequentialAStar":
                        //    AStarSequentialHeuristic aseq = new AStarSequentialHeuristic(grid.Cells, grid.Start, grid.Goal, 2, 1, 1);
                        //    aseq.Heuristics = new Delegates.HDelegate[] { Algorithms.Formulas.Heuristics.Manhattan, Algorithms.Formulas.Heuristics.Chebyshev };
                        //    Algorithms.DataStructures.AlgorithmResults ar = aseq.RunAlgorithm();
                        //    if (ar.Success)
                        //    {
                        //        System.Windows.Forms.MessageBox.Show("Success");
                        //    }
                        //    else
                        //        System.Windows.Forms.MessageBox.Show("No path found");
                        //    break;
                    }
                }
            }

            grid.Update(gameTime, mouseState);


            base.Update(gameTime);
        }
Ejemplo n.º 33
0
        public override void Update(UpdateState state)
        {
            if (Visible)
            {  //if we're not visible, do not update CityRenderer state...
                CoreGameScreen CurrentUIScr = (CoreGameScreen)GameFacade.Screens.CurrentUIScreen;

                m_LastMouseState = m_MouseState;
                m_MouseState     = Mouse.GetState();

                m_MouseMove = (m_MouseState.RightButton == ButtonState.Pressed);

                if (m_HandleMouse)
                {
                    if (m_MouseState.RightButton == ButtonState.Pressed && m_LastMouseState.RightButton == ButtonState.Released)
                    {
                        m_MouseStart = new Vector2(m_MouseState.X, m_MouseState.Y);  //if middle mouse button activated, record where we started pressing it (to use for panning)
                    }

                    else if (m_MouseState.LeftButton == ButtonState.Released && m_LastMouseState.LeftButton == ButtonState.Pressed)  //if clicked...
                    {
                        if (!m_Zoomed)
                        {
                            m_Zoomed = true;
                            double ResScale = 768.0 / m_ScrHeight;
                            double isoScale = (Math.Sqrt(0.5 * 0.5 * 2) / 5.10) * ResScale;
                            double hb       = m_ScrWidth * isoScale;
                            double vb       = m_ScrHeight * isoScale;

                            m_TargVOffX = (float)(-hb + m_MouseState.X * isoScale * 2);
                            m_TargVOffY = (float)(vb - m_MouseState.Y * isoScale * 2);  //zoom into approximate location of mouse cursor if not zoomed already
                        }
                        else
                        {
                            if (m_SelTile[0] != -1 && m_SelTile[1] != -1)
                            {
                                m_SelTileTmp[0] = m_SelTile[0];
                                m_SelTileTmp[1] = m_SelTile[1];

                                UIAlertOptions AlertCoords = new UIAlertOptions();
                                AlertCoords.Title = GameFacade.Strings.GetString("246", "1");
                                //AlertOptions.Message = GameFacade.Strings.GetString("215", "23", new string[]
                                //{ m_LotCost.ToString(), CurrentUIScr.ucp.MoneyText.Caption });

                                AlertCoords.Message = m_SelTile[0].ToString() + " " + m_SelTile[1].ToString();


                                foreach (LotTileEntry Lot in m_HousesData.LotTileData)
                                {
                                    if (Lot.x == m_SelTile[0] && Lot.y == m_SelTile[1])
                                    {
                                        m_CurrentLot = Lot;
                                    }
                                }


                                if (m_CurrentLot != null)
                                {
                                    UIAlertOptions AlertOptions = new UIAlertOptions();
                                    AlertOptions.Title = GameFacade.Strings.GetString("246", "1");
                                    //AlertOptions.Message = GameFacade.Strings.GetString("215", "23", new string[]
                                    //{ m_LotCost.ToString(), CurrentUIScr.ucp.MoneyText.Caption });

                                    AlertOptions.Message = m_CurrentLot.x.ToString() + " " + m_CurrentLot.y.ToString();
                                    //AlertOptions.Buttons = UIAlertButtons.YesNo;
                                }
                            }
                        }

                        CurrentUIScr.ucp.UpdateZoomButton();
                    }
                }
                else
                {
                    m_SelTile = new int[] { -1, -1 };
                }

                GameTime time = new GameTime();

                m_SecondsBehind += time.ElapsedGameTime.TotalSeconds;
                m_SecondsBehind -= 1 / 60;
                SetTimeOfDay(m_DayNightCycle % 1); //calculates sun/moon light colour and position
                m_DayNightCycle += 0.001;          //adjust the cycle speed here. When ingame, set m_DayNightCycle to to the percentage of time passed through the day. (0 to 1)

                m_ViewOffX = (m_TargVOffX) * m_ZoomProgress;
                m_ViewOffY = (m_TargVOffY) * m_ZoomProgress;
            }
        }
Ejemplo n.º 34
0
 public bool MouseOver()
 {
     return(Mouse.IsOver(Rect));
 }
Ejemplo n.º 35
0
        private void IconActions(bool draw)
        {
            // handle only right click
            if (!draw && !(Event.current.type == EventType.MouseDown && Event.current.button == 1))
            {
                return;
            }
            var unlocks = Unlocks();

            for (var i = 0; i < unlocks.Count; ++i)
            {
                var iconRect = new Rect(
                    IconsRect.xMax - (i + 1) * (IconSize.x + 4f),
                    IconsRect.yMin + (IconsRect.height - IconSize.y) / 2f,
                    IconSize.x,
                    IconSize.y);

                if (iconRect.xMin - IconSize.x < IconsRect.xMin &&
                    i + 1 < unlocks.Count)
                {
                    // stop the loop if we're about to overflow and have 2 or more unlocks yet to print.
                    iconRect.x = IconsRect.x + 4f;

                    if (draw)
                    {
                        GUI.DrawTexture(iconRect, Assets.MoreIcon, ScaleMode.ScaleToFit);
                        if (!PainterIs(Painter.Drag))
                        {
                            var tip = string.Join(
                                "\n",
                                unlocks.GetRange(i, unlocks.Count - i).Select(p => p.Second).ToArray());
                            TooltipHandler.TipRegion(iconRect, tip);
                        }
                    }
                    else if
                    (!draw && Mouse.IsOver(iconRect) &&
                     Find.WindowStack.FloatMenu == null)
                    {
                        var floatMenu = MakeInfoMenuFromDefs(unlocks.Skip(i).Select(p => p.First));
                        Find.WindowStack.Add(floatMenu);
                        Event.current.Use();
                    }
                    break;
                }
                var def = unlocks[i].First;

                if (draw)
                {
                    def.DrawColouredIcon(iconRect);
                    if (!PainterIs(Painter.Drag))
                    {
                        TooltipHandler.TipRegion(iconRect, unlocks[i].Second);
                    }
                }
                else if (Mouse.IsOver(iconRect))
                {
                    Dialog_InfoCard.Hyperlink link = new Dialog_InfoCard.Hyperlink(def);
                    link.OpenDialog();
                    Event.current.Use();
                    break;
                }
            }
        }
Ejemplo n.º 36
0
 protected override void PreUpdate(float state)
 {
     _mouseState = Mouse.GetState(_window);
     _isSlaping  = _mouseState.LeftButton == ButtonState.Pressed;
 }
Ejemplo n.º 37
0
        private static float DrawFactionRow(Faction faction, float rowY, Rect fillRect)
        {
            float num = fillRect.width - 250f - 40f - 90f - 16f - 120f;

            Faction[] array = Find.FactionManager.AllFactionsInViewOrder.Where((Faction f) => f != faction && f.HostileTo(faction) && ((!f.IsPlayer && !f.Hidden) || showAll)).ToArray();
            Rect      rect  = new Rect(90f, rowY, 250f, 80f);
            Rect      r     = new Rect(24f, rowY + 4f, 42f, 42f);
            float     num2  = 62f;

            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            DrawFactionIconWithTooltip(r, faction);
            string label = faction.Name.CapitalizeFirst() + "\n" + faction.def.LabelCap + "\n" + ((faction.leader != null) ? (faction.LeaderTitle.CapitalizeFirst() + ": " + faction.leader.Name.ToStringFull) : "");

            Widgets.Label(rect, label);
            Rect rect2 = new Rect(rect.xMax, rowY, 40f, 80f);

            Widgets.InfoCardButton(rect2.x, rect2.y, faction);
            Rect rect3 = new Rect(rect2.xMax, rowY, 90f, 80f);

            if (!faction.IsPlayer)
            {
                string str = (faction.HasGoodwill ? (faction.PlayerGoodwill.ToStringWithSign() + "\n") : "");
                str += faction.PlayerRelationKind.GetLabel();
                if (faction.defeated)
                {
                    str += "\n(" + "DefeatedLower".Translate() + ")";
                }
                GUI.color = faction.PlayerRelationKind.GetColor();
                Widgets.Label(rect3, str);
                GUI.color = Color.white;
                if (Mouse.IsOver(rect3))
                {
                    TaggedString str2 = (faction.HasGoodwill ? "CurrentGoodwillTip".Translate() : "CurrentRelationTip".Translate());
                    if (faction.HasGoodwill && faction.def.permanentEnemy)
                    {
                        str2 += "\n\n" + "CurrentGoodwillTip_PermanentEnemy".Translate();
                    }
                    else if (faction.HasGoodwill)
                    {
                        str2 += "\n\n";
                        switch (faction.PlayerRelationKind)
                        {
                        case FactionRelationKind.Ally:
                            str2 += "CurrentGoodwillTip_Ally".Translate(0.ToString("F0"));
                            break;

                        case FactionRelationKind.Neutral:
                            str2 += "CurrentGoodwillTip_Neutral".Translate((-75).ToString("F0"), 75.ToString("F0"));
                            break;

                        case FactionRelationKind.Hostile:
                            str2 += "CurrentGoodwillTip_Hostile".Translate(0.ToString("F0"));
                            break;
                        }
                        if (faction.def.goodwillDailyGain > 0f || faction.def.goodwillDailyFall > 0f)
                        {
                            float num3 = faction.def.goodwillDailyGain * 60f;
                            float num4 = faction.def.goodwillDailyFall * 60f;
                            str2 += "\n\n" + "CurrentGoodwillTip_NaturalGoodwill".Translate(faction.def.naturalColonyGoodwill.min.ToString("F0"), faction.def.naturalColonyGoodwill.max.ToString("F0"));
                            if (faction.def.naturalColonyGoodwill.min > -100)
                            {
                                str2 += " " + "CurrentGoodwillTip_NaturalGoodwillRise".Translate(faction.def.naturalColonyGoodwill.min.ToString("F0"), num3.ToString("F0"));
                            }
                            if (faction.def.naturalColonyGoodwill.max < 100)
                            {
                                str2 += " " + "CurrentGoodwillTip_NaturalGoodwillFall".Translate(faction.def.naturalColonyGoodwill.max.ToString("F0"), num4.ToString("F0"));
                            }
                        }
                    }
                    TooltipHandler.TipRegion(rect3, str2);
                }
                if (Mouse.IsOver(rect3))
                {
                    GUI.DrawTexture(rect3, TexUI.HighlightTex);
                }
            }
            float   xMax   = rect3.xMax;
            string  text   = "EnemyOf".Translate();
            Vector2 vector = Text.CalcSize(text);
            Rect    rect4  = new Rect(xMax, rowY + 4f, vector.x + 10f, 42f);

            xMax += rect4.width;
            Widgets.Label(rect4, text);
            for (int i = 0; i < array.Length; i++)
            {
                if (xMax >= rect3.xMax + num)
                {
                    xMax  = rect3.xMax + rect4.width;
                    rowY += vector.y + 5f;
                    num2 += vector.y + 5f;
                }
                DrawFactionIconWithTooltip(new Rect(xMax, rowY + 4f, vector.y, vector.y), array[i]);
                xMax += vector.y + 5f;
            }
            return(Mathf.Max(80f, num2));
        }
 // Creates a Default binding on an action for both mouse and controller inputs
 private void bindDefault(PlayerAction action, Mouse mouseInput, InputControlType controllerInput)
 {
     action.AddDefaultBinding(mouseInput);
     action.AddDefaultBinding(controllerInput);
 }
Ejemplo n.º 39
0
        public override void Update(GameTime gameTime)
        {
            #region move player

            KeyboardState keyPress = Keyboard.GetState();

            velocity.X = 0; //resetting velocity
            velocity.Z = 0;

            bool keyW     = false;
            bool keyA     = false;
            bool keyS     = false;
            bool keyD     = false;
            bool keyShift = false;
            bool keyAlt   = false;

            float runMod = 0;

            //movement depends on which keys are pressed, individually or together
            if (keyPress.IsKeyDown(Keys.W))
            {
                keyW = true;
            }
            if (keyPress.IsKeyDown(Keys.A))
            {
                keyA = true;
            }
            if (keyPress.IsKeyDown(Keys.S))
            {
                keyS = true;
            }
            if (keyPress.IsKeyDown(Keys.D))
            {
                keyD = true;
            }

            if (keyPress.IsKeyDown(Keys.LeftShift)) //for running
            {
                keyShift = true;
            }
            if (keyPress.IsKeyDown(Keys.LeftAlt)) //for walking slower
            {
                keyAlt = true;
            }

            if (keyShift)          //applying the appropreate move speed modifier
            {
                runMod = RUNSPEED; //move faster
            }
            else if (keyAlt)
            {
                runMod = -(RUNSPEED / 2); //move slower
            }

            if (keyW && !keyA && !keyD) //moving negative along x and positive z axis
            {
                velocity.X = -SPEED - runMod;
                velocity.Z = SPEED + runMod;
            }
            else if (keyA && !keyW && !keyS) //moving positive along x and z axis
            {
                velocity.X = SPEED + runMod;
                velocity.Z = SPEED + runMod;
            }
            else if (keyS && !keyA && !keyD) //moving positive along x axis and negative along z axis
            {
                velocity.X = SPEED + runMod;
                velocity.Z = -SPEED - runMod;
            }
            else if (keyD && !keyS && !keyW) //moving negative along x and z axis
            {
                velocity.X = -SPEED - runMod;
                velocity.Z = -SPEED - runMod;
            }
            else if (keyW && keyA) //moving positive along z axis
            {
                velocity.Z = (SPEED + runMod) * SPEEDMOD;
            }
            else if (keyW && keyD) //moving negative along x axis
            {
                velocity.X = (-SPEED - runMod) * SPEEDMOD;
            }
            else if (keyA && keyS) //moving positive along x axis
            {
                velocity.X = (SPEED + runMod) * SPEEDMOD;
            }
            else if (keyD && keyS) //moving negative along z axis
            {
                velocity.Z = (-SPEED - runMod) * SPEEDMOD;
            }

            if (velocity.X != 0 || velocity.Z != 0)
            {
                isMoving = true;
            }
            else
            {
                isMoving = false;
            }

            #endregion

            #region is colliding?

            Vector3 proposedLocation = new Vector3(modelPosition.X + velocity.X, 0f, modelPosition.Z + velocity.Z);

            foreach (Walls wall in basementWalls)
            {
                if (boundingBoxXNeg.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingXNeg = true;
                    if (velocity.X < 0)
                    {
                        proposedLocation.X = modelPosition.X - velocity.X;
                        //modelPosition.X += velocity.X * -0.1f;
                        velocity.X = 0;
                    }
                }
                else
                {
                    isCollidingXNeg = false;
                }
                if (boundingBoxXPos.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingXPos = true;
                    if (velocity.X > 0)
                    {
                        proposedLocation.X = modelPosition.X - velocity.X;
                        //modelPosition.X += velocity.X * -0.1f;
                        velocity.X = 0;
                    }
                }
                else
                {
                    isCollidingXPos = false;
                }
                if (boundingBoxZNeg.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingZNeg = true;
                    if (velocity.Z < 0)
                    {
                        proposedLocation.Z = modelPosition.Z - velocity.Z;
                        velocity.Z         = 0;
                    }
                }
                else
                {
                    isCollidingZNeg = false;
                }
                if (boundingBoxZPos.Intersects(wall.BoundingBox) && !wall.CanWalkThrough)
                {
                    isCollidingZPos = true;
                    if (velocity.Z > 0)
                    {
                        proposedLocation.Z = modelPosition.Z - velocity.Z;
                        velocity.Z         = 0;
                    }
                }
                else
                {
                    isCollidingZPos = false;
                }
            }

            #endregion

            if (!isPlayerDead) //while player is not dead, can move
            {
                //applying the move for the player
                modelPosition.X = proposedLocation.X;
                modelPosition.Z = proposedLocation.Z;
            }

            #region move camera

            cameraPosition   = modelPosition + cameraOffset; //camera is always fixed on the player
            cameraViewMatrix = Matrix.CreateLookAt(cameraPosition, modelPosition, cameraUpVector);

            #endregion

            #region getting mouse position

            //code modified from here
            //https://gamedev.stackexchange.com/questions/57625/getting-a-3d-mouse-position
            //https://gamedev.stackexchange.com/questions/23395/how-to-convert-screen-space-into-3d-world-space

            //need to create a fake world matrix where center of unproject will always be same as player character
            worldMatrix = Matrix.CreateTranslation(modelPosition);

            MouseState mouseState = Mouse.GetState();

            Vector3 nearSource = new Vector3((float)mouseState.X, (float)mouseState.Y, 0f);
            Vector3 farSource  = new Vector3((float)mouseState.X, (float)mouseState.Y, 1f);
            Vector3 nearPoint  = graphicsDevice.Viewport.Unproject(nearSource, _Initializations.GetProjectionMatrix(), cameraViewMatrix, worldMatrix);
            Vector3 farPoint   = graphicsDevice.Viewport.Unproject(farSource, _Initializations.GetProjectionMatrix(), cameraViewMatrix, worldMatrix);

            // Create a ray from the near clip plane to the far clip plane.
            Vector3 direction = farPoint - nearPoint;
            direction.Normalize();

            // Create a ray.
            Ray ray = new Ray(nearPoint, direction);

            // Calculate the ray-plane intersection point.
            Vector3 n = new Vector3(0f, 1f, 0f);
            Plane   p = new Plane(n, 0f);

            // Calculate distance of intersection point from r.origin.
            float denominator = Vector3.Dot(p.Normal, ray.Direction);
            float numerator   = Vector3.Dot(p.Normal, ray.Position) + p.D;
            float t           = -(numerator / denominator);

            // Calculate the picked position on the y = 0 plane.
            mousePosition = nearPoint + direction * t;

            #endregion

            #region player lighting

            playerLightDirection = -cameraPosition;

            #endregion

            base.Update(gameTime);
        }
Ejemplo n.º 40
0
        public override State update(GameTime gameTime, KeyboardState ks)
        {
            if (clear)
            {
                mTimeAfterClear += gameTime.ElapsedGameTime.TotalSeconds;
                if (mTimeAfterClear >= 3.0f)
                {
                    mTimeAfterClear = 0.0f;
                    return(State.SELECTION);
                }
                return(State.PLAY);
            }


            mTimeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds;
            mTimeAfterMenu      -= gameTime.ElapsedGameTime.TotalSeconds;
            if (mTimeSinceLastInput >= MIN_TIME && mTimeAfterMenu <= 0)
            {
                KeyboardState newState = Keyboard.GetState();

                if (newState.IsKeyDown(Keys.Space))
                {
                    mTimeAfterMenu = WAIT_MENU;
                    return(State.MENU);
                }
                mTimeSinceLastInput = 0.0f;
            }
            MouseState mouse = Mouse.GetState();

            time.update(gameTime);

            timeSinceLastInput += (float)gameTime.ElapsedGameTime.TotalSeconds;

            if (timeSinceLastInput >= MinTimeSinceLastInput)
            {
                for (int y = 0; y < 9; y++)
                {
                    for (int x = 0; x < 9; x++)
                    {
                        Rectangle currentSquare = new Rectangle(x * 53, y * 53, 53, 53);

                        if ((mouse.RightButton == ButtonState.Pressed))
                        {
                            map[y, x].update(mouse.X - 45, mouse.Y - 45, true);
                        }
                        else if ((mouse.LeftButton == ButtonState.Pressed))
                        {
                            map[y, x].update(mouse.X - 45, mouse.Y - 45, false);
                        }
                    }
                }


                timeSinceLastInput = 0.0f;
            }
            for (int y = 0; y < 9; y++)
            {
                for (int x = 0; x < 9; x++)
                {
                    if (map[y, x].checkclear())
                    {
                        checkFlagCount++;
                    }
                }
            }

            if (checkFlagCount == 81)
            {
                time.IsStop = true;
                clear       = true;
            }
            else
            {
                checkFlagCount = 0;
            }

            return(State.PLAY);
        }
Ejemplo n.º 41
0
 public void Load()
 {
     oldMouseState = Mouse.GetState();
 }
Ejemplo n.º 42
0
    public InputHandler()
    {
        previousMouseState = Mouse.GetState();

        mousePosition = new Vector2(previousMouseState.Position.X, previousMouseState.Position.Y);
    }
Ejemplo n.º 43
0
        /// <summary>
        /// Updates and fires input events for the mouse.
        /// </summary>
        /// <param name="gameContext">
        /// The game context.
        /// </param>
        private void UpdateMouse(IGameContext gameContext)
        {
            var mouseState = Mouse.GetState();

            if (this.m_LastMouseState == null)
            {
                this.m_LastMouseState = mouseState;
                return;
            }

            var leftChange   = mouseState.LeftChanged(this);
            var middleChange = mouseState.MiddleChanged(this);
            var rightChange  = mouseState.RightChanged(this);

            if (leftChange == ButtonState.Pressed)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MousePressEvent {
                    Button = MouseButton.Left, MouseState = mouseState
                });
            }

            if (middleChange == ButtonState.Pressed)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MousePressEvent {
                    Button = MouseButton.Middle, MouseState = mouseState
                });
            }

            if (rightChange == ButtonState.Pressed)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MousePressEvent {
                    Button = MouseButton.Right, MouseState = mouseState
                });
            }

            if (leftChange == ButtonState.Released)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MouseReleaseEvent {
                    Button = MouseButton.Left, MouseState = mouseState
                });
            }

            if (middleChange == ButtonState.Released)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MouseReleaseEvent {
                    Button = MouseButton.Middle, MouseState = mouseState
                });
            }

            if (rightChange == ButtonState.Released)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MouseReleaseEvent {
                    Button = MouseButton.Right, MouseState = mouseState
                });
            }

            if (mouseState.X != this.m_LastMouseState.Value.X || mouseState.Y != this.m_LastMouseState.Value.Y)
            {
                this.m_EventEngine.Fire(
                    gameContext,
                    new MouseMoveEvent
                {
                    X          = mouseState.X,
                    Y          = mouseState.Y,
                    LastX      = this.m_LastMouseState.Value.X,
                    LastY      = this.m_LastMouseState.Value.Y,
                    MouseState = mouseState
                });
            }

            this.m_LastMouseState = mouseState;
        }
Ejemplo n.º 44
0
 /// <summary>
 /// call mouse move to handle paint after scroll or html change affecting mouse cursor.
 /// </summary>
 protected virtual void InvokeMouseMove()
 {
     _htmlContainer.HandleMouseMove(this, Mouse.GetPosition(this));
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keyState = Keyboard.GetState();
            GamePadState  padState = GamePad.GetState(PlayerIndex.One);

            // Allows the game to exit
            if ((padState.Buttons.Back == ButtonState.Pressed) ||
                (keyState.IsKeyDown(Keys.Escape)))
            {
                this.Exit();
            }

            //Reset
            if (keyState.IsKeyDown(Keys.R))
            {
                gameResetKeyDown = true;
            }
            else if (keyState.IsKeyUp(Keys.R) && gameResetKeyDown)
            {
                gameResetKeyDown = false;

                //Reset The Game Here
                Reset();
            }

            CheckPauseMenu(keyState, Mouse.GetState());

            //Screenie
            if (keyState.IsKeyDown(Keys.PrintScreen))
            {
                gameScreenieKeyDown = true;
            }
            else if (keyState.IsKeyUp(Keys.PrintScreen) && gameScreenieKeyDown)
            {
                gameScreenieKeyDown = false;
                gamePaused          = true;

                ResolveTexture2D screenShot = new ResolveTexture2D(graphics.GraphicsDevice, 400, 600, 0, SurfaceFormat.Vector4);

                graphics.GraphicsDevice.ResolveBackBuffer(screenShot);

                //Find A Place TO Save Screenshot :)
                ulong append = 0;

                if (!Directory.Exists("Screenshots"))
                {
                    Directory.CreateDirectory("Screenshots");
                }

                while (File.Exists("Screenshots\\underAttackScreen-" + append + ".png"))
                {
                    append++;
                }

                screenShot.Save("Screenshots\\underAttackScreen-" + append + ".png", ImageFileFormat.Png);
            }

            if ((gameTime.TotalGameTime.TotalMilliseconds - lastAnimUpdate) > 100)
            {
                foreach (GameUnit unit in animations)
                {
                    if (unit.IsAnimating)
                    {
                        unit.CurrentFrame = unit.CurrentFrame + 1;
                        if (unit.CurrentFrame >= (sprites[unit.SpriteName].FrameCount))
                        {
                            deadAnims.Add(unit);
                        }
                    }
                }

                //Time Updating here too - ONLY when game is running
                if (!gameOver && !gamePaused)
                {
                    timePassed++;
                    timeParam.SetValue(timePassed / 20f);
                }
                lastAnimUpdate = gameTime.TotalGameTime.TotalMilliseconds;
            }

            if (!gameOver && !gamePaused)
            {
                //Count time alive
                timeAlive += gameTime.ElapsedGameTime.TotalSeconds;

                //Motion Input
                CheckPlayerInput(keyState);

                //Move all Units where auto-motion is req.
                MoveGameUnits();

                //Check For A Press And Release To Fire...Make Sure Every Release Is atleast 250 Ms apart
                if (keyState.IsKeyDown(Keys.Space) && !gameShootKeyDown && ((gameTime.TotalGameTime.TotalMilliseconds - lastShotUpdate) > 200))
                {
                    gameShootKeyDown = true;
                }
                else if (keyState.IsKeyUp(Keys.Space) && gameShootKeyDown)
                {
                    GameUnit bullet = new GameUnit("bullet", playerOne.Position - new Vector2(0, 32), new Vector2(4f, 4f));
                    bullet.Velocity = new Vector2(0, -2);
                    units.Add(bullet);

                    //Update last shot time
                    lastShotUpdate = gameTime.TotalGameTime.TotalMilliseconds;

                    //Reset Press variable
                    gameShootKeyDown = false;
                }

                //Remove Dead Units
                foreach (GameUnit e in deadBullets)
                {
                    units.Remove(e);
                }

                foreach (GameUnit e in deadUnits)
                {
                    units.Remove(e);
                }

                foreach (GameUnit e in deadAnims)
                {
                    units.Remove(e);
                }

                //Clear already dead units.
                deadBullets.Clear();
                deadUnits.Clear();
                deadAnims.Clear();
            }
            base.Update(gameTime);
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }
            if (gameState == GameState.Menu)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                {
                    gameState = GameState.Game;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.Back))
                {
                    gameState = GameState.GameRules;
                }
                else if (Mouse.GetState().X >= 368 && Mouse.GetState().X <= 464 && Mouse.GetState().Y >= 505 && Mouse.GetState().Y <= 593 && Mouse.GetState().LeftButton == ButtonState.Pressed)
                {
                    gameState = GameState.Buttons;
                }
            }
            else if (gameState == GameState.Buttons || gameState == GameState.GameRules)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    gameState = GameState.Menu;
                }
            }
            else if (gameState == GameState.Game)
            {
                for (int i = 0; i < ObjectList.Count(); i++)
                {
                    ObjectList[i].Update(ObjectList);
                }
            }

            // TODO: Add your update logic here
            base.Update(gameTime);
        }
Ejemplo n.º 47
0
        void ITestModule.Run()
        {
            Mouse.DefaultMoveTime        = 300;
            Keyboard.DefaultKeyPressTime = 20;
            Delay.SpeedFactor            = 1.00;

            Init();

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence '{LMenu down}' with focus on 'BMCRemedySearch'.", repo.BMCRemedySearch.SelfInfo, new RecordItemIndex(0));
            repo.BMCRemedySearch.Self.EnsureVisible();
            Keyboard.Press("{LMenu down}");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key 'Ctrl+Alt+Shift+F2' Press with focus on 'BMCRemedySearch'.", repo.BMCRemedySearch.SelfInfo, new RecordItemIndex(1));
            Keyboard.PrepareFocus(repo.BMCRemedySearch.Self);
            Keyboard.Press(System.Windows.Forms.Keys.F2 | System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Alt, 60, Keyboard.DefaultKeyPressTime, 1, true);
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence '{LMenu up}' with focus on 'BMCRemedySearch'.", repo.BMCRemedySearch.SelfInfo, new RecordItemIndex(2));
            repo.BMCRemedySearch.Self.EnsureVisible();
            Keyboard.Press("{LMenu up}");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left DoubleClick item 'BMCRemedySearch.PageBodyPbChrome.ArdbnCustomerArfid303530000CharDf' at 5;53.", repo.BMCRemedySearch.PageBodyPbChrome.ArdbnCustomerArfid303530000CharDfInfo, new RecordItemIndex(3));
            repo.BMCRemedySearch.PageBodyPbChrome.ArdbnCustomerArfid303530000CharDf.DoubleClick("5;53");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'IncidentForm.txt_customer' at 35;7.", repo.IncidentForm.txt_customerInfo, new RecordItemIndex(4));
            repo.IncidentForm.txt_customer.Click("35;7");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence 'tosho' with focus on 'IncidentForm.txt_customer'.", repo.IncidentForm.txt_customerInfo, new RecordItemIndex(5));
            repo.IncidentForm.txt_customer.PressKeys("tosho");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence '{Return}' with focus on 'IncidentForm.txt_customer'.", repo.IncidentForm.txt_customerInfo, new RecordItemIndex(6));
            repo.IncidentForm.txt_customer.PressKeys("{Return}");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Down item 'BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl1' at 3;30.", repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl1Info, new RecordItemIndex(7));
            repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl1.MoveTo("3;30");
            Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'IncidentForm.txt_detailedDescription' at 37;22.", repo.IncidentForm.txt_detailedDescriptionInfo, new RecordItemIndex(8));
            repo.IncidentForm.txt_detailedDescription.Click("37;22");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'IncidentForm.txt_detailedDescription' at 74;16.", repo.IncidentForm.txt_detailedDescriptionInfo, new RecordItemIndex(9));
            repo.IncidentForm.txt_detailedDescription.Click("74;16");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence 'test notes' with focus on 'IncidentForm.txt_detailedDescription'.", repo.IncidentForm.txt_detailedDescriptionInfo, new RecordItemIndex(10));
            repo.IncidentForm.txt_detailedDescription.PressKeys("test notes");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'IncidentForm.txt_description' at 25;15.", repo.IncidentForm.txt_descriptionInfo, new RecordItemIndex(11));
            repo.IncidentForm.txt_description.Click("25;15");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence 'test summary' with focus on 'IncidentForm.txt_description'.", repo.IncidentForm.txt_descriptionInfo, new RecordItemIndex(12));
            repo.IncidentForm.txt_description.PressKeys("test summary");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Down item 'BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl2' at 4;12.", repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl2Info, new RecordItemIndex(13));
            repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl2.MoveTo("4;12");
            Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Down item 'IncidentForm.mn_impact' at 60;10.", repo.IncidentForm.mn_impactInfo, new RecordItemIndex(14));
            repo.IncidentForm.mn_impact.MoveTo("60;10");
            Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'IncidentForm.mn_impact' at 60;10.", repo.IncidentForm.mn_impactInfo, new RecordItemIndex(15));
            repo.IncidentForm.mn_impact.Click("60;10");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'BMCRemedySearch.TdTag3ModerateLimited1' at 24;8.", repo.BMCRemedySearch.TdTag3ModerateLimited1Info, new RecordItemIndex(16));
            repo.BMCRemedySearch.TdTag3ModerateLimited1.Click("24;8");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Down item 'BMCRemedySearch.PageBodyPbChrome.Text1' at 50;17.", repo.BMCRemedySearch.PageBodyPbChrome.Text1Info, new RecordItemIndex(17));
            repo.BMCRemedySearch.PageBodyPbChrome.Text1.MoveTo("50;17");
            Mouse.ButtonDown(System.Windows.Forms.MouseButtons.Left);
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'BMCRemedySearch.PageBodyPbChrome.Text1' at 50;17.", repo.BMCRemedySearch.PageBodyPbChrome.Text1Info, new RecordItemIndex(18));
            repo.BMCRemedySearch.PageBodyPbChrome.Text1.Click("50;17");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'BMCRemedySearch.TdTag3Medium1' at 38;8.", repo.BMCRemedySearch.TdTag3Medium1Info, new RecordItemIndex(19));
            repo.BMCRemedySearch.TdTag3Medium1.Click("38;8");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Move item 'BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl3' at 3;7.", repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl3Info, new RecordItemIndex(20));
            repo.BMCRemedySearch.PageBodyPbChrome.FieldSetTagPnl3.MoveTo("3;7");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Keyboard", "Key sequence 'service desk{Return}' with focus on 'BMCRemedySearch.PageBodyPbChrome.False2'.", repo.BMCRemedySearch.PageBodyPbChrome.False2Info, new RecordItemIndex(21));
            repo.BMCRemedySearch.PageBodyPbChrome.False2.PressKeys("service desk{Return}");
            Delay.Milliseconds(0);

            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'LoginPage.btn_logIn' at 9;2.", repo.LoginPage.btn_logInInfo, new RecordItemIndex(22));
            repo.LoginPage.btn_logIn.Click("9;2");
            Delay.Milliseconds(9090);
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }
            // mouse state
            MouseState mouse = Mouse.GetState();

            //update menu buttons when game state == menu

            if (currentState == GameState.Menu)
            {
                if (!firstTimeState)
                {
                    // clear menu buttons
                    menuButtons.Clear();

                    //create all menu buttons
                    int menuButtonDistance = GameConstants.TOP_MENUBUTTON_OFFSET;
                    // create "new game" button and add to list
                    MenuButton newGameButton = new MenuButton(newGameButtonSprite, new Vector2(GameConstants.HORIZONTAL_MENUBUTTON_OFFSET, menuButtonDistance), GameState.Play);
                    menuButtons.Add(newGameButton);

                    menuButtonDistance = menuButtonDistance + GameConstants.VERTICAL_MENUBUTTON_SPACING;
                    // create "shop" button and add to list
                    MenuButton shopButton = new MenuButton(shopButtonSprite, new Vector2(GameConstants.HORIZONTAL_MENUBUTTON_OFFSET, menuButtonDistance), GameState.Shop);
                    menuButtons.Add(shopButton);


                    //clear messages
                    messages.Clear();



                    firstTimeState = true;
                }

                foreach (MenuButton menuButton in menuButtons)
                {
                    menuButton.Update(mouse);
                }
            }


            //update enamies when game state == play
            if (currentState == GameState.Play)
            {
                if (!firstTimeState)
                {
                    //when change state set current health
                    player.StartGame();

                    //clear messages
                    messages.Clear();
                    //add all massages
                    messages.Add(playerHealthMessage);
                    messages.Add(playerCashMessage);
                    //update messages
                    playerHealthMessage.Text = GameConstants.HEALTH_MESSAGE_PREFIX + player.CurrentHealth;
                    playerCashMessage.Text   = GameConstants.CASH_MESSAGE_PREFIX + player.CashPlayer;

                    //clear enemy lists
                    littleCircles.Clear();
                    bigCircles.Clear();

                    //spawn new enamies
                    // spawn all circles
                    for (int i = 0; i < GameConstants.NUMBER_OF_LITTLE_CIRCLE; i++)
                    {
                        SpawnLittleCircle();
                    }

                    for (int i = 0; i < GameConstants.NUMBER_OF_BIG_CIRCLE; i++)
                    {
                        SpawnBigCircle();
                    }

                    firstTimeState = true;
                }
                // update circles

                foreach (LittleCircle littleCircle in littleCircles)
                {
                    littleCircle.Update(gameTime, mouse);
                }

                foreach (BigCircle bigCircle in bigCircles)
                {
                    bigCircle.Update(gameTime, mouse);
                }

                // player give damage
                foreach (LittleCircle littleCircle in littleCircles)
                {
                    if (littleCircle.IsExitDownBorder)
                    {
                        player.CurrentHealth     = littleCircle.GiveDamage(player.CurrentHealth);
                        playerHealthMessage.Text = GameConstants.HEALTH_MESSAGE_PREFIX + player.CurrentHealth;
                    }
                }

                foreach (BigCircle bigCircle in bigCircles)
                {
                    if (bigCircle.IsExitDownBorder)
                    {
                        player.CurrentHealth     = bigCircle.GiveDamage(player.CurrentHealth);
                        playerHealthMessage.Text = GameConstants.HEALTH_MESSAGE_PREFIX + player.CurrentHealth;
                    }
                }


                // clean out inactive little circles
                for (int i = 0; i < littleCircles.Count; i++)
                {
                    if (!littleCircles[i].Active)
                    {
                        littleCircles.RemoveAt(i);
                    }
                }

                // clean out inactive big circles



                for (int i = 0; i < bigCircles.Count; i++)
                {
                    if (!bigCircles[i].Active)
                    {
                        //after big circle dead
                        // spawn new little Circles from 0 to 2
                        SpawnLittleCircle(bigCircles[i].DrawRectangle);
                        bigCircles.RemoveAt(i);
                    }
                }

                // add new little circles

                while (littleCircles.Count < GameConstants.NUMBER_OF_LITTLE_CIRCLE)
                {
                    SpawnLittleCircle();
                }


                // add new big circles
                while (bigCircles.Count < GameConstants.NUMBER_OF_BIG_CIRCLE)
                {
                    SpawnBigCircle();
                }

                //change state from Play to DisplayingResult
                if (player.CurrentHealth <= 0)
                {
                    ChangeState(GameState.DisplayingResult);
                }


                // mouse left click state
                // after enamy.Update because we check reaction enamy on click and then click on only window
                if (mouse.LeftButton == ButtonState.Pressed)
                {
                    clickReleased = false;
                }
                else
                {
                    clickReleased = true;
                }
            }


            if (currentState == GameState.DisplayingResult)
            {
                if (!firstTimeState)
                {
                    // clear menu buttons
                    menuButtons.Clear();
                    //create backButton and add to menuButtons
                    MenuButton backButton = new MenuButton(backButtonSprite, new Vector2(GameConstants.HORIZONTAL_BACK_MENUBUTTON_OFFSET, GameConstants.VERTICAL_BACK_MENUBUTTON_OFFSET), GameState.Menu);
                    menuButtons.Add(backButton);

                    //set default click support
                    // !!!ВАЖНО НАВЕРНО убирает баг: когда наводишь на кнопку "назад" в displayingResult State САМА иногда кликается
                    clickReleased = true;
                    clickStarted  = false;

                    firstTimeState = true;

                    //clear messages
                    messages.Clear();
                    //add "game over" message
                    messages.Add(textGameOver);
                }
                foreach (MenuButton menuButton in menuButtons)
                {
                    menuButton.Update(mouse);
                }
            }

            if (currentState == GameState.Shop)
            {
                if (!firstTimeState)
                {
                    // clear menu buttons
                    menuButtons.Clear();
                    //create backButton and add to menuButtons
                    MenuButton backButton = new MenuButton(backButtonSprite, new Vector2(GameConstants.HORIZONTAL_BACK_MENUBUTTON_OFFSET, GameConstants.VERTICAL_BACK_MENUBUTTON_OFFSET), GameState.Menu);
                    menuButtons.Add(backButton);

                    //set default click support
                    // !!!ВАЖНО НАВЕРНО убирает баг: когда наводишь на кнопку "назад" в displayingResult State САМА иногда кликается
                    clickReleased = true;
                    clickStarted  = false;

                    firstTimeState = true;

                    //set messages
                    messages.Clear();
                    //add all massages
                    messages.Add(playerHealthMessage);
                    messages.Add(playerCashMessage);
                    messages.Add(shopColorMessage);
                    messages.Add(shopContinueColorMessage);
                    messages.Add(shopMaxHealthMessage);
                    //update messages
                    playerHealthMessage.Text = GameConstants.HEALTH_MESSAGE_PREFIX + player.MaxHealth;
                    playerCashMessage.Text   = GameConstants.CASH_MESSAGE_PREFIX + player.CashPlayer;
                }

                foreach (MenuButton menuButton in menuButtons)
                {
                    menuButton.Update(mouse);
                }
                foreach (ShopButton shopButton in shopButtons)
                {
                    shopButton.Update(mouse);
                }
            }

            base.Update(gameTime);
        }
Ejemplo n.º 49
0
        public void Update(out Screen screen, Screen screenIn)
        {
            mouseState    = Mouse.GetState();
            keyboardState = Keyboard.GetState();
            this.screen   = screenIn;

            if (!WriteMass)
            {
                if (previousKeyboardState.IsKeyDown(Keys.Back) && keyboardState.IsKeyUp(Keys.Back))
                {
                    this.screen = Screen.Main;
                }

                //Program Start

                switch (mode)
                {
                case Mode.Idle:
                    SelectVertix(mouseState, previousMouseState);
                    break;

                case Mode.VA:
                    AddVertix(mouseState, previousMouseState);
                    break;

                case Mode.VM:
                    MoveVertix(mouseState, previousMouseState);
                    break;

                case Mode.EA:
                    AddEdge();
                    break;

                case Mode.ER:
                    RemoveEdge();
                    break;

                case Mode.VR:
                    RemoveVertix();
                    break;
                }


                //End

                if (previousKeyboardState.IsKeyDown(Keys.A) && keyboardState.IsKeyUp(Keys.A) && (selectedX == -1 || selectedY == -1))
                {
                    mode = Mode.VA;
                }

                /* else if (previousKeyboardState.IsKeyDown(Keys.A) && keyboardState.IsKeyUp(Keys.A) && selectedX != -1 && selectedY != -1)
                 *   mode = Mode.EA;
                 *
                 * if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R) && (selectedX == -1 && selectedY != -1 || selectedX != -1 && selectedY == -1))
                 *   mode = Mode.VR;
                 * else if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R) && selectedX != -1 && selectedY != -1)
                 *   mode = Mode.ER;
                 */

                if (previousKeyboardState.IsKeyDown(Keys.I) && keyboardState.IsKeyUp(Keys.I))
                {
                    mode = Mode.Idle;
                }
                if (previousKeyboardState.IsKeyDown(Keys.R) && keyboardState.IsKeyUp(Keys.R))
                {
                    Randomize();
                }
                if (previousKeyboardState.IsKeyDown(Keys.C) && keyboardState.IsKeyUp(Keys.C))
                {
                    Clear();
                }

                /*if (previousKeyboardState.IsKeyDown(Keys.M) && keyboardState.IsKeyUp(Keys.M))
                 *  mode = Mode.VM;*/

                if (previousKeyboardState.IsKeyDown(Keys.Enter) && keyboardState.IsKeyUp(Keys.Enter) && selectedX != -1 && selectedY != -1)
                {
                    WriteMass = true;
                    foreach (Edge eg in edge)
                    {
                        if (eg.x == selectedX && eg.y == selectedY || eg.y == selectedX && eg.x == selectedY)
                        {
                            selectedEdge = edge.IndexOf(eg);
                        }
                    }
                    que = 0;
                }


                if (previousKeyboardState.IsKeyDown(Keys.F) && keyboardState.IsKeyUp(Keys.F))
                {
                    if (find)
                    {
                        find = false;
                    }
                    else
                    {
                        find = true;
                    }
                }

                if (find && primeVertix != -1)
                {
                    Execute();
                }
            }
            else
            {
                if (previousKeyboardState.IsKeyDown(Keys.NumPad0) && keyboardState.IsKeyUp(Keys.NumPad0))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad1) && keyboardState.IsKeyUp(Keys.NumPad1))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 1;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad2) && keyboardState.IsKeyUp(Keys.NumPad2))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 2;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad3) && keyboardState.IsKeyUp(Keys.NumPad3))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 3;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad4) && keyboardState.IsKeyUp(Keys.NumPad4))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 4;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad5) && keyboardState.IsKeyUp(Keys.NumPad5))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 5;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad6) && keyboardState.IsKeyUp(Keys.NumPad6))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 6;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad7) && keyboardState.IsKeyUp(Keys.NumPad7))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 7;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad8) && keyboardState.IsKeyUp(Keys.NumPad8))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 8;
                }
                if (previousKeyboardState.IsKeyDown(Keys.NumPad9) && keyboardState.IsKeyUp(Keys.NumPad9))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass * 10 + 9;
                }
                if (previousKeyboardState.IsKeyDown(Keys.Back) && keyboardState.IsKeyUp(Keys.Back))
                {
                    edge[selectedEdge].mass = edge[selectedEdge].mass / 10;
                }
                if (previousKeyboardState.IsKeyDown(Keys.Enter) && keyboardState.IsKeyUp(Keys.Enter))
                {
                    WriteMass = false;
                    selectedX = -1;
                    selectedY = -1;
                }
            }



            screen                = this.screen;
            previousMouseState    = mouseState;
            previousKeyboardState = keyboardState;
        }
Ejemplo n.º 50
0
        public static void Update(GameTime gameTime)
        {
            // Update the states
            PreviousKeyState   = CurrentKeyState;
            PreviousMouseState = CurrentMouseState;
            CurrentKeyState    = Keyboard.GetState();
            CurrentMouseState  = Mouse.GetState();

            // Extract time info
            double totalSeconds        = gameTime.TotalGameTime.TotalSeconds;
            double totalMilliseconds   = gameTime.TotalGameTime.TotalMilliseconds;
            double elapsedSeconds      = gameTime.ElapsedGameTime.TotalSeconds;
            double elapsedMilliseconds = gameTime.ElapsedGameTime.TotalMilliseconds;

            // Check for one-off mouse events
            MouseButton pressedButtons  = GetPressedButtons();
            MouseButton draggingButtons = GetDraggingButtons();

            if (CurrentMouseState.Position != PreviousMouseState.Position)
            {
                mouseMoveEvent = new MouseMoveEventArgs()
                {
                    Buttons   = pressedButtons,
                    LastPoint = PreviousMouseState.Position,
                    CurrPoint = CurrentMouseState.Position,
                    IsDrag    = draggingButtons != MouseButton.None
                };
            }
            if (CurrentMouseState.ScrollWheelValue != PreviousMouseState.ScrollWheelValue)
            {
                mouseScrollEvent = new MouseScrollEventArgs()
                {
                    LastVal = PreviousMouseState.ScrollWheelValue,
                    CurrVal = CurrentMouseState.ScrollWheelValue
                };
            }

            // Detect key events
            foreach (Keys key in Enum.GetValues(typeof(Keys)))
            {
                if (IsKeyDown(key))
                {
                    double htime = holdTimes[key] += elapsedSeconds;
                    if (htime > KeyHoldTime)
                    {
                        keyEventList.Add(new KeyEventArgs()
                        {
                            Type = KeyEventType.Held, Key = key
                        });
                    }
                    if (IsKeyPreviouslyUp(key))
                    {
                        keyEventList.Add(new KeyEventArgs()
                        {
                            Type = KeyEventType.Pressed, Key = key
                        });
                    }
                }
                else if (IsKeyPreviouslyDown(key))
                {
                    keyEventList.Add(new KeyEventArgs()
                    {
                        Type = KeyEventType.Released, Key = key
                    });
                    holdTimes[key] = 0.0;
                }
            }

            // Detect mouse events
            foreach (MouseButton button in Enum.GetValues(typeof(MouseButton)))
            {
                if (button == MouseButton.None || button == MouseButton.Any)
                {
                    continue;
                }

                if (IsButtonDown(button))
                {
                    if (IsButtonPreviouslyUp(button))
                    {
                        buttonEventList.Add(new ButtonEventArgs()
                        {
                            Type = ButtonEventType.Pressed, Button = button
                        });
                        lastPressTime[button] = totalSeconds;
                    }
                }
                else if (IsButtonPreviouslyDown(button))
                {
                    buttonEventList.Add(new ButtonEventArgs()
                    {
                        Type = ButtonEventType.Released, Button = button
                    });
                    lastReleaseTime[button] = totalSeconds;

                    if (doubleClickNext[button] && canDoubleClick(button))
                    {
                        buttonEventList.Add(new ButtonEventArgs()
                        {
                            Type = ButtonEventType.DoubleClicked, Button = button
                        });
                        lastClickTime[button]   = totalSeconds;
                        doubleClickNext[button] = false;
                    }
                    else if (canClick(button))
                    {
                        buttonEventList.Add(new ButtonEventArgs()
                        {
                            Type = ButtonEventType.Clicked, Button = button
                        });
                        lastClickTime[button]   = totalSeconds;
                        doubleClickNext[button] = true;
                    }
                    else
                    {
                        doubleClickNext[button] = false;                         // The double click timed out
                    }
                }
            }

            // Fire off the events
            flushEvents();
        }
Ejemplo n.º 51
0
 public MouseAction(Mouse m) : this()
 {
     MouseType = m;
 }
Ejemplo n.º 52
0
 public static void SetMousePos(int x, int y)
 {
     Mouse.SetPosition(x, y);
 }
Ejemplo n.º 53
0
 public static bool RightClick(Rect rect)
 {
     return(Input.GetMouseButton(1) && Mouse.IsOver(rect));
 }
Ejemplo n.º 54
0
 public static void SetMousePos(Point p)
 {
     Mouse.SetPosition(p.X, p.Y);
 }
Ejemplo n.º 55
0
 private void EndDrag()
 {
     AppointmentModifications.FixBeginTimeDelta();
     mouseIsDown = false;
     Mouse.Capture(null);
 }
Ejemplo n.º 56
0
        public void Update(GameTime pGameTime)
        {
            float totalSeconds = (float)pGameTime.ElapsedGameTime.TotalSeconds;

            GamePadState currentState = GamePad.GetState(PlayerIndex.One);

            if (currentState.IsConnected)
            {
                // TODO gamepad support
            }
            else
            {
                if (_camera.Type == Camera.ProjectionType.PERSPECTIVE_PROJECTION)
                {
                    // Handle mouse input
                    MouseState mouseState = Mouse.GetState();

                    if (mouseState.LeftButton == ButtonState.Pressed)
                    {
                        if (!_mlb)
                        {
                            _mlb             = true;
                            _currentMousePos = new Vector2(mouseState.X, mouseState.Y);
                        }
                        else
                        {
                            Vector2 mPos  = new Vector2(mouseState.X, mouseState.Y);
                            Vector2 delta = mPos - _currentMousePos;
                            _currentMousePos = mPos;

                            float yaw   = delta.X;
                            float pitch = delta.Y;

                            _camera.Rotate(yaw, pitch);
                        }
                    }
                    else
                    {
                        _mlb = false;
                    }

                    //Zoom
                    if (_msw)
                    {
                        _msw         = true;
                        _scrollWheel = mouseState.ScrollWheelValue;
                    }
                    else
                    {
                        int delta = _scrollWheel - mouseState.ScrollWheelValue;

                        _camera.Zoom(delta);

                        _scrollWheel = mouseState.ScrollWheelValue;
                    }
                }
                else
                {
                    KeyboardState keyState = Keyboard.GetState();

                    if (keyState.IsKeyDown(Keys.Left))
                    {
                        _camera.Horizontal(-.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Right))
                    {
                        _camera.Horizontal(.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Up))
                    {
                        _camera.Vertical(.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Down))
                    {
                        _camera.Vertical(-.5f);
                    }
                    else if (keyState.IsKeyDown(Keys.Add))
                    {
                        _camera.Zoom(-1f);
                    }
                    else if (keyState.IsKeyDown(Keys.Subtract))
                    {
                        _camera.Zoom(1f);
                    }
                    else if (keyState.IsKeyDown(Keys.Space))
                    {
                        _nextMode = true;
                    }
                    else if (_nextMode)
                    {
                        Instancing.nextMode();
                        _nextMode = false;
                    }
                }
            }
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Handle the mouse down event which toggles autoscrolling behavior.
        /// </summary>
        /// <param name="sender">Mouse</param>
        /// <param name="e">Mouse button information</param>
        void OnMouseDown(Object sender, MouseButtonEventArgs e)
        {
            if (e.MiddleButton == MouseButtonState.Pressed)
            {
                if (!_autoScrolling)
                {
                    _startPos = e.GetPosition(_container);
                    Mouse.Capture(_container, CaptureMode.SubTree);
                    _autoScrolling    = true;
                    _container.Cursor = Cursors.ScrollAll;
                    if (_marker == null)
                    {
                        _marker = new Canvas();
                        Ellipse sign  = new Ellipse();
                        Brush   brush = new SolidColorBrush(Color.FromArgb(0x90, 0x90, 0x90, 0x90));
                        sign.Stroke          = brush;
                        sign.StrokeThickness = 2;
                        sign.Width           = 40;
                        sign.Height          = 40;
                        _marker.Children.Add(sign);

                        Polygon down = new Polygon
                        {
                            Points = new PointCollection(new Point[] { new Point(20 - 6, 28), new Point(20 + 6, 28), new Point(20, 34) }),
                            Fill   = brush
                        };
                        _marker.Children.Add(down);

                        Polygon up = new Polygon
                        {
                            Points = new PointCollection(new Point[] { new Point(20 - 6, 12), new Point(20 + 6, 12), new Point(20, 6) }),
                            Fill   = brush
                        };
                        _marker.Children.Add(up);

                        Polygon left = new Polygon
                        {
                            Points = new PointCollection(new Point[] { new Point(28, 20 - 6), new Point(28, 20 + 6), new Point(34, 20) }),
                            Fill   = brush
                        };
                        _marker.Children.Add(left);

                        Polygon right = new Polygon
                        {
                            Points = new PointCollection(new Point[] { new Point(12, 20 - 6), new Point(12, 20 + 6), new Point(6, 20) }),
                            Fill   = brush
                        };
                        _marker.Children.Add(right);

                        Ellipse dot = new Ellipse
                        {
                            Fill            = brush,
                            Width           = 3,
                            Height          = 3,
                            RenderTransform = new TranslateTransform(18, 18)
                        };
                        _marker.Children.Add(dot);
                    }
                    _container.Children.Add(_marker);
                    _marker.Arrange(new Rect(_startPos.X - 20, _startPos.Y - 20, 40, 40));
                    _container.InvalidateVisual();
                }
                else
                {
                    StopAutoScrolling();
                }
                e.Handled = true;
            }
            else
            {
                StopAutoScrolling();
            }
        }
Ejemplo n.º 58
0
 private void OnMouseUp(object sender, MouseEventArgs e)
 {
     Mouse.Capture(EventSource, CaptureMode.None);
 }
Ejemplo n.º 59
0
 public override void Initialize()
 {
     mouseX = Mouse.GetState().X;
     mouseY = Mouse.GetState().Y;
 }
Ejemplo n.º 60
0
        private bool InitRender(string wndTitle, ref GameConfigXml gameOptions)
        {
            root = Root.Singleton == null ? new Root() : Root.Singleton;
            root.FrameStarted += new FrameListener.FrameStartedHandler(frameStarted);

            log         = EngineLogManager.Instance.CreateLog("./Log/Engine.log");
            rendererLog = LogManager.Singleton.CreateLog("./Log/Mogre.log", true, true, false);
            rendererLog.SetDebugOutputEnabled(true);

            RenderSystem        rs     = null;
            IniConfigFileParser parser = new IniConfigFileParser();

            if (gameOptions == null)
            {
                gameOptions = GameConfigXml.Load("game.xml", root);
            }

            defaultRenderSystemName = gameOptions.GraphicConfig.CurrentRenderSystem;
            var renderParams = gameOptions.GraphicConfig[gameOptions.GraphicConfig.CurrentRenderSystem];

            if (!string.IsNullOrEmpty(defaultRenderSystemName))
            {
                var videModeRenderParam = renderParams.Where(o => o.Name == "Video Mode").First();
                rs = root.GetRenderSystemByName(defaultRenderSystemName);
                string strVideoMode = Regex.Match(
                    videModeRenderParam.Value,
                    "[0-9]{3,4} x [0-9]{3,4}").Value;
                VideoMode["Width"]  = strVideoMode.Split('x')[0].Trim();
                VideoMode["Height"] = strVideoMode.Split('x')[1].Trim();
            }

            var ogreConfigMap = rs.GetConfigOptions();

            if (rs != null && renderParams != null)
            {
                foreach (var kpl in renderParams)
                {
                    string renderParamKey   = kpl.Name;
                    string renderParamValue = kpl.Value;
                    //Validate the render parameter
                    if (!ogreConfigMap[renderParamKey].possibleValues.Contains(renderParamValue))
                    {
                        renderParamValue = ogreConfigMap[renderParamKey].possibleValues[0];
                    }
                    rs.SetConfigOption(renderParamKey, renderParamValue);
                }
                root.RenderSystem = rs;
            }

            renderWindow = root.Initialise(true, wndTitle);

            IntPtr hwnd;

            renderWindow.GetCustomAttribute("WINDOW", out hwnd);
            Helper.SetRenderWindowIcon(new System.Drawing.Icon(Path.Combine(Environment.CurrentDirectory, "app.ico")), hwnd);

            viewport = renderWindow.AddViewport(null);
            ColourValue cv = new ColourValue(0.5f, 0.5f, 0.5f);

            viewport.BackgroundColour = cv;

            viewport.Camera = null;

            int hWnd = 0;

            renderWindow.GetCustomAttribute("WINDOW", out hWnd);

            inputMgr        = MOIS.InputManager.CreateInputSystem((uint)hWnd);
            keyboard        = (Keyboard)inputMgr.CreateInputObject(MOIS.Type.OISKeyboard, true);
            mouse           = (Mouse)inputMgr.CreateInputObject(MOIS.Type.OISMouse, true);
            keyMouseManager = new InputKeyMouseManager();
            keyMouseManager.SomeKeyPressd += KeyMouseManager_SomeKeyPressd;

            MouseState_NativePtr mouseState = mouse.MouseState;

            mouseState.width  = viewport.ActualWidth;
            mouseState.height = viewport.ActualHeight;

            foreach (var resource in gameOptions.ResourcesConfig.Resources)
            {
                foreach (var resLoc in resource.ResourceLocs)
                {
                    ResourceGroupManager.Singleton.AddResourceLocation(resLoc, resource.Type, ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME);
                }
            }

            foreach (var keyMapper in gameOptions.InputConfig.Mappers)
            {
                KeyMapperManager.Instance.AddKeyMapper(keyMapper.GameKeyCode, keyMapper.GetKeyCollections());
            }

            if (!LocateSystem.Instance.IsInit)
            {
                LocateSystem.Instance.InitLocateSystem(LocateSystem.Instance.ConvertReadableStringToLocate(gameOptions.LocateConfig.CurrentLocate));
            }

            SkinManager.Instance.LoadSkin("Default.skn");

            ResourceGroupManager.Singleton.AddResourceLocation(
                string.Format("./Media/Engine/Fonts/{0}/", LocateSystem.Instance.Locate.ToString()), "FileSystem",
                "General");

            TextureManager.Singleton.DefaultNumMipmaps = 5;

            ResourceGroupManager.Singleton.InitialiseAllResourceGroups();

            UIManager.Instance.Init("AMOFTrayMgr", renderWindow, mouse, new UIListener());


            timer = new Timer();
            timer.Reset();

            renderWindow.IsActive = true;

            this.gameOptions = gameOptions;

            log.LogMessage("Game Started!");

            return(true);
        }