Esempio n. 1
0
        public bool WasPressed(ref TouchCollection touches)
        {
            foreach (var touch in touches)
            {
                if (touch.Id == _lastTouchId)
                    continue;
                if (touch.State != TouchLocationState.Pressed)
                    continue;

                if (_location.Contains(touch.Position))
                {
                    _lastTouchId = touch.Id;
                    _pressed = true;
                    return true;
                }
            }
            var mouseState = Mouse.GetState();
            if (_location.Contains(mouseState.Position) && mouseState.LeftButton == ButtonState.Pressed)
            {
                _pressed = true;
                return true;
            }

            _pressed = false;

            return false;
        }
Esempio n. 2
0
		private InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs, InputState prev)
		{
			Mouse = ms;
			Keyboard = ks;
			TouchPanel = ts;
			GamePad = gs;

			if (Mouse.LeftButton == ButtonState.Pressed)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(Mouse.Position);
			}
			else if (TouchPanel.Count > 0)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint());
			}
			else
			{
				IsDown = false;
				PointerPosition = prev.PointerPosition;
			}

			IsJustDown = IsDown && !prev.IsDown;
			IsJustUp = !IsDown && prev.IsDown;

			lastKeyState = prev.currentKeyState;
			currentKeyState = lastKeyState.ToDictionary(p => p.Key, p => ks.IsKeyDown(p.Key));
		}
Esempio n. 3
0
        /// <summary>
        /// Reads the latest state of the keyboard and gamepad.
        /// </summary>
        public void Update()
        {
            for (var i = 0; i < MaxInputs; i++)
            {
                LastKeyboardStates[i] = CurrentKeyboardStates[i];
                LastGamePadStates[i] = CurrentGamePadStates[i];

                CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i);
                CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);

                // Keep track of whether a gamepad has ever been
                // connected, so we can detect if it is unplugged.
                if (CurrentGamePadStates[i].IsConnected)
                {
                    GamePadWasConnected[i] = true;
                }
            }

            TouchState = TouchPanel.GetState();

            Gestures.Clear();
            while (TouchPanel.IsGestureAvailable)
            {
                Gestures.Add(TouchPanel.ReadGesture());
            }
        }
Esempio n. 4
0
        public static void Update()
        {
            m_Gesture = TouchPanel.IsGestureAvailable ? TouchPanel.ReadGesture() : new GestureSample();

            if (CurrentTouchCollection.Count > 0)
            {
                OldTouchCollection = CurrentTouchCollection;
            }

            CurrentTouchCollection = TouchPanel.GetState();

                    if (CurrentTouchCollection.Count > 0)
                    {
                        while (TouchPanel.IsGestureAvailable)
                        {
                            TouchPanel.ReadGesture();
                        }
                    }

            #if !Windows
            m_LastKeyboardState = m_CurrentKeyboardState;
            m_CurrentKeyboardState = Keyboard.GetState();

            m_LastMouseState = m_CurrentMouseState;
            m_CurrentMouseState = Mouse.GetState();
            #endif
        }
Esempio n. 5
0
        public static void ProcessTouchInput(out Vector2 player1Velocity, out bool isTappingGesture, out bool isFlickingGesture)
        {
            player1Velocity = new Vector2(0, 0);
            isTappingGesture = false;
            isFlickingGesture = false;

            previousTouches = touches;
            touches = TouchPanel.GetState();

            while (TouchPanel.IsGestureAvailable)
            {
                //take care of multitouches
                for (int i = 0; i < touches.Count; i++)
                {
                    if (touches[i].State != TouchLocationState.Pressed)
                        continue;
                    if (touches.Count >= 1)
                        isTappingGesture = true;
                }

                // take care of gestures
                GestureSample gestureSample = TouchPanel.ReadGesture();
                if (gestureSample.GestureType == GestureType.FreeDrag && gestureSample.Position.Y > 0)
                    player1Velocity += gestureSample.Delta;
                if (gestureSample.GestureType == GestureType.Flick && gestureSample.GestureType != GestureType.HorizontalDrag)
                    isFlickingGesture = true;
                if (gestureSample.GestureType == GestureType.Tap)
                    isTappingGesture = true;
            }
        }
Esempio n. 6
0
 public void update()
 {
     touches = TouchPanel.GetState();
     if (touches.Count <= 2)
     {
         foreach (TouchLocation touch in touches)
         {
             if (ret.Contains((int)touch.Position.X, (int)touch.Position.Y) && touch.State == TouchLocationState.Pressed)
             {
                 g.state = GameState.play;
                 g.player.stop();
             }
             else if (mainMenu.Contains((int)touch.Position.X, (int)touch.Position.Y) && touch.State == TouchLocationState.Pressed)
             {
                 g.state = GameState.mainMenu;
             }
             else if (reset.Contains((int)touch.Position.X, (int)touch.Position.Y) && touch.State == TouchLocationState.Pressed)
             {
                 g.state = GameState.play;
                 g.player.die();
             }
         }
     }
     GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
     if (gamepadState.Buttons.Back == ButtonState.Pressed)
     {
         g.state = GameState.play;
         g.player.stop();
     }
 }
        public void Update(TouchCollection touchLocationState)
        {
            Vector2? currentPosition = TouchPosition(touchLocationState);
            if (currentPosition == null)
            {
                if (touchPositions.Count > 0)
                {
                    alphaValue -= 20;
                    if (alphaValue <= 0)
                    {
                        touchPositions.Clear();
                        alphaValue = 255;
                    }
                }
            }
            else
            {
                if (alphaValue != 255)
                {
                    touchPositions.Clear();
                    alphaValue = 255;
                }

                touchPositions.Add((Vector2)currentPosition);
            }
        }
Esempio n. 8
0
 public void Update(TouchCollection NewCollection)
 {
     this.touchCollection = NewCollection;
     Touch = touchCollection[0];
     prevTouchState = curTouchState;
     curTouchState = Touch.State;
 }
Esempio n. 9
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            Content.RootDirectory = "Content";

            String ip = "";
            WebRequest req = WebRequest.Create("https://dl.dropbox.com/u/1814002/TurtleTurner2000/ip.txt");
            WebResponse resp = req.GetResponse();
            using (Stream streampje = resp.GetResponseStream())
            {
                using (TextReader reader = new StreamReader(streampje))
                {
                    ip = reader.ReadLine();
                }
            }

            deveClient = new DeveClient(ip, 1337);
            deveClient.Start();

            DeveOutgoingMessage outje = new DeveOutgoingMessage();
            outje.WriteInt32((int)ServerReceiveMessageType.LoginMessageControlClient); //Join message
            //outje.WriteInt32(1); //Android
            deveClient.Send(outje);

            graphics.IsFullScreen = true;
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 480;
            graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.LandscapeRight;

            this.currentTouchCollection = TouchPanel.GetState();
        }
Esempio n. 10
0
        /// <summary>
        /// Reads the latest state user input.
        /// </summary>
        public void Update()
        {
            for (int i = 0; i < MaxInputs; i++)
            {
                LastKeyboardStates[i] = CurrentKeyboardStates[i];
                LastGamePadStates[i] = CurrentGamePadStates[i];

                CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i);
                CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i);

                // Keep track of whether a gamepad has ever been
                // connected, so we can detect if it is unplugged.
                if (CurrentGamePadStates[i].IsConnected)
                {
                    GamePadWasConnected[i] = true;
                }
            }

            // Get the raw touch state from the TouchPanel
            TouchState = TouchPanel.GetState();

            // Read in any detected gestures into our list for the screens to later process
            Gestures.Clear();
            while (TouchPanel.IsGestureAvailable)
            {
                Gestures.Add(TouchPanel.ReadGesture());
            }
        }
 public void Update(TouchCollection touchLocationState)
 {
     foreach (TouchLocation touchLocation in touchLocationState)
     {
         switch (touchLocation.State)
         {
             case TouchLocationState.Invalid:
                 break;
             case TouchLocationState.Moved:
                 if (LastPressedLocation != null
                     && getRectangleFromPoint(touchLocation.Position).Intersects(ListeningArea))
                 {
                     LastMovedLocation = touchLocation.Position;
                 }
                 break;
             case TouchLocationState.Pressed:
                 if (getRectangleFromPoint(touchLocation.Position).Intersects(ListeningArea))
                 {
                     this.LastPressedLocation = touchLocation.Position;
                 }
                 break;
             case TouchLocationState.Released:
                 LastPressedLocation = null;
                 LastMovedLocation = null;
                 break;
         }
     }
 }
Esempio n. 12
0
        public void Update(TouchCollection toucheCollection, GameTime gameTime)
        {
            List<ITouch> touchesCopy = new List<ITouch>(Touches);
            this.Touches.Clear();

            foreach (TouchLocation touchLocation in toucheCollection)
            {
                bool isBegin = true;

                foreach (ITouch lastTouch in touchesCopy)
                {
                    if (lastTouch.SystemTouch.Id == touchLocation.Id)
                    {
                        Touches.Add(new Touch(touchLocation, new TouchPositions(touchLocation.Position, lastTouch.Positions.Current, lastTouch.Positions.Begin)));

                        isBegin = false;
                        break;
                    }
                }

                if (isBegin)
                {
                    Touches.Add(new Touch(touchLocation, new TouchPositions(touchLocation.Position, InvalidPosition, touchLocation.Position)));
                }
            }
        }
 public void FindFreeIndexWithoutAnyFreeIndices()
 {
     var touchCollection = new TouchCollection(null);
     for (int index = 0; index < touchCollection.ids.Length; index++)
         touchCollection.ids[index] = 1;
     Assert.AreEqual(-1, touchCollection.FindIndexByIdOrGetFreeIndex(546));
 }
Esempio n. 14
0
 public void Update()
 {
     touchState = TouchPanel.GetState();
     Gestures.Clear();
     while (TouchPanel.IsGestureAvailable)
         Gestures.Add(TouchPanel.ReadGesture());
 }
Esempio n. 15
0
		public InputState(SAMViewportAdapter adapter, KeyboardState ks, MouseState ms, TouchCollection ts, GamePadState gs)
		{
			Mouse = ms;
			Keyboard = ks;
			TouchPanel = ts;
			GamePad = gs;

			if (Mouse.LeftButton == ButtonState.Pressed)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(Mouse.Position);
			}
			else if (TouchPanel.Count > 0)
			{
				IsDown = true;
				PointerPosition = adapter.PointToScreen(TouchPanel[0].Position.ToPoint());
			}
			else
			{
				IsDown = false;
				PointerPosition = FPoint.Zero;
			}

			currentKeyState = new Dictionary<Keys, bool>(0);
		}
Esempio n. 16
0
        public void Update(GameTime gameTime, TouchCollection touchState)
        {
            if (MediaPlayer.State != MediaState.Playing && MediaPlayer.GameHasControl)
                MediaPlayer.Play(_song);

            if (_startButton.WasPressed(ref touchState))
                OnStart();
        }
Esempio n. 17
0
        public InputManager()
        {
            this.OldState = new MouseState();
            this.OldTouchState = new TouchCollection();
            this.IsMouseDown = false;

            this.IsMobile = LinesGame.IsMobile;
        }
Esempio n. 18
0
 public override void Update(GameTime gameTime, TouchCollection tc)
 {
     if (tc.Count > 0)
     {
         game.changeScreen(ScreenType.MainMenuScreen);
         game.getHumptyDumpty().Status = HumptyDumpty.ALIVE;
     }
     base.Update(gameTime, tc);
 }
Esempio n. 19
0
 public override bool HandleTouch(TouchCollection tc)
 {
     base.HandleTouch(tc);
     /*
      * TouchLocation tl = tc[0];
     bird.UpdatePosition(tl.Position.X, tl.Position.Y);
      * */
     return false;
 }
Esempio n. 20
0
        private void UpdateTouch(TimeSpan deltaTime)
        {
            // Touch input
              _touchCollection = TouchPanel.GetState();

              // Touch gestures
              _gestures.Clear();
              while (TouchPanel.IsGestureAvailable)
            _gestures.Add(TouchPanel.ReadGesture());
        }
