Ejemplo n.º 1
0
        /// <summary>
        /// Takes a game keytype and filters it into compatible XNA keytypes.
        /// </summary>
        /// <param name="key">The key being filtered.</param>
        /// <returns></returns>
        private static Microsoft.Xna.Framework.Input.Keys FilterKeyType(GameKeys key)
        {
            switch (key)
            {
            case GameKeys.Accept: return(Keys.Z);

            case GameKeys.Back:   return(Keys.X);

            case GameKeys.Up:     return(Keys.Up);

            case GameKeys.Right:  return(Keys.Right);

            case GameKeys.Down:   return(Keys.Down);

            case GameKeys.Left:   return(Keys.Left);

            case GameKeys.Start:  return(Keys.Enter);

            case GameKeys.Esc:    return(Keys.Escape);

            case GameKeys.Run:    return(Keys.LeftShift);

            default:              return(Keys.Z);
            }
        }
Ejemplo n.º 2
0
        protected override void Dispose(bool disposing)
        {
            GameKeys.Save();

            SaveGameConfig();

            SceneManager.Dispose();

            ResourceManager.Dispose();

            Log.Dispose();

            base.Dispose(disposing);
        }
        private bool HandleBlockGroupKey(IStateOwner pOwner, GameKeys key)
        {
            bool AnyTrue = false;

            foreach (var activeitem in PlayField.BlockGroups)
            {
                if (activeitem.Controllable)
                {
                    AnyTrue |= activeitem.HandleGameKey(pOwner, key);
                }
            }

            return(AnyTrue);
        }
Ejemplo n.º 4
0
        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            if (g == GameKeys.GameKey_Drop)
            {
                ChangeChar(1);
                TetrisGame.Soundman.PlaySound(Char_Change_Up_Sound, pOwner.Settings.std.EffectVolume);
                //change current character "upwards"
            }
            else if (g == GameKeys.GameKey_Down)
            {
                ChangeChar(-1);
                TetrisGame.Soundman.PlaySound(Char_Change_Up_Sound, pOwner.Settings.std.EffectVolume);
                //change current character "downwards"
            }
            else if (g == GameKeys.GameKey_Left)
            {
                int currpos = CurrentPosition;
                currpos--;
                if (currpos < 0)
                {
                    currpos = NameEntered.Length - 1;
                }
                CurrentPosition = currpos;
                TetrisGame.Soundman.PlaySound(Char_Pos_Left, pOwner.Settings.std.EffectVolume);
                //change current position -1 (wrapping to the end if needed)
            }
            else if (g == GameKeys.GameKey_Right)
            {
                int currpos = CurrentPosition;
                currpos++;
                if (currpos > NameEntered.Length - 1)
                {
                    currpos = 0;
                }
                CurrentPosition = currpos;
                TetrisGame.Soundman.PlaySound(Char_Pos_Right, pOwner.Settings.std.EffectVolume);
                //change current position 1 (wrapping tp the start if needed)
            }
            else if (g == GameKeys.GameKey_RotateCW)
            {
                String sEntry = NameEntered.ToString().Trim('_', ' ');
                if (ValidateEntry(pOwner, sEntry))
                {
                    CommitEntry(pOwner, sEntry);
                }
            }

            //throw new NotImplementedException();
        }
        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            switch (g)
            {
            case GameKeys.GameKey_Left:
                break;

            case GameKeys.GameKey_Right:
                break;

            case GameKeys.GameKey_RotateCCW:
                pOwner.CurrentState = _Owner;
                break;
            }
        }
Ejemplo n.º 6
0
        private void LoadGameConfig()
        {
            using (var file = File.OpenText(Constants.ConfigFile))
                using (var reader = new JsonTextReader(file)) {
                    var configJson = (JObject)JToken.ReadFrom(reader);
                    GraphicsDevice.PresentationParameters.BackBufferWidth  = (int)configJson["width"];
                    GraphicsDevice.PresentationParameters.BackBufferHeight = (int)configJson["height"];
                    GraphicsDevice.PresentationParameters.IsFullScreen     = (bool)configJson["fullScreen"];
                    SoundVolume = (float)configJson["soundVolume"];
                }

            Log.Info(
                $"Initialisation en cours .. \n Taille : {GraphicsDevice.PresentationParameters.BackBufferWidth}x{GraphicsDevice.PresentationParameters.BackBufferHeight}");

            GameKeys.Load();
        }
Ejemplo n.º 7
0
        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            GameKeys[] handledKeys = new GameKeys[] { GameKeys.GameKey_Down, GameKeys.GameKey_Drop, GameKeys.GameKey_RotateCW };
            if (!ScrollCompleted)
            {
                IncrementTimediff = new TimeSpan(0, 0, 0, 0, 50);
            }

            else if (ScrollCompleted && handledKeys.Contains(g))
            {
                if (g == GameKeys.GameKey_Drop)
                {
                    //move up...
                    SelectedScorePosition--;
                    if (SelectedScorePosition < 0)
                    {
                        SelectedScorePosition = _ScoreList.MaximumSize;
                    }
                }
                else if (g == GameKeys.GameKey_Down)
                {
                    SelectedScorePosition++;
                    if (SelectedScorePosition > _ScoreList.MaximumSize)
                    {
                        SelectedScorePosition = 0;
                    }
                }
                else if (g == GameKeys.GameKey_RotateCW)
                {
                    //This is where we will enter a "HighscoreDetails" state passing along this one specific high score.
                    var SelectedScore         = _ScoreList.GetScores().ToArray()[SelectedScorePosition];
                    ViewScoreDetailsState vsd = new ViewScoreDetailsState(this, SelectedScore, _BG, SelectedScorePosition + 1);
                    pOwner.CurrentState = vsd;
                }
            }

            else if (RevertState != null)
            {
                pOwner.CurrentState = RevertState;
            }
        }
Ejemplo n.º 8
0
        public String GameOverText = "GAME    OVER"; //+ ShowExtraLines.ToString();

        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            if (g == GameKeys.GameKey_RotateCW)
            {
                if (NewScorePosition > -1)
                {
                    if (GameOveredState is GameplayGameState)
                    {
                        var useStats  = ((GameplayGameState)GameOveredState).GameStats;
                        var MenuState = ((GameplayGameState)GameOveredState).MainMenuState;
                        if (useStats is TetrisStatistics)
                        {
                            EnterHighScoreState ehs = new EnterHighScoreState
                                                          (GameOveredState, pOwner, MenuState,
                                                          ((GameplayGameState)GameOveredState).GetLocalScores(), (n, s) => new XMLScoreEntry <TetrisHighScoreData>(n, s, new TetrisHighScoreData(useStats as TetrisStatistics))
                                                          , useStats as TetrisStatistics);
                            pOwner.CurrentState = ehs;
                            TetrisGame.Soundman.PlayMusic("highscoreentry", pOwner.Settings.std.MusicVolume, true);
                        }
                        else
                        {
                        }
                    }
                }
                else if (CompleteSummary)
                {
                    IBackground bg = null;
                    if (pOwner is BASeTris bt)
                    {
                        bg = StandardImageBackgroundGDI.GetStandardBackgroundDrawer();
                    }
                    else if (pOwner is BASeTrisTK)
                    {
                        bg = StandardImageBackgroundSkia.GetStandardBackgroundDrawer();
                    }
                    GenericMenuState TitleMenu = new GenericMenuState(bg, pOwner, new TitleMenuPopulator());
                    pOwner.CurrentState = TitleMenu;
                }
            }
        }
Ejemplo n.º 9
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     if (new GameKeys[] { GameKeys.GameKey_RotateCW, GameKeys.GameKey_RotateCCW }.Contains(g))
     {
         //proceed with procession function.
         var NextState = StateProcessionFunction();
         if (NextState == null)
         {
             throw new NullReferenceException("DrMarioLevelCompleteState: StateProcessionFunction returned null.");
         }
         if (NextState is GameplayGameState ggst)
         {
             ggst.FirstRun = false;
         }
         else if (NextState is ICompositeState <GameplayGameState> ggc)
         {
             ggc.GetComposite().FirstRun = false;
         }
         pOwner.CurrentState = NextState;
         //play the default music...
     }
 }
Ejemplo n.º 10
0
    public static void SaveDefaults(GameKeys keys)
    {
        SaveKeys save = new SaveKeys();

        save.keys   = new List <string>(keys.optionsList);
        save.values = new List <KeyCode>(keys.keysList);
        //Dictionary<string, KeyCode> Kb = new Dictionary<string, KeyCode>(KeyBinds);

        //save.binds = KeyBinds;
        string Json = JsonUtility.ToJson(save, true);
        //string codesJson = JsonUtility.ToJson(keyCodes, true);


        string path = Application.persistentDataPath;

        path = Application.dataPath + "/bin";

        if (!File.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        File.WriteAllText(path + "/defaults" + ".json", Json);
    }
Ejemplo n.º 11
0
 /**
  * Checks whether a game key has been released since the last update.
  *
  * @param gameKey The key to check.
  * @return True if gameKey is pressed.
  */
 public bool wasKeyJustReleased(GameKeys gameKey)
 {
     switch (deviceBindings[(int)gameKey])
     {
         case Devices.KEYBOARD:
             if (keyboard.IsKeyDown(Keys.LeftControl))
                 return !keyJustPressed[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)]
                     && keyPreviouslyPressed[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)];
             else if (keyboard.IsKeyDown(Keys.LeftAlt))
                 return !keyJustPressed[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)]
                     && keyPreviouslyPressed[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)];
             else if (keyboard.IsKeyDown(Keys.LeftShift))
                 return !keyJustPressed[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)]
                     && keyPreviouslyPressed[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)];
             else
             {
                 return !keyJustPressed[(int)gameKey] && keyPreviouslyPressed[(int)gameKey];
             }
         case Devices.MOUSE:
             if (keyboard.IsKeyDown(Keys.LeftControl))
                 return !mouseJustPressed[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)]
                     && mousePreviouslyPressed[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)];
             else if (keyboard.IsKeyDown(Keys.LeftAlt))
                 return !mouseJustPressed[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)]
                     && mousePreviouslyPressed[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)];
             else if (keyboard.IsKeyDown(Keys.LeftShift))
                 return !mouseJustPressed[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)]
                     && mousePreviouslyPressed[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)];
             else
                 return !mouseJustPressed[(int)gameKey] && mousePreviouslyPressed[(int)gameKey];
         case Devices.NONE:
             Console.WriteLine("request for key \"" + gameKey + "\" state but it's not bound!");
             return false;
         default:
             return false;
     }
 }
Ejemplo n.º 12
0
        /**
         * Clears all bindings related to a specific game key.
         *
         * @param gameKey The game key to clear bindings for.
         */
        public void clearBinding(GameKeys gameKey)
        {
            deviceBindings[(int)gameKey] = Devices.NONE;

            mouseBindings[(int)gameKey] = MouseButtons.NONE;
            mouseBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.CTRL)] = MouseButtons.NONE;
            mouseBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.SHIFT)] = MouseButtons.NONE;
            mouseBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.ALT)] = MouseButtons.NONE;

            keyboardBindings[(int)gameKey] = Keys.None;
            keyboardBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.CTRL)] = Keys.None;
            keyboardBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.SHIFT)] = Keys.None;
            keyboardBindings[(int)gameKey + (gameKeyCount * (int)ModifierKeys.ALT)] = Keys.None;
        }
Ejemplo n.º 13
0
 /**
  * Binds a game key to a specified keyboard key.
  * Keys in an enumeration of keyboard keys and is
  * part of the XNA framework.
  *
  * @param gameKey The game key to bind.
  * @param key The keyboard key to bind.
  */
 public void bind(GameKeys gameKey, Keys key, ModifierKeys modifier)
 {
     deviceBindings[(int)gameKey] = Devices.KEYBOARD;
     keyboardBindings[(int)gameKey + ((int)modifier * gameKeyCount)] = key;
 }
Ejemplo n.º 14
0
 /// <summary>
 /// Checa o estado da tecla e dispara os eventos.
 /// </summary>
 /// <param name="key">Tecla</param>
 /// <param name="prevState">Estado anterior</param>
 /// <param name="currState">Estado corrente</param>
 private void checkKeyState(GameKeys key, GameKeyState prevState, GameKeyState currState)
 {
     //Se o estado anterior era Released e o estado corrente é Pressed
     // dispara os dois eventos de Pressed e IsDown.
     if (prevState == GameKeyState.Released && currState == GameKeyState.Pressed)
     {
         handleGameKeyPressed(key);
         handleGameKeyIsDown(key);
     }
     // Se o estado anterior era pressed e o estado corrente é Released
     // dispara o evento Released.
     if (prevState == GameKeyState.Pressed && currState == GameKeyState.Released)
         handleGameKeyReleased(key);
     //Se o estado anterior é pressed e o corrente é pressed
     // dispara o evento Pressed.
     if (prevState == GameKeyState.Pressed && currState == GameKeyState.Pressed)
         handleGameKeyIsDown(key);
 }
 /// <summary>
 /// Used to retrieve the key mapping for the given Gamekey.
 /// </summary>
 /// <param name="key">The GameKey that the user wants to see the key mapping for</param>
 public Keys GetGameKeyMapping(GameKeys key)
 {
     return _gameKeyMappings[(int)key];
 }
 /// <summary>
 /// Used to add an event to the GameKeyReleased
 /// </summary>
 /// <param name="key">The selected GameKey</param>
 public void AddGameKeyReleased(GameKeys key, KeyboardEvent evt)
 {
     _gameKeyReleased[(int)key] += evt;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Checks whether a given key has been pressed or not.
 /// </summary>
 /// <param name="key">The key to check.</param>
 /// <returns></returns>
 public static bool KeyPressed(GameKeys key)
 {
     return(kbs_c.IsKeyDown(FilterKeyType(key)) && kbs_p.IsKeyUp(FilterKeyType(key)));
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Get if a game key was pressed down in this very frame.
 /// </summary>
 /// <param name="key">Game key to test.</param>
 /// <returns>If Game key was pressed in this frame.</returns>
 public bool IsKeyPressed(GameKeys key)
 {
     return(_gameKeysDown[key] && !_gamePreviousKeysDown[key]);
 }
Ejemplo n.º 19
0
 /// <summary>
 /// Get if a game key is currently down.
 /// </summary>
 /// <param name="key">Game key to test.</param>
 /// <returns>If Game key is currently down.</returns>
 public bool IsKeyDown(GameKeys key)
 {
     return(_gameKeysDown[key]);
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Assign a mouse button to a Game key.
 /// </summary>
 /// <param name="mouseButton">Mouse button.</param>
 /// <param name="gameKey">Game key.</param>
 public void AssignMouseButtonToGameKey(MouseButton mouseButton, GameKeys gameKey)
 {
     _mouseKeysMap[mouseButton] = gameKey;
 }
Ejemplo n.º 21
0
 /// <summary>
 /// Assign a keyboard key to a Game key.
 /// </summary>
 /// <param name="keyboardKey">Keyboard key.</param>
 /// <param name="gameKey">Game key.</param>
 public void AssignKeyboardKeyToGameKey(KeyboardKeys keyboardKey, GameKeys gameKey)
 {
     _keyboardMap[keyboardKey] = gameKey;
 }
Ejemplo n.º 22
0
        void Simulate()
        {
            if (networkOptions.Hosting)
            {
                // Prepare for simulation. Typically we use a time step of 1/60 of a
                // second (60Hz) and 10 iterations. This provides a high quality simulation
                // in most game scenarios.
                float timeStep = 1.0f / settingsHz;

                const int MoveSpeed = 450 * 9;

                BipedFixtureIndex[] fixturesToMove;
                float speedMultiplier = 1;

                if (server.Clients.Count != 0)
                {
                    for (int i = 0; i < 2; ++i)
                    {
                        if (server.Clients.Count == i)
                        {
                            break;
                        }

                        if ((server.Clients[i].Keys & GameKeys.Legs) != 0)
                        {
                            fixturesToMove  = new BipedFixtureIndex[] { BipedFixtureIndex.LFoot, BipedFixtureIndex.RFoot };
                            speedMultiplier = 0.25f;
                        }
                        else if ((server.Clients[i].Keys & GameKeys.Hands) != 0)
                        {
                            fixturesToMove  = new BipedFixtureIndex[] { BipedFixtureIndex.LHand, BipedFixtureIndex.RHand };
                            speedMultiplier = 0.25f;
                        }
                        else
                        {
                            fixturesToMove = new BipedFixtureIndex[] { BipedFixtureIndex.Chest }
                        };

                        if ((server.Clients[i].Keys & GameKeys.Up) != 0)
                        {
                            foreach (var x in fixturesToMove)
                            {
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2(0, MoveSpeed * speedMultiplier), players[i].Biped.Bodies[(int)x].WorldCenter);
                            }
                        }
                        if ((server.Clients[i].Keys & GameKeys.Down) != 0)
                        {
                            foreach (var x in fixturesToMove)
                            {
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2(0, (-MoveSpeed / 2) * speedMultiplier), players[i].Biped.Bodies[(int)x].WorldCenter);
                            }
                        }
                        if ((server.Clients[i].Keys & GameKeys.Left) != 0)
                        {
                            foreach (var x in fixturesToMove)
                            {
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2((-MoveSpeed / 2) * speedMultiplier, 0), players[i].Biped.Bodies[(int)x].WorldCenter);
                            }
                        }
                        if ((server.Clients[i].Keys & GameKeys.Right) != 0)
                        {
                            foreach (var x in fixturesToMove)
                            {
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2((MoveSpeed / 2) * speedMultiplier, 0), players[i].Biped.Bodies[(int)x].WorldCenter);
                            }
                        }

                        players[i].StickingHands = (server.Clients[i].Keys & GameKeys.StickHands) != 0;
                        players[i].StickingLegs  = (server.Clients[i].Keys & GameKeys.StickLegs) != 0;

                        if ((server.Clients[i].Keys & GameKeys.StiffToggle) != 0)
                        {
                            players[i].Biped.StickBody();
                            server.Clients[i].Keys &= ~GameKeys.StiffToggle;
                        }
                    }
                }

                // This is our little game loop.
                // Instruct the world to perform a single step of simulation.
                // It is generally best to keep the time step and iterations fixed.
                world.Step(timeStep);

                for (int z = 0; z < 2; ++z)
                {
                    for (int i = 0; i < players[z].WeldDefs.Length; ++i)
                    {
                        if (players[z].Welds[i] != null && players[z].WeldDefs[i])
                        {
                            world.AddJoint(players[z].Welds[i]);
                            players[z].WeldDefs[i] = false;
                        }

                        if (i < 2 && !players[z].StickingLegs ||
                            i >= 2 && !players[z].StickingHands)
                        {
                            if (players[z].Welds[i] != null)
                            {
                                world.RemoveJoint(players[z].Welds[i]);
                                players[z].Welds[i] = null;
                            }
                        }
                    }
                }

                server.Stream.Write((byte)Networking.EClientDataPacketType.FramePacket);
                server.Stream.Write(server.Frame);
                for (int i = 0; i < (int)BipedFixtureIndex.Max; ++i)
                {
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Position.X);
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Position.Y);
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Rotation);

                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Position.X);
                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Position.Y);
                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Rotation);
                }
            }
            else
            {
                if (_oldGameKeys != _gameKeys)
                {
                    client.Udp.Stream.Write((byte)Networking.EServerDataPacketType.ClientCmd);
                    client.Udp.Stream.Write((int)_gameKeys);

                    _oldGameKeys = _gameKeys;
                }

                if ((_gameKeys & GameKeys.StiffToggle) != 0)
                {
                    _gameKeys    &= ~GameKeys.StiffToggle;
                    _oldGameKeys &= ~GameKeys.StiffToggle;
                }
            }

            if (networkOptions.Hosting)
            {
                server.Check();

                server.Frame++;
            }
            else
            {
                client.Check();

                client.Frame++;
            }
        }

        void OnGLResize()
        {
            InitOpenGL(pictureBox1.Size, _currentZoom, PointF.Empty);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Dispacha o evento da tecla.
 /// </summary>
 /// <param name="evt">Evento</param>
 /// <param name="key">Tecla envolvida</param>
 private void dispatchEvent(gameInputHandler evt, GameKeys key)
 {
     if (evt != null)
         evt(this, getEventArgs(key));
 }
Ejemplo n.º 24
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     //do not allow this to pass through to the composite state, otherwise the BlockGroups will be able to be controlled.
 }
