forked from Kojirion/Tracks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScore.cpp
More file actions
73 lines (61 loc) · 1.84 KB
/
Score.cpp
File metadata and controls
73 lines (61 loc) · 1.84 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
#include "Score.hpp"
#include <SFML/Graphics/RenderTarget.hpp>
#include <fstream>
#include <iostream>
#include <cmath>
#include "ResourcePath.hpp"
static std::string toTwoDigits(int s){
std::string toReturn;
if (s<10)
toReturn += "0";
toReturn += std::to_string(s);
return toReturn;
}
static std::string timeToString(float milliseconds){
int minutes = milliseconds/60000;
int seconds = (static_cast<int>(std::ceil(milliseconds))/1000)%60;
int centiseconds = (static_cast<int>(std::ceil(milliseconds))/10)%100;
std::string totalTime = toTwoDigits(minutes) + ":" +
toTwoDigits(seconds) + ":" +
toTwoDigits(centiseconds);
return totalTime;
}
Score::Score():
m_milliseconds(0.f),
m_bestTime(std::nanf(""))
{
m_font.loadFromFile(resourcePath() + "KBZipaDeeDooDah.ttf");
m_text.setFont(m_font);
std::ifstream bestTime(savePath() + "BestTime");
if (bestTime.good() && bestTime >> m_bestTime)
m_bestTimeString = "Best: " + timeToString(m_bestTime);
}
Score::~Score()
{
try {
if (!std::isnan(m_bestTime)){
std::ofstream bestTime(savePath() + "BestTime");
bestTime << m_bestTime;
}
}catch(const std::exception& e){
std::cerr << "Failed to record highscore: " << e.what() << '\n';
}
}
void Score::update(const sf::Time &time)
{
m_milliseconds += time.asMilliseconds();
auto toDisplay = "Current: " + timeToString(m_milliseconds) + "\n" + m_bestTimeString;
m_text.setString(toDisplay);
}
void Score::newSegment()
{
if (std::isnan(m_bestTime) || m_milliseconds < m_bestTime){
m_bestTime = m_milliseconds;
m_bestTimeString = "Best: " + timeToString(m_bestTime);
}
m_milliseconds = 0.f;
}
void Score::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(m_text);
}