Esempio n. 21
0
 public override void Update(GameTime gameTime, TouchCollection collection, Vector3 acceleration)
 {
     countdown += gameTime.ElapsedGameTime.Milliseconds;
     if (countdown > 2000)
     {
         countdown = 0;
         gameReference.changeScreen(ScreenType.GameScreen);
     }
     base.Update(gameTime, collection, acceleration);
 }
 /// <summary>
 /// Determines if there are any touches on the screen.
 /// </summary>
 /// <param name="touchState">The current TouchCollection.</param>
 /// <returns>True if there are any touches in the Pressed or Moved state, false otherwise</returns>
 public static bool AnyTouch(TouchCollection touchState)
 {
     foreach (TouchLocation location in touchState)
     {
         if (location.State == TouchLocationState.Pressed || location.State == TouchLocationState.Moved)
         {
             return true;
         }
     }
     return false;
 }
Esempio n. 23
0
        public void Update(GameTime gameTime)
        {
            _touches = TouchPanel.GetState();
            _buffer = new List<Control>();
            _current = new List<Control>();
            _previous = new List<Control>();
            _blocked = new List<int>();

            _cooled = _previous.Except(_current).Distinct();
            _warmed = _current.Except(_previous).Distinct();
        }
        public void Update()
        {
            // Updates the touch handler with all the touch points
            m_touchCollection = TouchPanel.GetState();

            m_touches.Clear();

            foreach (TouchLocation tl in m_touchCollection) {
                m_touches.Add(tl);
            }
        }
        public void Update(TouchCollection toucheCollection, GameTime gameTime)
        {
            TouchLocation[] touchLocs = new TouchLocation[toucheCollection.Count];
            int i = 0;
            foreach (var touch in toucheCollection)
            {
                touchLocs[i++] = new TouchLocation(touch.Id, touch.State, orientation.Transform(touch.Position));
            }

            baseTC.Update(new TouchCollection(touchLocs), gameTime);
        }
 /// <summary>
 /// Add new touch indicators for new touch inputs
 /// </summary>
 /// <param name="content"></param>
 /// <param name="currentTouchLocationState"></param>
 private void AddNewIndicators(ContentManager content, TouchCollection currentTouchLocationState)
 {
     foreach (TouchLocation location in currentTouchLocationState)
     {
         bool isTouchIdAlreadyStored = touchPositions.Any(indicator => location.Id == indicator.TouchID);
         if (!isTouchIdAlreadyStored)
         {
             TouchIndicator indicator = new TouchIndicator(location.Id, content);
             touchPositions.Add(indicator);
         }
     }
 }
        /// <summary>
        /// Actualiza el pad y la pantalla táctil.
        /// </summary>
        public void Update()
        {
            AnteriorGamePadStates = ActualGamePadState;
                ActualGamePadState = GamePad.GetState(PlayerIndex.One);

            estadoPantallaTactil = TouchPanel.GetState();
            pantallaGesture.Clear();//limpiamos la lista de la pantalla táctil
            while (TouchPanel.IsGestureAvailable)
            {
                pantallaGesture.Add(TouchPanel.ReadGesture());//lee las pulsaciones de la pantalla
            }
        }
Esempio n. 28
0
        public InputHandler(Game game)
            : base(game)
        {
            keyboardState = Keyboard.GetState();
            framesSinceMouseMove = maxFramesSinceMouseMovement;
            gamePadStates = new GamePadState[Enum.GetValues(typeof(PlayerIndex)).Length];

            foreach (PlayerIndex index in Enum.GetValues(typeof(PlayerIndex)))
                gamePadStates[(int)index] = GamePad.GetState(index);

            touchState = TouchPanel.GetState();
        }
Esempio n. 29
0
        public void WorksWhenConstructedEmpty()
        {
            TouchCollection collection = new TouchCollection();

            Assert.AreEqual(0, collection.Count);
            foreach (var touch in collection)
                Assert.Fail("Shouldn't have any touches in an empty collection");

            Assert.AreEqual(-1, collection.IndexOf(new TouchLocation()));

            TouchLocation touchLocation;
            Assert.False(collection.FindById(1, out touchLocation));
        }
Esempio n. 30
0
        public void Update()
        {
            //update touch
            touch = TouchPanel.GetState();

            foreach (Area area in areas)
            {
                if (player.CurrentArea == area)
                {
                    area.Update(touch);
                }
            }
        }
Esempio n. 31
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++;
            }

            if (GraphicsDevice.PresentationParameters.Bounds.Width > GraphicsDevice.PresentationParameters.Bounds.Height)
            {
                if (!landscape)
                {
                    _backBuffer  = new RenderTarget2D(GraphicsDevice, 300, 3600);
                    _backBuffer2 = new RenderTarget2D(GraphicsDevice, 1920, 1080);
                    _backBuffer3 = new RenderTarget2D(GraphicsDevice, 1080, 1920);
                    landscape    = true;
                }
            }
            else
            {
                if (landscape)
                {
                    _backBuffer  = new RenderTarget2D(GraphicsDevice, 300, 800);
                    _backBuffer2 = new RenderTarget2D(GraphicsDevice, 1080, 1920);
                    _backBuffer3 = new RenderTarget2D(GraphicsDevice, 1, 1);
                    landscape    = false;
                }
            }

            curtime = (ManagedBass.Bass.ChannelBytes2Seconds(i, ManagedBass.Bass.ChannelGetPosition(i, ManagedBass.PositionFlags.Bytes)) * 1000);

            KeyboardState state = Keyboard.GetState();
            bool          zz    = false;
            bool          xx    = false;
            bool          cc    = false;
            bool          vv    = false;

            if (msecdelay > 0)
            {
                msecdelay = msecdelay - gameTime.ElapsedGameTime.Milliseconds;
                curtime   = -msecdelay;
            }
            else
            {
                if (letsaplay == false)
                {
                    ManagedBass.Bass.ChannelPlay(i);
                    letsaplay = true;
                }
            }

            /**
             * if (!(previousState.IsKeyDown(Keys.D)) && state.IsKeyDown(Keys.D))
             * { replay.inputs.Add(new ReplayInputs(1, (int)curtime, 1));  }
             * if (!(previousState.IsKeyDown(Keys.F)) && state.IsKeyDown(Keys.F))
             * { replay.inputs.Add(new ReplayInputs(3, (int)curtime, 1)); }
             * if (!(previousState.IsKeyDown(Keys.J)) && state.IsKeyDown(Keys.J))
             * { replay.inputs.Add(new ReplayInputs(5, (int)curtime, 1)); }
             * if (!(previousState.IsKeyDown(Keys.K)) && state.IsKeyDown(Keys.K))
             * { replay.inputs.Add(new ReplayInputs(7, (int)curtime, 1));  }
             * if (!(previousState.IsKeyUp(Keys.D)) && state.IsKeyUp(Keys.D))
             * { replay.inputs.Add(new ReplayInputs(1, (int)curtime, 2));  }
             * if (!(previousState.IsKeyUp(Keys.F)) && state.IsKeyUp(Keys.F))
             * { replay.inputs.Add(new ReplayInputs(3, (int)curtime, 2));  }
             * if (!(previousState.IsKeyUp(Keys.J)) && state.IsKeyUp(Keys.J))
             * { replay.inputs.Add(new ReplayInputs(5, (int)curtime, 2));  }
             * if (!(previousState.IsKeyUp(Keys.K)) && state.IsKeyUp(Keys.K))
             * { replay.inputs.Add(new ReplayInputs(7, (int)curtime, 2));  }
             **/

            //if (GamePad.GetState(PlayerIndex.One).Buttons.Back ==
            //ButtonState.Pressed)
            //    exit++;

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                ManagedBass.Bass.Free();
                exit = 5;
                Exit();
            }

            if (state.IsKeyDown(Keys.D))
            {
                zz = true;
            }
            else
            {
                zz = false;
            }

            if (state.IsKeyDown(Keys.F))
            {
                xx = true;
            }
            else
            {
                xx = false;
            }

            if (state.IsKeyDown(Keys.J))
            {
                cc = true;
            }
            else
            {
                cc = false;
            }

            if (state.IsKeyDown(Keys.K))
            {
                vv = true;
            }
            else
            {
                vv = false;
            }

            TouchCollection itouch = TouchPanel.GetState();

            if (landscape)
            {
                foreach (TouchLocation tl in itouch)
                {
                    if (tl.State == TouchLocationState.Moved)
                    {
                        int calcs = this.GraphicsDevice.Viewport.Width / 6;
                        if (tl.Position.X <= calcs * 2)
                        {
                            zz = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 3)
                        {
                            xx = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 4)
                        {
                            cc = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 6)
                        {
                            vv = true;
                        }
                    }
                }
            }
            else
            {
                foreach (TouchLocation tl in itouch)
                {
                    if (tl.State == TouchLocationState.Moved)
                    {
                        int calcs = this.GraphicsDevice.Viewport.Width / 4;
                        if (tl.Position.X <= calcs * 1)
                        {
                            zz = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 2)
                        {
                            xx = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 3)
                        {
                            cc = true;
                        }
                        else
                        if (tl.Position.X <= calcs * 4)
                        {
                            vv = true;
                        }
                    }
                }
            }

            if (!(z) && (zz))
            {
                replay.inputs.Add(new ReplayInputs(1, (int)curtime, 1));
            }

            if (!(x) && (xx))
            {
                replay.inputs.Add(new ReplayInputs(3, (int)curtime, 1));
            }

            if (!(c) && (cc))
            {
                replay.inputs.Add(new ReplayInputs(5, (int)curtime, 1));
            }

            if (!(v) && (vv))
            {
                replay.inputs.Add(new ReplayInputs(7, (int)curtime, 1));
            }

            if ((z) && !(zz))
            {
                replay.inputs.Add(new ReplayInputs(1, (int)curtime, 2));
            }

            if ((x) && !(xx))
            {
                replay.inputs.Add(new ReplayInputs(3, (int)curtime, 2));
            }

            if ((c) && !(cc))
            {
                replay.inputs.Add(new ReplayInputs(5, (int)curtime, 2));
            }

            if ((v) && !(vv))
            {
                replay.inputs.Add(new ReplayInputs(7, (int)curtime, 2));
            }

            if (zz)
            {
                z4 = 1.0f;
            }
            if (xx)
            {
                z3 = 1.0f;
            }
            if (cc)
            {
                z2 = 1.0f;
            }
            if (vv)
            {
                z1 = 1.0f;
            }

            if (state.IsKeyDown(Keys.U))
            {
                testz = testz + 0.05f; cameraPosition.Z = testz;
            }

            if (state.IsKeyDown(Keys.I))
            {
                testz = testz - 0.05f; cameraPosition.Z = testz;
            }

            if (state.IsKeyDown(Keys.O))
            {
                testy = testy + 0.05f; cameraPosition.Y = testy;
            }

            if (state.IsKeyDown(Keys.P))
            {
                testy = testy - 0.05f; cameraPosition.Y = testy;
            }

            var delta = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 16;

            if (z1 >= 0.5f)
            {
                z1 = z1 - (0.025f * delta);
            }
            if (z2 >= 0.5f)
            {
                z2 = z2 - (0.025f * delta);
            }
            if (z3 >= 0.5f)
            {
                z3 = z3 - (0.025f * delta);
            }
            if (z4 >= 0.5f)
            {
                z4 = z4 - (0.025f * delta);
            }
            previousState = state;

            if (ManagedBass.Bass.ChannelGetPosition(i, ManagedBass.PositionFlags.Bytes) == ManagedBass.Bass.ChannelGetLength(i, ManagedBass.PositionFlags.Bytes))
            {
                msecfinished = msecfinished + gameTime.ElapsedGameTime.Milliseconds;
                if (replay.saved == false)
                {
                    replay.saved = true;
                    if (legacy == false)
                    {
                        replay.SaveToJson();
                    }
                    else
                    {
                        replay.SaveToJson();
                        string path     = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                        string filename = "scores";

                        beatenhighscore = false;

                        string dbPath = Path.Combine(path, filename);
                        Ini    ini    = new Ini(dbPath);
                        string bmid   = Map.bmid.ToString();
                        float  score  = replay.score;
                        string maxmm  = replay.maxcombo.ToString();
                        //replay.CalculateMaxCombo(Map, ManagedBass.Bass.ChannelGetLength(i)).ToString();
                        string acc = replay.CalculateAccuracyAndTotals(Map, ManagedBass.Bass.ChannelGetLength(i));

                        if (int.Parse(ini.GetValue(bmid, "score", "0")) < score)
                        {
                            ini.WriteValue(bmid, "score", score.ToString());
                            ini.WriteValue(bmid, "maxmm", maxmm.ToString());
                            ini.WriteValue(bmid, "acc", acc.ToString());
                            ini.WriteValue(bmid, "totalhit", replay.totalhit.ToString());
                            ini.WriteValue(bmid, "totalmiss", replay.totalmiss.ToString());
                            beatenhighscore = true;
                        }

                        ini.Save();
                    }
                }
                else
                {
                    if (zz || xx || cc || vv)
                    {
                        exit = 5;
                    }
                }
            }

            replay.CalculateScore(Map, curtime);

            z = zz;
            x = xx;
            c = cc;
            v = vv;

            base.Update(gameTime);
        }
