Condividi tramite


Passaggio 3: aggiungere un timer per il conto alla rovescia

Poiché si tratta di un quiz a tempo, si aggiungerà un timer per il conto alla rovescia.Il programma deve tenere traccia del numero di secondi rimanenti a mano a mano che il gioco avanza.

Per aggiungere un timer per il conto alla rovescia

  1. Aggiungere un int (Integer) denominato timeLeft, esattamente come si è fatto precedentemente.Il codice dovrebbe essere analogo al seguente.

    Public Class Form1
    
        ' Create a Random object to generate random numbers.
        Private randomizer As New Random
    
        ' These Integers will store the numbers
        ' for the addition problem.
        Private addend1 As Integer
        Private addend2 As Integer
    
        ' This Integer will keep track of the time left.
        Private timeLeft As Integer
    
    public partial class Form1 : Form
    {
        // Create a Random object to generate random numbers.
        Random randomizer = new Random();
    
        // These ints will store the numbers
        // for the addition problem.
        int addend1;
        int addend2;
    
        // This int will keep track of the time left.
        int timeLeft;
    
  2. Ora è necessario aggiungere un controllo che esegue effettivamente il conteggio, quale un timer.Andare a Progettazione Windows Form e trascinare un controllo Timer dalla Casella degli strumenti (dalla categoria Componenti) nel form.Verrà visualizzato nell'area grigia nella parte inferiore di Progettazione Windows Form.

  3. Fare clic sull'icona timer1 appena aggiunta e impostare la proprietà Interval su 1000.Ciò fa in modo che l'evento Tick venga generato ogni secondo.Quindi, fare doppio clic sull'icona per aggiungere il gestore dell'evento Tick.Viene visualizzato l'editor di codice e si passa al nuovo metodo del gestore dell'evento.Aggiungere le istruzioni riportate di seguito.

    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;
        }
    }
    

    In base a ciò che si è aggiunto, ogni secondo il timer controlla se il tempo è scaduto controllando se l'int (Integer) timeLeft è maggiore di 0.Se lo è, rimane tempo.Il timer sottrae prima 1 da timeLeft, quindi aggiorna la proprietà Text del controllo timeLabel per mostrare all'utente quanti secondi sono rimasti.

    Se il tempo è esaurito, il timer si arresta e il testo del controllo timeLabel viene modificato in modo che venga visualizzato Tempo scaduto Viene visualizzata una finestra di messaggio che comunica all'utente che il quiz è terminato.La risposta viene rivelata, in questo caso aggiungendo addend1 e addend2.La proprietà Enabled del controllo startButton viene impostata su true, per rendere nuovamente disponibile il pulsante.In tal modo l'utente può iniziare nuovamente il quiz.

    Si è appena aggiunta un'istruzione if else, che rappresenta il modo in cui si comunica ai programmi di prendere decisioni.Di seguito è riportato un esempio di istruzione if else.

    If (something your program will check) Then
        ' statements that will get executed
        ' if the thing that the program checked is true 
    Else
        ' statements that will get executed
        ' if the thing that the program checked is NOT true
    End If
    
    if (something your program will check)
    {
        // statements that will get executed
        // if the thing that the program checked is true 
    }
    else
    {
        // statements that will get executed
        // if the thing that the program checked is NOT true
    }
    

    Esaminare attentamente l'istruzione che si è aggiunta al blocco else per visualizzare la risposta al problema di addizione.

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

    Come probabilmente si saprà, addend1 + addend2 esegue la somma dei due valori.La prima parte (sum.Value) utilizza la proprietà Value del controllo NumericUpDown per visualizzare la risposta corretta.La proprietà Value verrà utilizzata anche in un secondo momento per verificare le risposte al quiz.

    Un controllo NumericUpDown facilita l'immissione di numeri da parte degli utenti ed è per questo motivo che si utilizza il controllo per le risposte ai problemi matematici.Poiché tutte le risposte sono rappresentate da numeri da 0 a 100, si lasciano le proprietà predefinite Minimum e Maximum impostate su 0 e 100.Ciò fa in modo che il controllo consenta all'utente di immettere un numero da 0 a 100.Poiché le risposte possono essere solo numeri interi, si lascia la proprietà DecimalPlaces impostata su 0, che vuole dire che l'utente non può immettere numeri decimali.Se si desidera consentire all'utente di immettere 3,141 ma non 3,1415, è possibile impostare la proprietà DecimalPlaces su 3.

  4. Aggiungere tre righe alla fine del metodo StartTheQuiz(), in modo che il codice sia analogo al seguente.

    ''' <summary>
    ''' Start the quiz by filling in all of the problems
    ''' and starting the timer.
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub StartTheQuiz()
    
        ' Fill in the addition problem.
        addend1 = randomizer.Next(51)
        addend2 = randomizer.Next(51)
        plusLeftLabel.Text = addend1.ToString()
        plusRightLabel.Text = addend2.ToString()
        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 problems
    /// and starting the timer.
    /// </summary>
    public void StartTheQuiz()
    {
        // Fill in the addition problem.
        addend1 = randomizer.Next(51);
        addend2 = randomizer.Next(51);
        plusLeftLabel.Text = addend1.ToString();
        plusRightLabel.Text = addend2.ToString();
        sum.Value = 0;
    
        // Start the timer.
        timeLeft = 30;
        timeLabel.Text = "30 seconds"; 
        timer1.Start();
    }
    

    Ora, quando il quiz viene avviato, l'int (Integer) timeLeft viene impostato su 30 e la proprietà Text del controllo timeLabel viene modificata in 30 secondi.Viene quindi chiamato il metodo Start() del controllo Timer per avviare il conto alla rovescia.La risposta non viene ancora controllata. Ciò avverrà in seguito.

  5. Salvare ed eseguire il programma.Quando si fa clic sul pulsante Avvia, il timer inizia il conto alla rovescia.Quando il tempo è scaduto, il quiz termina e viene visualizzata la risposta.Nell'immagine seguente viene mostrato il quiz in corso.

    Quiz matematico in corso

    Quiz matematico in corso

Per continuare o rivedere l'esercitazione