Ejemplo n.º 25
0
        private void ShowSettings()
        {
            _keyboardListener.ClearEvent();

            var panel = new Panel(new Vector2(650, 650), PanelSkin.Fancy);

            panel.AddChild(new Header("Paramètres du jeu"));
            panel.AddChild(new HorizontalLine());

            var settingsPanel = new Panel(new Vector2(600, 100), PanelSkin.None, Anchor.Auto);

            settingsPanel.AddChild(new Paragraph("Volume audio"));
            settingsPanel.AddChild(new Slider(0, 100).Apply((ref Slider slider) => {
                slider.Value          = (PCGame.SoundVolume * 100f).Round();
                slider.OnValueChange += entity => PCGame.SoundVolume = ((Slider)entity).Value / 100f;
            }));

            panel.AddChild(settingsPanel);

            var settingsKeysPanel =
                new Panel(new Vector2(600, 350), PanelSkin.None, Anchor.Auto)
            {
                PanelOverflowBehavior = PanelOverflowBehavior.VerticalScroll
            };

            foreach (GameKeys.GKeys gk in Enum.GetValues(typeof(GameKeys.GKeys)))
            {
                var(description, key) = GameKeys.GetKey(gk);

                settingsKeysPanel.AddChild(new Paragraph(description));

                var btn = new Button(key.ToString())
                {
                    ToggleMode = true,
                    OnClick    = entity => {
                        foreach (var child in settingsKeysPanel.GetChildren())
                        {
                            if (!ReferenceEquals(child, entity) && child is Button b)
                            {
                                b.Checked = false;
                            }
                        }
                    }
                };

                _keyboardListener.OnKeyPressedEventArg += k => {
                    if (btn.Checked)
                    {
                        GameKeys.SetKey(gk, k);
                        btn.ButtonParagraph.Text = k.ToString();
                    }
                };

                settingsKeysPanel.AddChild(btn);
            }

            panel.AddChild(settingsKeysPanel);

            panel.AddChild(new Button("Fermer").Apply((ref Button btn) =>
                                                      btn.OnClick = entity => panel.RemoveFromParent()));

            UserInterface.Active.AddEntity(panel);
        }
    }
Ejemplo n.º 26
0
 /// <summary>
 /// Get if a game key was released in this very frame.
 /// </summary>
 /// <param name="key">Game key to test.</param>
 /// <returns>If Game key was released in this frame.</returns>
 public bool IsKeyReleased(GameKeys key)
 {
     return(!_gameKeysDown[key] && _gamePreviousKeysDown[key]);
 }
 /// <summary>
 /// Tells the user if the desired GameKey is currently released
 /// </summary>
 /// <param name="key">The selected GameKey</param>
 public bool IsKeyUp(GameKeys key)
 {
     return _lastKeyboardState.IsKeyDown(_gameKeyMappings[(int)key]);
 }
Ejemplo n.º 28
0
        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            //handle up and down to change the currently selected menu item.
            //Other game keys we pass on to the currently selected item itself for additional handling.
            bool triggered     = false;
            var  OriginalIndex = SelectedIndex;

            if (g == GameKeys.GameKey_Down)
            {
                if (ActivatedItem != null)
                {
                    ActivatedItem.ProcessGameKey(pOwner, g);
                }
                else
                {
                    //move selected index upwards.

                    SelectedIndex = GetNextIndex(SelectedIndex);
                    while (!MenuElements[SelectedIndex].GetSelectable())
                    {
                        SelectedIndex = GetNextIndex(SelectedIndex);
                    }
                }
                triggered = true;
                //should also skip if disabled...
            }
            else if (g == GameKeys.GameKey_Drop)
            {
                if (ActivatedItem != null)
                {
                    ActivatedItem.ProcessGameKey(pOwner, g);
                }
                else
                { //move selected index downwards.
                    SelectedIndex = GetPreviousIndex(SelectedIndex);

                    while (!MenuElements[SelectedIndex].GetSelectable())
                    {
                        SelectedIndex = GetPreviousIndex(SelectedIndex);
                    }
                }
                triggered = true;
            }

            if (g == GameKeys.GameKey_RotateCW || g == GameKeys.GameKey_MenuActivate || g == GameKeys.GameKey_Pause)
            {
                if (ActivatedItem != null)
                {
                    TetrisGame.Soundman.PlaySound(pOwner.AudioThemeMan.MenuItemActivated.Key, pOwner.Settings.std.EffectVolume);
                    ActivatedItem.OnDeactivated();
                    ActivatedItem = null;
                }
                else
                {
                    //Activate the currently selected item.
                    var currentitem = MenuElements[SelectedIndex];
                    TetrisGame.Soundman.PlaySound(pOwner.AudioThemeMan.MenuItemActivated.Key, pOwner.Settings.std.EffectVolume);
                    ActivatedItem = currentitem;
                    MenuItemActivated?.Invoke(this, new MenuStateMenuItemActivatedEventArgs(currentitem));

                    currentitem.OnActivated();
                }
                triggered = true;
            }

            else if (OriginalIndex != SelectedIndex)
            {
                TetrisGame.Soundman.PlaySound(pOwner.AudioThemeMan.MenuItemSelected.Key, pOwner.Settings.std.EffectVolume);
                var previousitem = MenuElements[OriginalIndex];
                var currentitem  = MenuElements[SelectedIndex];
                MenuItemDeselected?.Invoke(this, new MenuStateMenuItemSelectedEventArgs(previousitem));
                MenuItemSelected?.Invoke(this, new MenuStateMenuItemSelectedEventArgs(currentitem));
                previousitem.OnDeselected();
                currentitem.OnSelected();
            }

            if (!triggered)
            {
                var currentitem = MenuElements[SelectedIndex];
                currentitem.ProcessGameKey(pOwner, g);
            }
            //throw new NotImplementedException();
        }
 /// <summary>
 /// Used to remove an event from the GameKeyReleased
 /// </summary>
 /// <param name="key">The selected GameKey</param>
 public void RemoveGameKeyReleased(GameKeys key, KeyboardEvent evt)
 {
     _gameKeyReleased[(int)key] -= evt;
 }
