-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTimer.cpp
More file actions
81 lines (67 loc) · 1.98 KB
/
Timer.cpp
File metadata and controls
81 lines (67 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <SFML/Graphics.hpp>
int main() {
// Fullscreen Window //
sf::VideoMode vm(1920, 1080);
sf::RenderWindow window(vm, "Timer", sf::Style::Fullscreen);
// Text & Font
sf::Font timerFont;
sf::Text timerText;
timerFont.loadFromFile("fonts/ShipporiMincho-Regular.ttf");
timerText.setFont(timerFont);
timerText.setString("00:000");
timerText.setCharacterSize(300);
timerText.setFillColor(sf::Color::White);
// Text Position //
sf::FloatRect timerTextRect = timerText.getLocalBounds();
timerText.setOrigin(timerTextRect.left + timerTextRect.width / 2.0f, timerTextRect.top + timerTextRect.height / 2.0f);
timerText.setPosition(1920 / 2.0f, 1080 / 2.0f);
// Timer Variables //
sf::Clock clock;
float duration = 20.0f;
float fMilliseconds, fSeconds;
int intMilliseconds, intSeconds;
sf::String stringMilliseconds;
sf::String stringSeconds;
sf::String timerString;
while (window.isOpen()) {
// Handle Input //
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) {
window.close();
}
}
// (Re)start Timer //
sf::Time time = clock.restart();
// Timer Countdown //
if (duration > 0) {
// Calculate countdown
duration -= time.asSeconds();
fMilliseconds = std::modf(duration, &fSeconds);
// Change float to int
intSeconds = static_cast<int>(fSeconds);
intMilliseconds = static_cast<int>(fMilliseconds * 1000);
// Change int to string
stringMilliseconds = std::to_string(intMilliseconds);
stringSeconds =std::to_string(intSeconds);
if (intMilliseconds <= 0) {
stringMilliseconds = "000";
}
if (intSeconds <= 0) {
stringSeconds = "00";
}
else if (intSeconds < 10) {
stringSeconds = "0" + stringSeconds;
}
timerString = stringSeconds + ":" + stringMilliseconds;
timerText.setString(timerString);
}
window.clear();
window.draw(timerText);
window.display();
}
return 0;
}