Ejemplo n.º 1
0
    public GameWorld(int width, int height, ContentManager Content)
    {
        screenWidth = width;
        screenHeight = height;
        random = new Random();
        gameState = GameState.Menu;
        inputHelper = new InputHelper();
        block = Content.Load<Texture2D>("block");
        reset = Content.Load<Texture2D>("reset");
        font = Content.Load<SpriteFont>("SpelFont");
        font2 = Content.Load<SpriteFont>("SpriteFont1");
        font3 = Content.Load<SpriteFont>("SpriteFont2");
        playButton = Content.Load<Texture2D>("Play");
        optionsButton = Content.Load<Texture2D>("Options");
        backButton = Content.Load<Texture2D>("Back");
        polytris = Content.Load<Texture2D>("Polytris");
        grid = new TetrisGrid(block);
        level = 1;
        levelspeed = 1;
        score = 0;
        i = (int)random.Next(7) + 1;
        i2 = (int)random.Next(7) + 1;
        blockcounter = 1;

        blocks = new BlockList(block, Content);          //Voegen de verschillende blockobjecten toe aan de lijst
        block1 = new Block1(block, Content);
        blocks.Add(block1, 1);
        block2 = new Block2(block, Content);
        blocks.Add(block2, 2);
        block3 = new Block3(block, Content);
        blocks.Add(block3, 3);
        block4 = new Block4(block, Content);
        blocks.Add(block4, 4);
        block5 = new Block5(block, Content);
        blocks.Add(block5, 5);
        block6 = new Block6(block, Content);
        blocks.Add(block6, 6);
        block7 = new Block7(block, Content);
        blocks.Add(block7, 7);

        //Voegen de verschillende blockobjecten toe aan een tweede lijst voor het tekenen van het volgende blokje
        block1res = new Block1(block, Content);
        blocks.AddToReserve(block1res, 1);
        block2res = new Block2(block, Content);
        blocks.AddToReserve(block2res, 2);
        block3res = new Block3(block, Content);
        blocks.AddToReserve(block3res, 3);
        block4res = new Block4(block, Content);
        blocks.AddToReserve(block4res, 4);
        block5res = new Block5(block, Content);
        blocks.AddToReserve(block5res, 5);
        block6res = new Block6(block, Content);
        blocks.AddToReserve(block6res, 6);
        block7res = new Block7(block, Content);
        blocks.AddToReserve(block7res, 7);

        options = new Options(block, reset, backButton, width, height, font, blocks);
        menu = new Menu(playButton, optionsButton, polytris, width, height);
        gameOver = new GameOver(backButton, width, height);
    }
Ejemplo n.º 2
0
    /// <summary>
    /// HandleInput for the button
    /// </summary>
    /// <param name="inputHelper">The inputhelper to react to input</param>
    public override void HandleInput(InputHelper inputHelper)
    {
        wasMouseOver = isMouseOver;
        //Checking whether the mouse is hovering over a button or not
        if (BoundingBox.Contains((int)inputHelper.MousePosition.X, (int)inputHelper.MousePosition.Y))
            isMouseOver = true;
        else
            isMouseOver = false;

        if (!wasMouseOver && isMouseOver)
        {
            foreach (Sound sound in MusicPlayer.SoundEffect)
                if (sound.Name == "MouseOver")
                {
                    sound.PlaySound();
                }
        }

        buttonWasPressed = ButtonIsPressed;
        //Checking whether you are pressing the button or not
        if (inputHelper.MouseLeftButtonPressed() && isMouseOver)
            buttonIsPressed = true;
        else
            buttonIsPressed = false;

        if (!buttonWasPressed && buttonIsPressed)
        {
            foreach (Sound sound in MusicPlayer.SoundEffect)
                if (sound.Name == "MouseClick")
                {
                    sound.PlaySound();
                }
        }
    }
Ejemplo n.º 3
0
        public override void HandleInput(InputHelper inputHelper)
        {
            base.HandleInput(inputHelper);

            if (backButton.Pressed)
                GameEnvironment.GameStateManager.SwitchTo("titleMenu");
        }
 public override void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.IsKeyDown(Keys.Escape))
         escDown = true;
     else
         escDown = false;
 }
Ejemplo n.º 5
0
 public override void HandleInput(InputHelper inputHelper)
 {
     if (!inputHelper.KeyPressed(Keys.Space))
         return;
     playingState.Reset();
     GameEnvironment.GameStateManager.SwitchTo("playingState");
 }
 /// <summary>Enables going to the next level.</summary>
 public override void HandleInput(InputHelper inputHelper)
 {
     if (!(inputHelper.KeyPressed(Keys.Space) || inputHelper.ControlerButtonPressed(Buttons.A)))
         return;
     GameEnvironment.GameStateManager.SwitchTo("playingState");
     (playingState as PlayingState).NextLevel();
 }
Ejemplo n.º 7
0
 public GameObject(string id = "")
 {
     this.velocity = Vector2.Zero;
     this.visible = true;
     inputHelper = new InputHelper();
     this.id = id;
 }
Ejemplo n.º 8
0
        public override void HandleInput(InputHelper inputHelper)
        {
            base.HandleInput(inputHelper);

            if (obj == null)
            {
                Vector3 vectorToAdd = Vector3.Zero;

                if (inputHelper.IsKeyDown(Keys.W))
                    vectorToAdd -= Vector3.UnitZ;
                if (inputHelper.IsKeyDown(Keys.S))
                    vectorToAdd += Vector3.UnitZ;
                if (inputHelper.IsKeyDown(Keys.D))
                    vectorToAdd += Vector3.UnitX;
                if (inputHelper.IsKeyDown(Keys.A))
                    vectorToAdd -= Vector3.UnitX;
                if (inputHelper.IsKeyDown(Keys.Q))
                    vectorToAdd -= Vector3.UnitY;
                if (inputHelper.IsKeyDown(Keys.E))
                    vectorToAdd += Vector3.UnitY;
                if (inputHelper.IsKeyDown(Keys.R))
                    position = Vector3.Zero;
                if (inputHelper.IsKeyDown(Keys.D1))
                    walkSpeed /= 1.25f;
                if (inputHelper.IsKeyDown(Keys.D2))
                    walkSpeed *= 1.25f;

                inputHelper.AddMouseRotation(rotSpeed, ref rotation);
                Matrix cameraRotation = Matrix.CreateRotationX(rotation.X) * Matrix.CreateRotationY(rotation.Y);
                Vector3 rotatedVector = Vector3.Transform(vectorToAdd * walkSpeed, cameraRotation);
                position += rotatedVector;
            }
        }
