diff --git a/ranklist.cpp b/ranklist.cpp new file mode 100644 index 0000000..ba40806 --- /dev/null +++ b/ranklist.cpp @@ -0,0 +1,134 @@ +#include "RankList.h" +#include +#include +#include +#include +#include +#include +RankList::RankList() +{ + if (!this->m_msg.empty()) + { + this->m_msg.clear(); + } + + ReadFile(); +} + +void RankList::SaveMsg(PlayerMsg msg) +{ + WriteTime(msg); //写入时间 + + m_msg.push_back(msg); + std::sort(m_msg.begin(), m_msg.end(), SortPlayerMsg()); + + if (m_msg.size() > this->MAX_RANK) + { + m_msg.pop_back(); + } + + std::vector::iterator it = m_msg.begin(); + + //修改id + for (int i = 0; i < m_msg.size(); i++, it++) + { + it->id = i + 1; + } +} + +std::vector RankList::getRankList() +{ + return this->m_msg; +} + +void RankList::SaveToRank() +{ + WriteFile(); +} + +void RankList::WriteTime(PlayerMsg& msg) +{ + std::time_t now; + std::tm ltm; + + // 获取当前时间 + std::time(&now); + + // 使用localtime_s安全地将当前时间转换为本地时间 + localtime_s(<m, &now); + + std::stringstream sstream; + + // 输出 tm 结构的各个组成部分 + sstream << ltm.tm_year + 1900 << "-"; // 年 + sstream << ((ltm.tm_mon + 1 >= 10) ? "" : "0") << ltm.tm_mon + 1 << "-"; // 月 + sstream << ((ltm.tm_mday >= 10) ? "" : "0") << ltm.tm_mday << "_"; // 日 + sstream << ((ltm.tm_hour >= 10) ? "" : "0") << ltm.tm_hour << ":"; // 时 + sstream << ((ltm.tm_min >= 10) ? "" : "0") << ltm.tm_min; // 分 + + msg.r_time = sstream.str(); +} + +void RankList::ReadFile() +{ + std::ifstream infile; + + infile.open(m_rankfile, std::ios::in | std::ios::binary); + + if (!infile) + { + //如果文件不存在,则创建 + std::ofstream os; + os.open(m_rankfile); //默认会创建 + + if (!os) + { + //如果创建失败,只能结束程序 + exit(0); + } + + os.close(); + } + else + { + std::string line; + std::stringstream stream; + int index = 0; + PlayerMsg msg; + + while (std::getline(infile, line)) + { + stream.clear(); + stream.str(line); + + stream >> msg.id >> msg.score >> msg.len >> msg.r_time; + + m_msg.push_back(msg); + + index++; + } + + std::sort(m_msg.begin(), m_msg.end(), SortPlayerMsg()); + } + + infile.close(); +} + +void RankList::WriteFile() +{ + std::ofstream outfile; + outfile.open(m_rankfile, std::ios::out | std::ios::binary); //每次写文件都重新写一遍 + + if (!outfile) + { + return; + } + + for (int i = 0; i < m_msg.size(); ++i) + { + outfile << m_msg[i].id << " " << m_msg[i].score << " " << m_msg[i].len + << " " << m_msg[i].r_time << std::endl; + } + + outfile.close(); +} \ No newline at end of file