Ejemplo n.º 30
0
        void Simulate()
        {
            if (networkOptions.Hosting)
            {
                // Prepare for simulation. Typically we use a time step of 1/60 of a
                // second (60Hz) and 10 iterations. This provides a high quality simulation
                // in most game scenarios.
                float timeStep = 1.0f / settingsHz;

                const int MoveSpeed = 450 * 9;

                BipedFixtureIndex[] fixturesToMove;
                float speedMultiplier = 1;

                if (server.Clients.Count != 0)
                {
                    for (int i = 0; i < 2; ++i)
                    {
                        if (server.Clients.Count == i)
                            break;

                        if ((server.Clients[i].Keys & GameKeys.Legs) != 0)
                        {
                            fixturesToMove = new BipedFixtureIndex[] { BipedFixtureIndex.LFoot, BipedFixtureIndex.RFoot };
                            speedMultiplier = 0.25f;
                        }
                        else if ((server.Clients[i].Keys & GameKeys.Hands) != 0)
                        {
                            fixturesToMove = new BipedFixtureIndex[] { BipedFixtureIndex.LHand, BipedFixtureIndex.RHand };
                            speedMultiplier = 0.25f;
                        }
                        else
                            fixturesToMove = new BipedFixtureIndex[] { BipedFixtureIndex.Chest };

                        if ((server.Clients[i].Keys & GameKeys.Up) != 0)
                        {
                            foreach (var x in fixturesToMove)
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2(0, MoveSpeed * speedMultiplier), players[i].Biped.Bodies[(int)x].WorldCenter);
                        }
                        if ((server.Clients[i].Keys & GameKeys.Down) != 0)
                        {
                            foreach (var x in fixturesToMove)
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2(0, (-MoveSpeed / 2) * speedMultiplier), players[i].Biped.Bodies[(int)x].WorldCenter);
                        }
                        if ((server.Clients[i].Keys & GameKeys.Left) != 0)
                        {
                            foreach (var x in fixturesToMove)
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2((-MoveSpeed / 2) * speedMultiplier, 0), players[i].Biped.Bodies[(int)x].WorldCenter);
                        }
                        if ((server.Clients[i].Keys & GameKeys.Right) != 0)
                        {
                            foreach (var x in fixturesToMove)
                                players[i].Biped.Bodies[(int)x].ApplyForce(new Vector2((MoveSpeed / 2) * speedMultiplier, 0), players[i].Biped.Bodies[(int)x].WorldCenter);
                        }

                        players[i].StickingHands = (server.Clients[i].Keys & GameKeys.StickHands) != 0;
                        players[i].StickingLegs = (server.Clients[i].Keys & GameKeys.StickLegs) != 0;

                        if ((server.Clients[i].Keys & GameKeys.StiffToggle) != 0)
                        {
                            players[i].Biped.StickBody();
                            server.Clients[i].Keys &= ~GameKeys.StiffToggle;
                        }
                    }
                }

                // This is our little game loop.
                // Instruct the world to perform a single step of simulation.
                // It is generally best to keep the time step and iterations fixed.
                world.Step(timeStep);

                for (int z = 0; z < 2; ++z)
                for (int i = 0; i < players[z].WeldDefs.Length; ++i)
                {
                    if (players[z].Welds[i] != null && players[z].WeldDefs[i])
                    {
                        world.AddJoint(players[z].Welds[i]);
                        players[z].WeldDefs[i] = false;
                    }

                    if (i < 2 && !players[z].StickingLegs ||
                    i >= 2 && !players[z].StickingHands)
                    {
                        if (players[z].Welds[i] != null)
                        {
                            world.RemoveJoint(players[z].Welds[i]);
                            players[z].Welds[i] = null;
                        }
                    }
                }

                server.Stream.Write((byte)Networking.EClientDataPacketType.FramePacket);
                server.Stream.Write(server.Frame);
                for (int i = 0; i < (int)BipedFixtureIndex.Max; ++i)
                {
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Position.X);
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Position.Y);
                    server.Stream.Write(players[0].Biped.Bodies[(int)i].Rotation);

                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Position.X);
                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Position.Y);
                    server.Stream.Write(players[1].Biped.Bodies[(int)i].Rotation);
                }
            }
            else
            {
                if (_oldGameKeys != _gameKeys)
                {
                    client.Udp.Stream.Write((byte)Networking.EServerDataPacketType.ClientCmd);
                    client.Udp.Stream.Write((int)_gameKeys);

                    _oldGameKeys = _gameKeys;
                }

                if ((_gameKeys & GameKeys.StiffToggle) != 0)
                {
                    _gameKeys &= ~GameKeys.StiffToggle;
                    _oldGameKeys &= ~GameKeys.StiffToggle;
                }
            }

            if (networkOptions.Hosting)
            {
                server.Check();

                server.Frame++;
            }
            else
            {
                client.Check();

                client.Frame++;
            }
        }
 /// <summary>
 /// Used to set the key mapping for the given Gamekey.
 /// </summary>
 /// <param name="key">The GameKey that the user wants to change the key mapping for</param>
 public void SetGameKeyMapping(GameKeys gameKey, Keys newKey)
 {
     _gameKeyMappings[(int)gameKey] = newKey;
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Construtor dos argumentos 
 /// </summary>
 /// <param name="state">Estado dos botões</param>
 /// <param name="key">Key envolvida no evento</param>
 public InputHandlerEventArgs(GameKeysState state, GameKeys key)
 {
     this.gameKeysState = state;
     this.key = key;
 }
Ejemplo n.º 33
0
 private void handleGameKeyPressed(GameKeys key)
 {
     gameInputHandler gih = null;
     switch (key)
     {
         case GameKeys.Down:
             gih = onButtonDownPressed;
             break;
         case GameKeys.Up:
             gih = onButtonUpPressed;
             break;
         case GameKeys.Left:
             gih = onButtonLeftPressed;
             break;
         case GameKeys.Right:
             gih = onButtonRightPressed;
             break;
         case GameKeys.A:
             gih = onButtonAPressed;
             break;
         case GameKeys.B:
             gih = onButtonBPressed;
             break;
         case GameKeys.Y:
             gih = onButtonYPressed;
             break;
         case GameKeys.X:
             gih = onButtonXPressed;
             break;
         case GameKeys.Start:
             gih = onButtonStartPressed;
             break;
         case GameKeys.Back:
             gih = onButtonBackPressed;
             break;
         case GameKeys.LB:
             gih = onButtonL1Pressed;
             break;
         case GameKeys.LT:
             gih = onButtonL2Pressed;
             break;
         case GameKeys.RB:
             gih = onButtonR1Pressed;
             break;
         case GameKeys.RT:
             gih = onButtonR2Pressed;
             break;
         case GameKeys.UpLeft:
             gih = onButtonUpLeftPressed;
             break;
         case GameKeys.UpRight:
             gih = onButtonUpRightPressed;
             break;
         case GameKeys.DownLeft:
             gih = onButtonDownLeftPressed;
             break;
         case GameKeys.DownRight:
             gih = onButtonDownRightPressed;
             break;
         case GameKeys.NoneDirection:
             gih = onNoneDirectionPressed;
             break;
     }
     dispatchEvent(onAnyButtonPressed, key);
     dispatchEvent(gih, key);
 }
Ejemplo n.º 34
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     //Should we allow Game keys here? probably. We'll block them for the moment though. There shouldn't be an active Nomino during this process
     //so really there shouldn't be anything to control- Aside, of course, from pause for example.
     //throw new NotImplementedException();
 }
Ejemplo n.º 35
0
 /**
  * Binds a game key to a specified mouse button.
  * <code>MouseButtons</code> is an enumeration of
  * the mouse buttons that it is possible to bind to
  * and is part of the <code>GameInput</code> namespace.
  *
  * @param gameKey The game key to bind.
  * @param button The mouse button to bind.
  */
 public void bind(GameKeys gameKey, MouseButtons button, ModifierKeys modifier)
 {
     deviceBindings[(int)gameKey] = Devices.MOUSE;
     mouseBindings[(int)gameKey + ((int)modifier * gameKeyCount)] = button;
 }
Ejemplo n.º 36
0
 private void handleGameKeyReleased(GameKeys key)
 {
     gameInputHandler gih = null;
     switch (key)
     {
         case GameKeys.Down:
             gih = onButtonDownReleased;
             break;
         case GameKeys.Up:
             gih = onButtonUpReleased;
             break;
         case GameKeys.Left:
             gih = onButtonLeftReleased;
             break;
         case GameKeys.Right:
             gih = onButtonRightReleased;
             break;
         case GameKeys.A:
             gih = onButtonAReleased;
             break;
         case GameKeys.B:
             gih = onButtonBReleased;
             break;
         case GameKeys.Y:
             gih = onButtonYReleased;
             break;
         case GameKeys.X:
             gih = onButtonXReleased;
             break;
         case GameKeys.Start:
             gih = onButtonStartReleased;
             break;
         case GameKeys.Back:
             gih = onButtonBackReleased;
             break;
         case GameKeys.LB:
             gih = onButtonL1Released;
             break;
         case GameKeys.LT:
             gih = onButtonL2Released;
             break;
         case GameKeys.RB:
             gih = onButtonR1Released;
             break;
         case GameKeys.RT:
             gih = onButtonR2Released;
             break;
         case GameKeys.UpLeft:
             gih = onButtonUpLeftReleased;
             break;
         case GameKeys.UpRight:
             gih = onButtonUpRightReleased;
             break;
         case GameKeys.DownLeft:
             gih = onButtonDownLeftReleased;
             break;
         case GameKeys.DownRight:
             gih = onButtonDownRightReleased;
             break;
         case GameKeys.NoneDirection:
             gih = onNoneDirectionReleased;
             break;
     }
     dispatchEvent(onAnyButtonReleased, key);
     dispatchEvent(gih, key);
 }
