コード例 #1
0
        private void UpdateKeys(KeyboardState state, GameTime gameTime)
        {
#if (!XBOX && !XBOX_FAKE)
            KeyEventArgs e = new KeyEventArgs();

            e.Caps = (((ushort)NativeMethods.GetKeyState(0x14)) & 0xffff) != 0;

            foreach (Keys key in state.GetPressedKeys())
            {
                if (key == Keys.LeftAlt || key == Keys.RightAlt)
                {
                    e.Alt = true;
                }
                else if (key == Keys.LeftShift || key == Keys.RightShift)
                {
                    e.Shift = true;
                }
                else if (key == Keys.LeftControl || key == Keys.RightControl)
                {
                    e.Control = true;
                }
            }

            foreach (InputKey key in keys)
            {
                if (key.Key == Keys.LeftAlt || key.Key == Keys.RightAlt ||
                    key.Key == Keys.LeftShift || key.Key == Keys.RightShift ||
                    key.Key == Keys.LeftControl || key.Key == Keys.RightControl)
                {
                    continue;
                }

                bool pressed = state.IsKeyDown(key.Key);

                double ms = gameTime.ElapsedGameTime.TotalMilliseconds;
                if (pressed)
                {
                    key.Countdown -= ms;
                }

                if ((pressed) && (!key.Pressed))
                {
                    key.Pressed = true;
                    e.Key       = key.Key;

                    if (KeyDown != null)
                    {
                        KeyDown.Invoke(this, e);
                    }
                    if (KeyPress != null)
                    {
                        KeyPress.Invoke(this, e);
                    }
                }
                else if ((!pressed) && (key.Pressed))
                {
                    key.Pressed   = false;
                    key.Countdown = RepeatDelay;
                    e.Key         = key.Key;

                    if (KeyUp != null)
                    {
                        KeyUp.Invoke(this, e);
                    }
                }
                else if (key.Pressed && key.Countdown < 0)
                {
                    key.Countdown = RepeatRate;
                    e.Key         = key.Key;

                    if (KeyPress != null)
                    {
                        KeyPress.Invoke(this, e);
                    }
                }
            }
#endif
        }
コード例 #2
0
        /// <summary>Get the buttons pressed in the given stats.</summary>
        /// <param name="keyboard">The keyboard state.</param>
        /// <param name="mouse">The mouse state.</param>
        /// <param name="controller">The controller state.</param>
        /// <remarks>Thumbstick direction logic derived from <see cref="ButtonCollection"/>.</remarks>
        private IEnumerable <SButton> GetPressedButtons(KeyboardState keyboard, MouseState mouse, GamePadState controller)
        {
            // keyboard
            foreach (Keys key in keyboard.GetPressedKeys())
            {
                yield return(key.ToSButton());
            }

            // mouse
            if (mouse.LeftButton == ButtonState.Pressed)
            {
                yield return(SButton.MouseLeft);
            }
            if (mouse.RightButton == ButtonState.Pressed)
            {
                yield return(SButton.MouseRight);
            }
            if (mouse.MiddleButton == ButtonState.Pressed)
            {
                yield return(SButton.MouseMiddle);
            }
            if (mouse.XButton1 == ButtonState.Pressed)
            {
                yield return(SButton.MouseX1);
            }
            if (mouse.XButton2 == ButtonState.Pressed)
            {
                yield return(SButton.MouseX2);
            }

            // controller
            if (controller.IsConnected)
            {
                // main buttons
                if (controller.Buttons.A == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerA);
                }
                if (controller.Buttons.B == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerB);
                }
                if (controller.Buttons.X == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerX);
                }
                if (controller.Buttons.Y == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerY);
                }
                if (controller.Buttons.LeftStick == ButtonState.Pressed)
                {
                    yield return(SButton.LeftStick);
                }
                if (controller.Buttons.RightStick == ButtonState.Pressed)
                {
                    yield return(SButton.RightStick);
                }
                if (controller.Buttons.Start == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerStart);
                }

                // directional pad
                if (controller.DPad.Up == ButtonState.Pressed)
                {
                    yield return(SButton.DPadUp);
                }
                if (controller.DPad.Down == ButtonState.Pressed)
                {
                    yield return(SButton.DPadDown);
                }
                if (controller.DPad.Left == ButtonState.Pressed)
                {
                    yield return(SButton.DPadLeft);
                }
                if (controller.DPad.Right == ButtonState.Pressed)
                {
                    yield return(SButton.DPadRight);
                }

                // secondary buttons
                if (controller.Buttons.Back == ButtonState.Pressed)
                {
                    yield return(SButton.ControllerBack);
                }
                if (controller.Buttons.BigButton == ButtonState.Pressed)
                {
                    yield return(SButton.BigButton);
                }

                // shoulders
                if (controller.Buttons.LeftShoulder == ButtonState.Pressed)
                {
                    yield return(SButton.LeftShoulder);
                }
                if (controller.Buttons.RightShoulder == ButtonState.Pressed)
                {
                    yield return(SButton.RightShoulder);
                }

                // triggers
                if (controller.Triggers.Left > 0.2f)
                {
                    yield return(SButton.LeftTrigger);
                }
                if (controller.Triggers.Right > 0.2f)
                {
                    yield return(SButton.RightTrigger);
                }

                // left thumbstick direction
                if (controller.ThumbSticks.Left.Y > SInputState.LeftThumbstickDeadZone)
                {
                    yield return(SButton.LeftThumbstickUp);
                }
                if (controller.ThumbSticks.Left.Y < -SInputState.LeftThumbstickDeadZone)
                {
                    yield return(SButton.LeftThumbstickDown);
                }
                if (controller.ThumbSticks.Left.X > SInputState.LeftThumbstickDeadZone)
                {
                    yield return(SButton.LeftThumbstickRight);
                }
                if (controller.ThumbSticks.Left.X < -SInputState.LeftThumbstickDeadZone)
                {
                    yield return(SButton.LeftThumbstickLeft);
                }

                // right thumbstick direction
                if (this.IsRightThumbstickOutsideDeadZone(controller.ThumbSticks.Right))
                {
                    if (controller.ThumbSticks.Right.Y > 0)
                    {
                        yield return(SButton.RightThumbstickUp);
                    }
                    if (controller.ThumbSticks.Right.Y < 0)
                    {
                        yield return(SButton.RightThumbstickDown);
                    }
                    if (controller.ThumbSticks.Right.X > 0)
                    {
                        yield return(SButton.RightThumbstickRight);
                    }
                    if (controller.ThumbSticks.Right.X < 0)
                    {
                        yield return(SButton.RightThumbstickLeft);
                    }
                }
            }
        }