Esempio n. 32
0
 public virtual void Update(GameTime gameTime, TouchCollection collection, Vector3 acceleration)
 {
 }
Esempio n. 33
0
        protected override void Update(GameTime gameTime)
        {
#if DEBUG
            // SAVE ME KEY
            if (Keyboard.GetState().IsKeyDown(Keys.F12))
            {
                Exit();
            }
#endif

            if (GameData.Instance.CurrentScreen == Screen.Ingame || GameData.Instance.CurrentScreen == Screen.Editor)
            {
                //TargetElapsedTime = TimeSpan.FromSeconds(1.0f / 500.0f);
            }
            else
            {
                TargetElapsedTime = OGTimeSpan;
#if WINDOWS
                if (!GameData.Instance.Options.Fullscreen)
                {
                    Window.IsBorderless = false;
                }
#endif
            }

            var p = Mouse.GetState(Window).Position;

            CursorLocation = new Rectangle(p, new Point(1, 1));

            if (Windows)
            {
                Click = false;
                MouseState current = Mouse.GetState();
                if (current.LeftButton == ButtonState.Pressed &&
                    OldMouseState.LeftButton == ButtonState.Released &&
                    IsActive)
                {
                    Click = true;
                }
                OldMouseState = current;
            }
            else
            {
                TouchCollection touchCollection = TouchPanel.GetState();

                var pos = new Point(0, 0);
                Click = false;
                if (touchCollection.Any())
                {
                    pos.X  = (int)touchCollection[0].Position.X;
                    pos.Y  = (int)touchCollection[0].Position.Y;
                    Click  = touchCollection[0].State == TouchLocationState.Pressed && oldtls == 0;
                    oldtls = touchCollection[0].State;
                }
                else
                {
                    oldtls = 0;
                }

                CursorLocation = new Rectangle(pos, new Point(1, 1));
            }

            GameData.Instance.Screens.Find(x => x.Name == GameData.Instance.CurrentScreen).Update(gameTime, CursorLocation, Click);
            base.Update(gameTime);
            if (GameData.Instance.Exiting)
            {
                Exit();
            }
        }
Esempio n. 34
0
 public Enumerator(TouchCollection collection)
 {
     this.collection = collection;
     this.position   = -1;
 }
Esempio n. 35
0
 /// <summary>Initializes a new touch panel state</summary>
 /// <param name="isAttached">Whether the touch panel is connected</param>
 /// <param name="touches">Touch events since the last update</param>
 public TouchState(bool isAttached, TouchCollection touches)
 {
     this.isAttached = isAttached;
     this.touches    = touches;
 }
        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            // TODO: Add your update code here



            TouchCollection touchCollection = TouchPanel.GetState();

            if (currentScreen != prevFrameScreen)
            {
                SetupGestures();

                if (currentScreen == GameScreen.PlayingScreen)
                {
                    GameInProgress = true;
                }

                prevFrameScreen = currentScreen;
            }
            HandleMenuButton();
            UpdateInput(gameTime);
            ButtonCheckState(touchCollection);
            //Check Current

            while (TouchPanel.IsGestureAvailable && GameInProgress)
            {
                GestureSample gs = TouchPanel.ReadGesture();

                switch (gs.GestureType)
                {
                case GestureType.Tap:
                    int   x       = (int)(gs.Position.X - _x_ball) / _padding_cell;
                    int   y       = (int)(gs.Position.Y - _y_ball) / _padding_cell;
                    Point current = new Point(x, y);
                    if ((current.X < 7) && (current.Y < 7) && (current.X >= 0) && (current.Y >= 0))
                    {
                        if (_pre != current)
                        {
                            _selected = _pre;
                            _pre      = current;
                        }


                        if (_array[current.X, current.Y] != 0)
                        {
                            _pressed      = true;
                            _ball_pressed = new Point(current.X, current.Y);
                        }
                    }
                    if (_array[_selected.X, _selected.Y] != 0 && _array[current.X, current.Y] == 0)
                    {
                        ListPath = new ListPoint();
                        ListPath = Algorithms.Algorithms.havePath(_array, _selected.X, _selected.Y, current.X, current.Y);

                        if (ListPath != null)
                        {
                            _moved     = true;
                            _draw_path = true;
                        }
                        else
                        {
                            _moved   = false;
                            _pressed = false;
                        }
                    }
                    //else if (_pressed && _array[_selected.X, _selected.Y] != 0 && current.X == _selected.X && current.Y == _selected.Y)
                    //{
                    //    _pressed = false;
                    //}


                    if (_moved)
                    {
                        //random_ball_next(_array);
                        _array[current.X, current.Y]     = _array[_selected.X, _selected.Y];
                        _array[_selected.X, _selected.Y] = 0;
                        current  = _pre = _selected;
                        _moved   = false;
                        _pressed = false;
                        ListPoint list_del = new ListPoint();
                        list_del = Algorithms.Algorithms.KiemTra(_array);
                        if (list_del.Count >= 4)
                        {
                            Algorithms.Algorithms.del_ball(_array, list_del);
                        }
                        else
                        {
                            random_ball_next(_array);
                            list_del = Algorithms.Algorithms.KiemTra(_array);
                            if (list_del.Count >= 4)
                            {
                                Algorithms.Algorithms.del_ball(_array, list_del);
                            }
                        }
                    }

                    Debug.WriteLine(current.ToString() + _pre.ToString() + _selected.ToString() + _moved.ToString() + _pressed.ToString());
                    break;

                default:
                    break;
                }
            }

            base.Update(gameTime);
        }
Esempio n. 37
0
        public override void Update(GameTime gameTime, Camera2D camera)
        {
            // Update bubble positions
            foreach (Bubble bubble in bubbleGrid.Bubbles)
            {
                Vector2 oldPosition = bubble.Position;
                bubble.Update(gameTime);
                HandleCollision(bubble);
                if (Equals(oldPosition, bubble.Position))
                {
                    bubble.IsFalling = false;
                }
                else
                {
                    bubble.IsFalling = true;
                }
            }

            bubbleGrid.CollapseBubbleColumns();

            //Get current state of inputs so that we can check whether the player has clicked/tapped the screen
            MouseState      newState        = Mouse.GetState();
            TouchCollection touchCollection = TouchPanel.GetState();

            /* If the player has clicked the left button of the mouse (only if previously unclicked, otherwise this will
             * execute multiple times even if the player seemingly only clicked once) or if the player has touched some
             * location on the screen, then we check for the rest of the game mechanics */
            if (newState.LeftButton == ButtonState.Pressed && oldState.LeftButton == ButtonState.Released || touchCollection.Count > 0)
            {
                Vector2 clickLocation = camera.ScreenToWorld(new Vector2(newState.X, newState.Y));
                Vector2 touchLocation = Vector2.Zero;

                /* Only Fire Select Once it's been released. This will make it so that even if the user holds their finger down,
                 * we will only assign a different touch location other than 0,0 when they release their finger. */
                if (touchCollection.Count > 0)
                {
                    if (touchCollection[0].State == TouchLocationState.Pressed)
                    {
                        touchLocation = camera.ScreenToWorld(touchCollection[0].Position);
                    }
                }

                /* First, we see if any bubbles have been clicked on. If it's not an activated bubble, we need to deactivate all
                 * the bubbles so we can prepare to activate the set that the user just clicked on. If they clicked on a bubble that
                 * IS activated, then we get ready to clear out all the activated bubbles. */
                foreach (Bubble bubble in bubbleGrid.Bubbles)
                {
                    if (bubble.Intersects(clickLocation) || bubble.Intersects(touchLocation))
                    {
                        if (!bubble.Activated)
                        {
                            bubbleGrid.DeactivateAllBubbles();
                        }
                        else if (bubble.Activated && bubbleGrid.BubbleHasSameColorNeighbor(bubble))
                        {
                            readyToRemoveActivatedBubbles = true;
                            break; //We can exit early before doing anything with any other bubbles remaining in the foreach loop
                        }
                    }
                }

                if (readyToRemoveActivatedBubbles)
                {
                    score.Add(bubbleGrid.NumberOfActivatedBubbles(), level);
                    bubbleGrid.RemoveActivatedBubbles();
                    readyToRemoveActivatedBubbles = false;
                    oldState = newState;
                    if (LevelIsCleared()) //May eventually pass in score.Value
                    {
                        if (difficulty < 6)
                        {
                            level++;
                        }
                        StartNextLevel();
                    }
                    return;
                }

                /* If we've gotten this far, it means that the user hasn't clicked on a bubble that was already activated. So we
                 * again check to see if they clicked on a bubble, and if it's not activated, we activate it. Then we activate
                 * all the connected bubbles of the same color. */
                foreach (Bubble bubble in bubbleGrid.Bubbles)
                {
                    if (bubble.Intersects(clickLocation) || bubble.Intersects(touchLocation))
                    {
                        if (!bubble.Activated)
                        {
                            bubble.Activate();
                            break; //We found the one they clicked on and activated it, so we can leave this loop early
                        }
                    }
                }
                bubbleGrid.ActivateAllConnectedBubbles();
            }

            /* We update the old mouse state so that we can keep accurately acting through single mouse clicks rather than
             * if the mouse is held for a few frames (when the user THINKS they only clicked once) */
            oldState = newState;
        }
