Im doing a game in C on console application and I need to print a timer while the user play the game at the same time, I don’t know how to program that well, actually I just start using this compiler so I don’t know a lot of multithreads and stuff but this is the far as I get, here is an example of two functions the first one is the “timer” and the second its just some question, my doubt is if I can run these 2 functions at the same time, and how I can print the timer while I can answer those 2 question without interrupting the console.
EXAMPLE:
#include <windows.h>
#include <stdio.h>
#include <time.h>
DWORD WINAPI Timer(int limit)
{
int secs = 1;
time_t unix;
struct tm * timeinfo;
time(&unix);
timeinfo = localtime(&unix);
int t1 = timeinfo->tm_sec;
int t2 = timeinfo->tm_sec;
int i = 0;
while(1 == 1)
{
time(&unix);
timeinfo = localtime(&unix);
if((t1 + i) == timeinfo->tm_sec)
{
system("cls");
printf("time left %d seconds\n", timeinfo->tm_sec - t2 - limit);
i++;
}
if(timeinfo->tm_sec >= (t1 + limit))
{
break;
printf("Your time its done");
}
}
return 0;
}
DWORD WINAPI Questionary()
{
puts("testing\n\n");
int age, height;
printf("Please write your age: ");
scanf("%d", &age);
printf("Please write your height: ");
scanf("%d", &height);
printf("\n\nThe numbers written are %d y %d", age, height);
return NULL;
}
int main()
{
int i, limit;
HANDLE tempo;
HANDLE questions;
DWORD ThreadId;
printf("\nHow much time would you like for your timer countdown? ");
scanf("%d", &limit);
//Funcion Handle
questions= CreateThread(NULL,0,Questionary,1,0,&ThreadId);
WaitForSingleObject(preguntas,INFINITE);
tempo= CreateThread(NULL,0,Timer(limit),1,0,&ThreadId);
WaitForSingleObject(tiempofinal,limit*40);
return 0;
}
You can print the question, and instead of waiting for an answer in a blocking call (like
scanf) you loop while polling for new input, and use ANSI escape codes to print the time at another position.Something like the following pseudo-code: