Поделиться через


Шаг 4. Добавление метода CheckTheAnswer()

Игра должна проверять, дает ли пользователь правильный ответ.К счастью, написание методов, которые выполняют простые вычисления, например, метода CheckTheAnswer(), не является сложной задачей.

ПримечаниеПримечание

Для тех, кто разрабатывает игру на Visual Basic необходимо отметить, что поскольку метод возвращает значение, вместо обычного ключевого слова Sub будет использоваться ключевое слово Function.Это объясняется просто — процедуры не возвращают значения, в отличие от функций.

Добавление метода CheckTheAnswer()

  1. Добавьте метод CheckTheAnswer(), который выполняет сложение переменной addend1 и переменной addend2 и выполняет проверку, что сумма равна значению sum элемента управления NumericUpDown.Если значение суммы равно значению sum метод возвращает значение true; в противном случае — false.Код должен выглядеть так, как показано ниже.

    ''' <summary>
    ''' Check the answer to see if the user got everything right.
    ''' </summary>
    ''' <returns>True if the answer's correct, false otherwise.</returns>
    ''' <remarks></remarks>
    Public Function CheckTheAnswer() As Boolean
    
        If addend1 + addend2 = sum.Value Then
            Return True
        Else
            Return False
        End If
    
    End Function
    
    /// <summary>
    /// Check the answer to see if the user got everything right.
    /// </summary>
    /// <returns>True if the answer's correct, false otherwise.</returns>
    private bool CheckTheAnswer()
    {
        if (addend1 + addend2 == sum.Value)
            return true;
        else
            return false;
    }
    

    Программа должна вызвать этот метод для проверки, правильный ли ответ дал пользователь.Это выполняется путем добавления оператора if else.Оператор выглядит следующим образом.

    If CheckTheAnswer() Then
        ' statements that will get executed
        ' if the answer is correct 
    ElseIf timeLeft > 0 Then
        ' statements that will get executed
        ' if there's still time left on the timer
    Else
        ' statements that will get executed if the timer ran out
    End If
    
    if (CheckTheAnswer())
    {
          // statements that will get executed
          // if the answer is correct 
    }
    else if (timeLeft > 0)
    {
          // statements that will get executed
          // if there's still time left on the timer
    }
    else
    {
          // statements that will get executed if the timer ran out
    }  
    
  2. Затем выполняется изменение обработчика событий Tick для проверки ответа.Новый обработчик с проверкой ответа должен содержать следующее.

    Private Sub Timer1_Tick() Handles Timer1.Tick
    
        If CheckTheAnswer() Then
            ' If the user got the answer right, stop the timer
            ' and show a MessageBox.
            Timer1.Stop()
            MessageBox.Show("You got all of the answers right!", "Congratulations!")
            startButton.Enabled = True
        ElseIf timeLeft > 0 Then
            ' Decrease the time left by one second and 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 (CheckTheAnswer())
        {
            // If the user got the answer right, stop the timer 
            // and show a MessageBox.
            timer1.Stop();
            MessageBox.Show("You got all the answers right!",
                            "Congratulations");
            startButton.Enabled = true;
        }
        else if (timeLeft > 0)
        {
            // Decrease the time left by one second and display 
            // the new time left by updating the Time Left label.
            timeLeft--;
            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;
        }
    }
    

    Теперь если обработчик события таймера обнаруживает, что пользователь дал правильный ответ, обработчик событий останавливает таймер, показывает сообщение с поздравлением и делает снова доступной кнопку Пуск.

  3. Сохраните и выполните программу.Начните игру, введите правильный ответ для задачи на сложение.

    ПримечаниеПримечание

    При вводе ответа можно заметить некую странность в поведении элемента управления NumericUpDown.Если начать ввод ответа, не выделив при этом ответ полностью, нуль остается, его необходимо удалить вручную.Такое странное поведение будет исправлено в этом руководстве позднее.

  4. При вводе правильного ответа должно открыться окно сообщений, кнопка Пуск должна стать доступной, таймер должен остановиться.Нажмите снова кнопку Пуск и убедитесь в этом.

Продолжить или повторить пройденный материал