「C++小游戏教程」计时器

本章主要讲解如何自制一个用于倒计时的计时器。
前置芝士:

对于每个初学 C++ 的读者,必定都计算过时分秒。
那为了倒计时时的可读性,我们这边将输入的秒数转换为 hh:mm:ss 的形式。

puts("I am Timer. Please tell me your time (seconds): ");
int n;
scanf("%d",&n);
int rsth=n/3600,rstm=n/60%60,rsts=n%60;

利用 Sleep() 进行倒数 3 s 3\text s 3 s,这里不再赘述方法。
开始时,便用 system("cls"); 清空屏幕开始计时。

puts("OK. Are you ready?");
for(int i=3;i;i--)
{
    Sleep(1000);
    cout<<i<<endl;
}
system("cls");
puts("Start!");

外面一个循环——当 r s t h , r s t m , r s t s rsth,rstm,rsts r s t h ,r s t m ,r s t s 中有至少一个非零,则继续倒计时(废话。
将变量减少时,可以模拟一下,类似六十进制,不足零就向前面一个借 1 1 1 当 60 60 6 0。
然后输出,接着再等待 1 s 1\text s 1 s,清空,再执行。

while(rsth||rstm||rsts)
{
    if(!rsts)
    {
        rsts=59;
        if(!rstm) rstm=59,rsth--;
        else rstm--;
    }
    else rsts--;
    printf("%02d:%02d:%02d",rsth,rstm,rsts);
    Sleep(1000);
    system("cls");
}

为了防止用户走神,我们在输出提示后使用 Beep() 以提示。

puts("Time over!");
Beep(1000,1000);
Beep(1000,1000);
Beep(1000,1000);

示例代码:

#include
#include
using namespace std;

int main()
{
    puts("I am Timer. Please tell me your time (seconds): ");
    int n;
    scanf("%d",&n);
    int rsth=n/3600,rstm=n/60%60,rsts=n%60;
    puts("OK. Are you ready?");
    for(int i=3;i;i--)
    {
        Sleep(1000);
        cout<<i<<endl;
    }
    system("cls");
    puts("Start!");
    while(rsth||rstm||rsts)
    {
        if(!rsts)
        {
            rsts=59;
            if(!rstm) rstm=59,rsth--;
            else rstm--;
        }
        else rsts--;
        printf("%02d:%02d:%02d",rsth,rstm,rsts);
        Sleep(1000);
        system("cls");
    }
    puts("Time over!");
    Beep(1000,1000);
    Beep(1000,1000);
    Beep(1000,1000);
    return 0;
}

这样,一个简易的计时器便做好了,相信读者收获的许多。
最后,感谢大家的支持!

Original: https://blog.csdn.net/Leo_Chenjy/article/details/127819878
Author: JYqwq
Title: 「C++小游戏教程」计时器

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/658334/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球