コード例 #3
0
        public List <QueuedInput> GetInputQueue()
        {
            QueueLock.WaitOne();
            var r = Queued;

            Queued = new List <QueuedInput>();
            var now = DateTime.Now;

            // Generate mouse events.
            var newMouseState    = Mouse.GetState();
            var newKeyboardState = Keyboard.GetState();

            if (newMouseState.X != OldMouseState.X || newMouseState.Y != OldMouseState.Y)
            {
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseMove,
                    Args    = new InputEventArgs
                    {
                        X       = newMouseState.X,
                        Y       = newMouseState.Y,
                        Alt     = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift   = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }

            if (newMouseState.LeftButton == ButtonState.Pressed && OldMouseState.LeftButton == ButtonState.Released)
            {
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseDown,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 0,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }

            if (newMouseState.LeftButton == ButtonState.Released && OldMouseState.LeftButton == ButtonState.Pressed)
            {
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseUp,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 0,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseClick,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 0,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }


            if (newMouseState.RightButton == ButtonState.Pressed && OldMouseState.RightButton == ButtonState.Released)
            {
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseDown,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 1,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }

            if (newMouseState.RightButton == ButtonState.Released && OldMouseState.RightButton == ButtonState.Pressed)
            {
                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseUp,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 1,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });

                r.Add(new QueuedInput
                {
                    Message = InputEvents.MouseClick,
                    Args    = new InputEventArgs
                    {
                        X           = newMouseState.X,
                        Y           = newMouseState.Y,
                        MouseButton = 1,
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }

            if (newMouseState.ScrollWheelValue != OldMouseState.ScrollWheelValue)
            {
                r.Add(new QueuedInput()
                {
                    Message = InputEvents.MouseWheel,
                    Args    = new InputEventArgs()
                    {
                        ScrollValue = (newMouseState.ScrollWheelValue - OldMouseState.ScrollWheelValue),
                        Alt         = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                        Shift       = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                        Control     = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                    }
                });
            }

            OldMouseState = newMouseState;


            foreach (var key in newKeyboardState.GetPressedKeys())
            {
                if (!OldKeyboardState.IsKeyDown(key))
                {
                    r.Add(new QueuedInput
                    {
                        Message = InputEvents.KeyDown,
                        Args    = new InputEventArgs
                        {
                            KeyValue = (int)key,
                            Alt      = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                            Shift    = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                            Control  = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                        }
                    });

                    PressedTime[key] = now;
                }
                else
                {
                    if (PressedTime.ContainsKey(key) && (now - PressedTime[key]).TotalSeconds > GameSettings.Current.FNAONLY_KeyRepeatRate)
                    {
                        PressedTime[key] = now;

                        r.Add(new QueuedInput
                        {
                            Message = InputEvents.KeyDown,
                            Args    = new InputEventArgs
                            {
                                KeyValue = (int)key,
                                Alt      = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                                Shift    = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                                Control  = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                            }
                        });
                    }
                }
            }

            foreach (var key in OldKeyboardState.GetPressedKeys())
            {
                if (!newKeyboardState.IsKeyDown(key))
                {
                    r.Add(new QueuedInput
                    {
                        Message = InputEvents.KeyUp,
                        Args    = new InputEventArgs
                        {
                            KeyValue = (int)key,
                            Alt      = newKeyboardState.IsKeyDown(Keys.LeftAlt) || newKeyboardState.IsKeyDown(Keys.RightAlt),
                            Shift    = newKeyboardState.IsKeyDown(Keys.LeftShift) || newKeyboardState.IsKeyDown(Keys.RightShift),
                            Control  = newKeyboardState.IsKeyDown(Keys.LeftControl) || newKeyboardState.IsKeyDown(Keys.RightControl)
                        }
                    });

                    if (key == Keys.OemTilde)
                    {
                        ConsoleTogglePressed = true;
                    }

                    if (PressedTime.ContainsKey(key))
                    {
                        PressedTime.Remove(key);
                    }
                }
            }

            OldKeyboardState = newKeyboardState;

            QueueLock.ReleaseMutex();
            return(r);
        }
コード例 #4
0
 public bool IsAnyKeyPressed()
 {
     return(curKeyboardState.GetPressedKeys().Length > 0);
 }
コード例 #5
0
        private Enumeration.Input GetKeyboardInput(KeyboardState keyboardState)
        {
            Enumeration.Input input = Enumeration.Input.none;

            if (keyboardState.GetPressedKeys().Count() == 0)
            {
                return(input);
            }

            Keys?shiftKey = null;

            //////////
            //SHIFT SUBST FOR LEFT OR RIGHT SHIFT
            //////////
            for (int x = 0; x < keyboardState.GetPressedKeys().Count(); x++)
            {
                if (keyboardState.GetPressedKeys()[x] == Keys.LeftShift)
                {
                    shiftKey = Keys.LeftShift;
                    continue;
                }
                if (keyboardState.GetPressedKeys()[x] == Keys.RightShift)
                {
                    shiftKey = Keys.LeftShift;
                }
            }


            if (keyboardState.GetPressedKeys().Count() == 1 & shiftKey == Keys.LeftShift)
            {
                return(Enumeration.Input.shift);
            }

            //////////
            //LEFT
            //////////
            if (keyboardState.IsKeyDown(Keys.Up) & keyboardState.IsKeyDown(Keys.Left))
            {
                return(Enumeration.Input.leftup);
            }

            if (keyboardState.IsKeyDown(Keys.Down) & keyboardState.IsKeyDown(Keys.Left))
            {
                return(Enumeration.Input.leftdown);
            }

            if (keyboardState.IsKeyDown(Keys.Left) & (shiftKey == Keys.LeftShift))
            {
                return(Enumeration.Input.leftshift);
            }

            if (keyboardState.IsKeyDown(Keys.Left) || keyboardState.IsKeyDown(Keys.A))
            {
                return(Enumeration.Input.left);
            }

            //////////
            //RIGHT
            //////////
            if (keyboardState.IsKeyDown(Keys.Up) & keyboardState.IsKeyDown(Keys.Right) || keyboardState.IsKeyDown(Keys.E))
            {
                return(Enumeration.Input.rightup);
            }

            if (keyboardState.IsKeyDown(Keys.Down) & keyboardState.IsKeyDown(Keys.Right) || keyboardState.IsKeyDown(Keys.C))
            {
                return(Enumeration.Input.righdown);
            }

            if (keyboardState.IsKeyDown(Keys.Right) & shiftKey == Keys.LeftShift)
            {
                return(Enumeration.Input.rightshift);
            }

            if (keyboardState.IsKeyDown(Keys.Right) || keyboardState.IsKeyDown(Keys.D))
            {
                return(Enumeration.Input.right);
            }
            //////
            //UP//
            //////

            if (keyboardState.IsKeyDown(Keys.Up) || keyboardState.IsKeyDown(Keys.W))
            {
                return(Enumeration.Input.up);
            }
            ///////
            //DOWN/
            ///////
            if (keyboardState.IsKeyDown(Keys.Down) || keyboardState.IsKeyDown(Keys.S))
            {
                return(Enumeration.Input.down);
            }

            ////////
            //NONE//
            return(Enumeration.Input.none);
        }
コード例 #6
0
        //Will return the next state of the menu
        public MenuState NextState(MenuState currentState, MouseState mouseState, MouseState previousMouseState)
        {
            //Gets the current state of the keyboard
            //Gets the current and previous state of the mouse
            kbState        = Keyboard.GetState();
            mState         = mouseState;
            previousMState = previousMouseState;

            //Switch case for the menu state
            switch (currentState)
            {
            case MenuState.Title:     //If the menu is on the instructions screen
                if (SingleMouseClick() || kbState.GetPressedKeys().Length > 0)
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Main;
                }
                break;

            case MenuState.Instructions:     //If the menu is on the instructions screen
                if (back.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Main;
                }
                break;

            case MenuState.Main:     //If you are at the main menu
                if (instructions.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Instructions;
                }
                else if (start.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    ResetPortraits(4);
                    //Change this once selection screen is implemented
                    currentState = MenuState.Selection;
                }
                else if (quit.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Quit;
                }
                else if (creditButton.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Credits;
                }
                break;

            case MenuState.Selection:     //If you are on the selection screen
                if (play.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Start;
                }
                else if (options.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Options;
                }
                else if (selectBack.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Main;
                }
                break;

            case MenuState.Options:     //If you are on the options screen
                CheckOptions();
                if (back.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Selection;
                }
                break;

            case MenuState.Credits:     //If you are on the credits screen
                if (back.MouseHovering(mState.X, mState.Y) && SingleMouseClick())
                {
                    clickSound.CreateInstance().Play();
                    currentState = MenuState.Main;
                }
                break;
            }
            previousKbState = kbState;
            return(currentState);
        }
コード例 #7
0
ファイル: DebugCommandUI.cs プロジェクト: hoangvantu/Gem
        /// <summary>
        /// Handle keyboard input.
        /// </summary>
        /// <param name="dt"></param>
        public void ProcessKeyInputs(float dt)
        {
            KeyboardState keyState = Keyboard.GetState();

            Keys[] keys = keyState.GetPressedKeys();

            bool shift = keyState.IsKeyDown(Keys.LeftShift) ||
                         keyState.IsKeyDown(Keys.RightShift);

            foreach (Keys key in keys)
            {
                if (!IsKeyPressed(key, dt))
                {
                    continue;
                }

                char ch;
                if (KeyboardUtils.KeyToString(key, shift, out ch))
                {
                    // Handle typical character input.
                    commandLine = commandLine.Insert(cursorIndex, new string(ch, 1));
                    cursorIndex++;
                }
                else
                {
                    switch (key)
                    {
                    case Keys.Back:
                        if (cursorIndex > 0)
                        {
                            commandLine = commandLine.Remove(--cursorIndex, 1);
                        }
                        break;

                    case Keys.Delete:
                        if (cursorIndex < commandLine.Length)
                        {
                            commandLine = commandLine.Remove(cursorIndex, 1);
                        }
                        break;

                    case Keys.Left:
                        if (cursorIndex > 0)
                        {
                            cursorIndex--;
                        }
                        break;

                    case Keys.Right:
                        if (cursorIndex < commandLine.Length)
                        {
                            cursorIndex++;
                        }
                        break;

                    case Keys.Enter:
                        // Run the command.
                        ExecuteCommand(commandLine);
                        commandLine = string.Empty;
                        cursorIndex = 0;
                        break;

                    case Keys.Up:
                        // Show command history.
                        if (commandHistory.Count > 0)
                        {
                            commandHistoryIndex =
                                Math.Max(0, commandHistoryIndex - 1);

                            commandLine = commandHistory[commandHistoryIndex];
                            cursorIndex = commandLine.Length;
                        }
                        break;

                    case Keys.Down:
                        // Show command history.
                        if (commandHistory.Count > 0)
                        {
                            commandHistoryIndex = Math.Min(commandHistory.Count - 1,
                                                           commandHistoryIndex + 1);
                            commandLine = commandHistory[commandHistoryIndex];
                            cursorIndex = commandLine.Length;
                        }
                        break;

                    case Keys.Tab:
                        Hide();
                        break;
                    }
                }
            }
        }
 private static IEnumerable <Keys> GetPressedKeys(KeyboardState keyboard)
 => keyboard.GetPressedKeys().Where(key => key != Keys.None);
コード例 #9
0
ファイル: InputManager.cs プロジェクト: PulsarcGame/Pulsarc
        static public void InputUpdater()
        {
            var running            = true;
            var threadLimiterWatch = new Stopwatch();

            threadLimiterWatch.Start();

            while (running)
            {
                Thread.Yield();
                if (threadLimiterWatch.ElapsedMilliseconds >= 1)
                {
                    threadLimiterWatch.Restart();

                    try
                    {
                        KeyboardState = Keyboard.GetState();
                        MouseState    = Mouse.GetState();

                        if (KeyboardState.GetPressedKeys().Count() > 0)
                        {
                            foreach (Keys key in KeyboardState.GetPressedKeys())
                            {
                                if (!PressedKeys.Contains(key))
                                {
                                    PressActions.Enqueue(new KeyValuePair <double, Keys>(AudioManager.GetTime(), key));
                                    PressedKeys.Add(key);

                                    if (key == Keys.CapsLock)
                                    {
                                        CapsLock = !CapsLock;
                                        Caps     = CapsLock;
                                    }

                                    if (key == Keys.LeftShift || key == Keys.RightShift)
                                    {
                                        Caps = !CapsLock;
                                    }
                                }
                            }
                        }

                        for (int i = 0; i < PressedKeys.Count; i++)
                        {
                            Keys key = PressedKeys[i];

                            if (!KeyboardState.IsKeyDown(key))
                            {
                                // Used if LN handling
                                //keyboardReleases.Enqueue(new KeyValuePair<double, Keys>(time, key));
                                PressedKeys.RemoveAt(i);
                                i--;


                                if (key == Keys.LeftShift || key == Keys.RightShift)
                                {
                                    Caps = CapsLock;
                                }
                            }
                        }

                        if (LastMouseClick.Value == 0 && MouseState.LeftButton == ButtonState.Pressed)
                        {
                            LastMouseClick.Key   = MouseState;
                            LastMouseClick.Value = 1;
                        }
                        else if (LastMouseClick.Value == 1 && MouseState.LeftButton == ButtonState.Released)
                        {
                            LastMouseClick.Key   = MouseState;
                            LastMouseClick.Value = 2;
                        }
                    }
                    catch { }
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Reads the keyboard state using the <see cref="GameTime"/> from the update frame.
        /// </summary>
        /// <param name="gameTime"></param>
        public void Update(GameTime gameTime)
        {
            KeysPressedInternal.Clear();
            KeysReleasedInternal.Clear();

            // Cycle all the keys down known if any are up currently, remove them from KeysDownInternal
            _state = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            bool shiftPressed = _state.IsKeyDown(Keys.LeftShift) || _state.IsKeyDown(Keys.RightShift);

            Keys[] unmappedVirtualKeys = _state.GetPressedKeys();

            for (int i = 0; i < KeysDownInternal.Count;)
            {
                if (_state.IsKeyUp(UnmappedVirtualKeysDown[i]))
                {
                    KeysReleasedInternal.Add(KeysDownInternal[i]);
                    RemoveKeyDownAt(i);
                }
                else
                {
                    i++;
                }
            }

            // KeysDownInternal now contains all the keys that are currently down except potentially newly pressed keys
            // however the shift state may have changed so if there was an 'a' previously and the shift key was
            // just pressed, then the 'a' needs to get replaced with 'A'.

            // For all new keys down, if we don't know them, add them to pressed, add them to down.
            foreach (Keys unmappedVirtualKey in unmappedVirtualKeys)
            {
                bool firstPressed = false;

                AsciiKey key = new AsciiKey();
                AsciiKey keyOppositeShift = new AsciiKey();
                int      activeKeyIndex   = -1;

                // These keys will be mapped since Fill does the mapping automatically
                key.Fill(unmappedVirtualKey, shiftPressed, _state);
                keyOppositeShift.Fill(unmappedVirtualKey, !shiftPressed, _state);

                if (KeysDownInternal.Contains(key))
                {
                    activeKeyIndex = KeysDownInternal.FindIndex(k => k == key);
                    AsciiKey thisKey = KeysDownInternal[activeKeyIndex];
                    thisKey.TimeHeld += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    KeysDownInternal[activeKeyIndex] = thisKey;
                }
                else if (KeysDownInternal.Contains(keyOppositeShift))
                {
                    activeKeyIndex = KeysDownInternal.FindIndex(k => k == keyOppositeShift);
                    AsciiKey thisKey = KeysDownInternal[activeKeyIndex];
                    thisKey.Character = key.Character;
                    thisKey.TimeHeld += (float)gameTime.ElapsedGameTime.TotalSeconds;
                    KeysDownInternal[activeKeyIndex] = thisKey;
                }
                else
                {
                    // The physical key (independent of shift) for this character was not being pressed before
                    // so add it in.
                    firstPressed   = true;
                    activeKeyIndex = KeysDownInternal.Count;
                    AddKeyDown(key, unmappedVirtualKey);
                }

                AsciiKey activeKey = KeysDownInternal[activeKeyIndex];

                if (firstPressed)
                {
                    KeysPressedInternal.Add(activeKey);
                }
                else if (activeKey.PostInitialDelay == false && activeKey.TimeHeld >= InitialRepeatDelay)
                {
                    activeKey.PostInitialDelay = true;
                    activeKey.TimeHeld         = 0f;
                    KeysPressedInternal.Add(activeKey);
                    KeysDownInternal[activeKeyIndex] = activeKey;
                }
                else if (activeKey.PostInitialDelay && activeKey.TimeHeld >= RepeatDelay)
                {
                    activeKey.TimeHeld = 0f;
                    KeysPressedInternal.Add(activeKey);
                    KeysDownInternal[activeKeyIndex] = activeKey;
                }
            }
        }
コード例 #11
0
        protected override void Update(GameTime gameTime)
        {
            keyState = Keyboard.GetState();
            Keys[] pressedKeys = keyState.GetPressedKeys();

            if (keyState.IsKeyUp(Keys.Enter))
            {
                EnterKeyHasBeenUp = true;
            }

            // Allows the game to exit
            if (keyState.IsKeyDown(Keys.Escape) && !oldState.IsKeyDown(Keys.Escape))
            {
                if (StateOfGame != GameState.Credits)
                {
                    StateOfGame = GameState.Credits;
                }
                else
                {
                    this.Exit();
                }
            }

            if ((keyState.IsKeyDown(Keys.LeftAlt) && keyState.IsKeyDown(Keys.Enter)) && !(oldState.IsKeyDown(Keys.LeftAlt) && oldState.IsKeyDown(Keys.Enter)))
            {
                graphics.ToggleFullScreen();
                return;
            }

            // Allows the developers to fastforward to next level
            if (keyState.IsKeyDown(Keys.N) && !oldState.IsKeyDown(Keys.N) && keyState.IsKeyDown(Keys.LeftControl))
            {
                BeginLevel();
            }


            //<<<<<<< .mine=======
            for (int i = 0; i < pops.Count; i++)
            {
                pops[i].Timeout -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                //>>>>>>> .theirs/
                //<<<<<<< .mine
                //=======
                if (pops[i].Timeout < 0)
                {
                    pops.Remove(pops[i]);
                }
            }

            //>>>>>>> .theirs
            switch (StateOfGame)
            {
            case GameState.Introduction:
                if (EnterKeyHasBeenUp && keyState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter))
                {
                    sound_music_intro.Stop();
                    sound_music_a.Play();
                    BeginLevel();
                }

                if (keyState.IsKeyDown(Keys.F1) && !oldState.IsKeyDown(Keys.F1))
                {
                    StateOfGame = GameState.Help;
                }
                break;


            case GameState.Help:
                if (keyState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter))
                {
                    StateOfGame = GameState.Introduction;
                }
                break;

            case GameState.Playing:

                #region Playing



                if ((keyState.IsKeyDown(Keys.Pause) && !oldState.IsKeyDown(Keys.Pause)) || (keyState.IsKeyDown(Keys.P) && !oldState.IsKeyDown(Keys.P)))
                {
                    StateOfGame = GameState.Paused;
                    sound_music_a.Pause();
                }

                millisecondsToNextPointPayout -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;

                if (millisecondsToNextPointPayout <= 0)
                {
                    AddPoints(Adversary[hunter]);
                    millisecondsToNextPointPayout = millisecondsBetweenPayouts;
                }

                if (!oldState.IsKeyDown(Keys.LeftControl) && keyState.IsKeyDown(Keys.LeftControl) && player1.Role == Role.Hunted)
                {
                    AddClone(player1);
                }

                if (!oldState.IsKeyDown(Keys.RightControl) && keyState.IsKeyDown(Keys.RightControl) && player2.Role == Role.Hunted)
                {
                    AddClone(player2);
                }

                foreach (PlayingPiece piece in pieces)
                {
                    //If the piece is not where it wants to be
                    if (piece.Direction != Vector2.Zero)
                    {
                        //move it!
                        MovePiece(piece, (float)gameTime.ElapsedGameTime.TotalMilliseconds);
                    }
                    else
                    {
                        //set new direction from keys
                        SetWantedDirection(piece, pressedKeys);
                    }
                }

                foreach (PlayingPiece clone in clones)
                {
                    //If the piece is not where it wants to be
                    if (clone.Direction != Vector2.Zero)
                    {
                        //move it!
                        MovePiece(clone, (float)gameTime.ElapsedGameTime.TotalMilliseconds);
                    }
                    else
                    {
                        //if we need to start up the clone
                        if (clone.Direction == Vector2.Zero)
                        {
                            Vector2 potentialTarget = clone.Position + clone.PreviousDirection * tileSize;

                            //if (clone.PreviousDirection != Vector2.Zero && TileIsClear(potentialTarget))
                            //{
                            //    clone.Direction = clone.PreviousDirection;
                            //}
                            //else
                            //{
                            //    //set new direction from keys
                            //    SetRandomValidDirection(clone);
                            //}

                            SetRandomValidDirectionButNotPrevious(clone);
                        }
                    }
                }
                DoCollisionDetection();

                #endregion

                break;

            case GameState.BetweenRounds:

                betweenRoundsPauseLeft -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (betweenRoundsPauseLeft <= 0)
                {
                    StateOfGame            = GameState.Playing;
                    betweenRoundsPauseLeft = betweenRoundsPause;
                }
                break;

            case GameState.Paused:
                if (keyState.GetPressedKeys().Length > 0)
                {
                    StateOfGame = GameState.Playing;
                    sound_music_a.Resume();
                }
                break;

            case GameState.GameOver:
                if (keyState.IsKeyDown(Keys.Enter) && !oldState.IsKeyDown(Keys.Enter))
                {
                    ResetData();
                    BeginLevel();
                }
                break;

            default:
                break;
            }

            base.Update(gameTime);
            oldState = keyState;
        }
コード例 #12
0
        protected override void Update(GameTime gameTime)
        {
            if (!this.IsActive || Settings.GUI.Visible)
            {
                this.mouseAim = false;
            }
            else
            {
                Vector3    zero   = Vector3.Zero;
                MouseState state1 = Mouse.GetState();
                if (!Settings.GUI.Visible && state1.LeftButton == ButtonState.Pressed && this.mouseState.LeftButton == ButtonState.Released)
                {
                    this.mouseState = Mouse.GetState();
                    if (this.showColorWheel && new Rectangle((int)this.colorWheelLocation.X, (int)this.colorWheelLocation.Y, this.colorWheel.Width, this.colorWheel.Height).Contains(new Point(this.mouseState.X, this.mouseState.Y)))
                    {
                        Color[] data = new Color[this.colorWheel.Width * this.colorWheel.Height];
                        this.colorWheel.GetData <Color>(data);
                        int index = this.mouseState.X + this.mouseState.Y * this.colorWheel.Width;
                        if (index < data.Length)
                        {
                            this.selectedColor = data[index];
                        }
                    }
                    else
                    {
                        this.mouseAim = !this.mouseAim;
                    }
                }
                if (this.mouseAim)
                {
                    this.camera.Yaw   -= (float)(state1.X - this.mouseState.X) * (1f / 500f);
                    this.camera.Pitch -= (float)(state1.Y - this.mouseState.Y) * (1f / 500f);
                    this.camera.Zoom  += (float)(this.mouseState.ScrollWheelValue - state1.ScrollWheelValue) * 0.05f;
                    Viewport viewport = this.GraphicsDevice.Viewport;
                    int      x        = viewport.Width / 2;
                    viewport = this.GraphicsDevice.Viewport;
                    int y = viewport.Height / 2;
                    Mouse.SetPosition(x, y);
                }
                this.mouseState = Mouse.GetState();
                KeyboardState state2 = Keyboard.GetState();
                foreach (Keys pressedKey in state2.GetPressedKeys())
                {
                    switch (pressedKey)
                    {
                    case Keys.S:
                    case Keys.End:
                    case Keys.Down:
                        this.camera.Pitch -= 0.025f;
                        break;

                    case Keys.W:
                    case Keys.Home:
                    case Keys.Up:
                        this.camera.Pitch += 0.025f;
                        break;

                    case Keys.LeftShift:
                        --this.camera.Zoom;
                        break;

                    case Keys.Space:
                        ++this.camera.Zoom;
                        break;

                    case Keys.PageDown:
                    case Keys.Right:
                    case Keys.D:
                        this.camera.Yaw -= 0.025f;
                        break;

                    case Keys.Left:
                    case Keys.Delete:
                    case Keys.A:
                        this.camera.Yaw += 0.025f;
                        break;
                    }
                }
                if (state2.IsKeyDown(Keys.Tab) && !this.keyboardState.IsKeyDown(Keys.Tab))
                {
                    this.CurrentRasterizeState = this.CurrentRasterizeState == this.WireframeRasterizeState ? this.FillRasterizeState : this.WireframeRasterizeState;
                }
                if (state2.IsKeyDown(Keys.F10) && !this.keyboardState.IsKeyDown(Keys.F10))
                {
                    int backBufferWidth  = this.GraphicsDevice.PresentationParameters.BackBufferWidth;
                    int backBufferHeight = this.GraphicsDevice.PresentationParameters.BackBufferHeight;
                    this.Draw(new GameTime());
                    int[] data = new int[backBufferWidth * backBufferHeight];
                    this.GraphicsDevice.GetBackBufferData <int>(data);
                    Texture2D texture2D = new Texture2D(this.GraphicsDevice, backBufferWidth, backBufferHeight, false, this.GraphicsDevice.PresentationParameters.BackBufferFormat);
                    texture2D.SetData <int>(data);
                    Stream stream = (Stream)File.OpenWrite("Screenshots/" + (object)Environment.TickCount + ".jpg");
                    texture2D.SaveAsJpeg(stream, backBufferWidth, backBufferHeight);
                    stream.Dispose();
                    texture2D.Dispose();
                }
                if (state2.IsKeyDown(Keys.F1) && !this.keyboardState.IsKeyDown(Keys.F1))
                {
                    Settings.GUI.Show();
                }
                if (state2.IsKeyDown(Keys.F5) && !this.keyboardState.IsKeyDown(Keys.F5))
                {
                    System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                    string str = (Settings.Conquer_Path + "c3/weapon/").Replace('/', '\\');
                    openFileDialog.InitialDirectory = str;
                    if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Settings.Scene.LoadModel(openFileDialog.FileName);
                        this.centerCamera();
                    }
                }
                if (state2.IsKeyDown(Keys.F2) && !this.keyboardState.IsKeyDown(Keys.F2))
                {
                    System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                    if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        Settings.Scene.LoadModel(openFileDialog.FileName);
                        this.centerCamera();
                    }
                }
                if (state2.IsKeyDown(Keys.F3) && !this.keyboardState.IsKeyDown(Keys.F3))
                {
                    System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
                    if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        if (Settings.GUI.SelectedModel == null)
                        {
                            Settings.GUI.SelectedModel = Settings.Scene.Models.FirstOrDefault <GameModel>();
                        }
                        if (Settings.GUI.SelectedModel != null)
                        {
                            DDSLib.DDSFromFile(openFileDialog.FileName, this.GraphicsDevice, false, out Settings.GUI.SelectedModel.Texture);
                        }
                    }
                }
                if (state2.IsKeyDown(Keys.F12) && !this.keyboardState.IsKeyDown(Keys.F12))
                {
                    Settings.Scene = new GameScene();
                    Settings.GUI   = new Manager();
                }
                foreach (GameModel model in Settings.Scene.Models)
                {
                    foreach (Physics physicalObject in model.PhysicalObjects)
                    {
                        if (physicalObject.Motion != null && DateTime.Now > this.nextFrame)
                        {
                            this.nextFrame            = DateTime.Now.AddMilliseconds(30.0);
                            physicalObject.FrameIndex = (physicalObject.FrameIndex + 1) % physicalObject.Motion.KeyFrames.Count;
                        }
                        if (!(physicalObject.UV_Step == Vector2.Zero))
                        {
                            foreach (Vertex normalVertex in physicalObject.NormalVertexes)
                            {
                                normalVertex.UV += physicalObject.UV_Step;
                            }
                            foreach (Vertex alphaVertex in physicalObject.AlphaVertexes)
                            {
                                alphaVertex.UV += physicalObject.UV_Step;
                            }
                        }
                    }
                }
                this.keyboardState = state2;
                base.Update(gameTime);
            }
        }
コード例 #13
0
        private void UpdateText(KeyboardState keyboard)
        {
            if (HasFocus)
            {
                PressedKeys = (IList <Keys>)keyboard.GetPressedKeys();

                foreach (Keys k in PressedKeys)
                {
                    if (!LastPressedKeys.Contains(k))
                    {
                        if (Text.Length < MaxTextLength)
                        {
                            switch (k)
                            {
                            case Keys.OemMinus:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '_';
                                }
                                else
                                {
                                    Text += '-';
                                }
                                break;

                            case Keys.D1:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '!';
                                }
                                else
                                {
                                    Text += '1';
                                }
                                break;

                            case Keys.D2:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '"';
                                }
                                else
                                {
                                    Text += '2';
                                }
                                break;

                            case Keys.D3:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '§';
                                }
                                else
                                {
                                    Text += '3';
                                }
                                break;

                            case Keys.D4:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '$';
                                }
                                else
                                {
                                    Text += '4';
                                }
                                break;

                            case Keys.D5:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '%';
                                }
                                else
                                {
                                    Text += '5';
                                }
                                break;

                            case Keys.D6:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '&';
                                }
                                else
                                {
                                    Text += '6';
                                }
                                break;

                            case Keys.D7:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '/';
                                }
                                else
                                {
                                    Text += '7';
                                }
                                break;

                            case Keys.D8:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '(';
                                }
                                else
                                {
                                    Text += '8';
                                }
                                break;

                            case Keys.D9:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += ')';
                                }
                                else
                                {
                                    Text += '9';
                                }
                                break;

                            case Keys.D0:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += '=';
                                }
                                else
                                {
                                    Text += '0';
                                }
                                break;

                            case Keys.OemSemicolon:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += ';';
                                }
                                else
                                {
                                    Text += ',';
                                }
                                break;

                            case Keys.NumPad0:
                                Text += "0";
                                break;

                            case Keys.NumPad1:
                                Text += "1";
                                break;

                            case Keys.NumPad2:
                                Text += "2";
                                break;

                            case Keys.NumPad3:
                                Text += "3";
                                break;

                            case Keys.NumPad4:
                                Text += "4";
                                break;

                            case Keys.NumPad5:
                                Text += "5";
                                break;

                            case Keys.NumPad6:
                                Text += "6";
                                break;

                            case Keys.NumPad7:
                                Text += "7";
                                break;

                            case Keys.NumPad8:
                                Text += "8";
                                break;

                            case Keys.NumPad9:
                                Text += "9";
                                break;

                            case Keys.OemPeriod:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += ":";
                                }
                                else
                                {
                                    Text += '.';
                                }
                                break;

                            case Keys.Back:
                                if (Text.Length > 0)
                                {
                                    Text = Text.Remove(Text.Length - 1);
                                }
                                break;

                            case Keys.LeftShift:
                                break;

                            case Keys.RightShift:
                                break;

                            case Keys.V:
                                if (PressedKeys.Contains(Keys.LeftControl) || PressedKeys.Contains(Keys.RightControl))
                                {
                                    break;     //todo
                                }
                                else
                                {
                                    goto default;
                                }

                            case Keys.RightControl:
                            case Keys.LeftControl:
                                break;

                            default:
                                if (PressedKeys.Contains(Keys.LeftShift) || PressedKeys.Contains(Keys.RightShift))
                                {
                                    Text += char.ToUpper((char)k);
                                }
                                else
                                {
                                    Text += char.ToLower((char)k);
                                }
                                break;
                            }
                        }
                    }
                }
                LastPressedKeys = PressedKeys;
            }
            TextPosition = Position + new Vector2(Hitbox.Width / 2, Hitbox.Height / 2) - ButtonFont.MeasureString(Text) / 2;
            NamePosition = Position + new Vector2(0, -TextboxNameFont.MeasureString(TextboxName).Y);
        }