Ejemplo n.º 37
0
 /**
  * Checks whether a game key is pressed.
  *
  * @param gameKey The key to check.
  * @return True if gameKey is pressed.
  */
 public bool isKeyPressed(GameKeys gameKey)
 {
     /*
      * To find out if a key is pressed:
      * 1. A mapping must be queried to determine which device the key is bound to.
      * 2. Modifiers must be checked so the appropiate device key is looked up.
      * 3. Look up device key according to modifiers and game key in a bindings mapping
      *    specific to the device.
      * 4. Check the state of the device key.
      */
     switch (deviceBindings[(int)gameKey])
     {
         case Devices.KEYBOARD:
             if (keyboard.IsKeyDown(Keys.LeftControl))
                 return keyboard.IsKeyDown(keyboardBindings[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)]);
             else if(keyboard.IsKeyDown(Keys.LeftAlt))
                 return keyboard.IsKeyDown(keyboardBindings[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)]);
             else if(keyboard.IsKeyDown(Keys.LeftShift))
                 return keyboard.IsKeyDown(keyboardBindings[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)]);
             else
                 return keyboard.IsKeyDown(keyboardBindings[(int)gameKey]);
         case Devices.MOUSE:
             if (keyboard.IsKeyDown(Keys.LeftControl))
                 return isMouseButtonPressed(mouseBindings[(int)gameKey + ((int)ModifierKeys.CTRL * gameKeyCount)]);
             else if (keyboard.IsKeyDown(Keys.LeftAlt))
                 return isMouseButtonPressed(mouseBindings[(int)gameKey + ((int)ModifierKeys.ALT * gameKeyCount)]);
             else if (keyboard.IsKeyDown(Keys.LeftShift))
                 return isMouseButtonPressed(mouseBindings[(int)gameKey + ((int)ModifierKeys.SHIFT * gameKeyCount)]);
             else
                 return isMouseButtonPressed(mouseBindings[(int)gameKey]);
         case Devices.NONE:
             Console.WriteLine("request for key \"" + gameKey + "\" state but it's not bound!");
             return false;
         default:
             return false;
     }
 }
 public override void RefreshValues()
 {
     base.RefreshValues();
     Description = Module.CurrentModule.GlobalTextManager.FindText("str_key_category_name", _categoryId).ToString();
     GameKeys.ApplyActionOnAllItems(x => x.RefreshValues());
 }
Ejemplo n.º 39
0
        public override void OnInspectorGUI()
        {
            e = Event.current;
            GameKeys g = target as GameKeys;

            options = g.optionsList;
            int i = 0;

            if (options == null)
            {
                return;
            }
            if (g.optionsList == null)
            {
                return;
            }
            foreach (var option in g.optionsList)
            {
                while (tracker.Count < g.keysList.Count)
                {
                    tracker.Add(KeyCode.None);
                }

                while (g.keysList.Count < g.optionsList.Count)
                {
                    g.keysList.Add(KeyCode.None);
                }
                while (keys.Count < g.optionsList.Count)
                {
                    keys.Add("");
                }
                if (g.keysList.Count > g.optionsList.Count)
                {
                    g.keysList.RemoveRange(g.optionsList.Count - 1, g.keysList.Count - g.optionsList.Count);
                }
                EditorGUILayout.LabelField(g.optionsList[i] + ": " + g.keysList[i]);

                keys[i] = GUILayout.TextField(keys[i]).ToLower();
                //Debug.Log(keys[i]);
                if (tracker[i] != g.keysList[i])
                {
                    continue;
                }
                if (keys[i] != "")
                {
                    g.keysList[i] = InputMap.WhatKeyCode(keys[i]);
                    // tracker[i] = g.keysList[i];
                }

                i++;
            }
            tracker = g.keysList;
            if (listen)
            {
                KeyCode code = KeyCode.None;

                if (e == null)
                {
                    return;
                }

                if (e.isKey)
                {
                    string str = e.character.ToString();
                    code = InputMap.WhatKeyCode(str);
                }
                if (e.isMouse)
                {
                    if (e.type == EventType.MouseDown)
                    {
                        code = InputMap.WhatMouseButton(e.button);
                    }
                }
            }
            base.OnInspectorGUI();
        }
Ejemplo n.º 40
0
 private void handleGameKeyIsDown(GameKeys key)
 {
     gameInputHandler gih = null;
     switch (key)
     {
         case GameKeys.Down:
             gih = onButtonDownIsDown;
             break;
         case GameKeys.Up:
             gih = onButtonUpIsDown;
             break;
         case GameKeys.Left:
             gih = onButtonLeftIsDown;
             break;
         case GameKeys.Right:
             gih = onButtonRightIsDown;
             break;
         case GameKeys.A:
             gih = onButtonAIsDown;
             break;
         case GameKeys.B:
             gih = onButtonBIsDown;
             break;
         case GameKeys.Y:
             gih = onButtonYIsDown;
             break;
         case GameKeys.X:
             gih = onButtonXIsDown;
             break;
         case GameKeys.Start:
             gih = onButtonStartIsDown;
             break;
         case GameKeys.Back:
             gih = onButtonBackIsDown;
             break;
         case GameKeys.LB:
             gih = onButtonL1IsDown;
             break;
         case GameKeys.LT:
             gih = onButtonL2IsDown;
             break;
         case GameKeys.RB:
             gih = onButtonR1IsDown;
             break;
         case GameKeys.RT:
             gih = onButtonR2IsDown;
             break;
         case GameKeys.UpLeft:
             gih = onButtonUpLeftIsDown;
             break;
         case GameKeys.UpRight:
             gih = onButtonUpRightIsDown;
             break;
         case GameKeys.DownLeft:
             gih = onButtonDownLeftIsDown;
             break;
         case GameKeys.DownRight:
             gih = onButtonDownRightIsDown;
             break;
         case GameKeys.NoneDirection:
             gih = onNoneDirectionIsDown;
             break;
     }
     dispatchEvent(onAnyButtonIsDown, key);
     dispatchEvent(gih, key);
 }
