制作了一个猜数字的小程序,我想要用循环和sleep(1000)增加一个倒计时的功能 这个功能是输入一个单位位秒的时间 然后进行倒计时,倒计时结束后游戏自动停止
但是发现按游戏进程和倒计时进程无法同时进行
所以这个该怎么改
下面是我的写的小游戏进程代码
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int n=0;
int num = rand() % 100 + 1; //生成1-100随机数
cout << "please input a number (1-100):";
while (n != num)
{
cin >> n;
if (n > num)
{
cout << "too big" << endl;
}
else if(n<num)
{
cout << "to small" << endl;
}
}
cout<<"the number is "<<num<<endl;
system("pause");
return 0;
}
下面是没有使用线程来同步监控时间的办法(采用线程来监控时间,因为while循环因为要获取输入后才判断时间,所以时间误差度和不使用线程应该也差不多,但可能也有更好的实现,个人理解),仅在while循环前和获取输入和判断结果后简单统计使用时间来判断游戏时间是否没有超过指定时间,所以时间判断上稍有出入。
参考链接:
C++计时器(用于计算算法运行时间等)_KiraFenvy的博客-CSDN博客_c++计时器
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
//https://blog.csdn.net/m0_51371693/article/details/121589590
srand((unsigned int)time(NULL));
clock_t begin, end;
double usetime ;
int n=0;
int num = rand() % 100 + 1; //生成1-100随机数
cout << "please input a number (1-100):";
begin = clock();
while (n != num&&usetime<=10) //如果没有猜正数字以及游戏时间没有超过10秒
{
cin >> n;
if (n > num)
{
cout << "too big" << endl;
}
else if(n<num)
{
cout << "to small" << endl;
}
end = clock();
usetime = double(end - begin) / CLOCKS_PER_SEC ;
cout<<"game use "<<usetime<<" seconds, time left "<<10-usetime<<" seconds."<<endl;
}
cout<<"the number is "<<num<<endl;
system("pause");
return 0;
}