73 lines
1.5 KiB
C++
73 lines
1.5 KiB
C++
#include "ScoreManager.h"
|
|
#include <fstream>
|
|
#include <iostream>
|
|
|
|
ScoreManager::ScoreManager(const std::string& filename) : highscoreFile(filename) {
|
|
loadHighscore();
|
|
}
|
|
|
|
void ScoreManager::loadHighscore() {
|
|
std::ifstream file(highscoreFile);
|
|
|
|
if (!file.is_open()) {
|
|
std::cout << "No highscore file found, creating new file.\n";
|
|
highScore = 9999;
|
|
bestTime = 99999.99;
|
|
return;
|
|
}
|
|
|
|
std::string key;
|
|
while (file >> key) {
|
|
if (key == "score") file >> highScore;
|
|
else if (key == "time") file >> bestTime;
|
|
}
|
|
|
|
file.close();
|
|
|
|
// If file contains useless values (like old format), reset
|
|
if (highScore <= 0 || highScore > 9999) highScore = 9999;
|
|
if (bestTime <= 0 || bestTime > 99999.99) bestTime = 99999.99;
|
|
}
|
|
|
|
|
|
void ScoreManager::incrementScore() {
|
|
currentScore++;
|
|
}
|
|
|
|
void ScoreManager::resetScore() {
|
|
currentScore = 0;
|
|
}
|
|
|
|
void ScoreManager::saveHighScore(int finalScore, double finalTime) {
|
|
bool updated = false;
|
|
|
|
if (finalScore < highScore) {
|
|
highScore = finalScore;
|
|
updated = true;
|
|
}
|
|
|
|
if (finalTime < bestTime) {
|
|
bestTime = finalTime;
|
|
updated = true;
|
|
}
|
|
|
|
// For safety: If file was default → always write
|
|
if (highScore == 9999 && bestTime == 99999.99)
|
|
updated = true;
|
|
|
|
if (!updated) return;
|
|
|
|
std::ofstream file(highscoreFile);
|
|
if (!file.is_open()) {
|
|
std::cerr << "❌ ERROR: Can't write highscore file\n";
|
|
return;
|
|
}
|
|
|
|
file << "score " << highScore << "\n";
|
|
file << "time " << bestTime << "\n";
|
|
file.close();
|
|
|
|
std::cout << "✅ Highscore updated!\n";
|
|
}
|
|
|