작은 걸음 II — 만들며 배우기
타이머의 값을 화면에 표시하기
타이머의 값을 화면에 표시하기
이번에 배울 것
콜백에서는 값을 바꾸고, 창의 반복문에서는 그 값을 읽어 그림을 그릴 수 있습니다.
실행해 보기
예제 · 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가 전역 seconds를 늘리고 draw_text가 현재 값을 표시합니다. format은 글자와 값을 이어 붙인 String을 돌려줍니다. print와 달리 직접 출력하지 않습니다.
Timer는 별도 계산 스레드가 아닙니다. show나 sleep이 이벤트를 처리할 때 콜백을 실행하므로 긴 계산은 호출을 늦출 수 있습니다. 정확한 시간 측정은 StopWatch로 하세요.
Exercise — 창의 제목 바꾸기
Timer callback이 1초마다 level을 1씩 증가시키게 하세요. Window loop에서는 현재 level을 set_title("Level ", level)로 제목에 표시하세요.
연습 문제 코드 · 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
callback에서는 전역 int level만 바꾸고, Window title은 main loop에서 갱신하면 간단합니다.
풀이 보기
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();
}