Ejemplo n.º 41
0
        //TODO:
        //make functions for IsAnyKeysPressed() and IsAllKeysPressed()
        //they should accept params of keys
        public bool GetKey(GameKeys KeyToFind, InputDeviceManagerAccess.ControllerIdType CurrControllerId)
        {
            bool RetVal = false;

            if (this._TypeOfDevice == InputDeviceAccess.TypeOfDevices.Keyboard)
            {
                foreach (DirectInput.Key a in this.PressedKeys)
                {
                    if ((DirectInput.Key) this.KeyTable[CurrControllerId.DeviceUserId - 1][KeyToFind] == a)
                    {
                        RetVal = true;
                        break;
                    }
                }
            }
            else if (this._TypeOfDevice == InputDeviceAccess.TypeOfDevices.Gamepad)
            {
                byte[] ButtonStatus;
                int[]  HatStatus;

                //Check hats and axis
                if (KeyToFind >= InputDeviceAccess.GameKeys.Up && KeyToFind <= InputDeviceAccess.GameKeys.Right)
                {
                    HatStatus = this.device.CurrentJoystickState.GetPointOfView();
                    int PressedKeyValue = (int)(this.KeyTable[CurrControllerId.DeviceUserId - 1][KeyToFind]);
                    switch (KeyToFind)
                    {
                    case (InputDeviceAccess.GameKeys.Up):
                        if (HatStatus[0] == 0 || HatStatus[0] == 4500 || HatStatus[0] == 31500)
                        {
                            RetVal = true;
                        }
                        break;

                    case (InputDeviceAccess.GameKeys.Left):
                        if (HatStatus[0] == 27000 || HatStatus[0] == 31500 || HatStatus[0] == 22500)
                        {
                            RetVal = true;
                        }
                        break;

                    case (InputDeviceAccess.GameKeys.Right):
                        if (HatStatus[0] == 9000 || HatStatus[0] == 4500 || HatStatus[0] == 13500)
                        {
                            RetVal = true;
                        }
                        break;

                    case (InputDeviceAccess.GameKeys.Down):
                        if (HatStatus[0] == 18000 || HatStatus[0] == 22500 || HatStatus[0] == 13500)
                        {
                            RetVal = true;
                        }
                        break;
                    }
                }
                //Check buttons
                else if (KeyToFind == InputDeviceAccess.GameKeys.Attack)
                {
                    ButtonStatus = this.device.CurrentJoystickState.GetButtons();
                    int PressedKeyValue = (int)(this.KeyTable[CurrControllerId.DeviceUserId - 1][KeyToFind]);
                    if (ButtonStatus[PressedKeyValue] > 0)
                    {
                        RetVal = true;
                    }
                }
            }

            return(RetVal);
        }