Esempio n. 38
0
        /// <summary>
        /// Handling aller Eingaben, Mausbewegungen und Updaten aller Screens und Controls.
        /// </summary>
        /// <param name="gameTime"></param>
        public override void Update(GameTime gameTime)
        {
            if (Game.IsActive)
            {
                #region Mouse Interaction

                if (MouseEnabled)
                {
                    MouseState mouse = Mouse.GetState();

                    // Mausposition anhand des Mouse Modes ermitteln
                    Point mousePosition = mouse.Position;
                    if (MouseMode == MouseMode.Captured)
                    {
                        mousePosition = new Point(
                            mousePosition.X - (GraphicsDevice.Viewport.Width / 2),
                            mousePosition.Y - (GraphicsDevice.Viewport.Height / 2));
                    }

                    // Mouse Move
                    if (mousePosition != lastMousePosition)
                    {
                        MouseEventArgs moveArgs = new MouseEventArgs()
                        {
                            MouseMode      = MouseMode,
                            GlobalPosition = mousePosition,
                            LocalPosition  = mousePosition,
                        };

                        root.InternalMouseMove(moveArgs);
                        if (!moveArgs.Handled && MouseMove != null)
                        {
                            MouseMove(moveArgs);
                        }

                        // Start Drag Handling
                        if (mouse.LeftButton == ButtonState.Pressed &&
                            DraggingArgs == null)
                        {
                            DraggingArgs = new DragEventArgs()
                            {
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition,
                            };

                            draggingId = null;

                            root.InternalStartDrag(DraggingArgs);
                            if (!DraggingArgs.Handled && StartDrag != null)
                            {
                                StartDrag(DraggingArgs);
                            }
                        }

                        // Drop move
                        if (mouse.LeftButton == ButtonState.Pressed &&
                            DraggingArgs != null &&
                            draggingId == null &&
                            DraggingArgs.Handled)
                        {
                            DragEventArgs args = new DragEventArgs()
                            {
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition,
                                Content        = DraggingArgs.Content,
                                Icon           = DraggingArgs.Icon,
                                Sender         = DraggingArgs.Sender
                            };

                            root.InternalDropMove(args);
                            if (!args.Handled && DropMove != null)
                            {
                                DropMove(args);
                            }
                        }
                    }

                    // Linke Maustaste
                    if (mouse.LeftButton == ButtonState.Pressed)
                    {
                        if (!lastLeftMouseButtonPressed)
                        {
                            MouseEventArgs leftDownArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };

                            // Linke Maustaste wurde neu gedrückt
                            root.InternalLeftMouseDown(leftDownArgs);
                            if (!leftDownArgs.Handled && LeftMouseDown != null)
                            {
                                LeftMouseDown(leftDownArgs);
                            }
                        }
                        lastLeftMouseButtonPressed = true;
                    }
                    else
                    {
                        if (lastLeftMouseButtonPressed)
                        {
                            // Handle Drop
                            if (DraggingArgs != null && DraggingArgs.Handled)
                            {
                                DragEventArgs args = new DragEventArgs()
                                {
                                    GlobalPosition = mousePosition,
                                    LocalPosition  = mousePosition,
                                    Content        = DraggingArgs.Content,
                                    Icon           = DraggingArgs.Icon,
                                    Sender         = DraggingArgs.Sender
                                };

                                root.InternalEndDrop(args);
                                if (!args.Handled && EndDrop != null)
                                {
                                    EndDrop(args);
                                }
                            }

                            // Discard Dragging Infos
                            DraggingArgs = null;
                            draggingId   = null;

                            // Linke Maustaste wurde losgelassen
                            MouseEventArgs leftClickArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };

                            root.InternalLeftMouseClick(leftClickArgs);
                            if (!leftClickArgs.Handled && LeftMouseClick != null)
                            {
                                LeftMouseClick(leftClickArgs);
                            }

                            if (lastLeftClick.HasValue &&
                                gameTime.TotalGameTime - lastLeftClick.Value < TimeSpan.FromMilliseconds(DoubleClickDelay))
                            {
                                // Double Left Click
                                MouseEventArgs leftDoubleClickArgs = new MouseEventArgs
                                {
                                    MouseMode      = MouseMode,
                                    GlobalPosition = mousePosition,
                                    LocalPosition  = mousePosition
                                };

                                root.InternalLeftMouseDoubleClick(leftDoubleClickArgs);
                                if (!leftDoubleClickArgs.Handled && LeftMouseDoubleClick != null)
                                {
                                    LeftMouseDoubleClick(leftDoubleClickArgs);
                                }

                                lastLeftClick = null;
                            }
                            else
                            {
                                lastLeftClick = gameTime.TotalGameTime;
                            }

                            // Mouse Up
                            MouseEventArgs leftUpArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };

                            root.InternalLeftMouseUp(leftUpArgs);
                            if (!leftUpArgs.Handled && LeftMouseUp != null)
                            {
                                LeftMouseUp(leftUpArgs);
                            }
                        }
                        lastLeftMouseButtonPressed = false;
                    }

                    // Rechte Maustaste
                    if (mouse.RightButton == ButtonState.Pressed)
                    {
                        if (!lastRightMouseButtonPressed)
                        {
                            // Rechte Maustaste neu gedrückt
                            MouseEventArgs rightDownArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };

                            root.InternalRightMouseDown(rightDownArgs);
                            if (!rightDownArgs.Handled && RightMouseDown != null)
                            {
                                RightMouseDown(rightDownArgs);
                            }
                        }
                        lastRightMouseButtonPressed = true;
                    }
                    else
                    {
                        if (lastRightMouseButtonPressed)
                        {
                            // Rechte Maustaste losgelassen
                            MouseEventArgs rightClickArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };
                            root.InternalRightMouseClick(rightClickArgs);
                            if (!rightClickArgs.Handled && RightMouseClick != null)
                            {
                                RightMouseClick(rightClickArgs);
                            }

                            if (lastRightClick.HasValue &&
                                gameTime.TotalGameTime - lastRightClick.Value < TimeSpan.FromMilliseconds(DoubleClickDelay))
                            {
                                // Double Left Click
                                MouseEventArgs rightDoubleClickArgs = new MouseEventArgs
                                {
                                    MouseMode      = MouseMode,
                                    GlobalPosition = mousePosition,
                                    LocalPosition  = mousePosition
                                };

                                root.InternalRightMouseDoubleClick(rightDoubleClickArgs);
                                if (!rightDoubleClickArgs.Handled && RightMouseDoubleClick != null)
                                {
                                    RightMouseDoubleClick(rightDoubleClickArgs);
                                }

                                lastRightClick = null;
                            }
                            else
                            {
                                lastRightClick = gameTime.TotalGameTime;
                            }

                            MouseEventArgs rightUpArgs = new MouseEventArgs
                            {
                                MouseMode      = MouseMode,
                                GlobalPosition = mousePosition,
                                LocalPosition  = mousePosition
                            };
                            root.InternalRightMouseUp(rightUpArgs);
                            if (!rightUpArgs.Handled && RightMouseUp != null)
                            {
                                RightMouseUp(rightUpArgs);
                            }
                        }
                        lastRightMouseButtonPressed = false;
                    }

                    // Mousewheel
                    if (lastMouseWheelValue != mouse.ScrollWheelValue)
                    {
                        int diff = (mouse.ScrollWheelValue - lastMouseWheelValue);

                        MouseScrollEventArgs scrollArgs = new MouseScrollEventArgs
                        {
                            MouseMode      = MouseMode,
                            GlobalPosition = mousePosition,
                            LocalPosition  = mousePosition,
                            Steps          = diff
                        };
                        root.InternalMouseScroll(scrollArgs);
                        if (!scrollArgs.Handled && MouseScroll != null)
                        {
                            MouseScroll(scrollArgs);
                        }

                        lastMouseWheelValue = mouse.ScrollWheelValue;
                    }

                    // Potentieller Positionsreset
                    if (MouseMode == MouseMode.Free)
                    {
                        lastMousePosition = mouse.Position;
                    }
                    else if (mousePosition.X != 0 || mousePosition.Y != 0)
                    {
                        Mouse.SetPosition(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
                    }
                }

                #endregion

                #region Keyboard Interaction

                if (KeyboardEnabled)
                {
                    KeyboardState keyboard = Keyboard.GetState();

                    bool shift = keyboard.IsKeyDown(Keys.LeftShift) | keyboard.IsKeyDown(Keys.RightShift);
                    bool ctrl  = keyboard.IsKeyDown(Keys.LeftControl) | keyboard.IsKeyDown(Keys.RightControl);
                    bool alt   = keyboard.IsKeyDown(Keys.LeftAlt) | keyboard.IsKeyDown(Keys.RightAlt);

                    KeyEventArgs args;
                    foreach (Keys key in Enum.GetValues(typeof(Keys)))
                    {
                        if (keyboard.IsKeyDown(key))
                        {
                            if (!pressedKeys.ContainsKey(key))
                            {
                                // Taste ist neu

                                args = new KeyEventArgs()
                                {
                                    Key   = key,
                                    Shift = shift,
                                    Ctrl  = ctrl,
                                    Alt   = alt
                                };
                                root.InternalKeyDown(args);

                                if (!args.Handled)
                                {
                                    if (KeyDown != null)
                                    {
                                        KeyDown(args);
                                    }
                                }

                                args = new KeyEventArgs()
                                {
                                    Key   = key,
                                    Shift = shift,
                                    Ctrl  = ctrl,
                                    Alt   = alt
                                };
                                root.InternalKeyPress(args);
                                pressedKeys.Add(key, gameTime.TotalGameTime.TotalMilliseconds + 500);



                                // Spezialfall Tab-Taste (falls nicht verarbeitet wurde)
                                if (key == Keys.Tab && !args.Handled)
                                {
                                    if (shift)
                                    {
                                        root.InternalTabbedBackward();
                                    }
                                    else
                                    {
                                        root.InternalTabbedForward();
                                    }
                                }
                            }
                            else
                            {
                                // Taste ist immernoch gedrückt
                                if (pressedKeys[key] <= gameTime.TotalGameTime.TotalMilliseconds)
                                {
                                    args = new KeyEventArgs()
                                    {
                                        Key   = key,
                                        Shift = shift,
                                        Ctrl  = ctrl,
                                        Alt   = alt
                                    };
                                    root.InternalKeyPress(args);
                                    if (!args.Handled)
                                    {
                                        if (KeyPress != null)
                                        {
                                            KeyPress(args);
                                        }
                                    }
                                    pressedKeys[key] = gameTime.TotalGameTime.TotalMilliseconds + 50;
                                }
                            }
                        }
                        else
                        {
                            if (pressedKeys.ContainsKey(key))
                            {
                                // Taste losgelassen
                                args = new KeyEventArgs()
                                {
                                    Key   = key,
                                    Shift = shift,
                                    Ctrl  = ctrl,
                                    Alt   = alt
                                };
                                root.InternalKeyUp(args);
                                pressedKeys.Remove(key);

                                if (!args.Handled)
                                {
                                    if (KeyUp != null)
                                    {
                                        KeyUp(args);
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                #region Touchpanel Interaction

                if (TouchEnabled)
                {
                    TouchCollection touchPoints = TouchPanel.GetState();
                    foreach (var touchPoint in touchPoints)
                    {
                        Point          point = touchPoint.Position.ToPoint();
                        TouchEventArgs args  = new TouchEventArgs()
                        {
                            TouchId        = touchPoint.Id,
                            GlobalPosition = point,
                            LocalPosition  = point
                        };

                        switch (touchPoint.State)
                        {
                        case TouchLocationState.Pressed:
                            root.InternalTouchDown(args);
                            if (!args.Handled && TouchDown != null)
                            {
                                TouchDown(args);
                            }
                            break;

                        case TouchLocationState.Moved:

                            // Touch Move
                            root.InternalTouchMove(args);
                            if (!args.Handled && TouchMove != null)
                            {
                                TouchMove(args);
                            }

                            // Start Dragging
                            if (DraggingArgs == null)
                            {
                                DraggingArgs = new DragEventArgs()
                                {
                                    GlobalPosition = point,
                                    LocalPosition  = point,
                                };

                                draggingId = touchPoint.Id;

                                root.InternalStartDrag(DraggingArgs);
                                if (!DraggingArgs.Handled && StartDrag != null)
                                {
                                    StartDrag(DraggingArgs);
                                }
                            }

                            // Drop move
                            if (DraggingArgs != null &&
                                draggingId == touchPoint.Id &&
                                DraggingArgs.Handled)
                            {
                                DragEventArgs moveArgs = new DragEventArgs()
                                {
                                    GlobalPosition = point,
                                    LocalPosition  = point,
                                    Content        = DraggingArgs.Content,
                                    Icon           = DraggingArgs.Icon,
                                    Sender         = DraggingArgs.Sender
                                };

                                root.InternalDropMove(moveArgs);
                                if (!args.Handled && DropMove != null)
                                {
                                    DropMove(moveArgs);
                                }
                            }

                            break;

                        case TouchLocationState.Released:

                            // Handle Drop
                            if (DraggingArgs != null &&
                                draggingId == touchPoint.Id &&
                                DraggingArgs.Handled)
                            {
                                DragEventArgs dropArgs = new DragEventArgs()
                                {
                                    GlobalPosition = point,
                                    LocalPosition  = point,
                                    Content        = DraggingArgs.Content,
                                    Icon           = DraggingArgs.Icon,
                                    Sender         = DraggingArgs.Sender
                                };

                                root.InternalEndDrop(dropArgs);
                                if (!args.Handled && EndDrop != null)
                                {
                                    EndDrop(dropArgs);
                                }
                            }

                            // Discard Dragging Infos
                            DraggingArgs = null;
                            draggingId   = null;

                            // Linke Maustaste wurde losgelassen
                            TouchEventArgs tapArgs = new TouchEventArgs
                            {
                                TouchId        = touchPoint.Id,
                                GlobalPosition = point,
                                LocalPosition  = point
                            };

                            root.InternalTouchTap(tapArgs);
                            if (!tapArgs.Handled && TouchTap != null)
                            {
                                TouchTap(tapArgs);
                            }

                            if (lastTouchTap.HasValue &&
                                gameTime.TotalGameTime - lastLeftClick.Value < TimeSpan.FromMilliseconds(DoubleClickDelay))
                            {
                                // Double Tap
                                TouchEventArgs doubleTapArgs = new TouchEventArgs
                                {
                                    TouchId        = touchPoint.Id,
                                    GlobalPosition = point,
                                    LocalPosition  = point
                                };

                                root.InternalTouchDoubleTap(doubleTapArgs);
                                if (!doubleTapArgs.Handled && TouchDoubleTap != null)
                                {
                                    TouchDoubleTap(doubleTapArgs);
                                }

                                lastTouchTap = null;
                            }
                            else
                            {
                                lastTouchTap = gameTime.TotalGameTime;
                            }

                            root.InternalTouchUp(args);
                            if (!args.Handled && TouchUp != null)
                            {
                                TouchUp(args);
                            }
                            break;
                        }
                    }
                }

                #endregion
            }

            #region Recalculate Sizes

            if (root.HasInvalidDimensions())
            {
                Point available = new Point(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
                Point required  = root.GetExpectedSize(available);
                root.SetActualSize(available);
            }

            root.Update(gameTime);

            #endregion

            #region Form anpassen

            string screentitle = ActiveScreen != null ? ActiveScreen.Title : string.Empty;
            string windowtitle = TitlePrefix + (string.IsNullOrEmpty(screentitle) ? "" : " - " + screentitle);

            if (Game.Window != null && Game.Window.Title != windowtitle)
            {
                Game.Window.Title = windowtitle;
            }

            #endregion
        }
Esempio n. 39
0
        /// <summary>
        /// Read keyboard and gamepad input
        /// </summary>
        private void HandleInput(float elapsedTime)
        {
            previousGamePadState  = currentGamePadState;
            previousKeyboardState = currentKeyboardState;
            previousMouseState    = currentMouseState;
            currentGamePadState   = GamePad.GetState(PlayerIndex.One);
            currentKeyboardState  = Keyboard.GetState();
            currentMouseState     = Mouse.GetState();

            currentTouchCollection = TouchPanel.GetState();

            //bool touched = false;
            int touchCount = 0;

            // tap the screen to select
            foreach (TouchLocation location in currentTouchCollection)
            {
                switch (location.State)
                {
                case TouchLocationState.Pressed:
                    //touched = true;
                    touchCount++;
                    cursorLocation = location.Position;
                    break;

                case TouchLocationState.Moved:
                    break;

                case TouchLocationState.Released:
                    break;
                }
            }

            if (currentMouseState.LeftButton == ButtonState.Released && previousMouseState.LeftButton == ButtonState.Pressed)
            {
                cursorLocation.X = currentMouseState.X;
                cursorLocation.Y = currentMouseState.Y;
                touchCount       = 1;
            }

            if (currentMouseState.MiddleButton == ButtonState.Released && previousMouseState.MiddleButton == ButtonState.Pressed)
            {
                touchCount = 2;
            }

            if (currentMouseState.RightButton == ButtonState.Released && previousMouseState.RightButton == ButtonState.Pressed)
            {
                touchCount = 3;
            }

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

            // Update the cursor location by listening for left thumbstick input on
            // the GamePad and direction key input on the Keyboard, making sure to
            // keep the cursor inside the screen boundary
            cursorLocation.X +=
                currentGamePadState.ThumbSticks.Left.X * cursorMoveSpeed * elapsedTime;
            cursorLocation.Y -=
                currentGamePadState.ThumbSticks.Left.Y * cursorMoveSpeed * elapsedTime;

            if (currentKeyboardState.IsKeyDown(Keys.Up))
            {
                cursorLocation.Y -= elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Down))
            {
                cursorLocation.Y += elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
                cursorLocation.X -= elapsedTime * cursorMoveSpeed;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Right))
            {
                cursorLocation.X += elapsedTime * cursorMoveSpeed;
            }
            cursorLocation.X = MathHelper.Clamp(cursorLocation.X, 0f, screenWidth);
            cursorLocation.Y = MathHelper.Clamp(cursorLocation.Y, 0f, screenHeight);

            // Change the tank move behavior if the user pressed B on
            // the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.B == ButtonState.Released &&
                 currentGamePadState.Buttons.B == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.B) &&
                 currentKeyboardState.IsKeyDown(Keys.B)) || (touchCount == 2))
            {
                tank.CycleBehaviorType();
            }

            // Add the cursor's location to the WaypointList if the user pressed A on
            // the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.A == ButtonState.Released &&
                 currentGamePadState.Buttons.A == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.A) &&
                 currentKeyboardState.IsKeyDown(Keys.A)) || (touchCount == 1))
            {
                tank.Waypoints.Enqueue(cursorLocation);
            }

            // Delete all the current waypoints and reset the tanks’ location if
            // the user pressed X on the GamePad or on the Keyboard.
            if ((previousGamePadState.Buttons.X == ButtonState.Released &&
                 currentGamePadState.Buttons.X == ButtonState.Pressed) ||
                (previousKeyboardState.IsKeyUp(Keys.X) &&
                 currentKeyboardState.IsKeyDown(Keys.X)) || (touchCount == 3))
            {
                tank.Reset(
                    new Vector2((float)screenWidth / 4, (float)screenHeight / 4));
            }
        }