コード例 #14
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)
        {
            mymouse.update();

            MouseState mouse = Mouse.GetState();

            curStatekeyboard = Keyboard.GetState();
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }


            switch (CurrentGameState)
            {
            case GameState.MainMenu:
                if (btnPlay.isClicked)
                {
                    CurrentGameState = GameState.Playing;
                }
                btnPlay.Update(mouse);
                break;

            case GameState.Playing:
                // If space bar is pressed in the current state and the previous state the space bar was not pressed then the dice are rolled.
                if (curStatekeyboard.IsKeyDown(Keys.Space) && prevStatekeyboard.IsKeyUp(Keys.Space))
                {
                    dieSet.Roll();
                    CurrentGameState = GameState.Question;
                }
                break;

            case GameState.Question:
                if (prevStatekeyboard.GetPressedKeys().Length <= 0 && curStatekeyboard.GetPressedKeys().Length > 0)
                {
                    Console          = Process.Start("QuestionConsole.exe");
                    CurrentGameState = GameState.Waiting;
                }
                break;

            case GameState.Waiting:
                if (Console.HasExited)
                {
                    if (Console.ExitCode == 2)
                    {
                    }
                    //yeey gewonnen
                    else if (Console.ExitCode == 3)
                    {
                    }
                    CurrentGameState = GameState.Playing;
                }
                break;
            }



            // TODO: Add your update logic here


            prevStatekeyboard = curStatekeyboard;
            base.Update(gameTime);
        }
コード例 #15
0
        public void Update()
        {
            if (!connected)
            {
                if (threadUpdate != null)
                {
                    threadUpdate.Abort();
                }
                KeyboardState kbState     = Keyboard.GetState();
                Keys[]        pressedKeys = kbState.GetPressedKeys();

                //check if any of the previous update's keys are no longer pressed
                //foreach (Keys key in lastPressedKeys)
                //{
                //    if (!pressedKeys.Contains(key))
                //        OnKeyUp(key);
                //}

                //check if the currently pressed keys were already pressed
                foreach (Keys key in pressedKeys)
                {
                    if (!lastPressedKeys.Contains(key))
                    {
                        if (key.ToString().Contains("D") && key.ToString().Length > 1)
                        {
                            ip += key.ToString()[1];
                        }
                        else if (key == Keys.OemPeriod)
                        {
                            if (pressedKeys.Contains(Keys.LeftShift) || pressedKeys.Contains(Keys.RightShift))
                            {
                                ip += ":";
                            }
                            else
                            {
                                ip += ".";
                            }
                        }
                        else if (key == Keys.Back)
                        {
                            ip = ip.Truncate(ip.Length - 1);
                        }
                        else if (key == Keys.Enter)
                        {
                            string         serverIP   = ip.Split(':').First();
                            int            serverPort = int.Parse(ip.Split(':').Last());
                            ConnectionInfo connInfo   = new ConnectionInfo(serverIP, serverPort);
                            tCPConn = TCPConnection.GetConnection(connInfo);
                            tCPConn.AppendIncomingPacketHandler <bool>("JoinedServerRespond", JoinedServerRespond, NetworkComms.DefaultSendReceiveOptions);
                            tCPConn.AppendIncomingPacketHandler <UpdatePackage>("HostPos", HostPos, NetworkComms.DefaultSendReceiveOptions);
                            tCPConn.SendObject <string>("JoinServer", "Player2");
                        }
                        //else
                        //{
                        //    ip += key;
                        //}
                    }
                }
                //save the currently pressed keys so we can compare on the next update
                lastPressedKeys = pressedKeys;
            }
            else
            {
                if (threadUpdate == null)
                {
                    threadUpdate = new Thread(ThreadUpdate);
                    threadUpdate.Start();
                }
                else if (!threadUpdate.IsAlive)
                {
                    threadUpdate.Start();
                }
            }
        }
コード例 #16
0
        public void Update(KeyboardState kbState, KeyboardState prevKBState)
        {
            // Assign the returned array of pressed keys for that frame to a variable.
            LiveStringArray = kbState.GetPressedKeys();



            //Need:
            //draw method.Look at Game1s draw fsm for things to copy paste.
            //to draw a pop up window first.Pop up because it is smaller than the rest of the window, so it looks
            //like it has been overlaid.Need to also determine when to show the pop up.
            //Button to submit the name.Also add functionality for enter key possibly.

            // TEXT INPUT TESTER CODE



            // For all intents and purposes, the following code works sufficiently well.
            // Mixing GetPressedKeys() with IsKeyUp/Down()
            // Loop through GetPressedKeys()'s returned array to see if the keys are pressed
            // If they are, do not add them to LiveStringArray - only add those that are not pressed.

            // Loop through the above returned array.
            for (int i = 0; i < LiveStringArray.Length; i++)
            {
                // Detect single presses of keys in the array. Only proceed if the current key
                //		being checked is in permittedKeys AND was up in the previous frame.
                //		Otherwise skip and check the next key in the array. This effectively
                //		allows for regular typing, save for the character repeat aspect. This
                //		is because a few keys are pressed simultaneously while typing normally,
                //		and this solution accommodates such a scenario.
                if (permittedKeys.Contains(LiveStringArray[i]) &&
                    kbState.IsKeyDown(LiveStringArray[i]) &&
                    prevKBState.IsKeyUp(LiveStringArray[i]))
                {
                    // If Backspace is pressed...
                    if (LiveStringArray[i] == Keys.Back)
                    {
                        // ...and if the string is empty, do nothing.
                        if (LiveString.Length == 0)
                        {
                            // Do nothing.
                            // This prevents an index out of range error from occurring.
                        }
                        // ...otherwise, add characters up to a max length of 3.
                        else if (LiveString.Length > 0 ||
                                 LiveString.Length <= 3)
                        {
                            // Strings are immutable, and so must be reassigned should they be modified,
                            //		similarly with how structs behave.
                            LiveString = LiveString.Remove(LiveString.Length - 1);
                        }
                    }
                    // If Space is pressed...
                    else if (LiveStringArray[i] == Keys.Space)
                    {
                        // ...add space up to a max length of 3.
                        if (LiveString.Length < 3)
                        {
                            LiveString += " ";
                        }
                    }
                    // For all other Keys, concatenate them in the order they were pressed i.e. the
                    //		order in which they appear in LiveStringArray up to a max length of 3.
                    else
                    {
                        if (LiveString.Length < 3)
                        {
                            LiveString += LiveStringArray[i];
                        }
                    }
                }
            }
        }
