Exemplo n.º 1
0
 private void ProcessTouch()
 {
     ProcessTouch(TouchPanel.GetState());
 }
Exemplo n.º 2
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }

            proceedText();

            base.Update(gameTime);

            bool nextLetter = true;

            foreach (TouchLocation location in TouchPanel.GetState())
            {
                // Letter control
                for (int i = 0; i < Braile.cBraileDotsNum; i++)
                {
                    if (braileData.braileLetter1[i].rect.Contains((int)location.Position.X, (int)location.Position.Y))
                    {
                        if (braileData.braileLetter1[i].state)
                        {
                            // start vibe
                            Debug.WriteLine("Yes vibe! {0}", i);
                            vibrate.Start(TimeSpan.FromMilliseconds(200));
                        }
                        else
                        {
                            // stop vibe
                            Debug.WriteLine("No vibe! {0}", i);
                            vibrate.Stop();
                        }

                        braileData.braileLetter1[i].touched = true;
                        nextLetter = false;
                    }
                }

                // Controls
                if (controls.letterControl.Contains((int)location.Position.X, (int)location.Position.Y))
                {
                    //Debug.WriteLine("Start controling letter");

                    while (TouchPanel.IsGestureAvailable)
                    {
                        GestureSample gs = TouchPanel.ReadGesture();
                        switch (gs.GestureType)
                        {
                        case GestureType.HorizontalDrag:
                            controls.letterControlDeltaX += gs.Delta.X;
                            Debug.WriteLine("VerticalDrag {0}", gs.Delta.X);
                            break;

                        case GestureType.DragComplete:
                            if (controls.letterControlDeltaX > 10.0)
                            {
                                if (wordPos + 1 < braileText.Length)
                                {
                                    wordPos++;
                                    letterPos = 0;
                                }
                                else
                                {
                                    Debug.WriteLine("End of text");
                                }

                                Debug.WriteLine("Next word!");
                            }
                            else if (controls.letterControlDeltaX < -10.0)
                            {
                                if (letterPos == 0 && wordPos != 0)
                                {
                                    wordPos--;
                                    Debug.WriteLine("Previous word");
                                }

                                letterPos = 0;
                                Debug.WriteLine("Begining of the word");
                            }

                            Debug.WriteLine("{0}", controls.letterControlDeltaX);

                            controls.letterControlDeltaX = 0;
                            break;
                        }
                    }
                }
            }

            if (braileData.braileLetter1.All(x => x.touched) && nextLetter)
            {
                Debug.WriteLine("Next letter!");
                if (letterPos + 1 < braileText[wordPos].Length)
                {
                    letterPos++;
                }
                else
                {
                    letterPos = 0;

                    if (wordPos + 1 < braileText.Length)
                    {
                        vibrate.Start(TimeSpan.FromMilliseconds(100));
                        System.Threading.Thread.Sleep(200);
                        vibrate.Start(TimeSpan.FromMilliseconds(100));

                        wordPos++;
                    }
                    else
                    {
                        Debug.WriteLine("End of text!");
                    }
                }

                for (int i = 0; i < braileData.braileLetter1.Length; i++)
                {
                    braileData.braileLetter1[i].touched = false;
                }
            }
        }
Exemplo n.º 3
0
    public static void onTouchEvents()
    {
        // PATCH
        var state = new List <TouchLocation>();

        if (TouchPanel.GetCapabilities().IsConnected)
        {
            state.AddRange(TouchPanel.GetState());
        }
        else
        {
            var mouseState = Mouse.GetState();
            if (wasPressed)
            {
                state.Add(new TouchLocation(0, mouseState.LeftButton == ButtonState.Released ?
                                            (wasPressed ? TouchLocationState.Released : TouchLocationState.Moved) : TouchLocationState.Pressed,
                                            new Vector2(mouseState.X, mouseState.Y), TouchLocationState.Invalid, new Vector2()));
            }
            wasPressed = mouseState.LeftButton == ButtonState.Pressed;
        }

        for (int i = 0; i < 4; i++)
        {
            touchMarked[i] = false;
        }
        for (int j = 0; j < 4; j++)
        {
            int id = 0;
            TouchLocationState touchLocationState;
            if (j >= state.Count)
            {
                touchLocationState = TouchLocationState.Invalid;
                posVector.X        = -1f;
                posVector.Y        = -1f;
                int num = 0;
                while (num < 4 && touchMarked[num])
                {
                    num++;
                }
                int num2 = num;
                touchMarked[num2] = true;
            }
            else
            {
                TouchLocation touchLocation = state[j];
                float         x             = touchLocation.Position.X;
                float         y             = touchLocation.Position.Y;
                screen2real(ref x, ref y);
                posVector.X        = x;
                posVector.Y        = y;
                touchLocationState = touchLocation.State;
                id = touchLocation.Id;
                int num2 = amFindTouchIndex(id);
                touchMarked[num2] = true;
            }

            switch (touchLocationState)
            {
            case TouchLocationState.Invalid:
                amIPhoneTouchCanceled(j);
                break;

            case TouchLocationState.Released:
                amIPhoneTouchEnded(j);
                break;

            case TouchLocationState.Pressed:
                amIPhoneTouchBegan(ref posVector, j, id);
                break;

            case TouchLocationState.Moved:
                amIPhoneTouchMoved(ref posVector, j, id);
                break;
            }
        }
    }
Exemplo n.º 4
0
        void UpdateTouch()
        {
            TouchCollection touches = TouchPanel.GetState();

            if (touches.Count > 0)
            {
                TouchLocation tl = touches[0];

                Console.WriteLine("Touch (0 / {0}): {1}", touches.Count, tl.Position);
                m_DragArgs.CurrentX = (int)tl.Position.X;
                m_DragArgs.CurrentY = (int)tl.Position.Y;
                switch (tl.State)
                {
                case TouchLocationState.Pressed:
                    m_MousePressedX = m_DragArgs.CurrentX;
                    m_MousePressedY = m_DragArgs.CurrentY;
                    m_bDragging     = false;
                    break;

                case TouchLocationState.Moved:
                    break;

                case TouchLocationState.Released:
                    break;
                }
                if (tl.State == TouchLocationState.Released)
                {
                    if (m_bDragging)
                    {
                        Invoke_OnDragEnd(this, m_DragArgs);
                        m_bDragging = false;
                    }
                    else
                    {
                        Invoke_OnClick(this, m_DragArgs);
                    }
                }
                else if (tl.State == TouchLocationState.Moved)
                {
                    int deltaX = m_DragArgs.CurrentX - m_MousePressedX;
                    int deltaY = m_DragArgs.CurrentY - m_MousePressedY;
                    if (Math.Abs(deltaX) > m_DragThreshold || Math.Abs(deltaY) > m_DragThreshold)
                    {
                        if (!m_bDragging)
                        {
                            // Start dragging
                            m_DragArgs.StartX = m_MousePressedX;
                            m_DragArgs.StartY = m_MousePressedY;

                            Invoke_OnDragBegin(this, m_DragArgs);
                            m_bDragging = true;
                        }
                        else
                        {
                            // Still dragging
                            Invoke_OnDrag(this, m_DragArgs);
                        }
                    }
                }
            }
        }
Exemplo n.º 5
0
        public void Update(GameTime gameTime)
        {
            Vector2 delta;
            var     currentTouchState = TouchPanel.GetState();

            _taps.RemoveAll(p => p.Value <= TimeSpan.Zero);
            _touches.RemoveAll(p => p.Value <= TimeSpan.Zero);
            _gestures.RemoveAll(p => p.Value <= TimeSpan.Zero);

            for (var index = 0; index < _taps.Count; index++)
            {
                _taps[index] = new KeyValuePair <Vector2, TimeSpan>(_taps[index].Key,
                                                                    _taps[index].Value - gameTime.ElapsedGameTime);
            }
            for (var index = 0; index < _touches.Count; index++)
            {
                _touches[index] = new KeyValuePair <Vector2, TimeSpan>(_touches[index].Key,
                                                                       _touches[index].Value - gameTime.ElapsedGameTime);
            }
            for (var index = 0; index < _gestures.Count; index++)
            {
                _gestures[index] = new KeyValuePair <GestureSample, TimeSpan>(_gestures[index].Key,
                                                                              _gestures[index].Value - gameTime.ElapsedGameTime);
            }

            while (TouchPanel.IsGestureAvailable && GesturesEnabled)
            {
                var remove  = new List <Procedure <GestureSample> >();
                var gesture = TouchPanel.ReadGesture();
                if (_gestures.All(p => p.Key.GestureType != gesture.GestureType))
                {
                    _gestures.Add(new KeyValuePair <GestureSample, TimeSpan>(gesture, new TimeSpan(_gestureSensitivity.Ticks)));
                }

                foreach (var guestureListeners in GestureListeners)
                {
                    try
                    {
                        guestureListeners(gesture);
                    }
                    catch
                    {
                        remove.Add(guestureListeners);
                    }
                }
                GestureListeners.RemoveAll(remove.Contains);
            }

            var first   = true;
            var dremove = new List <Operation <Vector2> >();

            //If no touches the notify existing drag listeners
            if (currentTouchState.Count == 0)
            {
                IsTouched = false;
                if (DragFrom != Vector2.Zero && DragFrom != Location)
                {
                    foreach (var listener in DraggedListeners)
                    {
                        try
                        {
                            delta = DragFrom - Location;
                            //Only Notify if changed
                            if (Math.Abs(delta.X) > 20 || Math.Abs(delta.Y) > 20)
                            {
                                listener(DragFrom, Location);
                            }
                        }
                        catch
                        {
                            dremove.Add(listener);
                        }
                    }
                    DraggedListeners.RemoveAll(dremove.Contains);
                    dremove.Clear();
                }
                Location = Vector2.Zero;
                DragFrom = Vector2.Zero;
            }
            else
            {
                IsTouched = true;
            }


            foreach (var touch in currentTouchState)
            {
                TouchLocation prevLoc;
                if (first)
                {
                    delta = touch.Position - Location;
                    if ((touch.State == TouchLocationState.Pressed || touch.State == TouchLocationState.Moved) && DragFrom == Vector2.Zero)
                    {
                        if (Math.Abs(delta.X) > 4 || Math.Abs(delta.Y) > 4 && Location != Vector2.Zero)
                        {
                            DragFrom = touch.Position;
                        }
                    }
                    delta    = touch.Position - Location;
                    Location = touch.Position;

                    if (Math.Abs(delta.X) > 4 || Math.Abs(delta.Y) > 4)
                    {
                        foreach (var listener in DraggingListeners)
                        {
                            try
                            {
                                listener(DragFrom, Location);
                            }
                            catch
                            {
                                dremove.Add(listener);
                            }
                        }
                        DraggingListeners.RemoveAll(dremove.Contains);
                        dremove.Clear();
                    }
                    first = false;
                }

                //Add Touches that dont currently Exist
                if (_touches.All(p => p.Key != new Vector2(touch.Position.X, touch.Position.Y)))
                {
                    _touches.Add(new KeyValuePair <Vector2, TimeSpan>(new Vector2(touch.Position.X, touch.Position.Y), new TimeSpan(_touchSensitivity.Ticks)));
                }


                var remove = new List <Procedure <Vector2> >();

                if (touch.State != TouchLocationState.Released)
                {
                    continue;
                }
                if (_taps.All(p => p.Key != new Vector2(touch.Position.X, touch.Position.Y)))
                {
                    _taps.Add(new KeyValuePair <Vector2, TimeSpan>(new Vector2(touch.Position.X, touch.Position.Y), new TimeSpan(_tapSensitivity.Ticks)));
                }


                //Notify Tap Listeners on Release
                if (touch.State != TouchLocationState.Pressed)
                {
                    foreach (var tapListener in TapListeners)
                    {
                        try
                        {
                            // if (DragFrom == Vector2.Zero)
                            tapListener(new Vector2(touch.Position.X, touch.Position.Y));
                        }
                        catch
                        {
                            remove.Add(tapListener);
                        }
                    }
                    TapListeners.RemoveAll(remove.Contains);
                }
                remove.Clear();

                if (!touch.TryGetPreviousLocation(out prevLoc))
                {
                    continue;
                }

                if (prevLoc.State == TouchLocationState.Moved)
                {
                    delta = touch.Position - prevLoc.Position;
                    if (Math.Abs(delta.X) >= 6 || Math.Abs(delta.Y) >= 6)
                    {
                        foreach (var moveListener in MoveListeners)
                        {
                            try
                            {
                                moveListener(new Vector2(touch.Position.X, touch.Position.Y));
                            }
                            catch
                            {
                                remove.Add(moveListener);
                            }
                        }
                        MoveListeners.RemoveAll(remove.Contains);
                    }
                }
                remove.Clear();
            }
        }
