养成游戏——时间的获取与保存

时间是养成游戏比较重要的部分,像coc的金币、圣水、暗黑重油都是基于离线上线的时间差来确定的,所以简单讲一下c/c++如何获取时间

获取当前时间

1.localtime方法

#include<time.h>

using namespace std;

int main()
{
    time_t now_time = time(NULL);

    time_t time_seconds = time(NULL);
    struct tm nowtime;
    localtime_s(&nowtime, &time_seconds);

    printf("%d-%d-%d %d:%d:%d\n", nowtime.tm_year + 1900, nowtime.tm_mon + 1,
        nowtime.tm_mday, nowtime.tm_hour, nowtime.tm_min, nowtime.tm_sec);
    system("pause");
    return 0;
}

输出结果:2018-5-29 14:24:58

2.time_t方法

#include<iostream>
#include<stdlib.h>
#include<fstream>
#include<time.h>
#include<string>

using namespace std;

int main()
{
    string s;
    time_t now_time ;
    ifstream fin;
    ofstream fout;
    fout.open("data.txt");//以写入打开文件
    for (int i = 0; i < 10; i++)//写入10次
    {
        fout << time(&now_time) << endl;
        Sleep(1000);
    }
    fin.open("data.txt");
    while (getline(fin, s)) {
        cout << s.c_str() << endl;
    }
    system("pause");
    return 0;
}

输出结果:
1527579584
1527579585
1527579586
1527579587
1527579588
1527579589
1527579590
1527579591
1527579592
1527579593

在养成游戏中,数据是很重要的,所以要用文件或数据库来保存数据。如果新手制作的游戏数据不多且简单可以省点事用txt记录,时间充足可以学习如何用sqlite3数据库记录。
c++ sqlite3的使用参考https://www.cnblogs.com/KillerAery/p/9114124.html

猜你喜欢

转载自blog.csdn.net/qq_39169598/article/details/80355612
今日推荐