コード例 #17
0
ファイル: Game1.cs プロジェクト: StoneLabs/rocket
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                this.Exit();
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                rebootGame();
            }

            screenSize = new Vector2(Window.ClientBounds.Width, Window.ClientBounds.Height);
            if (oldScreenSize != screenSize)
            {
                oldScreenSize = screenSize;
                graphics.PreferredBackBufferWidth  = (int)screenSize.X;
                graphics.PreferredBackBufferHeight = (int)screenSize.Y;
                graphics.ApplyChanges();
            }

            if (Keyboard.GetState().IsKeyDown(Keys.F11))
            {
                graphics.IsFullScreen = true;
                graphics.ApplyChanges();
            }
            if (Keyboard.GetState().IsKeyDown(Keys.F10))
            {
                graphics.IsFullScreen = false;
                graphics.ApplyChanges();
            }
            if (Keyboard.GetState().IsKeyDown(Keys.F3))
            {
                showExtra = true;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.F2))
            {
                showExtra = false;
            }
            if (Keyboard.GetState().IsKeyDown(Keys.M))
            {
                if (sound.State == SoundState.Playing)
                {
                    sound.Stop();
                }
            }
            if (Keyboard.GetState().IsKeyDown(Keys.N))
            {
                if (sound.State == SoundState.Stopped)
                {
                    sound.Play();
                }
            }

            if (startState > 0)
            {
                middleText = "";
                if (startState > 90000 && startState < 100000)
                {
                    middleText = "A Game by Levy Ehrstein";
                }
                if (startState > 80000 && startState < 90000)
                {
                    middleText = "Music by Xythe";
                }
                if (startState > 70000 && startState < 80000)
                {
                    middleText = "Textures by Levy Ehrstein";
                }
                if (startState > 60000 && startState < 70000)
                {
                    middleText = "Code by Levy Ehrstein";
                }
                if (startState > 50000 && startState < 60000)
                {
                    middleText = "Move with the arrow keys!";
                }
                if (startState > 40000 && startState < 50000)
                {
                    middleText = "Press space to shoot!";
                }
                if (startState > 30000 && startState < 40000)
                {
                    middleText = "Press Esc to restart!";
                }
                if (startState > 20000 && startState < 30000)
                {
                    middleText = "Press m to stop music or n to start!";
                }
                if (startState > 0 && startState < 20000)
                {
                    middleText = "More at www.stone-apps.de";
                }
                if (startState > 100)
                {
                    if (random.Next(0, 10) == 1)
                    {
                        middleText = "";
                    }
                }
            }
            else
            {
                if (!pause)
                {
                    if (Keyboard.GetState().IsKeyDown(Keys.P) && !oks.IsKeyDown(Keys.P))
                    {
                        pause = true;
                    }

                    if (Keyboard.GetState().GetPressedKeys().Length > 0)
                    {
                        if (Keyboard.GetState().GetPressedKeys().Length != oks.GetPressedKeys().Length)
                        {
                            cheat += Keyboard.GetState().GetPressedKeys()[0];
                        }
                    }

                    if (cheat.Contains("INFINITY"))
                    {
                        lifes = int.MaxValue;
                        cheat = "";
                    }

                    if (cheat.Contains("MORELINES"))
                    {
                        cheatLines = true;
                        cheat      = "";
                    }

                    middleText = "Have fun :D";
                    if (startState < -10000)
                    {
                        middleText = "";
                    }
                    if (!(lifes < 1) && !(levelprogress > 99.99999f))
                    {
                        UpdateRocket();
                        UpdateMeteor();
                        UpdateBullet();
                        UpdateStars();
                        UpdatePowerUp();

                        if (powerUp1T > 0)
                        {
                            powerUp1T -= 10;
                        }
                        if (powerUp2T > 0)
                        {
                            powerUp2T -= 10;
                        }
                        if (powerUp3T > 0)
                        {
                            powerUp3T -= 10;
                        }

                        if (powerUp4T > 0)
                        {
                            powerUp4T -= 10;
                        }
                        if (powerUp5T > 0)
                        {
                            powerUp5T -= 10;
                        }
                        if (powerUp6T > 0)
                        {
                            powerUp6T -= 10;
                        }

                        punkte++;
                        shootTick++;
                        spawnNOT--;

                        if (spawnrate > 30)
                        {
                            spawnrate -= 0.0025f;
                        }
                        levelprogress += 0.0025f;

                        if ((levelprogress > 80 && levelprogress < 81) || (levelprogress > 81 && levelprogress < 82))
                        {
                            spawnNOT         = 10;
                            middleTextShacke = false;
                            middleText       = "Houston: We have discovered a large wave in front of you!";
                            createNoPowerUp  = true;
                        }

                        if ((levelprogress > 89 && levelprogress < 90))
                        {
                            spawnNOT         = 10;
                            middleTextShacke = false;
                            middleText       = "Houston: We have discovered a very very very large wave in front of you!";
                        }

                        if ((levelprogress > 90 && levelprogress < 91))
                        {
                            spawnNOT         = 10;
                            middleTextShacke = false;
                            middleText       = "Rocket: Roger! Wish us luck!";
                        }

                        if ((levelprogress > 91 && levelprogress < 92))
                        {
                            spawnNOT         = 10;
                            middleTextShacke = false;
                            middleText       = "Rocket Capitain to Weapons officer: All weapons maximal energy!";
                            fireRate         = 2;
                        }

                        if ((levelprogress > 95 && levelprogress < 95.25f))
                        {
                            middleTextShacke = false;
                            middleText       = "Rocket Capitain to Weapons officer: MORE ENERGY!";
                            extraWeapon      = true;
                        }

                        if (levelprogress > 80)
                        {
                            spawnrate = 999999;
                        }
                        if (levelprogress > 81)
                        {
                            spawnrate = 25;
                        }

                        if (levelprogress > 88)
                        {
                            spawnrate = 999999;
                        }
                        if (levelprogress > 91)
                        {
                            spawnrate = 2;
                            powerUp1T = 10000;
                            powerUp2T = 10000;
                            powerUp3T = 10000;
                        }
                        if (levelprogress > 95)
                        {
                            spawnrate = 1;
                        }

                        if (levelprogress > 98.75f)
                        {
                            spawnNOT = int.MaxValue;
                        }
                    }
                    else
                    {
                        middleText = "";
                        positionY -= 10;
                        UpdateBullet();
                    }
                }
                else
                {
                    if (Keyboard.GetState().IsKeyDown(Keys.P) && !oks.IsKeyDown(Keys.P))
                    {
                        pause = false;
                    }
                }
            }

            startState -= 50;

            oks = Keyboard.GetState();
            base.Update(gameTime);
        }
コード例 #18
0
ファイル: Input.cs プロジェクト: melari/Atomic
        public static string GetTyped()
        {
            string current = "";

            bool shift = Input.KeyDown(Keys.LeftShift) || Input.KeyDown(Keys.RightShift);

            foreach (Keys key in ks.GetPressedKeys())
            {
                if (pks.IsKeyUp(key))
                {
                    string l = key.ToString();
                    switch (l)
                    {
                    case "Enter":
                        current += "\n";
                        break;

                    case "OemTilde":
                        current += "~";
                        break;

                    case "OemMinus":
                        if (shift)
                        {
                            current += "_";
                        }
                        else
                        {
                            current += "-";
                        }
                        break;

                    case "OemPlus":
                        if (shift)
                        {
                            current += "+";
                        }
                        else
                        {
                            current += "=";
                        }
                        break;

                    case "Back":
                        current += Convert.ToChar(0x8);
                        break;

                    case "Space":
                        current += " ";
                        break;

                    case "OemQuotes":
                        if (shift)
                        {
                            current += "\"";
                        }
                        else
                        {
                            current += "'";
                        }
                        break;

                    case "OemQuestion":
                        if (shift)
                        {
                            current += "?";
                        }
                        else
                        {
                            current += "/";
                        }
                        break;

                    case "OemSemicolon":
                        if (shift)
                        {
                            current += ":";
                        }
                        else
                        {
                            current += ";";
                        }
                        break;

                    case "OemPeriod":
                        if (shift)
                        {
                            current += ">";
                        }
                        else
                        {
                            current += ".";
                        }
                        break;

                    case "OemComma":
                        if (shift)
                        {
                            current += "<";
                        }
                        else
                        {
                            current += ",";
                        }
                        break;

                    default:
                        if (l.Length > 1)
                        {
                            l = l.Substring(1);
                            int test;
                            if (!int.TryParse(l, out test))
                            {
                                break;
                            }

                            if (shift)
                            {
                                switch (l)
                                {
                                case "1":
                                    current += "!";
                                    continue;

                                case "2":
                                    current += "@";
                                    continue;

                                case "3":
                                    current += "#";
                                    continue;

                                case "4":
                                    current += "$";
                                    continue;

                                case "5":
                                    current += "%";
                                    continue;

                                case "6":
                                    current += "^";
                                    continue;

                                case "7":
                                    current += "&";
                                    continue;

                                case "8":
                                    current += "*";
                                    continue;

                                case "9":
                                    current += "(";
                                    continue;

                                case "0":
                                    current += ")";
                                    continue;
                                }
                            }
                        }
                        if (!shift)
                        {
                            l = l.ToLower();
                        }
                        current += l;
                        break;
                    }
                }
            }

            return(current);
        }
コード例 #19
0
        public override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Z))
            {
                P2P peer = new P2P();
                Global.host = int.Parse(boxValue[1]);
                Thread server = new Thread(() => peer.Listener(Global.host, Global.name));
                server.Start();
                Thread client = new Thread(() => peer.Client()); //Start the client, this is responcible for sending out all packets.
                client.Start();
                if (boxValue[0] != null && boxValue[0] != "")
                {
                    if (int.Parse(boxValue[0]) != 0)
                    {
                        Console.WriteLine("doing");
                        Thread connector = new Thread(() => peer.Connector(int.Parse(boxValue[0]), boxValue[2], Global.name)); //Start a new Connector connecing to the port of the first box and the IP of the third box
                        connector.Start();
                    }
                }
                SubmitTexture();
            }
            else if (GamePad.GetState(PlayerIndex.One).IsConnected&& GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.A))
            {
                SubmitTexture();
            }

            if (Keyboard.GetState().IsKeyDown(Keys.X))
            {
                ReloadImage();
            }
            KeyboardState kbState = Keyboard.GetState();

            Keys[] pressedKeys = kbState.GetPressedKeys();

            foreach (Keys key in lastPressedKey)
            {
                if (!pressedKeys.Contains(key))
                {
                    if (key == Keys.Back || key == Keys.Delete)
                    {
                        if (boxValue[target].Length > 0)
                        {
                            boxValue[target] = boxValue[target].Substring(0, boxValue[target].Length - 1);
                        }
                    }
                    else if (key == Keys.OemPeriod)
                    {
                        boxValue[target] += ".";
                    }
                    else if (key == Keys.Tab)
                    {
                        target++;
                        target = target % boxBox.Count();
                    }
                    else
                    {
                        if (boxValue[target].Length < maxLength[target])
                        {
                            boxValue[target] = boxValue[target] + (string)key.ToString().Substring(key.ToString().Length - 1);
                        }
                    }
                }
            }
            Console.WriteLine(boxValue[target]);
            lastPressedKey = pressedKeys;
        }