Exemplo n.º 6
0
        // Token: 0x06000070 RID: 112 RVA: 0x0000C6F0 File Offset: 0x0000A8F0
        protected override void Update(GameTime gameTime)
        {
            int num = 0;

            InputSystem.CheckKeyboardInput();
            TouchCollection state = TouchPanel.GetState();

            InputSystem.ClearTouchData();
            foreach (TouchLocation touchLocation in state)
            {
                switch (touchLocation.State)
                {
                case TouchLocationState.Pressed:
                    InputSystem.AddTouch(touchLocation.Position.X, touchLocation.Position.Y, num);
                    break;

                case TouchLocationState.Moved:
                    InputSystem.AddTouch(touchLocation.Position.X, touchLocation.Position.Y, num);
                    break;
                }
                num++;
            }
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                if (FileIO.activeStageList == 0)
                {
                    switch (StageSystem.stageListPosition)
                    {
                    case 4:
                    case 5:
                        InputSystem.touchData.start = 1;
                        break;

                    default:
                        InputSystem.touchData.buttonB = 1;
                        break;
                    }
                }
                else if (StageSystem.stageMode == 2)
                {
                    if (ObjectSystem.objectEntityList[9].state == 3 && GlobalAppDefinitions.gameMode == 1)
                    {
                        ObjectSystem.objectEntityList[9].state    = 4;
                        ObjectSystem.objectEntityList[9].value[0] = 0;
                        ObjectSystem.objectEntityList[9].value[1] = 0;
                        ObjectSystem.objectEntityList[9].alpha    = 248;
                        AudioPlayback.PlaySfx(27, 0);
                    }
                }
                else
                {
                    GlobalAppDefinitions.gameMessage = 2;
                }
            }
            if (StageSystem.stageMode != 2)
            {
                EngineCallbacks.ProcessMainLoop();
            }
            try
            {
                base.Update(gameTime);
            }
            catch (GameUpdateRequiredException e)
            {
                this.HandleGameUpdateRequired(e);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Menu.PrzyciskExit.Pojedyncze_wcisniecie)
            {
                this.Exit();
            }

            if (gameTime.IsRunningSlowly)
            {
            }
            TouchCollection TC = TouchPanel.GetState();

            Vector2[] klikniecia = new Vector2[4];
            int       i          = 0;

            foreach (TouchLocation TL in TC)
            {
                if (TL.State == TouchLocationState.Moved)
                {
                    klikniecia[i++] = TL.Position;
                }
            }


            ParticleSystem.Pracuj();
            if (GlobalAcc.StanGry == GameState.Game)
            {
                Mapy.Pracuj(klikniecia, i);
            }
            if (GlobalAcc.StanGry == GameState.Menu)
            {
                Menu.Pracuj(klikniecia, i);
            }
            if (GlobalAcc.StanGry == GameState.Info)
            {
                Info.Pracuj(klikniecia, i);
            }
            if (GlobalAcc.StanGry == GameState.Help)
            {
                Help.Pracuj(klikniecia, i);
            }

            if (GlobalAcc.StanGry == GameState.ChangingToInfoFromMenuP1 || GlobalAcc.StanGry == GameState.ChangingToGameFromMenuP1 || GlobalAcc.StanGry == GameState.ChangingToHelpFromMenuP1)
            {
                Menu.PracujPrzejscieDo();
            }
            if (GlobalAcc.StanGry == GameState.ChangingToMenuFromInfoP2 || GlobalAcc.StanGry == GameState.ChangingToMenuFromGameP2 ||
                GlobalAcc.StanGry == GameState.ChangingToMenuFromHelpP2)
            {
                Menu.PracujPrzejscieZ();
            }

            if (GlobalAcc.StanGry == GameState.ChangingToInfoFromMenuP2)
            {
                Info.PracujPrzejscieZ();
            }
            if (GlobalAcc.StanGry == GameState.ChangingToHelpFromMenuP2)
            {
                Help.PracujPrzejscieZ();
            }

            if (GlobalAcc.StanGry == GameState.ChangingToMenuFromInfoP1)
            {
                Info.PracujPrzejscieDo();
            }
            if (GlobalAcc.StanGry == GameState.ChangingToMenuFromHelpP1)
            {
                Help.PracujPrzejscieDo();
            }
            if (GlobalAcc.StanGry == GameState.ChangingToGameFromMenuP2)
            {
                Mapy.PrzejscieZ();
            }


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

            deltaFPSTime += elapsed;
            if (deltaFPSTime > 1)
            {
                float fps = 1 / elapsed;
                iloscfps      = "<" + fps.ToString() + ">";
                deltaFPSTime -= 1;
            }


            base.Update(gameTime);
        }
Exemplo n.º 8
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)
        {
            // TODO: Add your update logic here
            TouchCollection touchState = TouchPanel.GetState();

            switch (gameState)
            {
            case GameStates.StartScreen:
                // Touch Control Logic
                foreach (TouchLocation location in touchState)
                {
                    if (location.State == TouchLocationState.Pressed)
                    {
                        if (startgameButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            GetBlock();
                            GetNextBlock();
                            gameState = GameStates.Playing;
                            break;
                        }
                        else if (quitButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            this.Exit();
                        }
                    }
                }
                // End Touch Control Logic
                break;

            case GameStates.Playing:
                // refactor with Min()
                if ((Constants.STARTINGFPS - (hud.Level * Constants.FPSREDUCTIONPERLEVEL)) < Constants.MINFPS)
                {
                    millisecondsPerFrame = Constants.MINFPS;
                }
                else
                {
                    millisecondsPerFrame = Constants.STARTINGFPS - (hud.Level * Constants.FPSREDUCTIONPERLEVEL);
                }
                // Touch Control Logic
                foreach (TouchLocation location in touchState)
                {
                    if (location.State == TouchLocationState.Pressed)
                    {
                        if (new Rectangle(hud.PausedBoxPoint.X, hud.PausedBoxPoint.Y, hud.PausedBoxTexture.Width, hud.PausedBoxTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            gameState = GameStates.Paused;
                            break;
                        }
                        else if (new Rectangle(hud.UpControlPoint.X, hud.UpControlPoint.Y, hud.UpControlTexture.Width, hud.UpControlTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            currentBlock.Rotate(gridMap);
                            break;
                        }
                        else if (new Rectangle(hud.LeftControlPoint.X, hud.LeftControlPoint.Y, hud.LeftControlTexture.Width, hud.LeftControlTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            if (!CheckForCollision(Direction.Left))
                            {
                                currentBlock.Move(Direction.Left);
                            }
                            break;
                        }
                        else if (new Rectangle(hud.RightControlPoint.X, hud.RightControlPoint.Y, hud.RightControlTexture.Width, hud.RightControlTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            if (!CheckForCollision(Direction.Right))
                            {
                                currentBlock.Move(Direction.Right);
                            }
                            break;
                        }
                        else if (new Rectangle(hud.DownControlPoint.X, hud.DownControlPoint.Y, hud.DownControlTexture.Width, hud.DownControlTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            if (!CheckForCollision(Direction.Down))
                            {
                                currentBlock.Move(Direction.Down);
                            }
                            else
                            {
                                AddSpritesToMap();
                                if (CheckForClearedLines())
                                {
                                    gameState = GameStates.Flashing;
                                    break;
                                }
                                else
                                {
                                    currentBlock          = nextBlock;
                                    currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
                                    GetNextBlock();
                                }
                            }
                            break;
                        }
                    }
                }
                // End Touch Control Logic

                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > millisecondsPerFrame)
                {
                    timeSinceLastFrame -= millisecondsPerFrame;
                    if (!CheckForCollision(Direction.Down))
                    {
                        currentBlock.Move(Direction.Down);
                    }
                    else
                    {
                        AddSpritesToMap();
                        if (CheckForClearedLines())
                        {
                            gameState = GameStates.Flashing;
                            break;
                        }
                        else
                        {
                            currentBlock          = nextBlock;
                            currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
                            GetNextBlock();
                        }
                    }
                }
                break;

            case GameStates.Flashing:
                // Touch Control Logic
                foreach (TouchLocation location in touchState)
                {
                    if (location.State == TouchLocationState.Pressed)
                    {
                        if (new Rectangle(hud.PausedBoxPoint.X, hud.PausedBoxPoint.Y, hud.PausedBoxTexture.Width, hud.PausedBoxTexture.Height).Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            gameState = GameStates.Paused;
                            break;
                        }
                    }
                }
                // End Touch Control Logic
                timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
                if (timeSinceLastFrame > Constants.FLASHFPS)
                {
                    timeSinceLastFrame -= Constants.FLASHFPS;
                    flashINFO.flashcount++;
                    if (flashINFO.flashing)
                    {
                        flashINFO.flashing = false;
                    }
                    else
                    {
                        flashINFO.flashing = true;
                    }
                    if (flashINFO.flashcount > Constants.FLASHCOUNT)
                    {
                        gameState = GameStates.Playing;
                        RemoveClearedLines();
                        currentBlock          = nextBlock;
                        currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
                        GetNextBlock();
                    }
                }
                break;

            case GameStates.Paused:
                // Touch Control Logic
                foreach (TouchLocation location in touchState)
                {
                    if (location.State == TouchLocationState.Pressed)
                    {
                        if (resumeButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            gameState = GameStates.Playing;
                            break;
                        }
                        else if (quitButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            this.Exit();
                        }
                    }
                }
                // End Touch Control Logic
                break;

            case GameStates.GameOver:
                // Touch Control Logic
                foreach (TouchLocation location in touchState)
                {
                    if (location.State == TouchLocationState.Pressed)
                    {
                        if (startnewgameButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            gridMap.Clear();
                            gameState = GameStates.Playing;
                            hud.Restart();
                            GetBlock();
                            GetNextBlock();
                            break;
                        }
                        else if (quitButtonBounds.Contains(new Point((int)location.Position.X, (int)location.Position.Y)))
                        {
                            this.Exit();
                        }
                    }
                }
                // End Touch Control Logic
                break;

            default:
                break;
            }

            // TODO: Fix input below

            /*
             * switch (gameState)
             * {
             *  case GameStates.StartScreen:
             *      if (input.WasKeyPressed(Keys.Enter))
             *      {
             *          GetBlock();
             *          GetNextBlock();
             *          gameState = GameStates.Playing;
             *      }
             *      break;
             *  case GameStates.Playing:
             *      // refactor with Min()
             *      if ((Constants.STARTINGFPS - (hud.Level * Constants.FPSREDUCTIONPERLEVEL)) < Constants.MINFPS)
             *      {
             *          millisecondsPerFrame = Constants.MINFPS;
             *      }
             *      else
             *      {
             *          millisecondsPerFrame = Constants.STARTINGFPS - (hud.Level * Constants.FPSREDUCTIONPERLEVEL);
             *      }
             *      // TODO: Fix Input
             *      if (input.WasKeyPressed(Keys.Escape))
             *      {
             *          gameState = GameStates.Paused;
             *      }
             *      // add in holding down/left/right later
             *      if (input.WasKeyPressed(Keys.Up))
             *      {
             *          currentBlock.Rotate(gridMap);
             *      }
             *      if (input.WasKeyPressed(Keys.Left))
             *      {
             *          //check blocks & walls
             *          //      if no collision, move left
             *          if (!CheckForCollision(Direction.Left))
             *          {
             *              currentBlock.Move(Direction.Left);
             *          }
             *      }
             *      if (input.WasKeyPressed(Keys.Right))
             *      {
             *          //check blocks & walls
             *          //      if no collision, move right
             *          if (!CheckForCollision(Direction.Right))
             *          {
             *              currentBlock.Move(Direction.Right);
             *          }
             *      }
             *      if (input.WasKeyPressed(Keys.Down))
             *      {
             *          //check blocks & walls
             *          //      if collision
             *          //          check for cleared lines, and add sprites to Map and drop new block
             *          //      if no collision, move down
             *          if (!CheckForCollision(Direction.Down))
             *          {
             *              currentBlock.Move(Direction.Down);
             *          }
             *          else
             *          {
             *              AddSpritesToMap();
             *              if (CheckForClearedLines())
             *              {
             *                  gameState = GameStates.Flashing;
             *                  break;
             *              }
             *              else
             *              {
             *                  currentBlock = nextBlock;
             *                  currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
             *                  GetNextBlock();
             *              }
             *          }
             *      }
             *
             *      timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
             *      if (timeSinceLastFrame > millisecondsPerFrame)
             *      {
             *          timeSinceLastFrame -= millisecondsPerFrame;
             *          //check blocks & walls
             *          //      if collision
             *          //          check for cleared lines, and add sprites to Map and drop new block
             *          //      if no collision, move down
             *          if (!CheckForCollision(Direction.Down))
             *          {
             *              currentBlock.Move(Direction.Down);
             *          }
             *          else
             *          {
             *              AddSpritesToMap();
             *              if (CheckForClearedLines())
             *              {
             *                  gameState = GameStates.Flashing;
             *                  break;
             *              }
             *              else
             *              {
             *                  currentBlock = nextBlock;
             *                  currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
             *                  GetNextBlock();
             *              }
             *          }
             *      }
             *      break;
             *  case GameStates.Flashing:
             *      timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
             *      if (timeSinceLastFrame > Constants.FLASHFPS)
             *      {
             *          timeSinceLastFrame -= Constants.FLASHFPS;
             *          flashINFO.flashcount++;
             *          if (flashINFO.flashing)
             *          {
             *              flashINFO.flashing = false;
             *          }
             *          else
             *          {
             *              flashINFO.flashing = true;
             *          }
             *          if (flashINFO.flashcount > Constants.FLASHCOUNT)
             *          {
             *              gameState = GameStates.Playing;
             *              RemoveClearedLines();
             *              currentBlock = nextBlock;
             *              currentBlock.playarea = new Point(playAreaPos.X, playAreaPos.Y);
             *              GetNextBlock();
             *          }
             *      }
             *      break;
             *  case GameStates.Paused:
             *      if (input.WasKeyPressed(Keys.Enter))
             *      {
             *          gameState = GameStates.Playing;
             *      }
             *      break;
             *  case GameStates.GameOver:
             *      if (input.WasKeyPressed(Keys.Enter))
             *      {
             *          gridMap.Clear();
             *          gameState = GameStates.Playing;
             *          hud.Restart();
             *          GetBlock();
             *          GetNextBlock();
             *      }
             *      break;
             *  default:
             *      break;
             * }
             */
            base.Update(gameTime);
        }
Exemplo n.º 9
0
        /// <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)
        {
            touches = TouchPanel.GetState();

            //foreach (TouchLocation touch in touches)
            if (touches.Count > 0)
            {
                if (touches[0].Position.X < _screenHalfHorizontal)
                {
                    if (touches[0].Position.Y > _screenHalfVertical)
                    {
                        if (_lPaddleY + lPaddleRectangle.Height > _screenBottom)
                        {
                            //stop the paddle at the bottom
                            return;
                        }
                        else
                        {
                            TouchLocation x = touches[0];
                            _lPaddleY = _lPaddleY + LPaddleSpeed;
                        }
                    }

                    else
                    {
                        if (_lPaddleY < _screenTop)
                        {
                            //stop the paddle at the top
                            return;
                        }
                        else
                        {
                            _lPaddleY = _lPaddleY - LPaddleSpeed;
                        }
                    }
                }
            }
            //if (touches.Count > 0)
            //{
            //1st option to check for single touches
            //}

            _lPaddleRectangle.Y = (int)(_lPaddleY + 0.5f);

            #region BrenLogic
            //if (touches.Count > 0)
            //{
            //    //_paddleY=_lPaddleRectangle.Y;
            //    _paddleTop = _lPaddleRectangle.Y + LPaddleSpeed;
            //    _paddleBottom = _lPaddleRectangle.Y + LPaddleSpeed;

            //    _touchY = touches[0].Position.Y;
            //    //_touchTop = _touchY - _lPaddleRectangle.Height;
            //    //_touchBottom = _touchY + _lPaddleRectangle.Height;
            //    //TOP
            //    //If the touch is the top half we evaluate the top variables
            //    if ((_touchY > _screenTop))//(_touchY<_screenHalf) &&  IS TOP
            //    {
            //        _paddleY = _paddleY + LPaddleSpeed;
            //        //if the touch is inside the boundaries then keep on advancing to the TOP
            //        if ((Convert.ToInt32(_paddleY + 0.5f) > _screenTop))
            //        {
            //            avanza = Convert.ToInt32(_paddleY + 0.5f);
            //        }
            //        else
            //        {
            //            _paddleY = _paddleY - LPaddleSpeed;
            //            avanza = (int)_screenTop;
            //        }
            //    }
            //    //BOTTOM
            //    else// IF ((_touchY>=_screenHalf) && (_touchY < _screenBottom)) IS BOTTOM
            //    {
            //        _paddleY = _paddleY + LPaddleSpeed;
            //        if ((Convert.ToInt32(_paddleY + 0.5f) < _screenBottom))
            //        {
            //            avanza = Convert.ToInt32(_paddleY + 0.5f);
            //        }
            //        else
            //        {
            //            _paddleY = _paddleY - LPaddleSpeed;
            //            //_paddleY = (int)_screenBottom - _lPaddleRectangle.Height;
            //            avanza = (int)_screenBottom - _lPaddleRectangle.Height;
            //        }
            //    }
            //}

            //_lPaddleRectangle.Y = (int)avanza;
            #endregion

            base.Update(gameTime);
        }
        /// <summary>
        /// Updates the virtual thumbsticks based on current touch state. This must be called every frame.
        /// </summary>
        public static void Update()
        {
            TouchLocation?  leftTouch = null, rightTouch = null;
            TouchCollection touches = TouchPanel.GetState();

            // 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 (var 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're 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;
            }
        }
Exemplo n.º 11
0
        public void Update(GameTime gameTime)
        {
            var previousPosition = position;

            position += Velocity * (float)gameTime.ElapsedGameTime.TotalSeconds;

            var keyboardState   = Keyboard.GetState();
            var touchCollection = TouchPanel.GetState();

            if (fallen == false)
            {
                if (position.X < 0)
                {
                    Velocity.X = GetXVelocity(false);
                }
                else if (position.X > Resolution.VirtualWidth - texture.Width)
                {
                    Velocity.X = GetXVelocity(true);
                }
            }

            if (Landed == true)
            {
                if (this.position.Y < this.NextPosition.Y)
                {
                    Velocity.Y = 1000f;
                }

                if (this.position.Y >= this.NextPosition.Y)
                {
                    this.position.Y = this.NextPosition.Y;
                    Velocity.Y      = 0f;
                }
            }

            if (position.Y > Resolution.VirtualHeight)
            {
                Landed = true;
            }

            if (Landed == false)
            {
                ResolveCollisions();
            }

            if (keyboardState.IsKeyDown(Keys.Space) &&
                fallen == false)
            {
                fallen     = true;
                Velocity.Y = 2000f;
                Velocity.X = 0f;
            }
            else if (touchCollection.Count > 0)
            {
                if (touchCollection.Any(touchLocation => touchLocation.State == TouchLocationState.Pressed) &&
                    fallen == false)
                {
                    fallen     = true;
                    Velocity.Y = 2000f;
                    Velocity.X = 0f;
                }
            }
        }
Exemplo n.º 12
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>
        public override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                _game.Exit();
            }

            TouchCollection touches;
            SpriteObject    touchedText;

            // Update all game objects
            _game.UpdateAll(gameTime);

            // Has the player touched the screen?
            touches = TouchPanel.GetState();
            if (touches.Count == 1 && touches[0].State == TouchLocationState.Pressed)
            {
                // Find which text object (if any) has been touched
                touchedText = Game.GetSpriteAtPoint(touches[0].Position);
                // Did we get something?
                if (touchedText != null)
                {
                    // See what it was
                    switch (touchedText.Tag)
                    {
                    case "NewGame":
                        // Switch to gameplay mode
                        Game.SetGameMode <Mode_Game>();
                        // Reset for a new game
                        Game.CurrentGameModeHandler.Reset();
                        break;

                    case "ResumeGame":
                        // Is the game already active?
                        if (Game.GetGameModeHandler <Mode_Game>().GameIsActive)
                        {
                            // Yes, so switch back to the existing game
                            Game.SetGameMode <Mode_Game>();
                        }
                        break;

                    case "HighScores":
                        // Switch to High Scores mode
                        Game.SetGameMode <Mode_HighScores>();
                        break;

                    case "Settings":
                        // Switch to Settings mode
                        Game.SetGameMode <Mode_Settings>();
                        break;

                    case "Credits":
                        // Switch to Credits mode
                        Game.SetGameMode <Mode_Credits>();
                        break;
                    }
                }
            }

            base.Update(gameTime);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Handles input for quitting the game.
        /// </summary>
        void HandleInput()
        {
#if WINDOWS_PHONE
            KeyboardState currentKeyboardState = new KeyboardState();
#else
            KeyboardState currentKeyboardState = Keyboard.GetState();
            MouseState    currentMouseState    = Mouse.GetState();
#endif

#if IPHONE
            GamePadState currentGamePadState = GamePad.GetState(PlayerIndex.One);

            // Check for exit.
            if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
                currentGamePadState.Buttons.Back == ButtonState.Pressed)
            {
                Exit();
            }
#else
            // Check for exit.
            if (currentKeyboardState.IsKeyDown(Keys.Escape))
            {
                Exit();
            }
#endif

            // check to see if the user wants to move the cat. we'll create a vector
            // called catMovement, which will store the sum of all the user's inputs.
            Vector2 catMovement = Vector2.Zero;

            //Move toward the touch point. We slow down the cat when it gets within a distance of MaxCatSpeed to the touch point.
            float smoothStop = 1;

#if IPHONE
            // check to see if the user wants to move the cat. we'll create a vector
            // called catMovement, which will store the sum of all the user's inputs.
            catMovement = currentGamePadState.ThumbSticks.Left;

            // flip y: on the thumbsticks, down is -1, but on the screen, down is bigger
            // numbers.
            catMovement.Y *= -1;

            if (currentKeyboardState.IsKeyDown(Keys.Left) ||
                currentGamePadState.DPad.Left == ButtonState.Pressed)
            {
                catMovement.X -= 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Right) ||
                currentGamePadState.DPad.Right == ButtonState.Pressed)
            {
                catMovement.X += 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Up) ||
                currentGamePadState.DPad.Up == ButtonState.Pressed)
            {
                catMovement.Y -= 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Down) ||
                currentGamePadState.DPad.Down == ButtonState.Pressed)
            {
                catMovement.Y += 1.0f;
            }

            TouchCollection currentTouchCollection = TouchPanel.GetState();

            // tap the screen to select
            foreach (TouchLocation location in currentTouchCollection)
            {
                switch (location.State)
                {
                case TouchLocationState.Pressed:
                    Vector2 mousePosition = new Vector2(location.Position.X, location.Position.Y);
                    catMovement = mousePosition - catPosition;
                    float delta = MaxCatSpeed - MathHelper.Clamp(catMovement.Length(), 0, MaxCatSpeed);
                    smoothStop = 1 - delta / MaxCatSpeed;
                    break;

                case TouchLocationState.Moved:
                    break;

                case TouchLocationState.Released:
                    break;
                }
            }
#else
            if (currentKeyboardState.IsKeyDown(Keys.Left))
            {
                catMovement.X -= 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Right))
            {
                catMovement.X += 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Up))
            {
                catMovement.Y -= 1.0f;
            }
            if (currentKeyboardState.IsKeyDown(Keys.Down))
            {
                catMovement.Y += 1.0f;
            }

            Vector2 mousePosition = new Vector2(currentMouseState.X, currentMouseState.Y);
            if (currentMouseState.LeftButton == ButtonState.Pressed && mousePosition != catPosition)
            {
                catMovement = mousePosition - catPosition;
                float delta = MaxCatSpeed - MathHelper.Clamp(catMovement.Length(), 0, MaxCatSpeed);
                smoothStop = 1 - delta / MaxCatSpeed;
            }
#endif

            // normalize the user's input, so the cat can never be going faster than
            // CatSpeed.
            if (catMovement != Vector2.Zero)
            {
                catMovement.Normalize();
            }

            catPosition += catMovement * MaxCatSpeed * smoothStop;
        }
Exemplo n.º 14
0
        public override void Update(float deltatime)
        {
            // Mettre le jeu en pause
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                Globals.intStarCount = 0;
                _soundNyan.Stop();
                Globals.GameStateStack.Set(new MainMenu());
            }

            // R�cup�ration de l'�tat de l'�cran tactile
            TouchCollection touchCollection = TouchPanel.GetState();

            if (touchCollection.Count >= 1)
            {
                blnHasTouched = true;
            }

            if (!blnHasHit && blnHasTouched)
            {
                fltTotalTime      += deltatime;
                intScore          += (int)fltTotalTime;
                strScore           = "" + intScore;
                vecScoreSize       = Globals.ArialFont.MeasureString(strScore) * 2;
                vecScorePosition.X = 750 - vecScoreSize.X;
                vecScorePosition.Y = 50;

                // On test si l'�cran est touch� ou non, si oui le perso monte, sinon il descend
                if (touchCollection.Count >= 5)
                {
                    Nyan.ChangeSkin();
                }
                if (touchCollection.Count >= 1)
                {
                    if ((Nyan._vec2_NyanPos.Y - 10) >= 0)
                    {
                        Nyan._vec2_NyanPos.Y -= 10;
                        foreach (DrawCourse currentSky in lstSky)
                        {
                            blnHasHit = Nyan._rec_Destination.Intersects(currentSky._recDestination);
                            if (blnHasHit)
                            {
                                Nyan._vec2_NyanPos.Y = currentSky.fltPosY + 151;
                                break;
                            }
                        }
                    }
                }
                else if ((Nyan._vec2_NyanPos.Y + 8) < (480 - Nyan._tex_NyanCat.Height))
                {
                    Nyan._vec2_NyanPos.Y += 8;
                    foreach (DrawCourse currentGround in lstGround)
                    {
                        blnHasHit = Nyan._rec_Destination.Intersects(currentGround._recDestination);
                        if (blnHasHit)
                        {
                            Nyan._vec2_NyanPos.Y = currentGround.fltPosY - 81;
                            break;
                        }
                    }
                }

                Nyan.Update();

                // On test le nombre d'�toiles actuellement affich�es
                if (Globals.intStarCount < 4)
                {
                    DrawStar tmpDrawStar = new DrawStar(fltTotalTime);
                    lstStars.Add(tmpDrawStar);
                    Globals.intStarCount += 1;
                }


                // On actualise la position des bouts d'arc-en-ciels
                for (int x = 0; x < INT_NB_RAINBOW; x++)
                {
                    if (lstRainbow[x] != lstRainbow[INT_NB_RAINBOW - 1])
                    {
                        lstRainbow[x].Update(deltatime, lstRainbow[x + 1].intPubPosY);
                    }
                }

                lstRainbow[INT_NB_RAINBOW - 1].Update(deltatime, (int)Nyan._vec2_NyanPos.Y);

                // On actualise les �toiles
                foreach (DrawStar currentStar in lstStars)
                {
                    currentStar.Update(deltatime, fltTotalTime);
                }

                // On actualise les positions du sol
                for (int x = 0; x < INT_NB_GROUND; x++)
                {
                    if (lstGround[x] != lstGround[INT_NB_GROUND - 1])
                    {
                        lstGround[x].Update(deltatime, lstGround[x + 1].fltPosY);
                    }
                }

                float fltTemp = rand.Next(-1, 1);
                if (fltTemp < 0 && vecGroundPosition.Y < 455)
                {
                    vecGroundPosition.Y += 10;
                }
                else if (vecGroundPosition.Y > 350)
                {
                    vecGroundPosition.Y -= 10;
                }
                lstGround[INT_NB_GROUND - 1].Update(deltatime, vecGroundPosition.Y);

                // On actualise les positions du ciel
                for (int x = 0; x < INT_NB_SKY; x++)
                {
                    if (lstSky[x] != lstSky[INT_NB_SKY - 1])
                    {
                        lstSky[x].Update(deltatime, lstSky[x + 1].fltPosY);
                    }
                }

                float fltTempSky = rand.Next(-1, 1);
                if (fltTempSky < 0 && vecSkyPosition.Y < -10)
                {
                    vecSkyPosition.Y += 10;
                }
                else if (vecSkyPosition.Y > -115)
                {
                    vecSkyPosition.Y -= 10;
                }
                lstSky[INT_NB_SKY - 1].Update(deltatime, vecSkyPosition.Y);
            }
            else if (blnHasHit)
            {
                Globals.intStarCount = 0;
                _soundNyan.Stop();
                Globals.intLastScore = intScore;
                Globals.GameStateStack.Set(new GameOver());
            }
        }
Exemplo n.º 15
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>
        public void Update(GameTime gameTime)
        {
            if (game_state.local_player.getHealth() <= 0)
            {
                die();
                return;
            }

            PlayerDir pot_dir = game_state.local_player.getDirection();
            int       pot_x   = game_state.local_player.getX();
            int       pot_y   = game_state.local_player.getY();

            double new_width = ((double)health_bar_width) * (double)((double)game_state.local_player.getHealth() / (double)game_state.local_player.getMaxHealth());

            health_bar_rec.Width = (int)new_width;

            //Put a nicer function here
            TouchCollection touchCollection = TouchPanel.GetState();

            foreach (TouchLocation tl in touchCollection)
            // for each place the screen has been touched at the point of "getState"
            {
                //if the screen is pressed on an arrow, move sprite accordingly
                if (tl.State == TouchLocationState.Pressed || tl.State == TouchLocationState.Moved)
                {
                    if ((tl.Position.X >= 50) && (tl.Position.X <= 100) && (tl.Position.Y >= 345) && (tl.Position.Y <= 385)) // up arrow
                    {
                        //local_player.setY(local_player.getY() - 3);
                        pot_y  -= game_state.local_player.getSpeed();
                        pot_dir = PlayerDir.UP;
                        // -1 = up direction (axis goes down incresingly)
                    }

                    if ((tl.Position.X >= 50) && (tl.Position.X <= 100) && (tl.Position.Y >= 425) && (tl.Position.Y <= 465)) // down arrow
                    {
                        pot_y  += game_state.local_player.getSpeed();
                        pot_dir = PlayerDir.DOWN;
                        // local_player.setY(local_player.getY() + 3);
                    }

                    if ((tl.Position.X >= 15) && (tl.Position.X <= 55) && (tl.Position.Y >= 385) && (tl.Position.Y <= 425)) // left arrow
                    {
                        pot_x  -= game_state.local_player.getSpeed();
                        pot_dir = PlayerDir.LEFT;
                        //local_player.setX(local_player.getX() - 3); // -1 = left because left to right
                    }

                    if ((tl.Position.X >= 90) && (tl.Position.X <= 130) && (tl.Position.Y >= 385) && (tl.Position.Y <= 425)) // right arrow
                    {
                        pot_x  += game_state.local_player.getSpeed();
                        pot_dir = PlayerDir.RIGHT;
                        //local_player.setX(local_player.getX() + 3);
                    }


                    //Collision and updating
                    if (game_state.coll_engine.check_map_col(pot_x, pot_y, game_state.local_player.getWidth(), game_state.local_player.getHeight()) == false)
                    {
                        if (game_state.obj_mang.checkForGateAt(pot_x, pot_y, game_state.local_player.getWidth(), game_state.local_player.getHeight()) && !game_state.local_player.hasKey())
                        {
                            //there is a gate and the player does not have a key
                        }
                        else
                        {//no gate or the player has the key
                            game_state.local_player.setX(pot_x);
                            game_state.local_player.setY(pot_y);


                            //System.Diagnostics.Debug.WriteLine("Stuff: {0},{1}", pot_x, pot_y);

                            Item item = game_state.obj_mang.getItemAt(pot_x, pot_y, game_state.local_player.getWidth(), game_state.local_player.getHeight());
                            if (item != null)
                            {
                                game_state.local_player.addItem(item);
                                if (game_state.local_player.getWeapon() == weaponType.NONE)
                                {
                                    if (item.getType() == itemType.SWORD)
                                    {
                                        game_state.local_player.setWeapon(weaponType.SWORD);
                                    }
                                    if (item.getType() == itemType.LASER)
                                    {
                                        game_state.local_player.setWeapon(weaponType.LASER);
                                    }
                                }
                            }

                            if (!game_state.local_player.moving)
                            {
                                game_state.local_player.setDirection(pot_dir);
                                game_state.local_player.moving = true;
                                character_sprite[(int)game_state.local_player.getWeapon()].StartAnimating((int)pot_dir * 3, ((int)pot_dir * 3) + 2);
                            }
                        }
                    }
                }
                else if (tl.State == TouchLocationState.Released)
                {
                    if (tl.Position.X >= backpackpos.X && tl.Position.X <= backpackpos.X + backpack.Width && tl.Position.Y >= backpackpos.Y && tl.Position.Y <= backpackpos.Y + backpack.Height)
                    {
                        backpackmenu.backpack_touched = true;
                    }
                    if (backpackmenu.backpack_touched == false)
                    {
                        if ((tl.Position.X >= 700) && (tl.Position.Y >= 385)) // Fire button
                        {
                            if (game_state.local_player.getWeapon() == weaponType.LASER)
                            {
                                game_state.bullet_engine.fire(game_state.local_player.getX() + (int)character_sprite[(int)game_state.local_player.getWeapon()].size.X / 2,
                                                              game_state.local_player.getY() + (int)character_sprite[(int)game_state.local_player.getWeapon()].size.Y / 2,
                                                              game_state.local_player.getDirection(),
                                                              bulletOwner.PLAYER,
                                                              bulletType.SMALL);
                                game_state.fx_engine.RequestSound(soundType.SHOOT);
                            }
                            else if (game_state.local_player.getWeapon() == weaponType.SWORD)
                            {
                                sword_swing = true;
                                game_state.fx_engine.RequestSound(soundType.SWORD);
                                int bullet_x = 0;
                                int bullet_y = 0;
                                switch (game_state.local_player.getDirection())
                                {
                                case PlayerDir.DOWN:
                                    bullet_x = game_state.local_player.getX() - 2;
                                    bullet_y = game_state.local_player.getY() + game_state.local_player.getHeight();
                                    break;

                                case PlayerDir.UP:
                                    bullet_x = game_state.local_player.getX() - 2;
                                    bullet_y = game_state.local_player.getY() - game_state.local_player.getHeight();
                                    break;

                                case PlayerDir.LEFT:
                                    bullet_x = game_state.local_player.getX() - (game_state.local_player.getWidth());
                                    bullet_y = game_state.local_player.getY();     //+ game_state.local_player.getHeight();
                                    break;

                                case PlayerDir.RIGHT:
                                    bullet_x = game_state.local_player.getX() + game_state.local_player.getWidth();
                                    bullet_y = game_state.local_player.getY();     //+ game_state.local_player.getHeight();
                                    break;
                                }

                                sword_bullet = game_state.bullet_engine.fire(bullet_x, bullet_y, game_state.local_player.getDirection(), bulletOwner.PLAYER, bulletType.SWORD);
                            }
                        }
                    }
                    else
                    {
                        Vector2 formatpos = new Vector2(315, 170);
                        int     tileSize  = game_state.tile_engine.getTileSize();

                        Item toRemove = null;
                        foreach (Item i in game_state.local_player.getInventory())
                        {
                            Rectangle dest = new Rectangle((int)formatpos.X, (int)formatpos.Y, 300, 40);
                            if (dest.Contains((int)tl.Position.X, (int)tl.Position.Y))
                            {
                                //menu item Clicked
                                switch (i.getType())
                                {
                                case itemType.LASER: game_state.local_player.setWeapon(weaponType.LASER); break;

                                case itemType.SWORD: game_state.local_player.setWeapon(weaponType.SWORD); break;

                                case itemType.ATT_BOOST: toRemove = i; att_boost_delay = 10000; game_state.local_player.setAttackBonus(5); break;

                                case itemType.DEF_BOOST: toRemove = i; def_boost_delay = 10000; game_state.local_player.setDefenseBonus(5); break;

                                case itemType.KEY:
                                default: break;
                                }
                                backpackmenu.backpack_touched = false;  // exit from inventory now
                            }
                            formatpos.Y += 50;
                        }
                        if (toRemove != null)
                        {
                            game_state.local_player.removeItem(toRemove);
                        }

                        if (backpackExit.Contains((int)tl.Position.X, (int)tl.Position.Y)) // coordinates of the "exit" button in inventory
                        {
                            backpackmenu.backpack_touched = false;                         //user has exited, return to main game screen
                        }
                    }

                    character_sprite[(int)game_state.local_player.getWeapon()].StopAnimating();
                    game_state.local_player.moving = false;
                }
            }

            if (sword_swing)
            {
                sword_delay += gameTime.ElapsedGameTime.Milliseconds;
                if (sword_delay > 200)
                {
                    sword_delay = 0;
                    sword_swing = false;
                    game_state.bullet_engine.RemoveBullet(sword_bullet);
                }
            }

            if (game_state.local_player.getAttackBonus() > 0)
            {
                att_boost_delay -= gameTime.ElapsedGameTime.Milliseconds;
                if (att_boost_delay <= 0)
                {
                    game_state.local_player.setAttackBonus(0);
                }
            }

            if (game_state.local_player.getDefenseBonus() > 0)
            {
                def_boost_delay -= gameTime.ElapsedGameTime.Milliseconds;
                if (def_boost_delay <= 0)
                {
                    game_state.local_player.setDefenseBonus(0);
                }
            }

            List <ColToken> cols = game_state.local_player.col_tok.GetCollisions();

            for (int j = 0; j < cols.Count(); ++j)
            {
                ColToken coll = cols.ElementAt(j);
                if (coll.GetLocalType() != ColType.MAP)
                {
                    if (!game_state.local_player.hurt)
                    {
                        int damage = 0;
                        if (coll.GetLocalType() == ColType.BULLET)
                        {
                            //BulletEngine will deal the damage for this

                            /*
                             * Bullet bull = (Bullet)coll.GetParent();
                             * if (bull.owner == bulletOwner.ENEMY)
                             * {
                             *  switch (bull.type)
                             *  {
                             *      case bulletType.SMALL:
                             *          damage = 5;
                             *          break;
                             *      case bulletType.SWORD:
                             *          damage = 10;
                             *          break;
                             *
                             *  }
                             * }*/
                            Bullet bul = (Bullet)coll.GetParent();
                            if (bul.owner == bulletOwner.PLAYER)
                            {
                                continue;
                            }
                        }
                        else if (coll.GetLocalType() == ColType.MONSTER)
                        {
                            Enemy enem = (Enemy)coll.GetParent();
                            damage = enem.getAttack();
                        }
                        //Player gets hurt!

                        game_state.local_player.setHealth(game_state.local_player.getHealth() + game_state.local_player.getDefenseBonus() - damage);
                        game_state.local_player.hurt = true;

                        //Get hurt by a little
                        hurt_time = 500;
                    }
                }
            }
            game_state.local_player.col_tok.ResetCollisions();
            game_state.local_player.col_tok.update(game_state.local_player.getX(), game_state.local_player.getY());

            if (game_state.local_player.hurt)
            {
                hurt_time -= gameTime.ElapsedGameTime.Milliseconds;
                if (hurt_time <= 0)
                {
                    game_state.local_player.hurt = false;
                }
            }
            currTime -= gameTime.ElapsedGameTime; // start timer on actual game


            if (currTime.TotalSeconds <= 0)
            {
                return;
            }
            game_state.monster_engine.Update(gameTime.ElapsedGameTime.Milliseconds);
            game_state.bullet_engine.Update();

            game_state.coll_engine.Update();

            game_state.fx_engine.Update();
            if (testAtExit(game_state.local_player.getX(), (game_state.local_player.getY() + game_state.local_player.getHeight() - 1)) || testAtExit(game_state.local_player.getX() + game_state.local_player.getWidth(), (game_state.local_player.getY() + game_state.local_player.getHeight())))
            {
                int tempn = game_state.tile_engine.getCurrentLevel() + 1;
                LoadLevel(tempn);
            }
        }