Esempio n. 40
0
        private void ProcessTouch()
        {
            if (m_pDelegate != null)
            {
                newTouches.Clear();
                movedTouches.Clear();
                endedTouches.Clear();

                CCRect  viewPort = CCDrawManager.ViewPortRect;
                CCPoint pos;

                // TODO: allow configuration to treat the game pad as a touch device.

#if WINDOWS || WINDOWSGL || MACOS
                _prevMouseState = _lastMouseState;
                _lastMouseState = Mouse.GetState();

                if (_prevMouseState.LeftButton == ButtonState.Released && _lastMouseState.LeftButton == ButtonState.Pressed)
                {
#if NETFX_CORE
                    pos = TransformPoint(_lastMouseState.X, _lastMouseState.Y);
                    pos = CCDrawManager.ScreenToWorld(pos.X, pos.Y);
#else
                    pos = CCDrawManager.ScreenToWorld(_lastMouseState.X, _lastMouseState.Y);
#endif
                    _lastMouseId++;
                    m_pTouches.AddLast(new CCTouch(_lastMouseId, pos.X, pos.Y));
                    m_pTouchMap.Add(_lastMouseId, m_pTouches.Last);
                    newTouches.Add(m_pTouches.Last.Value);

                    m_bCaptured = true;
                }
                else if (_prevMouseState.LeftButton == ButtonState.Pressed && _lastMouseState.LeftButton == ButtonState.Pressed)
                {
                    if (m_pTouchMap.ContainsKey(_lastMouseId))
                    {
                        if (_prevMouseState.X != _lastMouseState.X || _prevMouseState.Y != _lastMouseState.Y)
                        {
#if NETFX_CORE
                            pos = TransformPoint(_lastMouseState.X, _lastMouseState.Y);
                            pos = CCDrawManager.ScreenToWorld(pos.X, pos.Y);
#else
                            pos = CCDrawManager.ScreenToWorld(_lastMouseState.X, _lastMouseState.Y);
#endif
                            movedTouches.Add(m_pTouchMap[_lastMouseId].Value);
                            m_pTouchMap[_lastMouseId].Value.SetTouchInfo(_lastMouseId, pos.X, pos.Y);
                        }
                    }
                }
                else if (_prevMouseState.LeftButton == ButtonState.Pressed && _lastMouseState.LeftButton == ButtonState.Released)
                {
                    if (m_pTouchMap.ContainsKey(_lastMouseId))
                    {
                        endedTouches.Add(m_pTouchMap[_lastMouseId].Value);
                        m_pTouches.Remove(m_pTouchMap[_lastMouseId]);
                        m_pTouchMap.Remove(_lastMouseId);
                    }
                }
#endif

                TouchCollection touchCollection = TouchPanel.GetState();

                foreach (TouchLocation touch in touchCollection)
                {
                    switch (touch.State)
                    {
                    case TouchLocationState.Pressed:
                        if (m_pTouchMap.ContainsKey(touch.Id))
                        {
                            break;
                        }

                        if (viewPort.ContainsPoint(touch.Position.X, touch.Position.Y))
                        {
                            pos = CCDrawManager.ScreenToWorld(touch.Position.X, touch.Position.Y);

                            m_pTouches.AddLast(new CCTouch(touch.Id, pos.X, pos.Y));
                            m_pTouchMap.Add(touch.Id, m_pTouches.Last);
                            newTouches.Add(m_pTouches.Last.Value);
                        }
                        break;

                    case TouchLocationState.Moved:
                        LinkedListNode <CCTouch> existingTouch;
                        if (m_pTouchMap.TryGetValue(touch.Id, out existingTouch))
                        {
                            pos = CCDrawManager.ScreenToWorld(touch.Position.X, touch.Position.Y);
                            var delta = existingTouch.Value.LocationInView - pos;
                            if (delta.LengthSQ > 1.0f)
                            {
                                movedTouches.Add(existingTouch.Value);
                                existingTouch.Value.SetTouchInfo(touch.Id, pos.X, pos.Y);
                            }
                        }
                        break;

                    case TouchLocationState.Released:
                        if (m_pTouchMap.TryGetValue(touch.Id, out existingTouch))
                        {
                            endedTouches.Add(existingTouch.Value);
                            m_pTouches.Remove(existingTouch);
                            m_pTouchMap.Remove(touch.Id);
                        }
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                if (newTouches.Count > 0)
                {
                    m_pDelegate.TouchesBegan(newTouches);
                }

                if (movedTouches.Count > 0)
                {
                    m_pDelegate.TouchesMoved(movedTouches);
                }

                if (endedTouches.Count > 0)
                {
                    m_pDelegate.TouchesEnded(endedTouches);
                }
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        ///
        public override void HandleInput(InputState input)
        {
            TouchCollection touchState    = TouchPanel.GetState();
            bool            touchDetected = false;
            Vector2         touchPosition = new Vector2();

            //interpert touch screen presses
            foreach (TouchLocation location in touchState)
            {
                switch (location.State)
                {
                case TouchLocationState.Pressed:
                    touchDetected = true;
                    touchPosition = location.Position;
                    break;

                case TouchLocationState.Moved:
                    break;

                case TouchLocationState.Released:
                    break;
                }
            }

            if (touchDetected)
            {
                foreach (MenuEntry menuEntry in menuEntries)
                {
                    Rectangle touchRect = new Rectangle((int)touchPosition.X - 5, (int)touchPosition.Y - 5,
                                                        10, 10);
                    if (menuEntry.EntryPosition.Intersects(touchRect))
                    {
                        menuEntry.OnSelectEntry();
                    }
                }
            }

            // Move to the previous menu entry?
            if (input.MenuUp)
            {
                selectedEntry--;

                if (selectedEntry < 0)
                {
                    selectedEntry = menuEntries.Count - 1;
                }
            }

            // Move to the next menu entry?
            if (input.MenuDown)
            {
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                {
                    selectedEntry = 0;
                }
            }

            // Accept or cancel the menu?
            if (input.MenuSelect)
            {
                OnSelectEntry(selectedEntry);
            }
            else if (input.MenuCancel)
            {
                OnCancel();
            }
        }
 private bool IsTouch(TouchCollection state, Rectangle area) => state.Any((s) => area.Contains(s.Position));
Esempio n. 43
0
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            // If the Save File dialog has returned, save the image
            if (!String.IsNullOrEmpty(filename))
            {
                diskTexture.SaveToPhotoLibrary(filename);
                filename = null;
            }

            // Disk rotates every 5 seconds
            double seconds = gameTime.TotalGameTime.TotalSeconds;

            currentAngle = (float)(2 * Math.PI * seconds / 5);

            // Colors cycle every 10 seconds
            float fraction = (float)(6 * (seconds % 10) / 10);

            if (fraction < 1)
            {
                currentColor = new Color(1, fraction, 0);
            }
            else if (fraction < 2)
            {
                currentColor = new Color(2 - fraction, 1, 0);
            }
            else if (fraction < 3)
            {
                currentColor = new Color(0, 1, fraction - 2);
            }
            else if (fraction < 4)
            {
                currentColor = new Color(0, 4 - fraction, 1);
            }
            else if (fraction < 5)
            {
                currentColor = new Color(fraction - 4, 0, 1);
            }
            else
            {
                currentColor = new Color(1, 0, 6 - fraction);
            }

            // First assume no finger movement
            foreach (TouchInfo touchInfo in touchDictionary.Values)
            {
                touchInfo.CurrentPosition = touchInfo.PreviousPosition;
            }

            // Get all touches
            TouchCollection touches = TouchPanel.GetState();

            foreach (TouchLocation touch in touches)
            {
                // Let Button components have first dibs on touch
                bool touchHandled = false;

                foreach (GameComponent component in this.Components)
                {
                    if (component is IProcessTouch &&
                        (component as IProcessTouch).ProcessTouch(touch))
                    {
                        touchHandled = true;
                        break;
                    }
                }

                if (touchHandled)
                {
                    continue;
                }

                // Set TouchInfo items from touch information
                int id = touch.Id;

                switch (touch.State)
                {
                case TouchLocationState.Pressed:
                    if (!touchDictionary.ContainsKey(id))
                    {
                        touchDictionary.Add(id, new TouchInfo());
                    }

                    touchDictionary[id].PreviousPosition = TranslateToTexture(touch.Position);
                    touchDictionary[id].CurrentPosition  = TranslateToTexture(touch.Position);
                    break;

                case TouchLocationState.Moved:
                    if (touchDictionary.ContainsKey(id))
                    {
                        touchDictionary[id].CurrentPosition =
                            TranslateToTexture(touch.Position);
                    }
                    break;

                case TouchLocationState.Released:
                    if (touchDictionary.ContainsKey(id))
                    {
                        touchDictionary.Remove(id);
                    }
                    break;
                }
            }

            // Calculate transforms for rotation
            Matrix translate1 = Matrix.CreateTranslation(-textureCenter.X, -textureCenter.Y, 0);
            Matrix translate2 = Matrix.CreateTranslation(textureCenter.X, textureCenter.Y, 0);

            Matrix previousRotation = translate1 *
                                      Matrix.CreateRotationZ(-previousAngle) *
                                      translate2;
            Matrix currentRotation = translate1 *
                                     Matrix.CreateRotationZ(-currentAngle) *
                                     translate2;

            bool textureNeedsUpdate = false;

            foreach (TouchInfo touchInfo in touchDictionary.Values)
            {
                // Now draw from previous to current points
                Vector2 point1 = Vector2.Transform(touchInfo.PreviousPosition, previousRotation);
                Vector2 point2 = Vector2.Transform(touchInfo.CurrentPosition, currentRotation);
                float   radius = 6;

                RoundCappedLine line = new RoundCappedLine(point1, point2, radius);

                int yMin = (int)(Math.Min(point1.Y, point2.Y) - radius);
                int yMax = (int)(Math.Max(point1.Y, point2.Y) + radius);

                yMin = Math.Max(0, Math.Min(diskTexture.Height, yMin));
                yMax = Math.Max(0, Math.Min(diskTexture.Height, yMax));

                for (int y = yMin; y < yMax; y++)
                {
                    xCollection.Clear();
                    line.GetAllX(y, xCollection);

                    if (xCollection.Count == 2)
                    {
                        int xMin = (int)(Math.Min(xCollection[0], xCollection[1]) + 0.5f);
                        int xMax = (int)(Math.Max(xCollection[0], xCollection[1]) + 0.5f);

                        xMin = Math.Max(0, Math.Min(diskTexture.Width, xMin));
                        xMax = Math.Max(0, Math.Min(diskTexture.Width, xMax));

                        for (int x = xMin; x < xMax; x++)
                        {
                            if (IsWithinCircle(x, y))
                            {
                                // Draw pixel in four quadrants
                                int xFlip = diskTexture.Width - x;
                                int yFlip = diskTexture.Height - y;

                                pixels[y * diskTexture.Width + x]         = currentColor.PackedValue;
                                pixels[y * diskTexture.Width + xFlip]     = currentColor.PackedValue;
                                pixels[yFlip * diskTexture.Width + x]     = currentColor.PackedValue;
                                pixels[yFlip * diskTexture.Width + xFlip] =
                                    currentColor.PackedValue;
                            }
                        }
                        textureNeedsUpdate = true;
                    }
                }
            }

            if (textureNeedsUpdate)
            {
                // Update the texture from the pixels array
                this.GraphicsDevice.Textures[0] = null;
                diskTexture.SetData <uint>(pixels);
            }

            // Prepare for next time through
            foreach (TouchInfo touchInfo in touchDictionary.Values)
            {
                touchInfo.PreviousPosition = touchInfo.CurrentPosition;
            }

            previousAngle = currentAngle;

            base.Update(gameTime);
        }
Esempio n. 44
0
        private void UpdateTilesUp(GameTime gameTime, KeyboardState keyboardState, GamePadState gamePadState, TouchCollection touchState, AccelerometerState accelState, DisplayOrientation orientation)
        {
            int y = Height - 1;

            for (int x = 0; x <= Width - 1; x++)
            {
                // If there is a visible Tile in that position
                Texture2D texture = null;
                texture = tiles[x, y].Texture;
                if (texture != null)
                {
                    // Draw it in screen space.
                    Rectangle rect     = new Rectangle(x * Convert.ToInt32(Math.Truncate(Tile.Size.X)), -1 * Convert.ToInt32(Math.Truncate(Tile.Size.Y)) - BOTTOM_BORDER, Convert.ToInt32(texture.Width), Convert.ToInt32(texture.Height));
                    Vector2   position = new Vector2(rect.X, rect.Y);
                    tiles[x, y].Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
                }
            }
        }
Esempio n. 45
0
        protected override void Update(GameTime gameTime)
        {
            // update our virtual thumbsticks
            VirtualThumbsticks.Update();


            if (!songstart)
            {
                MediaPlayer.Play(music);
                songstart = true;
            }



            switch (gameState)
            {
            case GameStates.TitleScreen:

                TouchCollection touchCollection = TouchPanel.GetState();
                foreach (TouchLocation tl in touchCollection)
                {
                    if ((tl.State == TouchLocationState.Pressed) ||
                        (tl.State == TouchLocationState.Moved))
                    {
                        GameManager.StartNewGame();
                        gameState        = GameStates.Playing;
                        Player.health    = 100;
                        Music.sound_flag = 0;
                    }
                }



                break;

            case GameStates.Playing:
                Player.Update(gameTime);
                WeaponManager.Update(gameTime);
                EnemyManager.Update(gameTime);
                GoalManager.Update(gameTime);



                if (GoalManager.ActiveTerminals == 0 && EnemyManager.Enemies.Count == 0)
                {
                    if (Enemy.rounder > 5)
                    {
                        gameState = GameStates.Victory;
                    }
                    else
                    {
                        gameState = GameStates.WaveComplete;
                    }
                }



                //Force the health to remain between 0 and 100
                Player.health = (int)MathHelper.Clamp(Player.health, 0, 100);

                Player.mana = (int)MathHelper.Clamp(Player.mana, 0, 100);

                break;

            case GameStates.WaveComplete:
            {
                GameManager.StartNewWave();
                Enemy.rounder++;
            }

                gameState = GameStates.Playing;



                break;

            //case GameStates.Victory:
            //    if ((GamePad.GetState(PlayerIndex.One).Buttons.Start ==
            //        ButtonState.Pressed) ||
            //        (Keyboard.GetState().IsKeyDown(Keys.Space)))
            //    {

            //        gameState = GameStates.Playing;
            //    }

            //    break;

            case GameStates.GameOver:
                gameOverTimer +=
                    (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (gameOverTimer > gameOverDelay)
                {
                    gameState     = GameStates.TitleScreen;
                    gameOverTimer = 0.0f;
                }
                break;
            }

            base.Update(gameTime);
        }
Esempio n. 46
0
        protected override void Update(GameTime gameTime)
        {
            if (Scale == 0)
            {
                Scale = GraphicsDevice.Viewport.Width / 480.0;
            }

            Stopwatch watch = new Stopwatch();

            Time = gameTime.TotalGameTime.TotalSeconds;

            LastInput = Input;
            TouchCollection      c             = TouchPanel.GetState();
            List <TouchLocation> scaledTouches = new List <TouchLocation>();

            foreach (TouchLocation orig in c)
            {
                scaledTouches.Add(new TouchLocation(orig.Id, orig.State, new Vector2(orig.Position.X, orig.Position.Y) / (float)Scale));
            }

            Input = new TouchCollection(scaledTouches.ToArray());

            if (_lastUpdateTime == 0)
            {
                _lastUpdateTime = Time;
            }

            DeltaTime = Time - _lastUpdateTime;

            if (OnUpdateBeforeState != null)
            {
                OnUpdateBeforeState(this, new UpdateEventArgs(DeltaTime, Time, TotalUpdates));
            }

            if (CurrentState != null)
            {
                CurrentState.Update(DeltaTime, Time, TotalUpdates);
                CurrentState.Coroutine.Advance();
            }

            TotalUpdates++;

            if (OnUpdateAfterState != null)
            {
                OnUpdateAfterState(this, new UpdateEventArgs(DeltaTime, Time, TotalUpdates));
            }

            _accumTime += DeltaTime;
            _framesSinceLastFpsReset++;
            _accumTimeSinceLastFpsReset += DeltaTime;

            if (_accumTimeSinceLastFpsReset >= 1.0)
            {
                FPS = _framesSinceLastFpsReset;
                _framesSinceLastFpsReset     = 0;
                _accumTimeSinceLastFpsReset -= 1.0;
            }

            watch.Stop();
            _timeInUpdate = watch.Elapsed.TotalMilliseconds;
            watch.Start();

            while (_accumTime >= (1.0 / FixedUpdatesPerSecond))
            {
                if (OnFixedUpdateBeforeState != null)
                {
                    OnFixedUpdateBeforeState(this, new FixedUpdateEventArgs(TotalFixedUpdates));
                }

                if (CurrentState != null)
                {
                    CurrentState.FixedUpdate(TotalFixedUpdates);
                }

                TotalFixedUpdates++;

                if (OnFixedUpdateAfterState != null)
                {
                    OnFixedUpdateAfterState(this, new FixedUpdateEventArgs(TotalFixedUpdates));
                }

                _accumTime -= (1.0 / FixedUpdatesPerSecond);
            }

            watch.Stop();
            _timeInFixedUpdate = watch.Elapsed.TotalMilliseconds;

            _lastUpdateTime = Time;

            base.Update(gameTime);
        }
        public override void HandleInput(GamePadState gamePadState, KeyboardState keyboardState, TouchCollection tocuCollection)
        {
            if (!keyboardState.GetPressedKeys().Any() && tocuCollection.All(a => a.State != TouchLocationState.Pressed))
            {
                return;
            }

            gameID = 1; // TODO Rework to actually select a game

            RequestStateChange(new LoadGameState(GsContainer));
        }
Esempio n. 48
0
 /// <summary>
 /// Updates state of touch panel and gamepad
 /// </summary>
 public void Update()
 {
     touchState   = TouchPanel.GetState();
     gamepadState = GamePad.GetState(PlayerIndex.One);
 }
Esempio n. 49
0
        /// <summary>
        /// Handles input, performs physics, and animates the player sprite.
        /// </summary>
        /// <remarks>
        /// We pass in all of the input states so that our game is only polling the hardware
        /// once per frame. We also pass the game's orientation because when using the accelerometer,
        /// we need to reverse our motion when the orientation is in the LandscapeRight orientation.
        /// </remarks>
        public void Update(
            GameTime gameTime,
            KeyboardState keyboardState,
            GamePadState gamePadState,
            TouchCollection touchState,
            AccelerometerState accelState,
            DisplayOrientation orientation)
        {
            HandleCollision();


            if (this.GetType() == typeof(Chomper))
            {
                ((Chomper)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (((Chomper)this).elapsedTimeOpen > ((Chomper)this).timeOpen)
                {
                    ((Chomper)this).Close();
                }
            }

            if (this.GetType() == typeof(Spikes))
            {
                ((Spikes)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (((Spikes)this).elapsedTimeOpen > ((Spikes)this).timeOpen)
                {
                    ((Spikes)this).Close();
                }
            }


            if (this.GetType() == typeof(Gate))
            {
                if (((Gate)this).infiniteOpen == true)
                {
                    return;
                }

                ((Gate)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (((Gate)this).elapsedTimeOpen > ((Gate)this).timeOpen)
                {
                    ((Gate)this).Close();
                }
            }

            //REMAIN OPEN FOREVER!!!
            //if (this.GetType() == typeof(Exit))
            //{
            //    ((Exit)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
            //    if (((Exit)this).elapsedTimeOpen > ((Exit)this).timeOpen)
            //        ((Exit)this).Close();
            //}

            if (this.GetType() == typeof(PressPlate))
            {
                if (((PressPlate)this).infinitePress == true)
                {
                    return;
                }

                ((PressPlate)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
                if (((PressPlate)this).elapsedTimeOpen > ((PressPlate)this).timeOpen & ((PressPlate)this).State == Enumeration.StateTile.dpressplate)
                {
                    ((PressPlate)this).DePress();
                }
            }

            if (this.GetType() == typeof(Loose))
            {
                if (((Loose)this).tileState.Value().state == Enumeration.StateTile.loose)
                {
                    ((Loose)this).elapsedTimeOpen += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (((Loose)this).elapsedTimeOpen > ((Loose)this).timeFall)
                    {
                        ((Loose)this).Fall();
                    }
                }
            }

            float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

            tileAnimation.UpdateFrameTile(elapsed, ref _position, ref flip, ref tileState);
        }
Esempio n. 50
0
        public void Update(GameTime gameTime, KeyboardState keyboardState, GamePadState gamePadState, TouchCollection touchState, AccelerometerState accelState, DisplayOrientation orientation)
        {
            //THIS IS FOR NOT UPDATE THE BLOCK ROOM AND SAVE SOME CPU TIME....
            if (this.roomName == "MAP_blockroom.xml")
            {
                return;
            }
            //player.Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);

            UpdateTilesTemporaney(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);

            UpdateTiles(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
            //maze.LeftRoom(this).UpdateTilesLeft(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);

            //maze.UpRoom(this).UpdateTilesUp(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);

            UpdateItems(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);

            //update spritesssss
            //UpdateSprites(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
        }
Esempio n. 51
0
 public void HandleInput(TouchCollection previousTouchCollection, TouchCollection currentTouchCollection, GameTime gameTime)
 {
 }
Esempio n. 52
0
 private void UpdateItems(GameTime gameTime, KeyboardState keyboardState, GamePadState gamePadState, TouchCollection touchState, AccelerometerState accelState, DisplayOrientation orientation)
 {
     for (int y = Height - 1; y >= 0; y += -1)
     {
         for (int x = 0; x <= Width - 1; x++)
         {
             if (tiles[x, y].item != null)
             {
                 tiles[x, y].item.Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
             }
         }
     }
 }
Esempio n. 53
0
        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            _leftBaseCoolDown.Update();
            _rightBaseCoolDown.Update();
            _middleBaseCoolDown.Update();

            //lose check
            if (_buildings[0].GetDeathState && _buildings[1].GetDeathState && _buildings[2].GetDeathState && _buildings[3].GetDeathState && _buildings[4].GetDeathState && _buildings[5].GetDeathState)
            {
                _lose = true;
                TextBlockFinalScores.Text = _score.ToString();
                CanvasGameOver.Visibility = System.Windows.Visibility.Visible;
            }
            if (_leftBase.GetDeathState && _middleBase.GetDeathState && _rightBase.GetDeathState)
            {
                _lose = true;
                TextBlockFinalScores.Text = _score.ToString();
                CanvasGameOver.Visibility = System.Windows.Visibility.Visible;
            }

            //mini buildings to test collisions
            for (int i = 0; i < _buildings.Length; i++)
            {
                if (!_buildings[i].GetDeathState)
                {
                    if (_missileManager.TestForMissileRectangleCollisions(_buildings[i].GetRectangle))
                    {
                        _city -= 1;
                        _percentMultiplier -= 0.1f;
                        UpdateOverlay();
                        _buildings[i].Destruction(Missile.missileManager.GetLandScape, 30, 30);
                    }
                }
            }

            //missile manager testcollision with buildings
            if (!_leftBase.GetDeathState)
            {
                if (_missileManager.TestForMissileRectangleCollisions(_leftBase.GetRectangle))
                {
                    BorderLeftArrow.Visibility = System.Windows.Visibility.Collapsed;

                    _missilesBases     -= 1;
                    _percentMultiplier -= 0.05f;
                    _leftBase.Destruction(Missile.missileManager.GetLandScape, 40, 30);

                    UpdateOverlay();
                }
            }
            if (!_middleBase.GetDeathState)
            {
                if (_missileManager.TestForMissileRectangleCollisions(_middleBase.GetRectangle))
                {
                    BorderMiddleArrow.Visibility = System.Windows.Visibility.Collapsed;

                    _missilesBases     -= 1;
                    _percentMultiplier -= 0.05f;
                    _middleBase.Destruction(Missile.missileManager.GetLandScape, 30, 30);

                    UpdateOverlay();
                }
            }
            if (!_rightBase.GetDeathState)
            {
                if (_missileManager.TestForMissileRectangleCollisions(_rightBase.GetRectangle))
                {
                    BorderRightArrow.Visibility = System.Windows.Visibility.Collapsed;

                    _missilesBases     -= 1;
                    _percentMultiplier -= 0.05f;
                    _rightBase.Destruction(Missile.missileManager.GetLandScape, 30, 30);
                    UpdateOverlay();
                }
            }

            TouchCollection touchCollection = TouchPanel.GetState();

            foreach (TouchLocation tl in touchCollection)
            {
                if (tl.State == TouchLocationState.Released)
                {
                    if (tl.Position.Y < (int)SharedGraphicsDeviceManager.DefaultBackBufferHeight - 40)
                    {
                        if (tl.Position.Y < HEIGHT - 50)
                        {
                            //adds a missile to the world
                            if (_selectedArrow == 1)
                            {
                                if (!_rightBaseCoolDown.IsOverHeated())
                                {
                                    if (!_rightBase.GetDeathState)
                                    {
                                        _rightBaseCoolDown.AddHeat(30);
                                        Missile.missileManager.Addmissile(new Vector2(_rightBase.GetRectangle.Left + _rightBase.GetRectangle.Width / 2, _rightBase.GetRectangle.Bottom - 2), tl.Position, new Missile.Player.PlayerNormalmissile());
                                    }
                                }
                            }
                            else if (_selectedArrow == 2)
                            {
                                if (!_middleBaseCoolDown.IsOverHeated())
                                {
                                    if (!_middleBase.GetDeathState)
                                    {
                                        _middleBaseCoolDown.AddHeat(30);
                                        Missile.missileManager.Addmissile(new Vector2(_middleBase.GetRectangle.Left + _middleBase.GetRectangle.Width / 2, _middleBase.GetRectangle.Bottom - 2), tl.Position, new Missile.Player.PlayerNormalmissile());
                                    }
                                }
                            }
                            else
                            {
                                if (!_leftBaseCoolDown.IsOverHeated())
                                {
                                    if (!_leftBase.GetDeathState)
                                    {
                                        _leftBaseCoolDown.AddHeat(30);
                                        Missile.missileManager.Addmissile(new Vector2(_leftBase.GetRectangle.Left + _leftBase.GetRectangle.Width / 2, _leftBase.GetRectangle.Bottom - 2), tl.Position, new Missile.Player.PlayerNormalmissile());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            _line.Update();
            // TODO: Add your update logic here
            _missileManager.Update();

            if (_oldScore != _score)
            {
                _oldScore = _score;
                UpdateOverlay();
            }
        }
Esempio n. 54
0
        private void UpdateSprites(GameTime gameTime, KeyboardState keyboardState, GamePadState gamePadState, TouchCollection touchState, AccelerometerState accelState, DisplayOrientation orientation)
        {
            foreach (Sprite s in SpritesInRoom())
            {
                switch (s.GetType().Name)
                {
                case "Guard":
                    ((Guard)s).Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
                    break;

                case "Skeleton":
                    ((Skeleton)s).Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
                    break;


                case "Serpent":
                    ((Serpent)s).Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
                    break;
                }
            }
        }
Esempio n. 55
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)
        {
            TouchCollection mscaDotknięte = new TouchCollection();

            mscaDotknięte = TouchPanel.GetState();

            if (stanGry)
            {
                //Sterowanie dotykowe
                foreach (TouchLocation dotyk in mscaDotknięte)
                {
                    pozDotyku = dotyk.Position;
                    //Równanie koła (x-a)^2 + (y-b)^2 <= r^2
                    if (dotyk.State == TouchLocationState.Moved)
                    {
                        if (((pozDotyku.X - 60) * (pozDotyku.X - 60)) + ((pozDotyku.Y - 690) * (pozDotyku.Y - 690)) <= 160)
                        {
                            gracz.MoveL();
                        }
                        if (((pozDotyku.X - 160) * (pozDotyku.X - 160)) + ((pozDotyku.Y - 690) * (pozDotyku.Y - 690)) <= 160)
                        {
                            gracz.MoveR();
                        }
                        if (((pozDotyku.X - 110) * (pozDotyku.X - 110)) + ((pozDotyku.Y - 645) * (pozDotyku.Y - 645)) <= 160)
                        {
                            gracz.MoveU();
                        }
                        if (((pozDotyku.X - 110) * (pozDotyku.X - 110)) + ((pozDotyku.Y - 740) * (pozDotyku.Y - 740)) <= 160)
                        {
                            gracz.MoveD();
                        }
                    }
                    else if (dotyk.State == TouchLocationState.Pressed)
                    {
                        if (((pozDotyku.X - 375) * (pozDotyku.X - 375)) + ((pozDotyku.Y - 695) * (pozDotyku.Y - 695)) <= 160)
                        {
                            gracz.Wystrzel();
                            if (!stanGry)
                            {
                                stanGry = true;
                            }
                        }
                    }
                }

                //Sterowanie klawiaturą
                if (Keyboard.GetState().IsKeyDown(Keys.S) || Keyboard.GetState().IsKeyDown(Keys.Down))
                {
                    gracz.MoveD();
                }
                if (Keyboard.GetState().IsKeyDown(Keys.W) || Keyboard.GetState().IsKeyDown(Keys.Up))
                {
                    gracz.MoveU();
                }
                if (Keyboard.GetState().IsKeyDown(Keys.A) || Keyboard.GetState().IsKeyDown(Keys.Left))
                {
                    gracz.MoveL();
                }
                if (Keyboard.GetState().IsKeyDown(Keys.D) || Keyboard.GetState().IsKeyDown(Keys.Right))
                {
                    gracz.MoveR();
                }
                if (Keyboard.GetState().IsKeyDown(Keys.Space))
                {
                    gracz.Wystrzel();
                }

                wrog.Update();
                wrog2.Update();
                DetekcjaKolizji();
                gracz.LotPocisku();
            }
            else
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                {
                    stanGry = true;
                    punkty  = 0;
                }
            }

            base.Update(gameTime);
        }
Esempio n. 56
0
 private void UpdateTilesTemporaney(GameTime gameTime, KeyboardState keyboardState, GamePadState gamePadState, TouchCollection touchState, AccelerometerState accelState, DisplayOrientation orientation)
 {
     try
     {
         //workaroud to thread unsafe...?
         lock (tilesTemporaney)
         {
             foreach (Tile item in tilesTemporaney)
             {
                 // Insert your code here.
                 item.Update(gameTime, keyboardState, gamePadState, touchState, accelState, orientation);
             }
         }
     }
     catch (Exception ex)
     {
         ex = new Exception();
     }
 }
Esempio n. 57
0
        protected void updatePacManBounce(GameTime gameTime)
        {
            //Elapsed time since last update
            float time = (float)gameTime.ElapsedGameTime.TotalMilliseconds;

            //Touchy Stuff
            Rectangle rect = new Rectangle((int)PacManLoc.X,
                                           (int)PacManLoc.Y, PacMan.Width, PacMan.Height); //get pacman rectangle
            Vector2 touchLoc;



            //Use Gravity to move the pacaman
            PacManDir = PacManDir + GravityDir;
            if (PacManSpeed < PacManSpeedMax)
            {
                PacManSpeed = PacManSpeed + GravityAccel;
            }
            else
            {
                PacManSpeed = PacManSpeedMax;
            }


            //Time corrected move. Moves PacMan By PacManDiv every Second
            PacManLoc = PacManLoc + ((PacManDir * (time / 1000)) * PacManSpeed);  //Simple Move PacMan by PacManDir


            //Keep PacMan On Screen
            //X right
            if (PacManLoc.X >
                graphics.GraphicsDevice.Viewport.Width - PacMan.Width)
            {
                //Negate X
                PacManDir   = PacManDir * new Vector2(-1, 1);
                PacManLoc.X = graphics.GraphicsDevice.Viewport.Width - PacMan.Width;
            }

            //X left
            if (PacManLoc.X < 0)
            {
                //Negate X
                PacManDir   = PacManDir * new Vector2(-1, 1);
                PacManLoc.X = 0;
            }

            //Y top
            if (PacManLoc.Y >
                graphics.GraphicsDevice.Viewport.Height - PacMan.Height)
            {
                //Negate Y
                PacManDir   = PacManDir * new Vector2(1, -1);
                PacManLoc.Y = graphics.GraphicsDevice.Viewport.Height - PacMan.Height;
            }

            //Y bottom
            if (PacManLoc.Y < 0)
            {
                //Negate Y
                PacManDir   = PacManDir * new Vector2(1, -1);
                PacManLoc.Y = 0;
            }

            //Touch pacman
            TouchCollection touchCollection = TouchPanel.GetState();

            foreach (TouchLocation tl in touchCollection)
            {
                if ((tl.State == TouchLocationState.Pressed) ||
                    (tl.State == TouchLocationState.Moved))
                {
                    touchLoc = new Vector2(tl.Position.X, tl.Position.Y);
                    if (rect.Contains((int)touchLoc.X, (int)touchLoc.Y))
                    {
                        //I should figure out acceleration
                        PacManSpeed = 10;

                        //and touch direction
                        TouchLocation tlo = tl;
                        tl.TryGetPreviousLocation(out tlo);
                        Vector2 dir = new Vector2(tl.Position.X, tl.Position.Y) - new Vector2(tlo.Position.X, tlo.Position.Y);
                        PacManDir = dir;

                        //Move the pacman to the touch
                        PacManLoc = new Vector2(tl.Position.X - PacMan.Width / 2, tl.Position.Y - PacMan.Height / 2);
                    }
                }
            }
        }
        /// <summary>
        /// Updates the virtual thumbsticks based on current touch state. This must be called every frame.
        /// </summary>
        public static void Update(InputState input)
        {
            TouchLocation?  leftTouch = null, rightTouch = null;
            TouchCollection touches = input.TouchState;

            // Examine all the touches to convert them to virtual dpad positions. Note that the 'touches'
            // collection is the set of all touches at this instant, not a sequence of events. The only
            // sequential information we have access to is the previous location for of each touch.
            foreach (TouchLocation touch in touches)
            {
                if (touch.Id == leftId)
                {
                    // This is a motion of a left-stick touch that we're already tracking
                    leftTouch = touch;
                    continue;
                }

                if (touch.Id == rightId)
                {
                    // This is a motion of a right-stick touch that we're already tracking
                    rightTouch = touch;
                    continue;
                }

                // We didn't continue an existing thumbstick gesture; see if we can start a new one.
                //
                // We'll use the previous touch position if possible, to get as close as possible to where
                // the gesture actually began.
                TouchLocation earliestTouch;
                if (!touch.TryGetPreviousLocation(out earliestTouch))
                {
                    earliestTouch = touch;
                }

                if (leftId == -1)
                {
                    // if we are not currently tracking a left thumbstick and this touch is on the left
                    // half of the screen, start tracking this touch as our left stick
                    if (earliestTouch.Position.X < TouchPanel.DisplayWidth / 2)
                    {
                        leftTouch = earliestTouch;
                        continue;
                    }
                }

                if (rightId == -1)
                {
                    // if we are not currently tracking a right thumbstick and this touch is on the right
                    // half of the screen, start tracking this touch as our right stick
                    if (earliestTouch.Position.X >= TouchPanel.DisplayWidth / 2)
                    {
                        rightTouch = earliestTouch;
                        continue;
                    }
                }
            }

            // if we have a left touch
            if (leftTouch.HasValue)
            {
                // if we have no center, this position is our center
                if (!LeftThumbstickCenter.HasValue)
                {
                    LeftThumbstickCenter = leftTouch.Value.Position;
                }

                // save the position of the touch
                leftPosition = leftTouch.Value.Position;

                // save the ID of the touch
                leftId = leftTouch.Value.Id;
            }
            else
            {
                // otherwise reset our values to not track any touches
                // for the left thumbstick
                LeftThumbstickCenter = null;
                leftId = -1;
            }

            // if we have a right touch
            if (rightTouch.HasValue)
            {
                // if we have no center, this position is our center
                if (!RightThumbstickCenter.HasValue)
                {
                    RightThumbstickCenter = rightTouch.Value.Position;
                }

                // save the position of the touch
                rightPosition = rightTouch.Value.Position;

                // save the ID of the touch
                rightId = rightTouch.Value.Id;
            }
            else
            {
                // otherwise reset our values to not track any touches
                // for the right thumbstick
                RightThumbstickCenter = null;
                rightId = -1;
            }
        }
Esempio n. 59
0
        public void Update(Camera cam)
        {
            camera = cam;

            // Clear all lists
            touchPoints.Clear();
            PressPoints.Clear();
            ClickPoints.Clear();

            // Update touch state
            TouchCollection touchCollection = TouchPanel.GetState();

            // Add touches to list
            foreach (TouchLocation touch in touchCollection)
            {
                touchPoints.Add(touch);
            }


            if (touchPoints.Count == 0)
            {
                // See if any release states were missed
                foreach (TouchLocation touch in prevTouchPoints)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {
                        ClickPoints.Add(touch.Position);
                    }
                    else if (touch.State == TouchLocationState.Moved)
                    {
                        TouchLocation prevTouch;
                        if (touch.TryGetPreviousLocation(out prevTouch))
                        {
                            var delta = touch.Position - prevTouch.Position;

                            // Allow some errors
                            if (delta.LengthSquared() < 2)
                            {
                                ClickPoints.Add(touch.Position);
                            }
                        }
                    }
                }
                swipeDirection = Vector2.Zero;
            }
            else if (touchPoints.Count == 1)
            {
                TouchLocation touch = touchPoints[0];

                if ((touch.State == TouchLocationState.Moved) || (touch.State == TouchLocationState.Pressed))
                {
                    TouchLocation prevTouch;

                    // Sometimes TryGetPreviousLocation can fail
                    if (touch.TryGetPreviousLocation(out prevTouch))
                    {
                        // Get swiping direction
                        swipeDirection = touch.Position - prevTouch.Position;
                    }
                    else
                    {
                        PressPoints.Add(touch.Position);
                    }
                }
                else if (touch.State == TouchLocationState.Released)
                {
                    TouchLocation prevTouch;
                    if (touch.TryGetPreviousLocation(out prevTouch))
                    {
                        var delta = touch.Position - prevTouch.Position;

                        // Allow some errors
                        if (delta.LengthSquared() < 2)
                        {
                            ClickPoints.Add(touch.Position);
                        }
                    }
                    else
                    {
                        ClickPoints.Add(touch.Position);
                    }
                }
            }
            else if (touchCollection.Count == 2)
            {
                // TODO
            }
            else
            {
                // TODO
            }

            // Update previous state
            prevTouchPoints.Clear();
            prevTouchPoints.AddRange(touchPoints);
        }
Esempio n. 60
0
        private void HandleTouchInput()
        {
            // we use raw touch points for selection, since they are more appropriate
            // for that use than gestures. so we need to get that raw touch data.
            TouchCollection touches = TouchPanel.GetState();

            // see if we have a new primary point down. when the first touch
            // goes down, we do hit detection to try and select one of our sprites.
            if (touches.Count > 0 && touches[0].State == TouchLocationState.Pressed)
            {
                // convert the touch position into a Point for hit testing
                Point touchPoint = new Point((int)touches[0].Position.X, (int)touches[0].Position.Y);

                // iterate our sprites to find which sprite is being touched. we iterate backwards
                // since that will cause sprites that are drawn on top to be selected before
                // sprites drawn on the bottom.
                selectedSprite = null;
                for (int i = sprites.Count - 1; i >= 0; i--)
                {
                    Sprite sprite = sprites[i];
                    if (sprite.HitBounds.Contains(touchPoint))
                    {
                        selectedSprite = sprite;
                        break;
                    }
                }

                if (selectedSprite != null)
                {
                    // make sure we stop selected sprites
                    selectedSprite.Velocity = Vector2.Zero;

                    // we also move the sprite to the end of the list so it
                    // draws on top of the other sprites
                    sprites.Remove(selectedSprite);
                    sprites.Add(selectedSprite);
                }
            }

            // next we handle all of the gestures. since we may have multiple gestures available,
            // we use a loop to read in all of the gestures. this is important to make sure the
            // TouchPanel's queue doesn't get backed up with old data
            while (TouchPanel.IsGestureAvailable)
            {
                // read the next gesture from the queue
                GestureSample gesture = TouchPanel.ReadGesture();

                // we can use the type of gesture to determine our behavior
                switch (gesture.GestureType)
                {
                // on taps, we change the color of the selected sprite
                case GestureType.Tap:
                case GestureType.DoubleTap:
                    if (selectedSprite != null)
                    {
                        selectedSprite.ChangeColor();
                    }
                    break;

                // on holds, if no sprite is selected, we add a new sprite at the
                // hold position and make it our selected sprite. otherwise we
                // remove our selected sprite.
                case GestureType.Hold:
                    if (selectedSprite == null)
                    {
                        // create the new sprite
                        selectedSprite        = new Sprite(gear);
                        selectedSprite.Center = gesture.Position;

                        // add it to our list
                        sprites.Add(selectedSprite);
                    }
                    else
                    {
                        sprites.Remove(selectedSprite);
                        selectedSprite = null;
                    }
                    break;

                // on drags, we just want to move the selected sprite with the drag
                case GestureType.FreeDrag:
                    if (selectedSprite != null)
                    {
                        selectedSprite.Center += gesture.Delta;
                    }
                    break;

                // on flicks, we want to update the selected sprite's velocity with
                // the flick velocity, which is in pixels per second.
                case GestureType.Flick:
                    if (selectedSprite != null)
                    {
                        selectedSprite.Velocity = gesture.Delta;
                    }
                    break;

                // on pinches, we want to scale the selected sprite
                case GestureType.Pinch:
                    if (selectedSprite != null)
                    {
                        // get the current and previous locations of the two fingers
                        Vector2 a    = gesture.Position;
                        Vector2 aOld = gesture.Position - gesture.Delta;
                        Vector2 b    = gesture.Position2;
                        Vector2 bOld = gesture.Position2 - gesture.Delta2;

                        // figure out the distance between the current and previous locations
                        float d    = Vector2.Distance(a, b);
                        float dOld = Vector2.Distance(aOld, bOld);

                        // calculate the difference between the two and use that to alter the scale
                        float scaleChange = (d - dOld) * .01f;
                        selectedSprite.Scale += scaleChange;
                    }
                    break;
                }
            }

            // lastly, if there are no raw touch points, we make sure no sprites are selected.
            // this happens after we handle gestures because some gestures like taps and flicks
            // will come in on the same frame as our raw touch points report no touches and we
            // still want to use the selected sprite for those gestures.
            if (touches.Count == 0)
            {
                selectedSprite = null;
            }
        }