首页 > 解决方案 > 当我的代码在linux上运行时如何每秒显示一个计时器

问题描述

我正在开发一个简单的游戏,您可以在其中猜测 0 到 100 之间的随机数。您有 7 秒和 6 次尝试猜测它,但我想在游戏运行时显示倒数计时器。(00:07 00:06 00:05......00:00) 我尝试使用gotoxy函数在侧面显示计时器,但显示一团糟,因为gotoxy在调用后将光标放在下一行。或者也许我没有正确使用它。

有没有办法显示时间(以秒为单位)而不会显示混乱?

这是我的尝试:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>

/*void gotoxy(int x, int y){
    printf("%c[%d;%df",0x1b,y,x);
}*/

void timer();
int c=6;

void main ()
{
    system("clear");
    int  a, num=200;

    signal(SIGALRM,timer);

    srand(time(NULL));
    a=rand()%101;
    int i=1;

    printf("try to guess a number between 0 and 100 in 7 seconds , you have only 6 tries \n\t good luck\n");
    alarm(1);
    //gotoxy(50,2);
    printf("00:07\n");

    while ((a != num)&&(i<=7)) { 

        if (i==7) printf("no more tries !!!! \n");
        else printf("try: %d  \n ",i);

        printf("give a number  \n ");
        scanf("%d",&num);
        if (a>num) 
        printf("it's more ! \n ");
        else if (a<num) 
        printf("it's less ! \n ");
        else  
        printf("\t\tGreat ! you won !!! \n ");
i++;

    }

}

void timer(){
    if(c<0){
    printf ("you lost \n");
    exit(1);
    }
    else{ 
    //gotoxy(50,2);    
    printf("00:0%d\n",c);
    c--;
    alarm(1);
    }
}

标签: clinux

解决方案


推荐阅读