Exemplo n.º 16
0
        private void DrawDebug(Room room)
        {
            if (CONFIG_DEBUG == false)
            {
                return;
            }

            Rectangle titleSafeArea = GraphicsDevice.Viewport.TitleSafeArea;
            Vector2   hudLocation   = new Vector2(titleSafeArea.X, titleSafeArea.Y);

            DrawShadowedString(fontPrinceOfPersia_bigger, "LEVEL NAME=" + maze.player.MyLevel.levelName, hudLocation, Color.White);
            hudLocation.Y = hudLocation.Y + 10;

            DrawShadowedString(fontPrinceOfPersia_bigger, "ROOM NAME=" + maze.player.MyRoom.roomName, hudLocation, Color.White);
            hudLocation.Y = hudLocation.Y + 10;

            DrawShadowedString(fontPrinceOfPersia_bigger, "POSTION X=" + maze.player.Position.X.ToString() + " Y=" + maze.player.Position.Y.ToString(), hudLocation, Color.White);
            hudLocation.Y = hudLocation.Y + 10;
            DrawShadowedString(fontPrinceOfPersia_bigger, "FRAME RATE=" + AnimationSequence.frameRate.ToString(), hudLocation, Color.White);

            hudLocation.Y = hudLocation.Y + 10;
            DrawShadowedString(fontPrinceOfPersia_bigger, "PLAYER STATE=" + maze.player.spriteState.Value().state + " SEQUENCE CountOffset=" + maze.player.sprite.sequence.CountOffSet, hudLocation, Color.White);

            hudLocation.Y = hudLocation.Y + 10;
            DrawShadowedString(fontPrinceOfPersia_bigger, "PLAYER FRAME=" + maze.player.spriteState.Value().Frame + " NAME=" + maze.player.spriteState.Value().Name, hudLocation, Color.White);

            hudLocation.Y = hudLocation.Y + 10;
            DrawShadowedString(fontPrinceOfPersia_bigger, "PLAYER SWORD=" + maze.player.Sword.ToString(), hudLocation, Color.White);

            TouchCollection touchState = TouchPanel.GetState();

            for (int x = 0; x < touchState.Count; x++)
            {
                hudLocation.Y = hudLocation.Y + 10;
                DrawShadowedString(fontPrinceOfPersia_bigger, "TOUCH_STATE=" + touchState[x].State.ToString(), hudLocation, Color.White);
                hudLocation.Y = hudLocation.Y + 10;
                DrawShadowedString(fontPrinceOfPersia_bigger, "TOUCH_LOCATION=" + touchState[x].Position.ToString(), hudLocation, Color.White);
            }

            hudLocation.Y = hudLocation.Y + 10;
            DrawShadowedString(fontPrinceOfPersia_bigger, "-SHIFTZONE=" + CntShiftZone.ToString(), hudLocation, Color.White);



            // Get the player's bounding rectangle and find neighboring tiles.
            Rectangle playerBounds = maze.player.Position.Bounding;
            Vector4   v4           = room.getBoundTiles(playerBounds);

            // For each potentially colliding Tile, warning the for check only the player row ground..W
            for (int y = (int)v4.Z; y <= (int)v4.W; ++y)
            {
                for (int x = (int)v4.X; x <= (int)v4.Y; ++x)
                {
                    //Rectangle tileBounds = room.GetBounds(x, y);
                    Tile    myTile = room.GetTile(x, y);
                    Vector2 depth  = RectangleExtensions.GetIntersectionDepth(playerBounds, myTile.Position.Bounding);
                    Enumeration.TileCollision tileCollision = room.GetCollision(x, y);
                    Enumeration.TileType      tileType      = room.GetType(x, y);

                    hudLocation.Y = hudLocation.Y + 10;
                    DrawShadowedString(fontPrinceOfPersia_bigger, "GRID X=" + x + " Y=" + y + " TILETYPE=" + tileType.ToString() + " BOUND X=" + myTile.Position.Bounding.X + " Y=" + myTile.Position.Bounding.Y + " DEPTH X=" + depth.X + " Y=" + depth.Y, hudLocation, Color.White);
                }
            }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Updates the global TouchPanel state used by all entities that use touch controls.
 /// </summary>
 public static void updateTouchPanel()
 {
     tc = TouchPanel.GetState();
 }
Exemplo n.º 18
0
        public override void Update(GameTime gametime)
        {
#if ANDROID
            CurrentTouchState = TouchPanel.GetState();
            if (CurrentTouchState.Count == 1)
            {
                PreviousGesturePosition = CurrentGesturePosition;
                CurrentGesturePosition  = CurrentTouchState[0].Position;
            }

            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                switch (gesture.GestureType)
                {
                case GestureType.None:
                    clearColor = Color.CornflowerBlue;
                    break;

                case GestureType.DoubleTap:
                    clearColor = clearColor == Color.CornflowerBlue ? Color.Red : Color.CornflowerBlue;
                    break;

                case GestureType.Tap:
                    clearColor = clearColor == Color.CornflowerBlue ? Color.Black : Color.CornflowerBlue;
                    break;

                case GestureType.Flick:
                    clearColor = clearColor == Color.CornflowerBlue ? Color.Pink : Color.CornflowerBlue;
                    break;

                case GestureType.HorizontalDrag:
                    clearColor = clearColor == Color.CornflowerBlue ? Color.Peru : Color.CornflowerBlue;
                    break;

                case GestureType.VerticalDrag:
                    clearColor = clearColor == Color.CornflowerBlue ? Color.Wheat : Color.CornflowerBlue;
                    break;
                }
                currentGestureType = gesture.GestureType;
            }
#endif
            PreviousPadState = currentPadState;
            previousKeyState = currentKeyState;

            currentPadState = GamePad.GetState(PlayerIndex.One);
            currentKeyState = Keyboard.GetState();


            previousMouseState = currentMouseState;
            currentMousePos    = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
            currentMouseState  = Mouse.GetState();

            KeysPressedInLastFrame.Clear();
            CheckForTextInput();

            UpdateControls();
            thumbStick = ApplyDeadZone(currentPadState.ThumbSticks);

            UpdateRumble((float)gametime.ElapsedGameTime.TotalSeconds);

            base.Update(gametime);
        }
Exemplo n.º 19
0
        public void update(ref Socket ws)
        {
            TouchCollection touch = TouchPanel.GetState();

            if (touch.Count > 0)
            {
                float tx = touch[0].Position.X;
                float ty = touch[0].Position.Y;

                Game1.output2 = "X: " + Math.Round(touch[0].Position.X / Game1.WIDTH, 3) + " | Y: " + Math.Round(touch[0].Position.Y / Game1.HEIGHT, 3);

                if (touch[0].State == TouchLocationState.Pressed)
                {
                    foreach (Button b in buttons)
                    {
                        if (tx > b.x && tx < b.x + b.w && ty > b.y && ty < b.y + b.h)
                        {
                            b.touch = true;
                        }
                        else
                        {
                            b.touch = false;
                        }
                    }

                    foreach (InputBox b in inputboxes)
                    {
                        if (tx > b.x && tx < b.x + b.w && ty > b.y && ty < b.y + b.h)
                        {
                            b.touch = true;
                        }
                        else
                        {
                            b.touch = false;
                        }
                    }
                }
                else if (touch[0].State == TouchLocationState.Released)
                {
                    foreach (Button b in buttons)
                    {
                        b.touch = false;
                    }

                    foreach (InputBox b in inputboxes)
                    {
                        b.touch = false;
                    }
                }
            }

            if (SCREEN == Screen.HOME)
            {
                screen_home.update();
            }
            else if (SCREEN == Screen.GAME)
            {
                screen_game.update(ref ws);
            }
            else if (SCREEN == Screen.LOAD)
            {
                screen_load.update(ref ws);
            }
            else if (SCREEN == Screen.FINISH)
            {
                screen_finish.update();
            }
            else if (SCREEN == Screen.LOGIN)
            {
                screen_login.update(ref ws);
            }
            else if (SCREEN == Screen.REGISTER)
            {
                screen_register.update(ref ws);
            }
            else if (SCREEN == Screen.HALL)
            {
                screen_hall.update(ref ws);
            }
            else if (SCREEN == Screen.ACTIVITY)
            {
                screen_activity.update(ref ws);
            }
            else if (SCREEN == Screen.JOIN_ACTIVITY)
            {
                screen_join_activity.update(ref ws);
            }
            else if (SCREEN == Screen.CREATE_ACTIVITY)
            {
                screen_create_activity.update(ref ws);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Alternative way to get contacts.  Instead of using TouchHook
        /// this uses the XNA touch support.
        /// </summary>
        public static Touch[] AltGetTouchContacts()
        {
#if DEBUG
            TouchPanelCapabilities caps = TouchPanel.GetCapabilities();
            Debug.Assert(caps.IsConnected, "Should be a touch panel?!?");
#endif

            // Get the contacts.
            TouchCollection collection = TouchPanel.GetState();

            // Translate the contacts into an array of Touch.
            List <Touch> touchList = new List <Touch>();
            foreach (TouchLocation tl in collection)
            {
                // Filter out Invalid ones.  No clue what to do with them anyway...
                if (tl.State != TouchLocationState.Invalid)
                {
                    Touch touch = new Touch();
                    touch.position = tl.Position;

                    // Set position with offset for Tutorial mode.
                    touch.position = touch.position - BokuGame.ScreenPosition;

                    touch.fingerId = tl.Id;
                    touch.phase    = TouchPhase.Stationary;
                    switch (tl.State)
                    {
                    case TouchLocationState.Moved:
                        touch.phase = TouchPhase.Moved;
                        break;

                    case TouchLocationState.Pressed:
                        touch.phase = TouchPhase.Began;
                        break;

                    case TouchLocationState.Released:
                        touch.phase = TouchPhase.Ended;
                        break;
                    }
                    touch.deltaTime = Time.WallClockFrameSeconds;

                    // Look for matching Id to calc deltaPosition.
                    touch.deltaPosition = Vector2.Zero;
                    if (prevTouchList != null)
                    {
                        foreach (Touch t in prevTouchList)
                        {
                            if (t.fingerId == touch.fingerId)
                            {
                                touch.deltaPosition = touch.position - t.position;
                            }
                        }
                    }

                    touchList.Add(touch);
                }
            }   // end of loop over collection

            // Save a reference to this list for next frame.
            prevTouchList = touchList;

            return(touchList.ToArray());
        }   // end of AltGetTouchContacts()
Exemplo n.º 21
0
        /// <summary>
        /// Updates the state of the game. This method checks the GameScreen.IsActive
        /// property, so the game will stop updating when the pause menu is active,
        /// or if you tab away to a different application.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                    bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, false);

            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            // Gradually fade in or out depending on whether we are covered by the pause screen.
            if (coveredByOtherScreen)
            {
                pauseAlpha = Math.Min(pauseAlpha + 1f / 32, 1);
            }
            else
            {
                pauseAlpha = Math.Max(pauseAlpha - 1f / 32, 0);
            }

            if (IsActive)
            {
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer);
                }

                TouchCollection touches = TouchPanel.GetState();
                if (!bTouching && touches.Count > 0)
                {
                    bTouching = true;
                    TouchLocation touch = touches[0];
                    if (boardHandler.MenuPressed(touch, spriteBatch))
                    {
                        ScreenManager.AddScreen(new PhonePauseScreen(), ControllingPlayer);
                    }
                    else
                    {
                        if (!boardHandler.InProgress)
                        {
                            boardHandler.Touch(touch, spriteBatch);
                        }
                    }
                }
                else if (touches.Count == 0)
                {
                    bTouching = false;
                }

                if (boardHandler.InProgress && !boardHandler.Rotating())
                {
                    boardHandler.CauseChainReaction();
                }
                else
                {
                    if (boardHandler.GetScore == boardHandler.GetTargetScore)
                    {
                        //Add save score here
                        string saveString = string.Format("{0},{1},{2}{3}", boardHandler.GetScore, boardHandler.Attempts, DateTime.Now.ToString(), Environment.NewLine);

                        // Open a storage container.
                        try
                        {
                            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication(); // grab the storage
                            FileStream          stream;
                            if (!store.FileExists(HIGHSCORE_FILE))
                            {
                                stream = store.CreateFile(HIGHSCORE_FILE);
                            }
                            else
                            {
                                stream = store.OpenFile(HIGHSCORE_FILE, FileMode.Append);
                            }
                            StreamWriter writer = new StreamWriter(stream);
                            writer.Write(saveString);
                            writer.Close();
                        }
                        catch (Exception ex)
                        {
                        }
                        ScreenManager.AddScreen(new FinishGameScreen(boardHandler.GetScore, boardHandler.Attempts), ControllingPlayer);
                    }
                }
            }
        }