Ejemplo n.º 9
0
 public BalloonFW()
 {
     Content.RootDirectory = "Content";
     graphics = new GraphicsDeviceManager(this);
     inputHelper = new InputHelper();
     this.IsMouseVisible = true;
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Checks the difference between the old and new mouse position
 /// </summary>
 /// <param name="inputHelper">The inputhelper to react to input</param>
 public override void HandleInput(InputHelper inputHelper)
 {
     inputHelper.Update();
     mouseDiff.X = inputHelper.MousePosition.X - prevMousePos.X;
     mouseDiff.Y = inputHelper.MousePosition.Y - prevMousePos.Y;
     prevMousePos = new Vector2(GameEnvironment.Screen.X / 2, GameEnvironment.Screen.Y / 2);
     Mouse.SetPosition((int)prevMousePos.X, (int)prevMousePos.Y);
 }
Ejemplo n.º 11
0
 public override void HandleInput(InputHelper inputHelper)
 {
     base.HandleInput(inputHelper);
     if (playButton.Pressed)
         GameEnvironment.GameStateManager.SwitchTo("levelMenu");
     else if (helpButton.Pressed)
         GameEnvironment.GameStateManager.SwitchTo("helpState");
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Responds to user input, accepting or cancelling the message box.
 /// </summary>
 public override void HandleInput(InputHelper input, GameTime gameTime)
 {
     if (input.IsMenuSelect() || input.IsMenuCancel() ||
         input.IsNewMouseButtonPress(MouseButtons.LeftButton))
     {
         ExitScreen();
     }
 }
Ejemplo n.º 13
0
 public override void HandleInput(InputHelper inputHelper)
 {
     //Als er op spatie wordt gedrukt, begint het spel opnieuw
     if (!inputHelper.KeyPressed(Keys.Space))
         return;
     playingState.Reset();
     GameEnvironment.GameStateManager.SwitchTo("playingState");
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes the component.
        /// </summary>
        public override void Initialize()
        {
#if WINDOWS_PHONE
            // Enable tap gesture
            TouchPanel.EnabledGestures = GestureType.Tap;
#endif
            // Get xbox cursor
            inputHelper = null;
            for (int componentIndex = 0; componentIndex < Game.Components.Count; componentIndex++)
            {
                if (Game.Components[componentIndex] is InputHelper)
                {
                    inputHelper = (InputHelper)Game.Components[componentIndex];
                    break;
                }
            }

            // Show mouse
            Game.IsMouseVisible = true;
            base.Initialize();

            spriteBatch = new SpriteBatch(Game.GraphicsDevice);

            // Calculate chips position for the chip buttons which allow placing the bet
            Rectangle size = chipsAssets[assetNames[0]].Bounds;

            Rectangle bounds = Game.GraphicsDevice.Viewport.TitleSafeArea();

            positions[chipsAssets.Count - 1] = new Vector2(bounds.Left + 10,
                bounds.Bottom - size.Height - 80);
            for (int chipIndex = 2; chipIndex <= chipsAssets.Count; chipIndex++)
            {
                size = chipsAssets[assetNames[chipsAssets.Count - chipIndex]].Bounds;
                positions[chipsAssets.Count - chipIndex] = positions[chipsAssets.Count - (chipIndex - 1)] -
                    new Vector2(0, size.Height + 10);
            }

            // Initialize bet button
            bet = new Button("ButtonRegular", "ButtonPressed", input, cardGame)
            {
                Bounds = new Rectangle(bounds.Left + 10, bounds.Bottom - 60, 100, 50),
                Font = cardGame.Font,
                Text = "Deal",
            };
            bet.Click += Bet_Click;
            Game.Components.Add(bet);

            // Initialize clear button
            clear = new Button("ButtonRegular", "ButtonPressed", input, cardGame)
            {
                Bounds = new Rectangle(bounds.Left + 120, bounds.Bottom - 60, 100, 50),
                Font = cardGame.Font,
                Text = "Clear",
            };
            clear.Click += Clear_Click;
            Game.Components.Add(clear);
            ShowAndEnableButtons(false);
        }
Ejemplo n.º 15
0
        public void Update(GameTime gameTime, InputHelper Input)
        {
            //otherwise it would be possible that the cursor rectangle is still on a button eventhough the controller is in use
            cursor = Input.ControllerInUse ? new Rectangle(0, 0, 0, 0) : new Rectangle(Input.MouseCheckPosition().X, Input.MouseCheckPosition().Y, 1, 1);

            //if the cursor is over a button or the button is selected with a controller, the button will change color
            if (cursor.Intersects(startButton) || selectedButton == Buttons.Start)
            {
                startColor.A = MouseOverAlpha;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    Start = true;
                }
            }
            else startColor.A = StandardAlpha;

            if (cursor.Intersects(optionsButton) || selectedButton == Buttons.Options)
            {
                optionsColor.A = 200;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    Options = true;
                }
            }
            else optionsColor.A = 255;

            if (cursor.Intersects(exitButton) || selectedButton == Buttons.ExitGame)
            {
                exitColor.A = 200;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    ExitGame = true;
                }
            }
            else exitColor.A = 255;

            //scrolling through menu with controller
            if (Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.LeftThumbstickDown))
            {
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.Start;
                else
                    selectedButton++;
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.Start;
            }

            if (Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.LeftThumbstickUp))
            {
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.ExitGame;
                else if (selectedButton == Buttons.Start)
                    selectedButton = Buttons.ExitGame;
                else
                    selectedButton--;
            }
        }
Ejemplo n.º 16
0
 public override void HandleInput(InputHelper input, GameTime gameTime)
 {
     if (input.KeyboardState.GetPressedKeys().Length > 0 ||
         input.GamePadState.IsButtonDown(Buttons.A | Buttons.Start | Buttons.Back) ||
         input.MouseState.LeftButton == ButtonState.Pressed)
     {
         _duration = TimeSpan.Zero;
     }
 }
Ejemplo n.º 17
0
 public override void HandleInput(InputHelper inputHelper)
 {
     base.HandleInput(inputHelper);
     if (quitButton.Pressed)
     {
         this.Reset();
         GameEnvironment.GameStateManager.SwitchTo("levelMenu");
     }
 }
 public override void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.IsKeyPressed(Keys.P))
     {
         paused = !paused;
         pausedText.Visible = paused;
     }
     base.HandleInput(inputHelper);
 }
 public GameEnvironment()
 {
     modelScale = Matrix.CreateScale(1, 1, 1);
     inputHelper = new InputHelper();
     gameStateManager = new GameStateManager();
     random = new Random();
     assetManager = new AssetManager(Content);
     gameSettingsManager = new GameSettingsManager();
 }
Ejemplo n.º 20
0
 public override void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.KeyPressed(Keys.Space))
         if (can_shoot == 0)
         {
             this.visible = true;
             Mirror = true;
         }
 }
 public override void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.IsKeyPressed(Keys.Space))
     {
         Practicum1.WinPaddle = null;
         Practicum1.GameStateManager.SwitchTo("mainMenuState");
     }
     
     base.HandleInput(inputHelper);
 }
Ejemplo n.º 22
0
 public TetrisGame()
 {
     GraphicsDeviceManager graphics = new GraphicsDeviceManager(this);
     this.Content.RootDirectory = "Content";
     graphics.PreferredBackBufferWidth = 800;
     graphics.PreferredBackBufferHeight = 600;
     inputHelper = new InputHelper();
     IsMouseVisible = true;
     random = new Random();
 }
Ejemplo n.º 23
0
        public override void Update(InputHelper Helper, GameTime GTime)
        {
            if (IsDrawn)
            {
                if (m_DoDrag)
                    m_WillWrightImg.Position = Position - new Vector2(-22, -42);
            }

            base.Update(Helper, GTime);
        }
Ejemplo n.º 24
0
    public GameEnvironment()
    {
        graphics = new GraphicsDeviceManager(this);

        inputHelper = new InputHelper();
        gameStateManager = new GameStateManager();
        spriteScale = Matrix.CreateScale(1, 1, 1);
        random = new Random();
        assetManager = new AssetManager(Content);
        gameSettingsManager = new GameSettingsManager();
    }
Ejemplo n.º 25
0
        public void Update(GameTime gameTime, InputHelper Input)
        {
            cursor = Input.ControllerInUse ? new Rectangle(0, 0, 0, 0) : new Rectangle(Input.MouseCheckPosition().X, Input.MouseCheckPosition().Y, 1, 1);

            if (cursor.Intersects(resumeButton) || selectedButton == Buttons.Resume)
            {
                resumeColor.A = 200;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    Resume = true;
                }
            }
            else resumeColor.A = 255;

            if (cursor.Intersects(optionsButton) || selectedButton == Buttons.Options)
            {
                optionsColor.A = 200;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    Options = true;
                }
            }
            else optionsColor.A = 255;

            if (cursor.Intersects(quitButton) || selectedButton == Buttons.Quit)
            {
                quitColor.A = 200;
                if (Input.MouseButtonCheckPressed(true) || Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.A))
                {
                    Quit = true;
                }
            }
            else quitColor.A = 255;

            if (Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.LeftThumbstickDown))
            {
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.Resume;
                else
                    selectedButton++;
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.Resume;
            }

            if (Input.GamePadCheckPressed(Microsoft.Xna.Framework.Input.Buttons.LeftThumbstickUp))
            {
                if (selectedButton == Buttons.None)
                    selectedButton = Buttons.Quit;
                else if (selectedButton == Buttons.Resume)
                    selectedButton = Buttons.Quit;
                else
                    selectedButton--;
            }
        }
 /// <summary>
 /// HandleInput for the level
 /// </summary>
 /// <param name="inputHelper">The inputhelper to react to input</param>
 public void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.IsKeyDown(Keys.Escape))
     {
         foreach (Sound sound in MusicPlayer.SoundEffect)
             if (sound.Name == "paperrustle")
                 sound.PlaySound();
         GameEnvironment.GameStateManager.SwitchTo("pauseScreenState");
     }
     level.HandleInput(inputHelper);
 }
Ejemplo n.º 27
0
 //Constructor
 public GUIObject(Game game, string newID, string command)
 {
     spriteBatch = (SpriteBatch)game.Services.GetService(typeof(SpriteBatch));
     spriteFont = (SpriteFont)game.Services.GetService(typeof(SpriteFont));
     inputHelper = (InputHelper)game.Services.GetService(typeof(InputHelper));
     id = newID;
     isClicked = false;
     isHovered = false;
     this.command = command;
     rect = new Rectangle();
 }
 /// <summary>
 /// Reacting to input from the player
 /// </summary>
 /// <param name="inputHelper">The inputhelper to react to input</param>
 public void HandleInput(InputHelper inputHelper)
 {
     if (inputHelper.AnyKeyPressed)
     {
         foreach (Sound sound in MusicPlayer.SoundEffect)
             if (sound.Name == "paperrustle2")
                 sound.PlaySound();
         Mouse.SetPosition(GameEnvironment.Screen.X / 2, GameEnvironment.Screen.Y / 2);
         GameEnvironment.GameStateManager.SwitchTo("playingState");
     }
 }
Ejemplo n.º 29
0
        public InputBuffer(InputHelper.ButtonState stateType, float bufferTimeout = 400f)
        {
            inputBuffer = new List<InputHelper.KeyPress>(MAX_BUFFER);
            inputState = new List<InputHelper.KeyPress>(MAX_BUFFER);
            currentStateStep = 0;

            this.bufferTimeout = bufferTimeout;
            this.stateType = stateType;

            InitiateState();
        }
Ejemplo n.º 30
0
    public TetrisGame()
    {
        graphics = new GraphicsDeviceManager(this);

        this.Content.RootDirectory = "Content";

        graphics.PreferredBackBufferWidth = 720;
        graphics.PreferredBackBufferHeight = 640;

        inputHelper = new InputHelper();
    }