Ejemplo n.º 42
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     //do nothing- we don't allow control here.
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Retorna verdadeiro se uma GameKeys for uma direção.
 /// </summary>
 /// <param name="key">GameKey</param>
 /// <returns>bool</returns>
 public bool GameKeysIsDirection(GameKeys key)
 {
     switch (key)
     {
         case GameKeys.Up:
         case GameKeys.Down:
         case GameKeys.Left:
         case GameKeys.Right:
         case GameKeys.UpLeft:
         case GameKeys.UpRight:
         case GameKeys.DownLeft:
         case GameKeys.DownRight:
             return true;
         default:
             return false;
     }
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Checks whether a given key is being held down or not.
 /// </summary>
 /// <param name="key">The key to check.</param>
 /// <returns></returns>
 public static bool KeyHeld(GameKeys key)
 {
     return(kbs_c.IsKeyDown(FilterKeyType(key)));
 }
Ejemplo n.º 45
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     base.HandleGameKey(pOwner, g);
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Cria os argumentos do evento.
 /// </summary>
 /// <param name="key">Tecla envolvida</param>
 /// <returns>InputHandlerEventArgs</returns>
 private InputHandlerEventArgs getEventArgs(GameKeys key)
 {
     return new InputHandlerEventArgs(_currentGameKeysState, key);
 }
Ejemplo n.º 47
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     //since we are "paused"
 }
        public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
        {
            if (HandleBlockGroupKey(pOwner, g))
            {
                return;
            }


            if (g == GameKeys.GameKey_RotateCW || g == GameKeys.GameKey_RotateCCW)
            {
                bool ccw = g == GameKeys.GameKey_RotateCCW;
                foreach (var activeitem in PlayField.BlockGroups)
                {
                    if (!activeitem.Controllable)
                    {
                        continue;
                    }
                    if (PlayField.CanRotate(activeitem, ccw))
                    {
                        PerformRotation(pOwner, activeitem, ccw);
                    }
                    else if (this.GameOptions.AllowWallKicks)

                    {
                        //we will add up to 3 and subtract up to 3 to the X coordinate. if any say we can rotate then we proceed with allowing the rotation.

                        int[] checkoffsets = new int[] { 1, -1, 2, -2, 3, -3 };


                        int     OriginalPos = activeitem.X;
                        Boolean revertpos   = true;

                        foreach (int currentoffset in checkoffsets)
                        {
                            if (currentoffset == 0)
                            {
                                continue;
                            }
                            activeitem.X = OriginalPos + currentoffset;
                            if (PlayField.CanRotate(activeitem, ccw))
                            {
                                PerformRotation(pOwner, activeitem, ccw);
                                revertpos = false;
                                break;
                            }
                        }

                        if (revertpos)
                        {
                            activeitem.X = OriginalPos;
                        }
                    }
                }
            }
            else if (g == GameKeys.GameKey_Down)
            {
                HandleActiveGroups(pOwner, true);
            }
            else if (g == GameKeys.GameKey_Drop)
            {
                //drop all active groups.
                Nomino FirstGroup = PlayField.BlockGroups.FirstOrDefault();



                if (FirstGroup != null)
                {
                    //store the block positions for each block in the nomino.


                    foreach (var activeitem in PlayField.BlockGroups)
                    {
                        if (!activeitem.Controllable)
                        {
                            continue;
                        }
                        List <Tuple <BCPoint, NominoElement> > StartBlockPositions = new List <Tuple <BCPoint, NominoElement> >();
                        List <Tuple <BCPoint, NominoElement> > EndBlockPositions   = new List <Tuple <BCPoint, NominoElement> >();
                        foreach (var element in activeitem)
                        {
                            StartBlockPositions.Add(new Tuple <BCPoint, NominoElement>(new BCPoint(activeitem.X + element.X, activeitem.Y + element.Y), element));
                        }
                        int dropqty = 0;
                        var ghosted = GetGhostDrop(pOwner, activeitem, out dropqty, 0);
                        foreach (var element in ghosted)
                        {
                            EndBlockPositions.Add(new Tuple <BCPoint, NominoElement>(new BCPoint(ghosted.X + element.X, ghosted.Y + element.Y), element));
                        }
                        GenerateDropParticles(StartBlockPositions, EndBlockPositions);
                        activeitem.X = ghosted.X;
                        activeitem.SetY(pOwner, ghosted.Y);
                        PlayField.SetGroupToField(activeitem);
                        PlayField.RemoveBlockGroup(activeitem);
                        if (GameStats is TetrisStatistics ts)
                        {
                            GameStats.AddScore((dropqty * (5 + (ts.LineCount / 10))));
                        }
                    }

                    pOwner.Feedback(0.6f, 200);
                    Sounds.PlaySound(pOwner.AudioThemeMan.BlockGroupPlace.Key, pOwner.Settings.std.EffectVolume);
                    GameHandler.ProcessFieldChange(this, pOwner, FirstGroup);
                    //ProcessFieldChangeWithScore(pOwner, FirstGroup);
                }
            }
            else if (g == GameKeys.GameKey_Right || g == GameKeys.GameKey_Left)
            {
                int XMove = g == GameKeys.GameKey_Right ? 1 : -1;
                foreach (var ActiveItem in PlayField.BlockGroups)
                {
                    if (!ActiveItem.Controllable)
                    {
                        continue;
                    }
                    if (PlayField.CanFit(ActiveItem, ActiveItem.X + XMove, ActiveItem.Y, false) == TetrisField.CanFitResultConstants.CanFit)
                    {
                        lastHorizontalMove = DateTime.Now;
                        ActiveItem.X      += XMove;
                        Sounds.PlaySound(pOwner.AudioThemeMan.BlockGroupMove.Key, pOwner.Settings.std.EffectVolume);
                        pOwner.Feedback(0.1f, 50);
                    }
                    else
                    {
                        Sounds.PlaySound(pOwner.AudioThemeMan.BlockStopped.Key, pOwner.Settings.std.EffectVolume);
                        pOwner.Feedback(0.4f, 75);
                    }
                }
            }
            else if (g == GameKeys.GameKey_Pause)
            {
                if (g == GameKeys.GameKey_Pause)
                {
                    pOwner.LastPausedTime = DateTime.Now;
                    pOwner.CurrentState   = new PauseGameState(pOwner, this);

                    var playing = Sounds.GetPlayingMusic_Active();
                    playing?.Pause();
                    Sounds.PlaySound(pOwner.AudioThemeMan.Pause.Key, pOwner.Settings.std.EffectVolume);
                }

                //pOwner.CurrentState = new PauseGameState(this);
            }
            else if (g == GameKeys.GameKey_Hold)
            {
                if (HoldBlock != null && !BlockHold)
                {
                    //if there is a holdblock, take it and put it into the gamefield and make the first active blockgroup the new holdblock,
                    //then set BlockHold to block it from being used until the next Tetromino is spawned.
                    Nomino FirstGroup = PlayField.BlockGroups.FirstOrDefault();
                    if (FirstGroup != null)
                    {
                        if (FirstGroup.Controllable)
                        {
                            PlayField.RemoveBlockGroup(FirstGroup);

                            PlayField.AddBlockGroup(HoldBlock);

                            //We probably should set the speed appropriately here for the level. As is it will retain the speed from whe nthe hold block was
                            //held.
                            PlayField.Theme.ApplyTheme(HoldBlock, GameHandler, PlayField, NominoTheme.ThemeApplicationReason.Normal);
                            HoldBlock.X = (int)(((float)PlayField.ColCount / 2) - ((float)HoldBlock.GroupExtents.Width / 2));
                            HoldBlock.SetY(pOwner, 0);
                            HoldBlock.HighestHeightValue = 0; //reset the highest height as well, so the falling animation doesn't goof
                            HoldBlock = FirstGroup;
                            Sounds.PlaySound(pOwner.AudioThemeMan.Hold.Key, pOwner.Settings.std.EffectVolume);
                            pOwner.Feedback(0.9f, 40);
                            BlockHold = true;
                        }
                    }
                }
                else if (!BlockHold)
                {
                    Nomino FirstGroup = PlayField.BlockGroups.FirstOrDefault();
                    if (FirstGroup != null)
                    {
                        if (FirstGroup.Controllable)
                        {
                            PlayField.RemoveBlockGroup(FirstGroup);
                            HoldBlock = FirstGroup;
                            BlockHold = true;
                            Sounds.PlaySound(pOwner.AudioThemeMan.Hold.Key, pOwner.Settings.std.EffectVolume);
                        }
                    }
                }
            }
            else if (g == GameKeys.GameKey_Debug1)
            {
                pOwner.CurrentState = new ShowHighScoresState(TetrisGame.ScoreMan["Standard"], pOwner.CurrentState);
            }
            else if (g == GameKeys.GameKey_Debug2)
            {
                OptionsMenuSettingsSelectorState OptionState = new OptionsMenuSettingsSelectorState(BackgroundDrawers.StandardImageBackgroundGDI.GetStandardBackgroundDrawer(),
                                                                                                    pOwner, pOwner.CurrentState);

                pOwner.CurrentState = OptionState;

                /*if (pOwner.CurrentState is StandardTetrisGameState)
                 * {
                 *  ((StandardTetrisGameState) pOwner.CurrentState).GameStats.Score += 1000;
                 * }*/
            }
            else if (g == GameKeys.GameKey_Debug3)
            {
                int  DesiredFontPixelHeight = (int)(pOwner.GameArea.Height * (23d / 644d));
                Font standardFont           = new Font(TetrisGame.RetroFont, DesiredFontPixelHeight, FontStyle.Bold, GraphicsUnit.Pixel);
                Font ItemFont = new Font(TetrisGame.RetroFont, (int)((float)DesiredFontPixelHeight * (3f / 4f)), FontStyle.Bold, GraphicsUnit.Pixel);
                //set state to a testing menu state.

                MenuState ms = new MenuState(BackgroundDrawers.StandardImageBackgroundGDI.GetStandardBackgroundDrawer());
                ms.StateHeader    = "This is a Menu";
                ms.HeaderTypeface = standardFont.Name;
                ms.HeaderTypeSize = standardFont.Size;

                MenuStateTextMenuItem returnitem = new MenuStateTextMenuItem();
                returnitem.FontFace  = ItemFont.Name;
                returnitem.FontSize  = ItemFont.Size;
                returnitem.Text      = "Return";
                returnitem.BackColor = Color.Transparent;
                returnitem.ForeColor = Color.DarkBlue;
                var OriginalState = pOwner.CurrentState;
                ms.MenuElements.Add(returnitem);

                var scaleitem = new MenuStateScaleMenuItem(pOwner);
                scaleitem.FontFace = ItemFont.Name;
                scaleitem.FontSize = ItemFont.Size;
                ms.MenuElements.Add(scaleitem);

                ms.MenuItemActivated += (obj, e) =>
                {
                    if (e.MenuElement == returnitem)
                    {
                        pOwner.CurrentState = OriginalState;
                    }
                };
                for (int i = 0; i < 8; i++)
                {
                    MenuStateTextMenuItem mts = new MenuStateTextMenuItem();
                    mts.FontFace  = ItemFont.Name;
                    mts.FontSize  = ItemFont.Size;
                    mts.BackColor = Color.Transparent;
                    mts.ForeColor = Color.Black;
                    mts.Text      = "Item " + i.ToString();
                    ms.MenuElements.Add(mts);
                }
                pOwner.CurrentState = ms;
            }
            else if (g == GameKeys.GameKey_Debug4)
            {
                if (pOwner is IGamePresenter gp)
                {
                    var _Present = gp.GetPresenter();
                    if (_Present.ai == null)
                    {
                        _Present.ai = new StandardNominoAI(pOwner);
                    }
                    else
                    {
                        _Present.ai.AbortAI();
                        _Present.ai = null;
                    }
                }
            }
        }
Ejemplo n.º 49
0
 public override void HandleGameKey(IStateOwner pOwner, GameKeys g)
 {
     //throw new NotImplementedException();
 }
Ejemplo n.º 50
0
 public KeyBuffer(GameKeys key)
 {
     Key = key;
     Consumed = false;
 }