Exemplo n.º 22
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 || MONOMAC
                _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);
                }
            }
        }
Exemplo n.º 23
0
        protected override void Update(GameTime gameTime)
        {
            switch (gameState)
            {
            //NOTE: LOAD LEVEL
            case GameState.LoadLevel:
                if (firstEntry)
                {
                    player.RePosition();
                    firstEntry = false;
                    Thread loadThread = new Thread(() =>
                    {
                        foreach (PlayerBackground item in backgroundList)
                        {
                            item.RePosition();
                        }
                        string level = LevelHelper.SelectLevel();
                        barriers     = new Barriers(level, 4);
                        barriers.Load(this);
                        moneys = new Moneys(level, 4);
                        moneys.Load(this);
                        modifiers = new Modifiers(level, 4);
                        modifiers.Load(this);

                        collosion = new Collosion(barriers, player, moneys, modifiers, backgroundList);
                        collosion.Load(this);
                        gameState = GameState.Gaming;
                        //Transitions.ChangeGameState(ref firstEntry);
                    });
                    loadThread.Start();
                }
                player.Update(this, ref firstEntry);
                backBackground.Scroll(this);
                foreBackground.Scroll(this);
                walkPlace.Scroll(this);
                break;

            //NOTE: GAMING
            case GameState.Gaming:
                if (firstEntry)
                {
                    firstEntry = false;
                }
                else
                {
                    if (LevelHelper.IsLevelEnd(moneys))
                    {
                        player.isEnd = true;
                        if (player.Position.X >= Consts.PhoneWidth)
                        {
                            Transitions.ChangeGameState(ref firstEntry);
                            gameState = GameState.InEndGameMenu;
                        }
                    }
                    player.Update(this, ref firstEntry);
                    backBackground.Scroll(this);
                    foreBackground.Scroll(this);
                    walkPlace.Scroll(this);
                    barriers.Scroll(this);
                    moneys.Scroll(this);
                    modifiers.Scroll(this);
                    collosion.Update();
                    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                    {
                        gameState  = GameState.InPauseMenu;
                        firstEntry = true;
                    }
                }
                break;

            //NOTE: MAIN MENU
            case GameState.InMainMenu:
                if (firstEntry)
                {
                    player.Score.LoadTotalScore();
                    player.Score.LoadHighScore();
                    mainMenu             = new Menu(mainButtons);
                    player.isDead        = false;
                    player.isEatMoney    = false;
                    player.isEatModifier = false;
                    backBackground.RePosition();
                    foreBackground.RePosition();
                    walkPlace.RePosition();
                    collosion.Reset();
                    firstEntry = false;
                }
                backBackground.Scroll(this);
                foreBackground.Scroll(this);
                walkPlace.Scroll(this);
                gameState = mainMenu.IsTouched(this, TouchPanel.GetState(), gameState, ref firstEntry);
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    this.Exit();
                }
                break;

            //NOTE: PAUSE MENU
            case GameState.InPauseMenu:
                if (firstEntry)
                {
                    pauseMenu  = new Menu(pauseButtons);
                    firstEntry = false;
                }
                gameState = pauseMenu.IsTouched(this, TouchPanel.GetState(), gameState, ref firstEntry);
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    Transitions.ChangeGameState(ref firstEntry);
                    player.Score.GameScore = 0;
                    gameState = GameState.InMainMenu;
                }
                break;

            //NOTE: TUTORIAL
            case GameState.InTutorial:
                backBackground.Scroll(this);
                foreBackground.Scroll(this);
                walkPlace.Scroll(this);
                gameState = tutorialMenu.IsTouched(this, TouchPanel.GetState(), gameState, ref firstEntry);
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    Transitions.ChangeGameState(ref firstEntry);
                    gameState = GameState.InMainMenu;
                }
                break;

            //NOTE: ABOUT
            case GameState.About:
                backBackground.Scroll(this);
                foreBackground.Scroll(this);
                walkPlace.Scroll(this);
                gameState = aboutMenu.IsTouched(this, TouchPanel.GetState(), gameState, ref firstEntry);
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                {
                    Transitions.ChangeGameState(ref firstEntry);
                    gameState = GameState.InMainMenu;
                }
                break;

            //NOTE: ENDGAME MENU
            case GameState.InEndGameMenu:
                player.Score.SaveTotalScore();
                player.Score.SaveHighScore();
                gameState = GameState.InMainMenu;
                break;

            default:
                break;
            }

            base.Update(gameTime);
        }
Exemplo n.º 24
0
        public void Update()
        {
            var keyboardState = Microsoft.Xna.Framework.Input.Keyboard.GetState();

            if (keyboardState.IsKeyDown(xInput.Keys.A))
            {
                buttonAPressed = true;
                aPressed       = ButtonState.Pressed;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.A) && buttonAPressed)
            {
                buttonAPressed = false;
                aPressed       = ButtonState.Released;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.B))
            {
                buttonBPressed = true;
                bPressed       = ButtonState.Pressed;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.B) && buttonBPressed)
            {
                buttonBPressed = false;
                bPressed       = ButtonState.Released;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.Space))
            {
                buttonXPressed = true;
                xPressed       = ButtonState.Pressed;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.Space) && buttonXPressed)
            {
                buttonXPressed = false;
                xPressed       = ButtonState.Released;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.Up))
            {
                buttonUpPressed = true;
                leftStick.Y     = 1;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.Up) && buttonUpPressed)
            {
                buttonUpPressed = false;
                leftStick.Y     = 0;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.Down))
            {
                buttonDownPressed = true;
                leftStick.Y       = -1;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.Down) && buttonDownPressed)
            {
                buttonDownPressed = false;
                leftStick.Y       = 0;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.Left))
            {
                buttonLeftPressed = true;
                leftStick.X       = -1;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.Left) && buttonLeftPressed)
            {
                buttonLeftPressed = false;
                leftStick.X       = 0;
            }

            if (keyboardState.IsKeyDown(xInput.Keys.Right))
            {
                buttonRightPressed = true;
                leftStick.X        = 1;
            }
            else if (keyboardState.IsKeyUp(xInput.Keys.Right) && buttonRightPressed)
            {
                buttonRightPressed = false;
                leftStick.X        = 0;
            }


#if WINDOWS_PHONE
            leftTouch  = null;
            rightTouch = null;
            fireTouch  = null;

            xTouch = null;
            yTouch = null;
            aTouch = null;
            bTouch = null;

            touches = TouchPanel.GetState();

            //foreach (var t in touches)
            for (int i = 0; i < touches.Count; i++)
            {
                TouchLocation t = touches[i];

                float x = t.Position.X;
                float y = t.Position.Y;

                #region Left stick is always updated
                if (t.Id == leftId)
                {
                    leftTouch = t;
                    continue;
                }

                if (leftId == -1)
                {
                    if (IsTouchingLeftStick(ref x, ref y))
                    {
                        leftTouch = t;
                        continue;
                    }
                }
                #endregion

                #region XTYPE OR NOT

                // XTYPE means that we have only ono Left Thumb Stick and four buttons A, B, X and Y
                if (XTYPE)
                {
                    #region X button
                    if (t.Id == xId)
                    {
                        xTouch = t;
                        continue;
                    }
                    if (xId == -1)
                    {
                        if (IsTouchingButton(ref x, ref y, ref xButtonCollision))
                        {
                            xTouch = t;
                            continue;
                        }
                    }
                    #endregion

                    #region Y button
                    if (t.Id == yId)
                    {
                        yTouch = t;
                        continue;
                    }
                    if (yId == -1)
                    {
                        if (IsTouchingButton(ref x, ref y, ref yButtonCollision))
                        {
                            yTouch = t;
                            continue;
                        }
                    }
                    #endregion

                    #region A button
                    if (t.Id == aId)
                    {
                        aTouch = t;
                        continue;
                    }
                    if (aId == -1)
                    {
                        if (IsTouchingButton(ref x, ref y, ref aButtonCollision))
                        {
                            aTouch = t;
                            continue;
                        }
                    }
                    #endregion

                    #region B button
                    if (t.Id == bId)
                    {
                        bTouch = t; continue;
                    }
                    if (bId == -1)
                    {
                        if (IsTouchingButton(ref x, ref y, ref bButtonCollision))
                        {
                            bTouch = t;
                            continue;
                        }
                    }
                    #endregion
                }
                else
                {
                    if (CurrentWeapon == WeaponType.Range)
                    {
                        if (t.Id == rightId)
                        {
                            rightTouch = t;
                            continue;
                        }
                        if (rightId == -1)
                        {
                            if (IsTouchingRightStick(t.Position))
                            {
                                rightTouch = t;
                                continue;
                            }
                        }
                    }
                    else
                    {
                        if (t.Id == fireId)
                        {
                            fireTouch = t;
                            continue;
                        }
                        if (fireId == -1)
                        {
                            if (IsTouchingButton(ref x, ref y, ref fireButtonCollision))
                            {
                                fireTouch = t;
                                continue;
                            }
                        }
                    }
                }
                #endregion
            }

            #region Left Stick
            if (leftTouch.HasValue)
            {
                LeftThumbPosition = new Vector2(
                    leftTouch.Value.Position.X - thumbTexture.Width / 2,
                    leftTouch.Value.Position.Y - thumbTexture.Height / 2);

                LeftThumbPosition = Vector2.Clamp(LeftThumbPosition, minLeft, maxLeft);
                leftId            = leftTouch.Value.Id;
            }
            else
            {
                leftId             = -1;
                LeftThumbPosition += (LeftThumbOriginalPosition - LeftThumbPosition) * 0.9f;
            }
            #endregion

            #region Right Stick
            if (rightTouch.HasValue)
            {
                RightThumbPosition = new Vector2(
                    rightTouch.Value.Position.X - thumbTexture.Width / 2,
                    rightTouch.Value.Position.Y - thumbTexture.Height / 2);

                RightThumbPosition = Vector2.Clamp(RightThumbPosition, minRight, maxRight);
                rightId            = rightTouch.Value.Id;
            }
            else
            {
                rightId             = -1;
                RightThumbPosition += (RightThumbOriginalPosition - RightThumbPosition) * 0.9f;
            }
            #endregion

            #region fireTouch
            if (fireTouch.HasValue)
            {
                FireButtonPressed = true;
            }
            else
            {
                fireId            = -1;
                FireButtonPressed = false;
            }
            #endregion

            #region x Touch
            if (xTouch.HasValue)
            {
                xPressed = ButtonState.Pressed;
                xColor   = Color.White;
            }
            else
            {
                xId      = -1;
                xPressed = ButtonState.Released;
                xColor   = Color.LightGray;
            }
            #endregion

            #region y Touch
            if (yTouch.HasValue)
            {
                yPressed = ButtonState.Pressed;
                yColor   = Color.White;
            }
            else
            {
                yId      = -1;
                yPressed = ButtonState.Released;
                yColor   = Color.LightGray;
            }
            #endregion

            #region a Touch
            if (aTouch.HasValue)
            {
                aPressed = ButtonState.Pressed;
                aColor   = Color.White;
            }
            else
            {
                aId      = -1;
                aPressed = ButtonState.Released;
                aColor   = Color.LightGray;
            }
            #endregion

            #region b Touch
            if (bTouch.HasValue)
            {
                bPressed = ButtonState.Pressed;
                bColor   = Color.White;
            }
            else
            {
                bId      = -1;
                bPressed = ButtonState.Released;
                bColor   = Color.LightGray;
            }
            #endregion
