首页 > 解决方案 > C# 事件处理程序

问题描述

我正在尝试在 WPF 应用程序上重新播放按钮来重置我的游戏。我这辈子都想不通。我的教授说要创建一个新的事件处理程序,但我仍然不明白我在做什么。我的代码如下,任何帮助将不胜感激!谢谢!

public partial class MainWindow : Window
{
    //declare and initialize variables
    private int lives = 10; //used to give lives for the game
    private int random = 0; //used to assign a random number

    public MainWindow()
    {
        InitializeComponent();
        Random r = new Random();
        //sets the range for the random number
        random = r.Next(0, 100);


        //play the game
        playGame();

    } //end MainWindow Constructor

    private void btnPlayAgain_Click(object sender, RoutedEventArgs e)
    {

        //call playGame to setup a new game
        playGame();

    }

    private void playGame()
    {
        //hide play again
        btnPlayAgain.Visibility = Visibility.Hidden;

    }

    private void txtInupt_KeyDown(object sender, KeyEventArgs e)
    {
        //when you run out of lives message pops up
        if (lives == 0)
        {
            lblFrom.Content = "You";
            lblTo.Content = "lost";
            return;
        }

        //when you guess the rigiht number message pops up
        if (e.Key == Key.Enter)
        {
            lives--;
            int userGuessed = Int32.Parse(txtInupt.Text);
            if (userGuessed == random)
            {
                lblFrom.Content = "You";
                lblTo.Content = "win!!";
                btnPlayAgain.Visibility = Visibility.Visible;
                txtInupt.Visibility = Visibility.Hidden;
                return;
            }
            if (userGuessed < random)
            {
                lblFrom.Content = userGuessed;
            }
            else
            {
                lblTo.Content = userGuessed;
            }

            //this is the countdown of how many lives you have
            lblStatus.Content = "Remaining Lives: " + lives;
            //changes the color toi rend when you have 3 or less lives
            if (this.lives <= 3)
            {
                this.lblStatus.Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
            }
            else
            {
                this.lblStatus.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 0));
            }
        }
    } //End txtInput_KeyDown
}//End Main Window

标签: c#wpfeventhandler

解决方案


推荐阅读