コード例 #20
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)
        {
            PreviousKeyboardInput = KeyboardInput;
            KeyboardInput         = Keyboard.GetState();
            var dt = (float)gameTime.ElapsedGameTime.TotalSeconds;

#if WINDOWS
            PreviousMouseInput = MouseInput;
            MouseInput         = Mouse.GetState();

            //Keep the mouse within the screen
            if (!IsMouseVisible)
            {
                Mouse.SetPosition(200, 200);
            }
#endif
            PreviousGamePadInput = GamePadInput;
            for (int i = 0; i < 4; i++)
            {
                GamePadInput = GamePad.GetState((PlayerIndex)i);
                if (GamePadInput.IsConnected)
                {
                    break;
                }
            }

            // Allows the default game to exit on Xbox 360 and Windows
            if (KeyboardInput.IsKeyDown(Keys.Escape) || GamePadInput.Buttons.Back == ButtonState.Pressed)
            {
                Exit();
            }

            //Toggle mouse control.  The camera will look to the IsMouseVisible to determine if it should turn.
            if (WasKeyPressed(Keys.Tab))
            {
                IsMouseVisible = !IsMouseVisible;
            }



            #region UI Toggles

#if !WINDOWS
            if (WasButtonPressed(Buttons.Start))
            {
                displayMenu = !displayMenu;
            }
#else
            if (WasKeyPressed(Keys.F1))
            {
                displayMenu = !displayMenu;
            }
#endif
            if (WasKeyPressed(Keys.I))
            {
                if (KeyboardInput.IsKeyDown(Keys.RightShift) || KeyboardInput.IsKeyDown(Keys.LeftShift))
                {
                    displayActiveEntityCount = !displayActiveEntityCount;
                }
                else
                {
                    displayUI = !displayUI;
                }
            }
            if (WasKeyPressed(Keys.J))
            {
                displayConstraints = !displayConstraints;
            }
            if (WasKeyPressed(Keys.K))
            {
                displayContacts = !displayContacts;
            }
            if (WasKeyPressed(Keys.U))
            {
                displayBoundingBoxes = !displayBoundingBoxes;
            }
            if (WasKeyPressed(Keys.Y))
            {
                displayEntities = !displayEntities;
            }
            if (WasKeyPressed(Keys.H))
            {
                displaySimulationIslands = !displaySimulationIslands;
            }
            if (WasKeyPressed(Keys.G))
            {
                ModelDrawer.IsWireframe = !ModelDrawer.IsWireframe;
            }

            #endregion

            #region Simulation Switcharoo

#if !WINDOWS
            int switchTo = -2;
            if (WasButtonPressed(Buttons.DPadLeft))
            {
                switchTo = currentSimulationIndex - 1;
            }
            else if (WasButtonPressed(Buttons.DPadRight))
            {
                switchTo = currentSimulationIndex + 1;
            }
            if (switchTo != -2)
            {
                if (switchTo < 1)
                {
                    switchTo += demoTypes.Length;
                }
                else if (switchTo > demoTypes.Length)
                {
                    switchTo = 1;
                }
                SwitchSimulation(switchTo);
            }
#else
            foreach (Keys key in KeyboardInput.GetPressedKeys())
            {
                int code = key.GetHashCode();

                if (code >= 48 && code <= 57)
                {
                    int simNumber;
                    if (code == 48)
                    {
                        simNumber = 10;
                    }
                    else
                    {
                        simNumber = code - 48;
                    }
                    if (KeyboardInput.IsKeyDown(Keys.LeftShift))
                    {
                        simNumber += 10;
                    }
                    if (KeyboardInput.IsKeyDown(Keys.LeftControl))
                    {
                        simNumber += 20;
                    }

                    if (simNumber <= demoTypes.Length)
                    {
                        SwitchSimulation(simNumber);
                    }
                }
            }
#endif

            #endregion

            currentSimulation.Update(dt);

            if (displayConstraints)
            {
                ConstraintDrawer.Update();
            }

            if (displayEntities)
            {
                ModelDrawer.Update();
            }
            base.Update(gameTime);
        }
コード例 #21
0
ファイル: PlayerManager.cs プロジェクト: Dragoonight/-Tools
      //The class handlespritemovement will have the values that are mention under it
      public void HandleSpriteMovement(GameTime gameTime)
      {
          //The previousKBState will get the value of the CurrentKBState
          prevoiusKBState = currentKBState;
          //The current KBState will get the values of the Keyboard State
          currentKBState = Keyboard.GetState();



          //The sourceRect will get new values that are mentioned under i
          sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);


          //If the current KBstate gets pressed the corresponding things will happen under it
          if (currentKBState.GetPressedKeys().Length == 0)
          {
              #region Frames < and > then gets this
              //Is not used in this project but don't wanna erase it
              //The frame will go from 0 to 3 (always under 4) and reset to 0 again
              if (currentFrame > 0 && currentFrame < 4)
              {
                  currentFrame = 0;
              }

              //the frame will go from 4 and to 7 and reset to 4 again
              if (currentFrame > 4 && currentFrame < 8)
              {
                  currentFrame = 0;
              }

              //The frame will go from 8 to 11 and reset to 8 again
              if (currentFrame > 8 && currentFrame < 11)
              {
                  currentFrame = 0;
              }

              //The frame will go from 12 to 15 and reset to 12 again
              if (currentFrame > 12 && currentFrame < 16)
              {
                  currentFrame = 0;
              }
              #endregion
              if (currentFrame > 0 && currentFrame < 16)
              {
                  currentFrame = 0;
              }
          }

          //When right keys is pressed the correspodning things will happen mentioned under
          if (currentKBState.IsKeyDown(Keys.Right) == true)
          {
              //Everyhthing will be related to AnimateRight
              AnimateRight(gameTime);
              //As long as the player position is under position.X 780 the Spritespeed goes +
              if (position.X < 645)
              {
                  position.X += spriteSpeed;
              }
          }


          //When left key is pressed the corresonding things will happen mentioned under
          if (currentKBState.IsKeyDown(Keys.Left) == true)
          {
              //Everything will be related to AnimateLeft
              AnimateLeft(gameTime);
              //As long as the player position is above position.X 20 the spritespeed goes -
              if (position.X > 100)
              {
                  position.X -= spriteSpeed;
              }
          }

          //When Down key is pressed the corresponding things will happen mentioned under
          if (currentKBState.IsKeyDown(Keys.Down) == true)
          {
              //Everything will be related to AnimateDown
              AnimateDown(gameTime);
              //As long as the player position is under position.Y 400 the spritespeed goes +
              if (position.Y < 400)
              {
                  position.Y += spriteSpeed;
              }
          }


          //When Up Key is pressed the corresponding things will happen mentioned under
          if (currentKBState.IsKeyDown(Keys.Up) == true)
          {
              //As long as the player position is above position.Y 25 the spritespeed goes -
              AnimateUp(gameTime);
              if (position.Y > 25)
              {
                  position.Y -= spriteSpeed;
              }
          }


          if (currentKBState.IsKeyDown(Keys.Space))
          {
              FireShot();
          }


          //Velocity gets a new vector also the Sourcerect.Width and sourceRect.Height is halfed for some reason
          Velocity = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
      }
コード例 #22
0
 public                Keys[] GetPressedKeys() => _currentKeyboardState.GetPressedKeys();