#endif
        }
Exemplo n.º 25
0
        public void Update(double time)
        {
            _mapManager.Update(time);
            _mapView.Update(time);

            MouseState mouse   = Mouse.GetState();
            var        oldZoom = Settings.Zoom;

            Settings.Zoom = 1f + (Settings.Zoom * mouse.ScrollWheelValue / 1000); //(mouse.ScrollWheelValue != 0 ? mouse.ScrollWheelValue / 1200f : 0);


            var touches = TouchPanel.GetState().ToList();

            //touches.RemoveAll(x => x.Pressure == 0);
            if (touches.Any() && _touches.Any())
            {
                if (touches.Count > 1 && _touches.Count > 1)
                {
                    var touch1 = touches.First();
                    var touch2 = touches[1];

                    var oldTouch1 = _touches.First();
                    var oldTouch2 = _touches[1];

                    Vector2 a    = touch1.Position;
                    Vector2 b    = touch2.Position;
                    float   dist = Vector2.Distance(a, b);

                    // prior positions
                    Vector2 aOld    = oldTouch1.Position;
                    Vector2 bOld    = oldTouch2.Position;
                    float   distOld = Vector2.Distance(aOld, bOld);

                    _pinchDistance = 0;
                    if (dist != distOld && Math.Abs(distOld - dist) > 1)
                    {
                        _pinchDistance = distOld - dist;
                        float scale = -(distOld - dist) * 0.1f;
                        Settings.Zoom += scale;

                        _mapView.Resize();
                    }

                    //var center = (touch1.Position - touch2.Position) / 2;
                    //_mapView.SetOffset((int)center.X, (int)center.Y);
                }
                else
                {
                    //Move
                    var touch    = touches.First();
                    var oldTouch = _touches.First();
                    var position = oldTouch.Position - touch.Position;
                    _mapView.SetOffset(-(int)position.X, -(int)position.Y);

                    _mapView.Move();
                }
            }
            _touches = touches;

            if (Settings.Zoom > 4)
            {
                Settings.Zoom = 4;
            }
            else if (Settings.Zoom < 0.5f)
            {
                Settings.Zoom = 0.5f;
            }

            if (oldZoom != Settings.Zoom)
            {
                _mapView.Resize();
            }
        }
Exemplo n.º 26
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(cat);
                        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;
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Updates and fires input events for a touch device.
        /// </summary>
        /// <param name="gameContext">
        /// The game context.
        /// </param>
        private void UpdateTouch(IGameContext gameContext)
        {
            var touchState = TouchPanel.GetState();

            if (this.m_LastTouchPanelState != null)
            {
                // Detect press events.
                foreach (var touch in touchState)
                {
                    var hasPrevious = false;

                    // Is there any previous touch event within 100 pixels?
                    foreach (var previousTouch in this.m_LastTouchPanelState.Value)
                    {
                        if ((previousTouch.Position - touch.Position).Length() < 100)
                        {
                            hasPrevious = true;
                            break;
                        }
                    }

                    if (!hasPrevious)
                    {
                        // There is no previous touch near this location, therefore
                        // it's a press event.
                        this._eventEngine.Fire(
                            gameContext,
                            new TouchPressEvent
                        {
                            X = touch.Position.X,
                            Y = touch.Position.Y,
                            TouchLocationState = touch.State
                        });
                    }
                }

                // Detect release events.
                foreach (var previousTouch in this.m_LastTouchPanelState.Value)
                {
                    var hasCurrent = false;

                    // Is there any current touch event within 100 pixels?
                    foreach (var touch in touchState)
                    {
                        if ((previousTouch.Position - touch.Position).Length() < 100)
                        {
                            hasCurrent = true;
                            break;
                        }
                    }

                    if (!hasCurrent)
                    {
                        // There is no longer any touch events in this location, so
                        // raise a release event.
                        this._eventEngine.Fire(
                            gameContext,
                            new TouchReleaseEvent
                        {
                            X = previousTouch.Position.X,
                            Y = previousTouch.Position.Y,
                            TouchLocationState = previousTouch.State
                        });
                    }
                }
            }

            foreach (var touch in touchState)
            {
                this._eventEngine.Fire(
                    gameContext,
                    new TouchHeldEvent
                {
                    X                  = touch.Position.X,
                    Y                  = touch.Position.Y,
                    Pressure           = touch.Pressure,
                    TouchLocationState = touch.State
                });
            }

            this.m_LastTouchPanelState = touchState;
        }
Exemplo n.º 28
0
        public override State Update(GameTime gameTime)
        {
            if (Menu)
            {
                TouchCollection touchCollection = TouchPanel.GetState();
                foreach (TouchLocation tl in touchCollection)
                {
                    if (tl.State == TouchLocationState.Pressed)
                    {
                        if (new Rectangle((int)playLocation.X, (int)playLocation.Y, (int)ButtonSize.X, (int)ButtonSize.Y).Contains((int)tl.Position.X, (int)tl.Position.Y))
                        {
                            playLocation.Y += 5;
                        }
                    }

                    if (tl.State == TouchLocationState.Released)
                    {
                        if (new Rectangle((int)playLocation.X, (int)playLocation.Y, (int)ButtonSize.X, (int)ButtonSize.Y).Contains((int)tl.Position.X, (int)tl.Position.Y))
                        {
                            playLocation.Y -= 5;
                            Menu            = false;
                            IsGameOver      = false;
                            GetReadE        = true;
                            buttonSound.Play();
                        }
                    }
                }

                obstacles.Update(gameTime, 0);
            }

            else
            {
                if (GetReadE)
                {
                    TouchCollection touchCollection = TouchPanel.GetState();
                    foreach (TouchLocation tl in touchCollection)
                    {
                        if (tl.State == TouchLocationState.Released)
                        {
                            buttonSound.Play();
                            GetReadE = false;
                        }
                    }
                    obstacles.Update(gameTime, 0);
                }

                else //The actual game loop
                {
                    if (IsGameOver)
                    {
                        GameOverLocation.Y   = TransitionY((viewport.Height / 30), viewport.Height / 4, GameOverLocation.Y);
                        ScoreboardLocation.Y = TransitionY(-(viewport.Height / 30), GameOverLocation.Y + GameOverSize.Y + viewport.Height / 20, ScoreboardLocation.Y);
                        playLocation.Y       = ScoreboardLocation.Y + ScoreboardSize.Y + viewport.Height / 20;

                        TouchCollection touchCollection = TouchPanel.GetState();
                        foreach (TouchLocation tl in touchCollection)
                        {
                            if (tl.State == TouchLocationState.Pressed)
                            {
                                if (new Rectangle((int)playLocation.X, (int)playLocation.Y, (int)ButtonSize.X, (int)ButtonSize.Y).Contains((int)tl.Position.X, (int)tl.Position.Y))
                                {
                                    playLocation.Y += 5;
                                }
                            }

                            if (tl.State == TouchLocationState.Released)
                            {
                                if (new Rectangle((int)playLocation.X, (int)playLocation.Y, (int)ButtonSize.X, (int)ButtonSize.Y).Contains((int)tl.Position.X, (int)tl.Position.Y))
                                {
                                    buttonSound.Play();

                                    playLocation.Y -= 5;

                                    player = new Player(viewport);
                                    player.LoadContent(content);

                                    obstacles = new Obstacles(viewport);
                                    obstacles.LoadContent(content);

                                    score.score = 0;

                                    Menu       = false;
                                    IsGameOver = false;
                                    GetReadE   = true;
                                }
                            }
                        }

                        obstacles.Update(gameTime, 0);
                    }

                    else
                    {
                        TouchCollection touchCollection = TouchPanel.GetState();
                        foreach (TouchLocation tl in touchCollection)
                        {
                            if (tl.State == TouchLocationState.Released)
                            {
                                buttonSound.Play();
                                player.TapUpdate();
                            }
                        }
                        obstacles.Update(gameTime, 4);
                        player.Update(gameTime);

                        if (PlayerIsRekt())
                        {
                            IsGameOver = true;
                            score.saveScore();
                        }
                    }
                }
            }
            return(this);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Read keyboard and gamepad input
        /// </summary>
        private void HandleInput(float elapsedTime)
        {
            previousGamePadState  = currentGamePadState;
            previousKeyboardState = currentKeyboardState;
            currentGamePadState   = GamePad.GetState(PlayerIndex.One);
            currentKeyboardState  = Keyboard.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;
                }
            }

            // 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));
            }
        }
Exemplo n.º 30
0
        void UpdateInput()
        {
#if WINDOWS_PHONE
            TouchCollection touchCollection = TouchPanel.GetState();

            bool idStillValid = false;
            if (Finger1Valid)
            {
                foreach (TouchLocation touch in touchCollection)
                {
                    if (touch.Id == Finger1.id)
                    {
                        idStillValid = true;
                        break;
                    }
                }
                if (!idStillValid)
                {
                    Finger1.id = -1;
                }
            }
            idStillValid = false;
            if (Finger2Valid)
            {
                foreach (TouchLocation touch in touchCollection)
                {
                    if (touch.Id == Finger2.id)
                    {
                        idStillValid = true;
                        break;
                    }
                }
                if (!idStillValid)
                {
                    Finger2.id = -1;
                }
            }

            foreach (TouchLocation touch in touchCollection)
            {
                if ((!Finger1Valid || Finger1.id == touch.Id) && Finger2.id != touch.Id)
                {
                    Finger1.id        = touch.Id;
                    Finger1.FingerPos = touch.Position;
                }
                if ((!Finger2Valid || Finger2.id == touch.Id) && Finger1.id != touch.Id)
                {
                    Finger2.id        = touch.Id;
                    Finger2.FingerPos = touch.Position;
                }
            }

            Finger1.FingerPos /= BaseGame.Get.BackBufferDimensions;
            Finger2.FingerPos /= BaseGame.Get.BackBufferDimensions;

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                OnBackPressed();
            }
#endif

            MouseState mouseState = Mouse.GetState();

            Point lastPoint = new Point(lastMouseState.X, lastMouseState.Y);
            Point point     = new Point(mouseState.X, mouseState.Y);

            if (lastPoint != point)
            {
                OnMouseMove(point);
            }

            if (lastMouseState.LeftButton != mouseState.LeftButton)
            {
                if (mouseState.LeftButton == ButtonState.Pressed)
                {
                    OnMouseDown(point);
                }
                else
                {
                    OnMouseUp(point);
                }
            }

            MouseDrag(point);



#if WINDOWS
            int dif = mouseState.ScrollWheelValue - lastMouseState.ScrollWheelValue;
            if (dif != 0)
            {
                OnMouseScroll(dif);
            }
#endif

            lastMouseState = mouseState;
        }