Ejemplo n.º 31
0
        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public void HandleInput(InputHelper input, GameTime gameTime)
        {
            // Mouse or touch on a menu item
            int hoverIndex = GetMenuEntryAt(input.Cursor);

            if (hoverIndex > -1 && _menuEntries[hoverIndex].IsSelectable() && !_scrollLock)
            {
                _selectedEntry = hoverIndex;
            }
            else
            {
                _selectedEntry = -1;
            }

            _scrollSlider.Hover = false;
            if (input.IsCursorValid)
            {
                _scrollUp.Collide(input.Cursor);
                _scrollDown.Collide(input.Cursor);
                _scrollSlider.Collide(input.Cursor);
            }
            else
            {
                _scrollUp.Hover   = false;
                _scrollDown.Hover = false;
                _scrollLock       = false;
            }

            // Accept or cancel the menu?
            if (input.IsMenuSelect() && _selectedEntry != -1)
            {
                if (_menuEntries[_selectedEntry].IsExitItem())
                {
                    Game.Exit();
                }

                //TODO:

                //else if (_menuEntries[_selectedEntry].Screen != null)
                //{
                //    ScreenManager.AddScreen(_menuEntries[_selectedEntry].Screen);

                //    if (_menuEntries[_selectedEntry].Screen is IDemoScreen)
                //        ScreenManager.AddScreen(new MessageBoxScreen((_menuEntries[_selectedEntry].Screen as IDemoScreen).GetDetails()));
                //}
            }
            else if (input.IsMenuCancel())
            {
                Game.Exit();
            }

            if (input.IsMenuPressed())
            {
                if (_scrollUp.Hover)
                {
                    _menuOffset = Math.Max(_menuOffset - 200f * (float)gameTime.ElapsedGameTime.TotalSeconds, 0f);
                    _scrollLock = false;
                }
                if (_scrollDown.Hover)
                {
                    _menuOffset = Math.Min(_menuOffset + 200f * (float)gameTime.ElapsedGameTime.TotalSeconds, _maxOffset);
                    _scrollLock = false;
                }
                if (_scrollSlider.Hover)
                {
                    _scrollLock = true;
                }
            }

            if (input.IsMenuReleased())
            {
                _scrollLock = false;
            }

            if (_scrollLock)
            {
                _scrollSlider.Hover = true;
                _menuOffset         = Math.Max(Math.Min(((input.Cursor.Y - _menuBorderTop) / (_menuBorderBottom - _menuBorderTop)) * _maxOffset, _maxOffset), 0f);
            }
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Calls HandleInout for all objects in this GameState.
 /// </summary>
 /// <param name="inputHelper">An object required for handling player input.</param>
 public virtual void HandleInput(InputHelper inputHelper)
 {
     gameObjects.HandleInput(inputHelper);
 }
Ejemplo n.º 33
0
 public override void Initialize()
 {
     InputHelper.Update();
     _target = new RenderTarget2D(Graphics, GameVars.GAME_WIDTH, GameVars.GAME_HEIGHT);
     _batch  = new SpriteBatch(Graphics);
 }
Ejemplo n.º 34
0
    void FullKeyboardInput()
    {
        if (IsPointerOverUIObject())
        {
            if (Input.GetMouseButtonDown(0))
            {
                wasUIClicked = true;
            }
        }

        List <Touch> touches = InputHelper.GetTouches();


        if (!wasUIClicked && Input.GetMouseButtonDown(0))
        //			if(touches[0].phase == TouchPhase.Began)
        {
            touchDownPos       = cam.ScreenToViewportPoint(Input.mousePosition);
            cameraTouchDownPos = transform.position;

            nextTimeToSwipe = Time.time + timeToSwipe;
        }
        if (!wasUIClicked && Input.GetMouseButton(0))
        //			if(touches[0].phase == TouchPhase.Moved)
        {
            //if(SelectionManager.singleton.selectedNode != null)
            //	return;

            Vector3 dir = touchDownPos - cam.ScreenToViewportPoint(Input.mousePosition);
            dir.z = dir.y;
            dir.y = 0;

            Vector3 newPosition = cameraTouchDownPos + dir * moveScale;
            newPosition.x = Mathf.Clamp(newPosition.x, coordXLimit.x, coordXLimit.y);
            newPosition.z = Mathf.Clamp(newPosition.z, coordZLimit.x, coordZLimit.y);

            transform.position = newPosition;

            targetPosition = newPosition;
        }
        else
        {
            prevTouchPos = Vector3.zero;
        }

        if (Input.GetMouseButtonUp(0))
        //			if(touches[0].phase == TouchPhase.Ended)
        {
            wasUIClicked = false;

            if (Time.time < nextTimeToSwipe)
            {
                RaycastToLabel();
            }
        }

// #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
        KeyboardInput();
// #endif

        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref dampVector, smoothTime);
    }
 public NavigationViewItemPresenter()
 {
     InputHelper.SetIsTapEnabled(this, true);
 }
Ejemplo n.º 36
0
 public void HandleInput(InputHelper inputHelper)
 {
     CurrentLevel.HandleInput(inputHelper);
 }