コード例 #23
0
        protected override void Update(GameTime gameTime)
        {
            int WindowWidth  = graphics.GraphicsDevice.Viewport.Width;
            int WindowHeight = graphics.GraphicsDevice.Viewport.Height;

            float CurrentSPF = (float)(gameTime.ElapsedGameTime.TotalSeconds * 60);

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                Exit();
            }

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

            // get pressed keys and their times
            Keys[] PressedKeys = KeyboardState.GetPressedKeys();
            for (int i = 0; i < PressedKeys.Length; i++)
            {
                Keys PressedKey = PressedKeys[i];
                if (!KeyPressTime.ContainsKey(PressedKey))
                {
                    KeyPressTime[PressedKey] = 0;
                }
            }

            List <Keys> KeysToUpdate = new List <Keys>();
            List <Keys> KeysToRemove = new List <Keys>();

            foreach (KeyValuePair <Keys, float> KeyVal in KeyPressTime)
            {
                if (PressedKeys.Contains(KeyVal.Key))
                {
                    KeysToUpdate.Add(KeyVal.Key);
                }
                else
                {
                    KeysToRemove.Add(KeyVal.Key);
                }
            }
            for (int i = 0; i < KeysToRemove.Count; i++)
            {
                KeyPressTime.Remove(KeysToRemove[i]);
            }
            for (int i = 0; i < KeysToUpdate.Count; i++)
            {
                KeyPressTime[KeysToUpdate[i]] += (float)gameTime.ElapsedGameTime.TotalSeconds;
            }
            //

            // handle input
            bool CanPlaceBlock = true;

            Vector2 MouseLocationInWorld = Vector2.Transform(new Vector2(MouseState.Position.X, MouseState.Position.Y), Matrix.Invert(Matrix.CreateTranslation(new Vector3((int)Camera_Position.X, (int)Camera_Position.Y, 0))));

            // handle UI input
            foreach (KeyValuePair <string, UserInterfaceComponent> KeyVal in UserInterface)
            {
                bool HoveringOver = KeyVal.Value.Update(gameTime, ref MouseState, ref OldMouseState);
                if (KeyVal.Value.IsDisplayed)
                {
                    if (HoveringOver == true)
                    {
                        CanPlaceBlock = false;
                    }
                    if (KeyVal.Value is TextBox && KeyVal.Value.IsFocused)
                    {
                        TextBox TextBox = (TextBox)KeyVal.Value;
                        if ((GetKeyPressTime(Keys.Left) > 0.5 || OldKeyboardState.IsKeyUp(Keys.Left) && KeyboardState.IsKeyDown(Keys.Left)) && TextBox.CursorPosition > 0)
                        {
                            TextBox.CursorPosition--;
                        }
                        else if ((GetKeyPressTime(Keys.Right) > 0.5 || OldKeyboardState.IsKeyUp(Keys.Right) && KeyboardState.IsKeyDown(Keys.Right)) && TextBox.CursorPosition < TextBox.Text.Length)
                        {
                            TextBox.CursorPosition++;
                        }
                        KeyboardState = new KeyboardState();
                    }
                }
            }

            if (KeyboardState.IsKeyDown(Keys.T))
            {
                CanPlaceBlock = false;

                string[] UserInterfacesToHide = { "SaveButton", "LoadButton" };
                if (OldMouseState.LeftButton == ButtonState.Pressed && MouseState.LeftButton == ButtonState.Released && PlayTesting == false)
                {
                    PlayTesting = true;

                    Camera_Position_Before_Playtest = Camera_Position;

                    Player = new Player(TileTextures[TileType.SMILEY + 0].Texture);
                    Player.Entity.Position     = MouseLocationInWorld + new Vector2(-Player.Entity.Physics_HitBox.Width / 2, -Player.Entity.Physics_HitBox.Height / 2);
                    Player.Entity.Old_Position = Player.Entity.Position;

                    BlocksInPlayTest.AddRange(BlocksInWorld);

                    foreach (KeyValuePair <string, UserInterfaceComponent> KeyVal in UserInterface)
                    {
                        if (UserInterfacesToHide.Contains(KeyVal.Key))
                        {
                            KeyVal.Value.Visible = false;
                        }
                    }
                }
                else if (OldKeyboardState.IsKeyUp(Keys.T) && PlayTesting == true)
                {
                    PlayTesting = false;

                    Camera_Position = Camera_Position_Before_Playtest;
                    Player          = null;
                    BlocksInPlayTest.Clear();

                    foreach (KeyValuePair <string, UserInterfaceComponent> KeyVal in UserInterface)
                    {
                        if (UserInterfacesToHide.Contains(KeyVal.Key))
                        {
                            KeyVal.Value.Visible = true;
                        }
                    }
                }
            }
            if (PlayTesting == false)
            {
                // camera movement
                Current_Camera_Speed = Math.Max(Camera_Speed, Current_Camera_Speed);

                if (KeyboardState.IsKeyDown(Keys.Left) || KeyboardState.IsKeyDown(Keys.A))
                {
                    Camera_Position.X += Current_Camera_Speed;
                }
                if (KeyboardState.IsKeyDown(Keys.Right) || KeyboardState.IsKeyDown(Keys.D))
                {
                    Camera_Position.X -= Current_Camera_Speed;
                }
                if (KeyboardState.IsKeyDown(Keys.Up) || KeyboardState.IsKeyDown(Keys.W))
                {
                    Camera_Position.Y += Current_Camera_Speed;
                }
                if (KeyboardState.IsKeyDown(Keys.Down) || KeyboardState.IsKeyDown(Keys.S))
                {
                    Camera_Position.Y -= Current_Camera_Speed;
                }

                // camera accelerating
                if (KeyboardState.IsKeyDown(Keys.Left) || KeyboardState.IsKeyDown(Keys.Right) ||
                    KeyboardState.IsKeyDown(Keys.Up) || KeyboardState.IsKeyDown(Keys.Down) ||

                    KeyboardState.IsKeyDown(Keys.A) || KeyboardState.IsKeyDown(Keys.D) ||
                    KeyboardState.IsKeyDown(Keys.W) || KeyboardState.IsKeyDown(Keys.S))
                {
                    Current_Camera_Speed += Camera_Acceleration * CurrentSPF;
                }
                else
                {
                    Current_Camera_Speed = Camera_Speed;
                }

                // camera center to 0,0
                if (KeyboardState.IsKeyDown(Keys.C) && OldKeyboardState.IsKeyUp(Keys.C))
                {
                    Camera_Position = new Vector2();
                }

                // undo and redoing
                if (KeyboardState.IsKeyDown(Keys.LeftControl))
                {
                    if (((GetKeyPressTime(Keys.Z) > 0.5 || OldKeyboardState.IsKeyUp(Keys.Z) && KeyboardState.IsKeyDown(Keys.Z)) && BlockUndoHistory.Count > 0) ||
                        ((GetKeyPressTime(Keys.Y) > 0.5 || OldKeyboardState.IsKeyUp(Keys.Y) && KeyboardState.IsKeyDown(Keys.Y)) && BlockRedoHistory.Count > 0))
                    {
                        bool             Redo                = (GetKeyPressTime(Keys.Y) > 0.5 || OldKeyboardState.IsKeyUp(Keys.Y) && KeyboardState.IsKeyDown(Keys.Y)) && BlockRedoHistory.Count > 0;
                        BlockContainer[] LastUndo            = (Redo? BlockRedoHistory.Last() : BlockUndoHistory.Last());
                        BlockContainer[] BlockContainerToAdd = new BlockContainer[LastUndo.Length];
                        for (int i = 0; i < LastUndo.Length; i++)
                        {
                            BlockContainer BlockToBeBroughtBack = LastUndo[i];
                            if (BlockToBeBroughtBack != null)
                            {
                                if (BlockToBeBroughtBack.Block != null)
                                {
                                    BlockContainerToAdd[i] = new BlockContainer(BlockToBeBroughtBack.Position, GetBlockByPoint(BlockToBeBroughtBack.Position));
                                    AddBlock(BlockToBeBroughtBack.Block);
                                }
                                else
                                {
                                    int   BlockIndex   = 0;
                                    Block CurrentBlock = GetBlockByPoint(BlockToBeBroughtBack.Position, out BlockIndex);
                                    if (CurrentBlock != null)
                                    {
                                        BlockContainerToAdd[i] = new BlockContainer(BlockToBeBroughtBack.Position, CurrentBlock);
                                        BlocksInWorld.RemoveAt(BlockIndex);
                                    }
                                }
                            }
                        }
                        if (Redo)
                        {
                            BlockUndoHistory.Add(BlockContainerToAdd);
                            BlockRedoHistory.RemoveAt(BlockRedoHistory.Count - 1);
                        }
                        else
                        {
                            BlockRedoHistory.Add(BlockContainerToAdd);
                            BlockUndoHistory.RemoveAt(BlockUndoHistory.Count - 1);
                        }
                    }
                }

                // block selecting
                {
                    int x = 0;
                    int y = 0;
                    while (BlockList.Count > x + (y * 16))
                    {
                        short blkID = (short)(x + (y * 16));

                        int absX = x * 16 + 1;
                        int absY = y * 16 + WindowHeight - 17;

                        Block blk = BlockList[blkID];
                        if (MouseState.Position.X >= absX && MouseState.Position.Y >= absY &&
                            MouseState.Position.X < absX + blk.Texture.Width && MouseState.Position.Y < absY + blk.Texture.Height)
                        {
                            CanPlaceBlock = false;
                            if (OldMouseState.LeftButton == ButtonState.Pressed && MouseState.LeftButton == ButtonState.Released)
                            {
                                SelectedBlockID = blkID;
                            }
                        }

                        x++;
                        if (x > 16)
                        {
                            x = 0; y++;
                        }
                    }
                }

                // block placing/deleting
                if (MouseState.LeftButton == ButtonState.Pressed && CanPlaceBlock == true && KeyboardState.IsKeyUp(Keys.LeftControl))
                {
                    int steps = OldMouseState.LeftButton == ButtonState.Pressed ? (int)Math.Ceiling(
                        Vector2.Distance(MouseLocationInWorld, OldMouseLocationInWorldWhileHoldingClick) / 16
                        ) : 0;
                    BlockContainer[] AddedBlocks = new BlockContainer[steps + 1];
                    for (int step = 0; step <= steps; step++)
                    {
                        double  LocStep = step / (double)steps > 0 ? step / (double)steps : 1;
                        Vector2 MouseLocationInWorldLerped = new Vector2(
                            (float)Math.Floor(Lerp(OldMouseLocationInWorldWhileHoldingClick.X, MouseLocationInWorld.X, LocStep) / 16) * 16,
                            (float)Math.Floor(Lerp(OldMouseLocationInWorldWhileHoldingClick.Y, MouseLocationInWorld.Y, LocStep) / 16) * 16
                            );

                        Block OldBlock = GetBlockByPoint(MouseLocationInWorldLerped);
                        Block Block    = new Block(SelectedBlockID, TileTextures[TileType.BLOCK + SelectedBlockID].Texture, new Vector2(MouseLocationInWorldLerped.X, MouseLocationInWorldLerped.Y), new Rectangle(0, 0, 16, 16));

                        AddedBlocks[step] = new BlockContainer(MouseLocationInWorldLerped, OldBlock);
                        if (OldBlock != null)
                        {
                            if (OldBlock.BlockID == Block.BlockID)
                            {
                                AddedBlocks[step] = null;
                            }
                        }

                        AddBlock(Block);
                    }
                    if (!AddedBlocks.All(item => item == null))
                    {
                        BlockUndoHistory.Add(AddedBlocks);
                        BlockRedoHistory.Clear();
                    }
                    OldMouseLocationInWorldWhileHoldingClick = MouseLocationInWorld;
                }
                else if (MouseState.RightButton == ButtonState.Pressed && CanPlaceBlock == true && KeyboardState.IsKeyUp(Keys.LeftControl))
                {
                    int steps = OldMouseState.RightButton == ButtonState.Pressed ? (int)Math.Ceiling(
                        Vector2.Distance(MouseLocationInWorld, OldMouseLocationInWorldWhileHoldingClick) / 16
                        ) : 0;
                    BlockContainer[] RemovedBlocks = new BlockContainer[steps + 1];
                    for (int step = 0; step <= steps; step++)
                    {
                        double  LocStep = step / (double)steps > 0 ? step / (double)steps : 1;
                        Vector2 MouseLocationInWorldLerped = new Vector2(
                            (float)Math.Floor(Lerp(OldMouseLocationInWorldWhileHoldingClick.X, MouseLocationInWorld.X, LocStep) / 16) * 16,
                            (float)Math.Floor(Lerp(OldMouseLocationInWorldWhileHoldingClick.Y, MouseLocationInWorld.Y, LocStep) / 16) * 16
                            );

                        // normal block
                        for (int i = BlocksInWorld.Count - 1; i >= 0; i--)
                        {
                            Block blk = BlocksInWorld[i];
                            if (blk != null)
                            {
                                if (MouseLocationInWorldLerped.Y >= blk.Position.Y && MouseLocationInWorldLerped.Y < blk.Position.Y + blk.HitBox.Height &&
                                    MouseLocationInWorldLerped.X < blk.Position.X + blk.HitBox.Width && MouseLocationInWorldLerped.X >= blk.Position.X)
                                {
                                    RemovedBlocks[step] = new BlockContainer(MouseLocationInWorldLerped, new Block(blk));
                                    BlocksInWorld.RemoveAt(i);
                                    break;
                                }
                            }
                        }
                    }
                    if (!RemovedBlocks.All(item => item == null))
                    {
                        BlockUndoHistory.Add(RemovedBlocks);
                        BlockRedoHistory.Clear();
                    }
                    OldMouseLocationInWorldWhileHoldingClick = MouseLocationInWorld;
                }
            }
            else // if its play testing then
            {
                if (Player != null)
                {
                    // player input before updating the player's entity
                    float TopSpeed     = 5f;
                    float Acceleration = 0.25f;
                    if ((KeyboardState.IsKeyDown(Keys.Left) | KeyboardState.IsKeyDown(Keys.A)))
                    {
                        Player.Entity.Velocity.X = Math.Max(-TopSpeed, Player.Entity.Velocity.X -
                                                            (Player.Entity.Velocity.X > 0 ? Player.Entity.Friction.X : (Player.Entity.Velocity.X < -TopSpeed ? -Math.Min(Player.Entity.Friction.X, Player.Entity.Velocity.X - TopSpeed) : Acceleration)) * CurrentSPF
                                                            );
                    }
                    else if ((KeyboardState.IsKeyDown(Keys.Right) | KeyboardState.IsKeyDown(Keys.D)))
                    {
                        Player.Entity.Velocity.X = Math.Min(TopSpeed, Player.Entity.Velocity.X +
                                                            (Player.Entity.Velocity.X < 0 ? Player.Entity.Friction.X : (Player.Entity.Velocity.X > TopSpeed ? -Math.Min(Player.Entity.Friction.X, Player.Entity.Velocity.X - TopSpeed) : Acceleration)) * CurrentSPF
                                                            );
                    }
                    else
                    {
                        if (Player.Entity.Velocity.X > 0)
                        {
                            Player.Entity.Velocity.X = Math.Max(0, Player.Entity.Velocity.X - Player.Entity.Friction.X * CurrentSPF);
                        }
                        else if (Player.Entity.Velocity.X < 0)
                        {
                            Player.Entity.Velocity.X = Math.Min(0, Player.Entity.Velocity.X + Player.Entity.Friction.X * CurrentSPF);
                        }
                        else
                        {
                            // align to center mechanic
                            int GridX = SnapToGrid(Player.Entity.Position.X, 16);
                            if (Player.Entity.Velocity.X == 0 && Math.Abs(GridX - Player.Entity.Position.X) < 1)
                            {
                                Player.Entity.Position.X = GridX;
                            }

                            // align to center mechanic
                            int GridY = SnapToGrid(Player.Entity.Position.Y, 16);
                            if (Player.Entity.Velocity.Y == 0 && Math.Abs(GridY - Player.Entity.Position.Y) < 1)
                            {
                                Player.Entity.Position.Y = GridY;
                            }
                        }
                    }

                    // delay the player's jumps (so they can't do 1x1 hookjumps easily)
                    Player.JumpDelay = Math.Max(0, Player.JumpDelay - (float)gameTime.ElapsedGameTime.TotalSeconds);

                    // get the block below the player
                    Block BlockBelowPlayer = GetBlockIntersectingWithRect(new Rectangle(
                                                                              (int)Player.Entity.Position.X, (int)Player.Entity.Position.Y + 1,
                                                                              Player.Entity.Physics_HitBox.Width, Player.Entity.Physics_HitBox.Height
                                                                              ), ref BlocksInPlayTest);

                    if (KeyboardState.IsKeyDown(Keys.Space) && BlockBelowPlayer != null && Player.JumpDelay <= 0 &&
                        (BlockBelowPlayer.Position.Y + BlockBelowPlayer.HitBox.Top) - (Player.Entity.Position.Y + Player.Entity.Physics_HitBox.Bottom) <= 0)
                    {
                        Player.Entity.Velocity.Y -= 9.6f;
                        Player.JumpDelay          = 0.1f;
                    }

                    // handle the camera
                    if (BlockBelowPlayer != null)
                    {
                        LastBlockBelowPlayer = BlockBelowPlayer;
                    }
                    if (LastBlockBelowPlayer != null)
                    {
                        Camera_Position.X -= LastBlockBelowPlayer.Velocity.X;
                        Camera_Position.Y -= LastBlockBelowPlayer.Velocity.Y;
                    }

                    Camera_Position = LerpVector(Camera_Position, new Vector2(
                                                     -Player.Entity.Position.X + Window.ClientBounds.Width / 2 - Player.Entity.Physics_HitBox.Width,
                                                     -Player.Entity.Position.Y + Window.ClientBounds.Height / 2 - Player.Entity.Physics_HitBox.Height
                                                     ), 0.25 * CurrentSPF);

                    for (int i = BlocksInPlayTest.Count - 1; i >= 0; i--)
                    {
                        Block blk = BlocksInPlayTest[i];
                        if (blk != null)
                        {
                            blk.Update(gameTime, CurrentSPF);              // update blocks first
                        }
                    }

                    // then update entities
                    Player.Entity.Update(gameTime, ref BlocksInPlayTest, .675f, CurrentSPF);
                }
            }

            // update old states
            OldKeyboardState = Keyboard.GetState();
            OldMouseState    = Mouse.GetState();

            base.Update(gameTime);
        }
