Step 3: Add a Countdown Timer

在本教程的第 3 部分中,您将添加一个倒计时计时器,用于跟踪测验对象完成测验所剩秒数。

说明说明

本主题是基本编码概念教程系列中的一部分。有关本教程的概述,请参阅Tutorial 2: Create a Timed Math Quiz

添加倒计时计时器

  1. 添加一个名为**“timeLeft”**的整型变量,就像在上一个过程中一样。您的代码应类似以下内容。

    Public Class Form1
    
        ' Create a Random object called randomizer  
        ' to generate random numbers. 
        Private randomizer As New Random
    
        ' These integer variables store the numbers  
        ' for the addition problem.  
        Private addend1 As Integer 
        Private addend2 As Integer 
    
        ' This integer variable keeps track of the  
        ' remaining time. 
        Private timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object called randomizer  
        // to generate random numbers.
        Random randomizer = new Random();
    
        // These integer variables store the numbers  
        // for the addition problem.  
        int addend1;
        int addend2;
    
        // This integer variable keeps track of the  
        // remaining time. 
        int timeLeft;
    

    现在您需要一个进行实际读秒的方法(例如计时器),此方法在您指定的时间后将引发一个事件。

  2. 在设计窗口中,将一个 Timer 控件从工具箱的**“组件”**类别移到您的窗体中。

    此控件显示在设计窗口底部的灰色区域内。

  3. 在窗体中,请选择您刚才添加的**“timer1”图标,并将其“Interval”属性设置为“1000”**。

    因为间隔值单位为毫秒,因此当值为 1000 时将使 Tick 事件每秒触发一次。

  4. 在窗体中,双击 Timer 控件,或将其选中,然后选择 Enter 键。

    此时将出现代码编辑器,并显示您刚才添加的 Tick 事件处理程序的方法。

  5. 将下面的语句添加到新事件处理程序方法。

    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        If timeLeft > 0 Then 
            ' Display the new time left 
            ' by updating the Time Left label.
            timeLeft -= 1
            timeLabel.Text = timeLeft & " seconds" 
        Else 
            ' If the user ran out of time, stop the timer, show 
            ' a MessageBox, and fill in the answers.
            Timer1.Stop()
            timeLabel.Text = "Time's up!"
            MessageBox.Show("You didn't finish in time.", "Sorry!")
            sum.Value = addend1 + addend2
            startButton.Enabled = True 
        End If 
    
    End Sub
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        if (timeLeft > 0)
        {
            // Display the new time left 
            // by updating the Time Left label.
            timeLeft = timeLeft - 1;
            timeLabel.Text = timeLeft + " seconds";
        }
        else
        {
            // If the user ran out of time, stop the timer, show 
            // a MessageBox, and fill in the answers.
            timer1.Stop();
            timeLabel.Text = "Time's up!";
            MessageBox.Show("You didn't finish in time.", "Sorry!");
            sum.Value = addend1 + addend2;
            startButton.Enabled = true;
        }
    }
    

    根据您刚才添加的语句,计时器将每秒检查一次**“timeLeft”整型变量是否大于 0,从而确定时间是否已用完。如果大于 0,则表示仍有剩余时间。首先,计时器将从 timeLeft 中减去 1,然后更新“timeLabel”**控件的“Text”属性,以便向测验对象显示剩余的秒数。

    如果没有剩余时间,则计时器将停止并更改 timeLabel 控件的文本,使之显示**“Time's up!”(时间到!)。此时将通过一个消息框宣布测验结束,并公布答案,在此示例中,是将 addend1 和 addend2 相加。startButton 控件的“Enabled”**属性将设置为 true,以便测验对象开始其他测试。

    您刚刚添加了 if else 语句,可通过这种方式告诉程序做出判断。if else 语句如下所示。

    说明说明

    下面的示例仅用于说明,请勿将其添加到您的项目。

    If (something that your program will check) Then
        ' One or more statements that will run
        ' if what the program checked is true. 
    Else
        ' One or more statements that will run
        ' if what the program checked is false.
    End If
    
    if (something that your program will check)
    {
        // One or more statements that will run
        // if what the program checked is true. 
    }
    else
    {
        // One or more statements that will run
        // if what the program checked is false.
    }
    

    请仔细查看您刚才在 else 块中添加的、用于显示加法题答案的语句。

    sum.Value = addend1 + addend2
    
    sum.Value = addend1 + addend2;
    

    语句 addend1 + addend2 会将两个变量中的值相加。第一部分 (sum.Value) 使用 sum NumericUpDown 控件的**“Value”**属性来显示正确答案。您稍后将使用相同的属性来检查测验的答案。

    测验对象可以使用 NumericUpDown 控件更轻松地输入数字,因此您应将此控件用于数学问题的答案。所有可能的答案均为 0 到 100 之间的整数。通过保留**“Minimum”“Maximum”“DecimalPlaces”属性的默认值,您可以确保测验对象不能输入小数、负数或过大的数字。(如果要允许测验对象输入 3.141 但不允许输入 3.1415,则可以将“DecimalPlaces”**属性设置为 3。)

  6. 将三行代码添加到 StartTheQuiz() 方法的结尾,以使代码类似于下面这样。

    ''' <summary> 
    ''' Start the quiz by filling in all of the problem  
    ''' values and starting the timer.  
    ''' </summary> 
    ''' <remarks></remarks> 
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem. 
        ' Generate two random numbers to add. 
        ' Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
    
        ' Convert the two randomly generated numbers 
        ' into strings so that they can be displayed 
        ' in the label controls.
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
    
        ' 'sum' is the name of the NumericUpDown control. 
        ' This step makes sure its value is zero before 
        ' adding any values to it.
        sum.Value = 0
    
        ' Start the timer.
        timeLeft = 30
        timeLabel.Text = "30 seconds"
        Timer1.Start()
    
    End Sub
    
    /// <summary> 
    /// Start the quiz by filling in all of the problem  
    /// values and starting the timer.  
    /// </summary> 
    public void StartTheQuiz()
    {
        // Fill in the addition problem. 
        // Generate two random numbers to add. 
        // Store the values in the variables 'addend1' and 'addend2'.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
    
        // Convert the two randomly generated numbers 
        // into strings so that they can be displayed 
        // in the label controls.
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
    
    
        // 'sum' is the name of the NumericUpDown control. 
        // This step makes sure its value is zero before 
        // adding any values to it.
        sum.Value = 0;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    现在,当您的测验开始时,**“timeLeft”变量将设置为 30,而 timeLabel 控件的“Text”**属性将设置为 30 秒。然后,Timer 控件的 Start() 方法将开始倒计时。(测验现在还不会检查答案,接下来将介绍此内容。)

  7. 保存并运行您的程序,然后选择窗体中的**“开始”**按钮。

    计时器将开始倒计时。当时间用完时,测验将结束,并显示答案。下图显示了正在进行的测验。

    正在进行的数学测验

    数学测验正在进行中

继续或查看