Ejemplo n.º 37
0
        public void NumberPanelChangingPageTest2()
        {
            using (var setup = new TestSetupHelper("PagerControl Tests"))
            {
                elements = new PagerControlTestPageElements();

                VerifyPageChanged(0);

                SetNumberPanelDisplayMode();
                VerifyNumberPanelDisplayMode();

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(1);
                VerifyNumberPanelContent("12345");

                InputHelper.LeftClick(elements.GetLastPageButton());
                VerifyPageChanged(4);
                VerifyNumberPanelContent("12345");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(3);
                VerifyNumberPanelContent("12345");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(2);
                VerifyNumberPanelContent("12345");

                ChangeNumberOfPages();
                VerifyNumberOfPages("100");

                InputHelper.LeftClick(elements.GetFirstPageButton());
                VerifyPageChanged(0);
                VerifyNumberPanelContent("12345More100");

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(1);
                VerifyNumberPanelContent("12345More100");

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(2);
                VerifyNumberPanelContent("12345More100");

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(3);
                VerifyNumberPanelContent("12345More100");

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(4);
                VerifyNumberPanelContent("1More456More100");

                InputHelper.LeftClick(elements.GetNextPageButton());
                VerifyPageChanged(5);
                VerifyNumberPanelContent("1More567More100");

                InputHelper.LeftClick(elements.GetLastPageButton());
                VerifyPageChanged(99);

                VerifyNumberPanelContent("1More96979899100");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(98);
                VerifyNumberPanelContent("1More96979899100");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(97);
                VerifyNumberPanelContent("1More96979899100");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(96);
                VerifyNumberPanelContent("1More96979899100");

                InputHelper.LeftClick(elements.GetPreviousPageButton());
                VerifyPageChanged(95);
                VerifyNumberPanelContent("1More959697More100");
            }
        }
        public void BasicInteractionTest()
        {
            using (var setup = new TestSetupHelper("RatingControl Tests")) // This literally clicks the button corresponding to the test page.
            {
                Log.Comment("Retrieve rating control as generic UIElement");
                UIObject ratingUIObject = FindElement.ByName("TestRatingControl");
                Verify.IsNotNull(ratingUIObject, "Verifying that we found a UIElement called TestRatingControl");

                Log.Comment("Retrieve the text block as a TextBlock");
                TextBlock textBlock = new TextBlock(FindElement.ByName("TestTextBlockControl"));

                Log.Comment("Verify a tap on the third star sets Rating to 3");
                InputHelper.Tap(ratingUIObject, 60, RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("3", textBlock.DocumentText);

                Log.Comment("Verify a tap on the third star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, 60, RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);

                Button phButton = new Button(FindElement.ByName("PHButton"));
                InputHelper.Tap(phButton);

                Log.Comment("Verify a tap on the first star sets Rating to 1");
                InputHelper.Tap(ratingUIObject, 12, RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("1", textBlock.DocumentText);

                Log.Comment("Verify a swipe off the left sets Rating to NOTHING");
                InputHelper.Pan(ratingUIObject, 200, Direction.West);
                Verify.AreEqual("!", textBlock.DocumentText);

                Log.Comment("Verify a right key on an unset Rating, sets rating to 1");
                KeyboardHelper.PressKey(ratingUIObject, Key.Right);

                Verify.AreEqual("1", textBlock.DocumentText);

                Log.Comment("Verify a left key on an RTL rating increases the rating.");
                TestSetupHelper.SetInnerFrameFlowDirection(FlowDirection.RightToLeft);
                Wait.ForIdle();

                KeyboardHelper.PressKey(ratingUIObject, Key.Left);
                Verify.AreEqual("2", textBlock.DocumentText);

                Log.Comment("Verify home/end keys in RTL");
                KeyboardHelper.PressKey(ratingUIObject, Key.Home);
                Verify.AreEqual("!", textBlock.DocumentText);

                KeyboardHelper.PressKey(ratingUIObject, Key.End);
                Verify.AreEqual("5", textBlock.DocumentText);

                Log.Comment("Verify up down keys in RTL");
                KeyboardHelper.PressKey(ratingUIObject, Key.Down);
                Verify.AreEqual("4", textBlock.DocumentText);

                KeyboardHelper.PressKey(ratingUIObject, Key.Up);
                Verify.AreEqual("5", textBlock.DocumentText);

                TestSetupHelper.SetInnerFrameFlowDirection(FlowDirection.LeftToRight);
                Wait.ForIdle();

                Log.Comment("Verify home/end keys in LTR");
                KeyboardHelper.PressKey(ratingUIObject, Key.Home);
                Verify.AreEqual("!", textBlock.DocumentText);

                KeyboardHelper.PressKey(ratingUIObject, Key.End);
                Verify.AreEqual("5", textBlock.DocumentText);

                Log.Comment("Verify up down keys in LTR");
                KeyboardHelper.PressKey(ratingUIObject, Key.Down);
                Verify.AreEqual("4", textBlock.DocumentText);

                KeyboardHelper.PressKey(ratingUIObject, Key.Up);
                Verify.AreEqual("5", textBlock.DocumentText);
            }
        }
Ejemplo n.º 39
0
        public void Update(GameTime gameTime)
        {
            if (_keyboardMappings != null || _buttonMappings != null)
            {
                var firePressed = false;
                if (_keyboardMappings != null)
                {
                    var pressed = _keyboardInput.PressedKeys;
                    Array.ForEach(_movementComponent, movement => movement.InputDirection = InputHelper.DirectionFromMapping(pressed, _keyboardMappings));

                    firePressed = pressed.Any(k => k == Keys.Space);
                }
                else if (_buttonMappings != null)
                {
                    var pressed = _buttonInput.ButtonsPressed;
                    Array.ForEach(_movementComponent, movement => movement.InputDirection = InputHelper.DirectionFromMapping(pressed, _buttonMappings));
                }

                _elapsedTimeMilliseconds += gameTime.ElapsedGameTime.TotalMilliseconds;

                if (firePressed && _elapsedTimeMilliseconds > GameConstants.RepeaterDelay)
                {
                    _elapsedTimeMilliseconds = 0;
                    Owner.Event(ObjectEvent.Fire);
                }
            }
        }
Ejemplo n.º 40
0
 // Use this for initialization
 void Start()
 {
     _helper            = InputHelper.Instance;
     transform.position = new Vector2(transform.position.x, InfoStorage.ClosedPanelPosY);
 }
Ejemplo n.º 41
0
 public virtual void HandleInput(InputHelper inputHelper)
 {
 }
Ejemplo n.º 42
0
 public Day9(Action <string> writeLine) : base(writeLine, InputHelper.Open(9))
 {
 }
Ejemplo n.º 43
0
 public override void Update(GameTime gameTime, InputHelper inputHelper)
 {
     base.Update(gameTime, inputHelper);
 }
        [TestProperty("Ignore", "True")] // Disabled as per tracking issue #3125
        public void VerifyRatingItemFallback()
        {
            // This test is actually performed in the test app itself, so go look at RatingControlPage.xaml.cs for the meat of it.

            using (var setup = new TestSetupHelper("RatingControl Tests")) // This literally clicks the button corresponding to the test page.
            {
                if (!PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone1))
                {
                    Log.Warning("Test is disabled on RS1 due to scrolling unreliability");
                    return;
                }

                Log.Comment("Retrieve PointerOverPlaceholderFallbackRating rating control as generic UIElement");
                UIObject popRating = FindElement.ById("PointerOverPlaceholderFallbackRating");
                Verify.IsNotNull(popRating, "Verifying that we found a UIElement called PointerOverPlaceholderFallbackRating");

                InputHelper.ScrollToElement(popRating);

                popRating.Tap(); // Since on phone it's touch, I do a tap to trigger that.
                popRating.Click();
                Wait.ForIdle();

                Log.Comment("Retrieve PointerOverFallbackRating rating control as generic UIElement");
                UIObject pointerOver = FindElement.ById("PointerOverFallbackRating");
                Verify.IsNotNull(pointerOver, "Verifying that we found a UIElement called PointerOverFallbackRating");
                InputHelper.ScrollToElement(pointerOver);
                pointerOver.Click();
                pointerOver.Tap();
                Wait.ForIdle();

                TextBlock textBlock = new TextBlock(FindElement.ById("UnsetFallbackTextBlock"));
                Verify.AreEqual("+", textBlock.DocumentText, "Verify Unset glyph falls back onto Glyph");
                TextBlock textBlock2 = new TextBlock(FindElement.ById("PlaceholderFallbackTextBlock"));
                Verify.AreEqual("+", textBlock2.DocumentText, "Verify Placeholder glyph falls back onto Glyph");
                TextBlock textBlock3 = new TextBlock(FindElement.ById("DisabledFallbackTextBlock"));
                Verify.AreEqual("+", textBlock3.DocumentText, "Verify Disabled glyph falls back onto Glyph");

                ElementCache.Clear();

                TextBlock textBlock4 = new TextBlock(FindElement.ById("PointerOverPlaceholderFallbackTextBlock"));
                Verify.AreEqual("+", textBlock4.DocumentText, "Verify PointerOverPlaceholder glyph falls back onto Placeholder");
                TextBlock textBlock5 = new TextBlock(FindElement.ById("PointerOverFallbackTextBlock"));
                Verify.AreEqual("+", textBlock5.DocumentText, "Verify PointerOver glyph falls back onto Glyph");
                TextBlock textBlock6 = new TextBlock(FindElement.ById("NoFallbackTextBlock"));
                Verify.AreEqual("+", textBlock6.DocumentText, "Verify a glyph didn't fall back if it wasn't meant to");

                // Image:
                Log.Comment("Retrieve PointerOverPlaceholderImageFallbackRating rating control as generic UIElement");
                popRating = FindElement.ById("PointerOverPlaceholderImageFallbackRating");
                Verify.IsNotNull(popRating, "Verifying that we found a UIElement called PointerOverPlaceholderImageFallbackRating");

                InputHelper.ScrollToElement(popRating);
                Wait.ForIdle();

                popRating.Tap(); // Since on phone it's touch, I do a tap to trigger that.
                popRating.Click();
                Wait.ForIdle();

                Log.Comment("Retrieve PointerOverImageFallbackRating rating control as generic UIElement");
                pointerOver = FindElement.ById("PointerOverImageFallbackRating");
                Verify.IsNotNull(pointerOver, "Verifying that we found a UIElement called PointerOverImageFallbackRating");
                pointerOver.Tap();
                pointerOver.Click();
                Wait.ForIdle();

                textBlock = new TextBlock(FindElement.ById("UnsetImageFallbackTextBlock"));
                Verify.AreEqual("+", textBlock.DocumentText, "Verify Unset image falls back onto Image");
                textBlock2 = new TextBlock(FindElement.ById("PlaceholderImageFallbackTextBlock"));
                Verify.AreEqual("+", textBlock2.DocumentText, "Verify Placeholder image falls back onto Image");
                textBlock3 = new TextBlock(FindElement.ById("DisabledImageFallbackTextBlock"));
                Verify.AreEqual("+", textBlock3.DocumentText, "Verify Disabled image falls back onto Image");

                ElementCache.Clear();
                textBlock4 = new TextBlock(FindElement.ById("PointerOverPlaceholderImageFallbackTextBlock"));
                Verify.AreEqual("+", textBlock4.DocumentText, "Verify PointerOverPlaceholder image falls back onto PlaceholderImage");
                textBlock5 = new TextBlock(FindElement.ById("PointerOverImageFallbackTextBlock"));
                Verify.AreEqual("+", textBlock5.DocumentText, "Verify PointerOver image falls back onto Image");
            }
        }
Ejemplo n.º 45
0
 public override void HandleInput(InputHelper inputHelper)
 {
     pressed = inputHelper.MouseLeftButtonPressed() && !level.Locked &&
               levelsSolved.BoundingBox.Contains((int)inputHelper.MousePosition.X, (int)inputHelper.MousePosition.Y);
 }
Ejemplo n.º 46
0
 public static void InitComponents(Game game)
 {
     game.Components.Add(InputHelper = new InputHelper(game));
 }
Ejemplo n.º 47
0
        public void Update(GameTime gameTime)
        {
            switch (State)
            {
            case States.UnitSelection:
                if (InputHelper.InputConfirmPressed())
                {
                    if (ListSelectedUnit.Contains(SelectedUnit))
                    {
                        ListSelectedUnit.Remove(SelectedUnit);
                    }
                    else if (MaxNumberOfUnitsToSpawn - ListSelectedUnit.Count > 0)
                    {
                        ListSelectedUnit.Add(SelectedUnit);
                        if (MaxNumberOfUnitsToSpawn - ListSelectedUnit.Count <= 0 || ListSelectedUnit.Count == ListVisibleUnit.Count)
                        {
                            State = States.SubMenu;
                        }
                    }
                }
                else if (InputHelper.InputCancelPressed())
                {
                    if (ListSelectedUnit.Count > 0)
                    {
                        UndoSelection();
                    }
                }
                else if (InputHelper.InputLButtonPressed())
                {
                    StatusMenu.ActiveSquad  = new Squad("", SelectedUnit);
                    StatusMenu.StatusPannel = StatusMenuScreen.StatusPannels.Unit;
                    State = States.StatusMenu;
                }
                else
                {
                    UnitSelectionMenu.Update(gameTime);
                }
                break;

            case States.StatusMenu:
                if (InputHelper.InputCancelPressed())
                {
                    State = States.UnitSelection;
                }
                break;

            case States.SubMenu:
                if (InputHelper.InputUpPressed())
                {
                    SubMenuIndex -= (SubMenuIndex > 0) ? 1 : 0;
                    sndSelection.Play();
                }
                else if (InputHelper.InputDownPressed())
                {
                    ++SubMenuIndex;

                    if (SubMenuIndex >= 4)
                    {
                        SubMenuIndex = 0;
                    }

                    sndSelection.Play();
                }
                break;
            }
        }
Ejemplo n.º 48
0
    public override void HandleInput(InputHelper inputHelper)
    {
        base.HandleInput(inputHelper);
        Unit unit = null;

        if (button1 != null && button1.Pressed && (tile as Building).level < (tile as Building).maxLevel)
        {
            if (GameData.player.MainResource - 300 >= 0 && GameData.player.SecondaryResource - 200 >= 0)
            {
                GameData.Cursor.HasClickedTile = false;
                GameData.LevelObjects.Remove(this);
                (this.tile as Building).level += 1;
            }
            else
            {
                Notification n = new Notification("Not enough resources, upgrading costs:", " 300 Sunlight and 200 Water", "", 3);
                n.CreateNotification();
                GameData.Cursor.HasClickedTile = false;
                GameData.LevelObjects.Remove(this);
            }
        }
        else if (button2 != null && button2.Pressed)
        {
            unit = new NatureWorker();
            if (player.MainResource - unit.ResourceCosts.X >= 0 && player.SecondaryResource - unit.ResourceCosts.Y >= 0)
            {
                player.MainResource      -= unit.ResourceCosts.X;
                player.SecondaryResource -= unit.ResourceCosts.Y;
                unit.Position             = new Vector2(tile.Position.X + new Tile().Sprite.Width / 2 - unit.Sprite.Width / 2, tile.Position.Y +
                                                        new Tile().Sprite.Height / 2);
                GameData.Cursor.HasClickedTile = false;
                //GameData.LevelObjects.Remove(this);
            }
            else
            {
                Notification n = new Notification("Not enough resources, it costs:", unit.ResourceCosts.X.ToString() + " Sunlight and " + unit.ResourceCosts.Y.ToString() + " Water", "", 3);
                n.CreateNotification(); unit = null;
            }
        }
        else if (button3 != null && button3.Pressed)
        {
            if (GameData.player.MainResource - 500 >= 0 && GameData.player.SecondaryResource - 500 >= 0)
            {
                spell = new SnowStorm();
                GameData.Cursor.Spell          = spell;
                GameData.Cursor.HasClickedTile = false;
                GameData.LevelObjects.Remove(this);
            }
            else
            {
                Notification n = new Notification("Not enough resources, it costs:", " 500 Sunlight and 500 Water", "", 3);
                n.CreateNotification();
            }
        }
        else if (button4 != null && button4.Pressed)
        {
            if (GameData.player.MainResource - 500 >= 0 && GameData.player.SecondaryResource - 500 >= 0)
            {
                spell = new MeteorStorm();
                GameData.Cursor.Spell          = spell;
                GameData.Cursor.HasClickedTile = false;
                GameData.LevelObjects.Remove(this);
            }
            else
            {
                Notification n = new Notification("Not enough resources, it costs:", " 500 Sunlight and 500 Water", "", 3);
                n.CreateNotification();
            }
        }
        if (unit != null)
        {
            GameData.AddUnit(unit);
            this.actionString = "$addu:" + unit.ID + "$type:" + unit.GetType() + "$posi:" + unit.Position.X + "," + unit.Position.Y;//;
        }
    }
Ejemplo n.º 49
0
        public void HandleInput(GameTime gameTime, InputHelper inputHelper)
        {
            //Exit on escape
            if (inputHelper.KeyPressed(Keys.Escape))
            {
                System.Environment.Exit(1);
            }

            //change what we do based on gamestate
            switch (gameState)
            {
            // default
            default:
                gameState = GameState.MainMenu;
                break;

            // Menu - main menu
            case GameState.MainMenu:

                // make sure that you cannot select a non-existent option
                if (inputHelper.KeyPressed(Keys.Up) && MainMenu.currentItem > 0)
                {
                    MainMenu.currentItem--;
                }

                if (inputHelper.KeyPressed(Keys.Down) && MainMenu.currentItem < 3)
                {
                    MainMenu.currentItem++;
                }

                if (inputHelper.KeyPressed(Keys.Enter))
                {
                    MainMenu.OnAction();
                }

                break;

            // Menu - settings
            case GameState.Settings:

                //same here
                if (inputHelper.KeyPressed(Keys.Up) && SettingsMenu.currentItem > 0)
                {
                    SettingsMenu.currentItem--;
                }

                if (inputHelper.KeyPressed(Keys.Down) && SettingsMenu.currentItem < SettingsMenu.GetLength() - 1)
                {
                    SettingsMenu.currentItem++;
                }

                if (inputHelper.KeyPressed(Keys.Right))
                {
                    Settings.ChangeSetting(true, Settings.GetSetting(SettingsMenu.currentItem));
                }

                if (inputHelper.KeyPressed(Keys.Left))
                {
                    Settings.ChangeSetting(false, Settings.GetSetting(SettingsMenu.currentItem));
                }

                if (inputHelper.KeyPressed(Keys.Enter))
                {
                    SettingsMenu.OnAction();
                }

                break;

            // Menu - credits
            case GameState.Credits:
                if (inputHelper.KeyPressed(Keys.Enter))
                {
                    Credits.OnAction();
                }
                break;

            // Menu - controls
            case GameState.Controls:
                if (inputHelper.KeyPressed(Keys.Enter))
                {
                    Controls.OnAction();
                }
                break;

            // Menu - game over
            case GameState.GameOver:
                if (inputHelper.KeyPressed(Keys.Enter))
                {
                    GameOver.OnAction();
                }
                break;

            // The game
            case GameState.Running:
                game.HandleInput(gameTime, inputHelper);
                break;
            }
        }
        public void ArrowKeyHierarchicalNavigationTest()
        {
            using (var setup = new TestSetupHelper(new[] { "NavigationView Tests", "HierarchicalNavigationView Markup Test" }))
            {
                //TODO: Re-enable for RS2 once arrow key behavior is matched with above versions
                if (!PlatformConfiguration.IsOsVersionGreaterThanOrEqual(OSVersion.Redstone3))
                {
                    Log.Warning("Test is disabled because the repeater arrow behavior is currently different for rs2.");
                    return;
                }

                // Set up tree and get references to all required elements
                UIObject item1 = FindElement.ByName("Menu Item 1");

                Log.Comment("Expand Menu Item 1");
                InputHelper.LeftClick(item1);
                Wait.ForIdle();

                UIObject item2 = FindElement.ByName("Menu Item 2");
                UIObject item3 = FindElement.ByName("Menu Item 3");

                Log.Comment("Expand Menu Item 2");
                InputHelper.LeftClick(item2);
                Wait.ForIdle();

                UIObject item4 = FindElement.ByName("Menu Item 4");
                UIObject item5 = FindElement.ByName("Menu Item 5");

                // Set up initial focus
                Log.Comment("Set focus on the pane toggle button");
                Button togglePaneButton = new Button(FindElement.ById("TogglePaneButton"));
                togglePaneButton.SetFocus();
                Wait.ForIdle();

                // Start down arrow key navigation test

                Log.Comment("Verify that down arrow navigates to Menu Item 1");
                KeyboardHelper.PressKey(Key.Down);
                Wait.ForIdle();
                Verify.IsTrue(item1.HasKeyboardFocus);

                Log.Comment("Verify that down arrow navigates to Menu Item 2");
                KeyboardHelper.PressKey(Key.Down);
                Wait.ForIdle();
                Verify.IsTrue(item2.HasKeyboardFocus);

                Log.Comment("Verify that down arrow navigates to Menu Item 4");
                KeyboardHelper.PressKey(Key.Down);
                Wait.ForIdle();
                Verify.IsTrue(item4.HasKeyboardFocus);

                Log.Comment("Verify that down arrow navigates to Menu Item 5");
                KeyboardHelper.PressKey(Key.Down);
                Wait.ForIdle();
                Verify.IsTrue(item5.HasKeyboardFocus);

                Log.Comment("Verify that down arrow navigates to Menu Item 3");
                KeyboardHelper.PressKey(Key.Down);
                Wait.ForIdle();
                Verify.IsTrue(item3.HasKeyboardFocus);

                // Start up arrow key navigation test

                Log.Comment("Verify that up arrow navigates to Menu Item 5");
                KeyboardHelper.PressKey(Key.Up);
                Wait.ForIdle();
                Verify.IsTrue(item5.HasKeyboardFocus);

                Log.Comment("Verify that up arrow navigates to Menu Item 4");
                KeyboardHelper.PressKey(Key.Up);
                Wait.ForIdle();
                Verify.IsTrue(item4.HasKeyboardFocus);

                Log.Comment("Verify that up arrow navigates to Menu Item 2");
                KeyboardHelper.PressKey(Key.Up);
                Wait.ForIdle();
                Verify.IsTrue(item2.HasKeyboardFocus);

                Log.Comment("Verify that up arrow navigates to Menu Item 1");
                KeyboardHelper.PressKey(Key.Up);
                Wait.ForIdle();
                Verify.IsTrue(item1.HasKeyboardFocus);

                Log.Comment("Verify that up arrow navigates to the pane toggle button");
                KeyboardHelper.PressKey(Key.Up);
                Wait.ForIdle();
                Verify.IsTrue(togglePaneButton.HasKeyboardFocus);
            }
        }
Ejemplo n.º 51
0
        public void ProcessParameters(object sender, string[] args)
        {
            // The form has loaded, and initialization will have been be done.

            // Add the command-line arguments to our textbox, just to confirm that
            // it reached here.
            if (args != null && args.Length != 0)
            {
                string dot = args[0];
                args[0] = args[0].Substring(0, 1);
                switch (args[0])
                {
                case "0":
                    txtArgs.Text += DateTime.Now.ToString() + " Stop\r\n";
                    AlgorithmRunner.RunStop();
                    break;

                case "1":
                    AlgorithmRunner.RunCreateAdjacencyMatrix();
                    txtArgs.Text += DateTime.Now.ToString() + " RunCreateAdjacencyMatrix\r\n";
                    break;

                case "2":
                    InputHelper.Rooms = InputHelper.InitRooms();
                    AlgorithmRunner.RunPriority();
                    AlgorithmRunner.RunCalc();
                    txtArgs.Text += DateTime.Now.ToString() + " RunCalc\r\n";
                    break;

                case "3":
                    //Tạo ma trận kề
                    AlgorithmRunner.RunCreateAdjacencyMatrix();
                    txtArgs.Text += DateTime.Now.ToString() + " RunCreateAdjacencyMatrix\r\n";
                    //------------------------
                    //Xếp giờ, phòng
                    InputHelper.Rooms = InputHelper.InitRooms();
                    AlgorithmRunner.RunPriority();
                    AlgorithmRunner.RunCalc();
                    txtArgs.Text += DateTime.Now.ToString() + " RunCalc\r\n";
                    //---------------------------
                    InputHelper.Rooms = InputHelper.InitRooms();
                    AlgorithmRunner.RunSaveToDatabase();
                    txtArgs.Text += DateTime.Now.ToString() + " RunSaveToDatabase\r\n";
                    break;

                case "4":
                    //InputHelper.IgnoreStudents = InputHelper.InitIgnoreStudents();
                    AlgorithmRunner.RunHandmade();
                    txtArgs.Text += DateTime.Now.ToString() + " Handmade\r\n";
                    break;

                case "5":
                    InputHelper.Rooms = InputHelper.InitRooms();
                    AlgorithmRunner.RunDeleteDatabase(dot.Substring(1, dot.Length - 1));
                    txtArgs.Text += DateTime.Now.ToString() + " DeleteToDatabase\r\n";
                    break;

                case "6":
                    AlgorithmRunner.RunFixSubject();
                    txtArgs.Text += DateTime.Now.ToString() + " FixSubject\r\n";
                    break;

                default:
                    txtArgs.Text += DateTime.Now.ToString() + " Not Run Anything\r\n";
                    break;
                }
            }
            else
            {
                txtArgs.Text += DateTime.Now.ToString() + " Run No Args: Init()\r\n";
            }
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Runs the Admin funtionality-page
        /// </summary>
        /// <returns>integer, user id if admin, 0 if not</returns>
        public int Run()
        {
            AdminView.StartPage();
            userId = new Login().Run();
            if (userId == 0)
            {
                return(0);
            }

            var result = CheckAdmin(userId);

            if (!result)
            {
                AdminView.VerifyAdminFailed();
                return(0);
            }

            bool keepGoing = true;

            while (keepGoing)
            {
                AdminView.AdminPage();
                var input = InputHelper.ParseInput();

                switch (input)
                {
                case 1:
                    AddBook(userId);
                    break;

                case 2:
                    SetAmount(userId);
                    break;

                case 3:
                    ViewAllUsers(userId);
                    break;

                case 4:
                    FindUser(userId);
                    break;

                case 5:
                    UpdateBook(userId);
                    break;

                case 6:
                    DeleteBook(userId);
                    break;

                case 7:
                    AddCategory(userId);
                    break;

                case 8:
                    AddBookToCategory(userId);
                    break;

                case 9:
                    UpdateCategory(userId);
                    break;

                case 10:
                    DeleteCategory(userId);
                    break;

                case 11:
                    AddUser(userId);
                    break;

                case 12:
                    ViewAllSoldItems(userId);
                    break;

                case 13:
                    ViewTotalIncome(userId);
                    break;

                case 14:
                    ViewBestCustomer(userId);
                    break;

                case 15:
                    PromoteUser(userId);
                    break;

                case 16:
                    DemoteUser(userId);
                    break;

                case 17:
                    ActivateUser(userId);
                    break;

                case 18:
                    InactivateUser(userId);
                    break;

                case 19:
                    keepGoing = false;
                    break;

                default:
                    MessageViews.DisplayNonAvailableMessage();
                    break;
                }
            }
            return(userId);
        }
Ejemplo n.º 53
0
 public void Update()
 {
     if (SceneManager.isIngame)
     {
         if (StatManager.sleep == null)
         {
             return;
         }
         if (StatManager.tiredness == null)
         {
             return;
         }
         if (StatManager.coffee == null)
         {
             return;
         }
         if (StatManager.vision == null)
         {
             return;
         }
         if (sleeping)
         {
             if (sleepLocation == SleepLocation.Floor && !DayNightCycle.main.IsInSkipTimeMode())
             {
                 StopSleep(Player.main, false);
             }
         }
         if (InputHelper.IsKeyDown(SettingsManager.keySleepStart) && !keySleepStartDown)
         {
             keySleepStartDown = true;
             if (!sleeping)
             {
                 if (NotifyGetCanSleep(Player.main))
                 {
                     if (SettingsManager.keySleepStart == SettingsManager.keySleepStop)
                     {
                         keySleepStopDown = true;
                     }
                     StartSleep(Player.main);
                 }
             }
         }
         else if (!InputHelper.IsKeyDown(SettingsManager.keySleepStart) && keySleepStartDown)
         {
             keySleepStartDown = false;
         }
         if (InputHelper.IsKeyDown(SettingsManager.keySleepStop) && !keySleepStopDown)
         {
             keySleepStopDown = true;
             if (sleeping)
             {
                 if (SettingsManager.keySleepStart == SettingsManager.keySleepStop)
                 {
                     keySleepStartDown = true;
                 }
                 StopSleep(Player.main, false);
             }
         }
         else if (!InputHelper.IsKeyDown(SettingsManager.keySleepStop) && keySleepStopDown)
         {
             keySleepStopDown = false;
         }
         float oldTime           = lastTime;
         float newTime           = SurvivalHelper.GetTime();
         float timePassed        = newTime - oldTime;
         float timePassedHours   = (float)(timePassed / (1d / 24));
         float timePassedMinutes = (float)(timePassedHours * 60);
         if (timePassedMinutes >= 1)
         {
             lastTime = newTime;
             if (SurvivalHelper.IsSurvival())
             {
                 StatManager.coffee.Value += SurvivalHelper.GetChangeValue(timePassedMinutes, coffeeFactor);
                 float oldCoffeeMod = StatManager.tiredness.GetModifier("coffee");
                 float newCoffeeMod = (StatManager.coffee.RealValue / 100) * -30f;
                 if (Math.Abs(oldCoffeeMod - newCoffeeMod) >= 0.5f)
                 {
                     StatManager.tiredness.SetModifier("coffee", Stat.ModifierType.ValueAbsolute, newCoffeeMod);
                 }
             }
             else
             {
                 float oldCoffeeMod = StatManager.tiredness.GetModifier("coffee");
                 if (oldCoffeeMod != 0f)
                 {
                     StatManager.tiredness.SetModifier("coffee", Stat.ModifierType.ValueAbsolute, 0f);
                 }
             }
             if (sleeping)
             {
                 if (sleepLocation == SleepLocation.Bed)
                 {
                     float hpOut = Player.main.liveMixin.health + SurvivalHelper.GetChangeValue(timePassedMinutes, healthFactorSleepingEfficient);
                     hpOut = hpOut > 100 ? 100 : hpOut < 0 ? 0 : hpOut;
                     Player.main.liveMixin.health = hpOut;
                     if (SurvivalHelper.IsSurvival())
                     {
                         StatManager.sleep.Value +=
                             SurvivalHelper.GetChangeValue(timePassedMinutes, sleepFactorSleepingEfficient);
                         StatManager.tiredness.Value += SurvivalHelper.GetChangeValue(timePassedMinutes,
                                                                                      tirednessFactorSleepingEfficient);
                         if (StatManager.sleep.RealValue >= 100)
                         {
                             StopSleep(Player.main, false);
                         }
                     }
                 }
                 else
                 {
                     float hpOut = Player.main.liveMixin.health + SurvivalHelper.GetChangeValue(timePassedMinutes, healthFactorSleepingInefficient);
                     hpOut = hpOut > 100 ? 100 : hpOut < 0 ? 0 : hpOut;
                     Player.main.liveMixin.health = hpOut;
                     if (SurvivalHelper.IsSurvival())
                     {
                         StatManager.sleep.Value += SurvivalHelper.GetChangeValue(timePassedMinutes,
                                                                                  sleepFactorSleepingInefficient);
                         StatManager.tiredness.Value += SurvivalHelper.GetChangeValue(timePassedMinutes,
                                                                                      tirednessFactorSleepingInefficient);
                         if (StatManager.sleep.RealValue >= 100)
                         {
                             StopSleep(Player.main, false);
                         }
                     }
                 }
                 if (SurvivalHelper.IsSurvival())
                 {
                     Survival pSurvival = Player.main.GetComponent <Survival>();
                     pSurvival.food += SurvivalHelper.GetChangeValue(timePassedMinutes,
                                                                     foodFactorSleeping);
                     pSurvival.water += SurvivalHelper.GetChangeValue(timePassedMinutes,
                                                                      waterFactorSleeping);
                     if (pSurvival.food <= 10f || pSurvival.water <= 10f)
                     {
                         StopSleep(Player.main, false);
                         if (pSurvival.food <= 10f)
                         {
                             pSurvival.foodWarningSounds[1].Play();
                         }
                         else if (pSurvival.water <= 10f)
                         {
                             pSurvival.waterWarningSounds[1].Play();
                         }
                     }
                 }
             }
             else if (sitting)
             {
                 if (SurvivalHelper.IsSurvival())
                 {
                     StatManager.sleep.Value +=
                         SurvivalHelper.GetChangeValue(timePassedMinutes, sleepFactorNormal);
                 }
                 // TODO Find a good way to replenish stamina (TBD) and tiredness.
             }
             else
             {
                 if (SurvivalHelper.IsSurvival())
                 {
                     StatManager.sleep.Value +=
                         SurvivalHelper.GetChangeValue(timePassedMinutes, sleepFactorNormal);
                     StatManager.tiredness.Value +=
                         SurvivalHelper.GetChangeValue(timePassedMinutes, tirednessFactorNormal);
                 }
             }
             if (SurvivalHelper.IsSurvival())
             {
                 if (StatManager.sleep.RealValue <= 0)
                 {
                     Player.main.liveMixin.TakeDamage(-SurvivalHelper.GetChangeValue(timePassedMinutes, healthFactorDying), default, DamageType.Starve);
Ejemplo n.º 54
0
 public void HandleInput(InputHelper inputHelper)
 {
 }
Ejemplo n.º 55
0
        public void RevealHoverLightPositionTests()
        {
            if (PlatformConfiguration.IsOSVersionLessThan(OSVersion.Redstone5))
            {
                Log.Warning("This test relies on touch input, the injection of which is only supported in RS5 and up. Test is disabled.");
                return;
            }

            using (IDisposable page1 = new TestSetupHelper("Reveal Tests"),
                   page2 = new TestSetupHelper("navigateToRevealStates"))
            {
                var result = new Edit(FindElement.ById("TestResult"));

                Log.Comment("Tap and hold Button at an offset. Verfiy RevealHoverLight uses pointer expression to position itself at the pointer.");
                var target = FindElement.ById("NarrowButton");
                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    // Move mouse pointer away so it does not create HoverLight on the item
                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    InputHelper.TapAndHold(target, 10, 35, 1000);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "HoverLightExpression_Button_Touch");

                Log.Comment("Activate Button with Keyboard. Validate RevealHoverLight uses keyboard expression to position itself at center of the control.");
                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    // Move mouse pointer away so it does not create BorderLight on the item
                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    // Tab to next button and activate it with keyboard
                    KeyboardHelper.PressKey(Key.Tab);
                    KeyboardHelper.PressKey(Key.Space);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "HoverLightExpression_Button_Keyboard");

                Log.Comment("Tap and hold ListViewItem at an offset. Verfiy RevealHoverLight uses pointer expression to position itself at the pointer.");
                target = FindElement.ById("OneMoreListViewItem");
                ChooseFromComboBox("TargetComboBox", "OneMoreListViewItem");
                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    // Move mouse pointer away so it does not create HoverLight on the item
                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    InputHelper.TapAndHold(target, 150, 35, 1000);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "HoverLightExpression_ListViewItem_Touch");
            }
        }
Ejemplo n.º 56
0
        public void RevealHoverLightPosition_Values()
        {
            if (PlatformConfiguration.IsOSVersionLessThan(OSVersion.Redstone2))
            {
                Log.Comment("RevealHoverLightPosition_Values needs to be running on RS2 or greater");
                return;
            }

            using (IDisposable page1 = new TestSetupHelper("Reveal Tests"),
                   page2 = new TestSetupHelper("navigateToRevealStates"))
            {
                var result = new Edit(FindElement.ById("TestResult"));
                var target = FindElement.ById("LargeButton2");

                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    // Note for this test case we specifically attach the hover light via hover, not press.
                    // This provides regression coverage for Bug 14079741: Reveal hover light doesn't follow pointer until first interaction/click
                    Log.Comment("Move pointer over LargeButton2 (which will attach RevealHoverLight).");
                    target.MovePointer(50, 50);
                    Wait.ForIdle();

                    ChooseFromComboBox("ValidationActionsComboBox", "HoverLight_ValidatePosition_Offset1_Values");
                    FindElement.ByName <Button>("StartLoggingValues").InvokeAndWait();

                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    Log.Comment("Move pointer to Offset1 [10, 90] on LargeButton2. Wait for light to position to reach expected values.");
                    target.MovePointer(10, 90);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "Offset1_Values");

                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    ChooseFromComboBox("ValidationActionsComboBox", "HoverLight_ValidatePosition_Offset2_Values");
                    FindElement.ByName <Button>("StartLoggingValues").InvokeAndWait();

                    // Move mouse pointer away so it does not create BorderLight on the item
                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    Log.Comment("Move pointer to Offset2 [50, 50]. Wait for light to position to reach expected values.");
                    target.MovePointer(50, 50);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "Offset2_Values");

                target = FindElement.ById("NarrowButton2");
                using (var waiter = new ValueChangedEventWaiter(result))
                {
                    Log.Comment("Tap and hold NarrowButton2 (which will attach RevealHoverLight).");
                    InputHelper.TapAndHold(target, 3000);
                    Wait.ForIdle();

                    ChooseFromComboBox("ValidationActionsComboBox", "HoverLight_ValidatePosition_Offset3_Values");
                    FindElement.ByName <Button>("StartLoggingValues").InvokeAndWait();

                    TestEnvironment.Application.CoreWindow.MovePointer(0, 0);
                    Wait.ForIdle();

                    Log.Comment("Tap on NarrowButton2 at [10, 40]. Wait for light position to reach expected values.");
                    InputHelper.Tap(target, 10, 40);
                    Wait.ForIdle();

                    waiter.Wait();
                }
                LogResult(result, "Offset3_Values");
            }
        }
        public void CanClearEveryValueTest()
        {
            using (var setup = new TestSetupHelper("RatingControl Tests")) // This literally clicks the button corresponding to the test page.
            {
                if (PlatformConfiguration.IsOSVersionLessThan(OSVersion.Redstone2))
                {
                    // For some reason this test sometimes fails on RS1 when the "bounding box" of the
                    // RatingControl has negative values, but it's not worth the investigation to fix:
                    Log.Comment("Test is disabled on RS1 due to reliability issues");
                    return;
                }

                TextBlock tb = new TextBlock(FindElement.ById("FrameDetails"));
                Log.Comment("FrameDetails: " + tb.DocumentText);

                Log.Comment("Retrieve rating control as generic UIElement");
                UIObject ratingUIObject = FindElement.ByName("TestRatingControl");
                Verify.IsNotNull(ratingUIObject, "Verifying that we found a UIElement called TestRatingControl");

                Log.Comment("Retrieve the text block as a TextBlock");
                TextBlock textBlock = new TextBlock(FindElement.ByName("TestTextBlockControl"));

                Wait.ForIdle();

                Log.Comment("Verify a tap on the first star sets Rating to 1");
                InputHelper.Tap(ratingUIObject, (0 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("1", textBlock.DocumentText);

                Log.Comment("Verify a tap on the first star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, (0 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);

                Log.Comment("Verify a tap on the second star sets Rating to 2");
                InputHelper.Tap(ratingUIObject, (1 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("2", textBlock.DocumentText);

                Log.Comment("Verify a tap on the second star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, (1 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);

                Log.Comment("Verify a tap on the third star sets Rating to 3");
                InputHelper.Tap(ratingUIObject, (2 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("3", textBlock.DocumentText);

                Log.Comment("Verify a tap on the third star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, (2 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);

                Log.Comment("Verify a tap on the fourth star sets Rating to 4");
                InputHelper.Tap(ratingUIObject, (3 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("4", textBlock.DocumentText);

                Log.Comment("Verify a tap on the fourth star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, (3 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);

                Log.Comment("Verify a tap on the fifth star sets Rating to 5");
                InputHelper.Tap(ratingUIObject, (4 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("5", textBlock.DocumentText);

                Log.Comment("Verify a tap on the second star sets Rating to 2.5 (placeholder value)");
                InputHelper.Tap(ratingUIObject, (4 * RATING_ITEM_WIDTH) + (RATING_ITEM_WIDTH / 2), RATING_ITEM_HEIGHT / 2);
                Verify.AreEqual("!2.5", textBlock.DocumentText);
            }
        }
Ejemplo n.º 58
0
 public void UpdateCamera(TiledMap map, InputHelper inputHelper)
 {
 }
Ejemplo n.º 59
0
        // The value of 'testName' should match that which was used when
        // registering the test in TestInventory.cs in the test app project.
        public TestSetupHelper(ICollection <string> testNames, string languageOverride = "", bool attemptRestartOnDispose = true)
        {
            // If a test crashes, it can take a little bit of time before we can
            // restart the app again especially if watson is collecting dumps. Adding a
            // delayed retry can help avoid the case where we might otherwise fail a slew of
            // tests that come after the one that crashes the app.
            var retryCount = 10;

            while (retryCount-- > 0)
            {
                try
                {
                    AttemptRestartOnDispose = attemptRestartOnDispose;
                    bool restartedTestApp = false;

                    if (TestEnvironment.ShouldRestartApplication)
                    {
                        ElementCache.Clear();
                        Wait.ResetIdleHelper();

                        TestEnvironment.ShouldRestartApplication = false;

                        Log.Comment("Restarting application to ensure test stability...");
                        TestEnvironment.Application.Close();

                        restartedTestApp = true;
                    }

                    if (restartedTestApp ||
                        (TestEnvironment.Application.Process != null && TestEnvironment.Application.Process.HasExited))
                    {
                        if (!restartedTestApp)
                        {
                            // If the test application process exited because something crashed,
                            // we'll restart it in order to make sure that other tests aren't affected.
                            Log.Comment("Application exited unexpectedly. Reinitializing...");
                        }

                        ElementCache.Clear();
                        Wait.ResetIdleHelper();

#if USING_TAEF
                        string deploymentDir = TestEnvironment.TestContext.TestDeploymentDir;
#else
                        // TestDeploymentDir doesn't exist on MSTest's TestContext.  The only thing we use it for
                        // is to install the AppX, and we install the AppX in other ways when using MSTest, so
                        // we don't need it there.
                        string deploymentDir = null;
#endif

                        TestEnvironment.Application.Initialize(true, deploymentDir);
                    }

                    ElementCache.Clear();
                    Wait.ForIdle();

                    // Before we navigate to the test page, we need to make sure that we've set the language to what was requested.
                    var languageChooser = TryFindElement.ById("LanguageChooser");

                    // Sometimes TestSetupHelper is used to navigate off of a page other than the main page.  In those circumstances,
                    // we won't have a pseudo-loc check box on the page, which is fine - we can just skip this step when that's the case,
                    // as we'll have already gone into whatever language we wanted previously.
                    if (languageChooser != null)
                    {
                        ComboBox languageChooserComboBox = new ComboBox(languageChooser);

                        if (!String.IsNullOrEmpty(languageOverride))
                        {
                            languageChooserComboBox.SelectItemById(languageOverride);
                        }
                    }

                    // We were hitting an issue in the lab where sometimes the very first click would fail to go through resulting in
                    // test instability. We work around this by clicking on element when the app launches.
                    var currentPageTextBlock = FindElement.ById("__CurrentPage");
                    if (currentPageTextBlock == null)
                    {
                        string errorMessage = "Cannot find __CurrentPage textblock";
                        Log.Error(errorMessage);
                        DumpHelper.DumpFullContext();
                        throw new InvalidOperationException(errorMessage);
                    }
                    InputHelper.LeftClick(currentPageTextBlock);

                    foreach (string testName in testNames)
                    {
                        Log.Comment(testName + " initializing TestSetupHelper");

                        var uiObject = FindElement.ByNameAndClassName(testName, "Button");
                        if (uiObject == null)
                        {
                            string errorMessage = string.Format("Cannot find test page for: {0}.", testName);

                            // We'll raise the error message first so the dump has proper context preceding it,
                            // and will then throw it as an exception so we immediately cease execution.
                            Log.Error(errorMessage);
                            DumpHelper.DumpFullContext();
                            throw new InvalidOperationException(errorMessage);
                        }

                        // We're now entering a new test page, so everything has changed.  As such, we should clear our
                        // element cache in order to ensure that we don't accidentally retrieve any stale UI objects.
                        ElementCache.Clear();

                        Log.Comment("Waiting until __TestContentLoadedCheckBox to be checked by test app.");
                        CheckBox cb = new CheckBox(FindElement.ById("__TestContentLoadedCheckBox"));

                        if (cb.ToggleState != ToggleState.On)
                        {
                            using (var waiter = cb.GetToggledWaiter())
                            {
                                var testButton = new Button(uiObject);
                                testButton.Invoke();
                                Wait.ForIdle();
                                waiter.Wait();
                            }
                        }
                        else
                        {
                            var testButton = new Button(uiObject);
                            testButton.Invoke();
                        }

                        Wait.ForIdle();

                        Log.Comment("__TestContentLoadedCheckBox checkbox checked, page has loaded");

                        OpenedTestPages++;
                    }

                    TestCleanupHelper.TestSetupHelperPendingDisposals++;
                    break;
                }
                catch
                {
                    Log.Warning("Failed to setup test. pending retries: " + retryCount);
                    if (retryCount > 0)
                    {
                        Log.Comment("Waiting before retry...");
                        TestEnvironment.ShouldRestartApplication = true;
                        Task.Delay(5000);
                    }
                    else
                    {
                        Log.Error("Failed to set up test!");
                        try
                        {
                            DumpHelper.DumpFullContext();
                        }
                        catch (Exception e)
                        {
                            Log.Error("Also failed to dump context because of an exception: {0}", e.ToString());
                        }

                        throw;
                    }
                }
            }
        }
        public void UIAValuePatternTest()
        {
            using (var setup = new TestSetupHelper("RatingControl Tests")) // This literally clicks the button corresponding to the test page.
            {
                Log.Comment("Retrieve rating control as generic UIElement");
                UIObject ratingUIObject = FindElement.ByName("TestRatingControl");

                TextBlock textBlock = new TextBlock(FindElement.ByName("TestTextBlockControl"));
                Verify.IsNotNull(ratingUIObject, "Verifying that we found a UIElement called TestRatingControl");

                Log.Comment("Verify the UIA Value before user clicks the control.");
                ratingUIObject.SetFocus(); // Setting focus just so we can use AE.FE below
                Wait.ForIdle();
                AutomationElement ratingPeer = AutomationElement.FocusedElement;

                VerifyValue_ValueEqualsOnAutomationElement(ratingPeer, "Community Rating, 2.5 of 5");

                if (PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone2)) // engagement doesn't work pre RS3
                {
                    Log.Comment("Verify moving right 2 times with the gamepad sets the control to 3");
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.A);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.DPadRight);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.DPadRight);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.A);
                    Wait.ForIdle();
                    Verify.AreEqual("3", textBlock.DocumentText);

                    Log.Comment("Verify rating of 3 sets UIA text to 3");

                    VerifyValue_ValueEqualsOnAutomationElement(ratingPeer, "Rating, 3 of 5");

                    // revert:
                    Log.Comment("Resetting control to community rating");
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.A);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.DPadLeft);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.DPadLeft);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.DPadLeft);
                    GamepadHelper.PressButton(ratingUIObject, GamepadButton.A);

                    VerifyValue_ValueEqualsOnAutomationElement(ratingPeer, "Community Rating, 2.5 of 5");
                }

                Log.Comment("Verify more complex navigation");
                KeyboardHelper.PressKey(ratingUIObject, Key.Right);
                KeyboardHelper.PressKey(ratingUIObject, Key.Right);
                KeyboardHelper.PressKey(ratingUIObject, Key.Right);
                KeyboardHelper.PressKey(ratingUIObject, Key.Left);
                VerifyValue_ValueEqualsOnAutomationElement(ratingPeer, "Rating, 2 of 5");

                // Verify read an unset rating
                ratingUIObject = FindElement.ByName("RatingBindingSample");
                Log.Comment("Verify the UIA Value of an unset Rating without a placeholder value");
                ratingUIObject.SetFocus();
                InputHelper.ScrollToElement(ratingUIObject);
                ratingPeer = AutomationElement.FocusedElement;

                VerifyValue_ValueEqualsOnAutomationElement(ratingPeer, "Rating Unset");

                // Verify rounding:
                Log.Comment("Verifying Value_Value rounding");
                UIObject round1 = FindElement.ById("ValuePatternRoundTest1");
                round1.SetFocus();
                AutomationElement roundAE1 = AutomationElement.FocusedElement;
                UIObject          round2   = FindElement.ById("ValuePatternRoundTest2");
                round2.SetFocus();
                AutomationElement roundAE2 = AutomationElement.FocusedElement;
                UIObject          round3   = FindElement.ById("ValuePatternRoundTest3");
                round3.SetFocus();
                AutomationElement roundAE3 = AutomationElement.FocusedElement;

                VerifyValue_ValueEqualsOnAutomationElement(roundAE1, "Rating, 1.5 of 5");
                VerifyValue_ValueEqualsOnAutomationElement(roundAE2, "Rating, 1.55 of 5");
                VerifyValue_ValueEqualsOnAutomationElement(roundAE3, "Rating, 1.5 of 5");
            }
        }