Small Steps II — Making Things

Displaying a timer's value

Display a timer's value on the screen.

What you will learn

A callback can change a value while the window loop reads that value and draws it.

Try it

Example · example2.cpp
int seconds = 0;

void on_second()
{
    seconds = seconds + 1;
}

void small_main()
{
    Window window;
    window.open(500, 250);

    Timer timer;
    timer.start(1.0, on_second);

    while (window.is_open())
    {
        window.clear(Black);
        window.draw_text(30, 80, format("Seconds: ", seconds), White, 28);
        window.show();
    }

    timer.stop();
}

on_second increases the global seconds, and draw_text displays its current value. format returns a String joining text and values. Unlike print, it does not produce output itself.

Timer is not a separate computation thread. Callbacks run when show or sleep processes events, so a long calculation may delay them. Use StopWatch for accurate elapsed-time measurement.

Exercise

Have a Timer callback increase level by 1 each second. In the Window loop, show the current level in the title with set_title("Level ", level).

Exercise starter · exercise2_starter.cpp
int level = 1;

void on_second()
{
    // Increase level.
}

void small_main()
{
    Window window;
    window.open(500, 300);

    Timer timer;
    timer.start(1.0, on_second);

    while (window.is_open())
    {
        // show level in the title.
        window.clear(Black);
        window.show();
    }

    timer.stop();
}

Hint

Change only the global int level in the callback and update the Window title in the main loop.

show solution
int level = 1;

void on_second()
{
    level = level + 1;
}

void small_main()
{
    Window window;
    window.open(500, 300);

    Timer timer;
    timer.start(1.0, on_second);

    while (window.is_open())
    {
        window.set_title("Level ", level);
        window.clear(Black);
        window.show();
    }

    timer.stop();
}
← Previous lessonNext lesson →