コード例 #24
0
 public bool WasAnyKeyJustDown() => _previousKeyboardState.GetPressedKeys().Any();
コード例 #25
0
ファイル: KeyboardHelper.cs プロジェクト: BadBreath69/Citysim
 public static Keys[] GetPressedKeys()
 {
     return(keyboardState.GetPressedKeys());
 }
コード例 #26
0
ファイル: GameKeyboard.cs プロジェクト: BlueTRaven/BrUtility
 public Keys[] GetCurrentPressedKeys()
 {
     return(currentState.GetPressedKeys());
 }
コード例 #27
0
ファイル: InputHandler.cs プロジェクト: VilRan/Legatus
        private void UpdateKeyboard(GameTime gameTime)
        {
            KeyboardState keyboard = Keyboard.GetState();

            Keys[] pressedKeys = keyboard.GetPressedKeys();

            if (pressedKeys.Length > 0)
            {
                if (pressedKeys.Contains(Keys.LeftShift) || pressedKeys.Contains(Keys.RightShift))
                {
                    if (pressedKeys.Length > 1)
                    {
                        KeyRepeatDelayRemaining -= gameTime.ElapsedGameTime.Milliseconds;
                        if (KeyRepeatDelayRemaining < 0)
                        {
                            KeyRepeatDelayRemaining = 0;
                        }
                    }
                }
                else
                {
                    KeyRepeatDelayRemaining -= gameTime.ElapsedGameTime.Milliseconds;
                    if (KeyRepeatDelayRemaining < 0)
                    {
                        KeyRepeatDelayRemaining = 0;
                    }
                }
            }
            else
            {
                KeyRepeatDelayRemaining = KeyRepeatDelayFull;
            }

            foreach (Keys key in pressedKeys)
            {
                if (!PreviousPressedKeys.Contains(key))
                {
                    OnKeyPressed(key, pressedKeys, gameTime);
                }
                else if (KeyRepeatDelayRemaining == 0)
                {
                    OnKeyRepeated(key, pressedKeys, gameTime);
                }

                OnKeyHeld(key, pressedKeys, gameTime);
            }

            foreach (Keys key in PreviousPressedKeys)
            {
                if (!pressedKeys.Contains(key))
                {
                    OnKeyReleased(key, pressedKeys, gameTime);
                }
            }

            if (KeyRepeatDelayRemaining == 0 && pressedKeys.Length > 0)
            {
                KeyRepeatDelayRemaining = KeyRepeatDelayShort;
            }

            PreviousPressedKeys = pressedKeys;
            PreviousKeyboard    = keyboard;
        }
コード例 #28
0
ファイル: CKeyboard.cs プロジェクト: ProjectSciFy/ZeldaRemake
        public void Update()
        {
            linkState = game.linkStateMachine;
            KeyboardState  keyState     = Keyboard.GetState();
            HashSet <Keys> releasedKeys = new HashSet <Keys>(heldKeys);

            Keys[] pressedKeys      = keyState.GetPressedKeys();
            int    lastMoveKeyCount = movementKeys.Count;

            for (int i = 0; i < pressedKeys.Length; i++)
            {
                releasedKeys.Remove(pressedKeys[i]);
                if (keyBinds.ContainsKey(pressedKeys[i]) && !heldKeys.Contains(pressedKeys[i]))
                {
                    keyBinds[pressedKeys[i]].Execute();
                    heldKeys.Add(pressedKeys[i]);
                    if (pressedKeys[i] == Keys.W || pressedKeys[i] == Keys.A || pressedKeys[i] == Keys.S || pressedKeys[i] == Keys.D || pressedKeys[i] == Keys.Up || pressedKeys[i] == Keys.Left || pressedKeys[i] == Keys.Down || pressedKeys[i] == Keys.Right)
                    {
                        movementKeys.Add(pressedKeys[i], 0);
                        if (movementKeys.ContainsKey(Keys.W))
                        {
                            movementKeys[Keys.W] = movementKeys[Keys.W] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.A))
                        {
                            movementKeys[Keys.A] = movementKeys[Keys.A] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.S))
                        {
                            movementKeys[Keys.S] = movementKeys[Keys.S] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.D))
                        {
                            movementKeys[Keys.D] = movementKeys[Keys.D] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.Up))
                        {
                            movementKeys[Keys.Up] = movementKeys[Keys.Up] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.Left))
                        {
                            movementKeys[Keys.Left] = movementKeys[Keys.Left] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.Down))
                        {
                            movementKeys[Keys.Down] = movementKeys[Keys.Down] + 1;
                        }
                        if (movementKeys.ContainsKey(Keys.Right))
                        {
                            movementKeys[Keys.Right] = movementKeys[Keys.Right] + 1;
                        }
                    }
                }
            }
            foreach (Keys releasedKey in releasedKeys)
            {
                heldKeys.Remove(releasedKey);
                if (movementKeys.ContainsKey(releasedKey))
                {
                    int movePriority = movementKeys[releasedKey];
                    if (movementKeys.ContainsKey(Keys.W) && movementKeys[Keys.W] > movePriority)
                    {
                        movementKeys[Keys.W] = movementKeys[Keys.W] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.A) && movementKeys[Keys.A] > movePriority)
                    {
                        movementKeys[Keys.A] = movementKeys[Keys.A] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.S) && movementKeys[Keys.S] > movePriority)
                    {
                        movementKeys[Keys.S] = movementKeys[Keys.S] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.D) && movementKeys[Keys.D] > movePriority)
                    {
                        movementKeys[Keys.D] = movementKeys[Keys.D] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.Up) && movementKeys[Keys.Up] > movePriority)
                    {
                        movementKeys[Keys.Up] = movementKeys[Keys.Up] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.Left) && movementKeys[Keys.Left] > movePriority)
                    {
                        movementKeys[Keys.Left] = movementKeys[Keys.Left] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.Down) && movementKeys[Keys.Down] > movePriority)
                    {
                        movementKeys[Keys.Down] = movementKeys[Keys.Down] - 1;
                    }
                    if (movementKeys.ContainsKey(Keys.Right) && movementKeys[Keys.Right] > movePriority)
                    {
                        movementKeys[Keys.Right] = movementKeys[Keys.Right] - 1;
                    }
                    movementKeys.Remove(releasedKey);
                }
            }
            if (movementKeys.Count > 0)
            {
                int  newMoveKeyCount = movementKeys.Count;
                Keys currentMoveKey;
                if (movementKeys.ContainsKey(Keys.W) && movementKeys[Keys.W] == 1)
                {
                    currentMoveKey = Keys.W;
                }
                else if (movementKeys.ContainsKey(Keys.A) && movementKeys[Keys.A] == 1)
                {
                    currentMoveKey = Keys.A;
                }
                else if (movementKeys.ContainsKey(Keys.S) && movementKeys[Keys.S] == 1)
                {
                    currentMoveKey = Keys.S;
                }
                else if (movementKeys.ContainsKey(Keys.D) && movementKeys[Keys.D] == 1)
                {
                    currentMoveKey = Keys.D;
                }
                else if (movementKeys.ContainsKey(Keys.Up) && movementKeys[Keys.Up] == 1)
                {
                    currentMoveKey = Keys.Up;
                }
                else if (movementKeys.ContainsKey(Keys.Left) && movementKeys[Keys.Left] == 1)
                {
                    currentMoveKey = Keys.Left;
                }
                else if (movementKeys.ContainsKey(Keys.Down) && movementKeys[Keys.Down] == 1)
                {
                    currentMoveKey = Keys.Down;
                }
                else
                {
                    currentMoveKey = Keys.Right;
                }
                if (newMoveKeyCount < lastMoveKeyCount)
                {
                    keyBinds[currentMoveKey].Execute();
                }
            }
            else
            {
                new IdleLink(linkState).Execute();
            }
        }
コード例 #29
0
 public Keys[] GetKeysDown()
 {
     return(_currentKeyboardState.GetPressedKeys());
 }
コード例 #30
0
        /// <summary>
        /// Hand keyboard input.
        /// </summary>
        /// <param name="dt"></param>
        public void ProcessKeyInputs(float dt)
        {
            KeyboardState keyState = vxEngine.InputManager.KeyboardState;

            Keys[] keys = keyState.GetPressedKeys();

            bool shift = keyState.IsKeyDown(Keys.LeftShift) ||
                         keyState.IsKeyDown(Keys.RightShift);

            foreach (Keys key in keys)
            {
                if (!IsKeyPressed(key, dt))
                {
                    continue;
                }

                char ch;
                if (KeyboardUtils.KeyToString(key, shift, out ch))
                {
                    // Handle typical character input.
                    Text = Text.Insert(cursorIndex, new string(ch, 1));
                    cursorIndex++;


                    // Raise the 'TextChanged' event.
                    if (TextChanged != null)
                    {
                        TextChanged(this, new EventArgs());
                    }
                }
                else
                {
                    switch (key)
                    {
                    case Keys.Back:
                        if (cursorIndex > 0)
                        {
                            Text = Text.Remove(--cursorIndex, 1);
                        }
                        break;

                    case Keys.Delete:
                        if (cursorIndex < Text.Length)
                        {
                            Text = Text.Remove(cursorIndex, 1);
                        }
                        break;

                    case Keys.Left:
                        if (cursorIndex > 0)
                        {
                            cursorIndex--;
                        }
                        break;

                    case Keys.Right:
                        if (cursorIndex < Text.Length)
                        {
                            cursorIndex++;
                        }
                        break;
                    }
                }
            }
        }