I would like to make “engine” for my console application that will count the time passed and force the application to do time-based event when certain amount of time has passed. I think about creating a simple text-based strategy game for education purposes (not for homework, just for me).
I tried to create the engine but I didn’t go too far. I do not know how can I apply time-based events break currently pending action in application etc, first here is how I made it:
#include <stdio.h>
#include <conio.h>
#include <Windows.h>
void _sleep(int t);
int main()
{
int seconds_passed = 0; //counts how much time passed since application started
while(1)
{
//if(seconds_passed == 100) ... time based action
_sleep(1000);
printf("test");
seconds_passed += 1;
}
return 0;
}
void _sleep(int t)
{
int i;
for (i = 0; i < (t/100); i++)
{
Sleep(100);
if (kbhit()!= 0)
{
getch();
break;
}
}
}
I tried to make function similar to Sleep() from windows.h, but with ability to break the delay when key is pressed (I don’t know if im going the correct way) – in loop it will start “time passing”, but I want it to be independent of the rest of the code, so it will work silently and take control over action in rest of the code. I need help in any of following things:
-using keyboard to break _sleep() function shouldn’t automatically increase amount of “seconds passed”
-how to make timer independent of action happening in the code? I thought about creating something that could break the whole while(1) loop every second (probably it could be my modified _sleep function), increase counter and go back to the code part where it broke (it would abuse scanf() actions in application but it isnt a problem for now)
-I heard about select() function that maybe could be useful here, anybody has any experience with it and can tell me more?
Don’t know if this is a usable answer but when I built a rudimetary game I made it multi threaded in this way:
queue when the user does something.
the screen and then sleeps for a certain amount of time.
In this way the event thread could remain blocked until user input occurred while game logic and input/output was done in a simple synchronized way.
Windows has a threading library you can use (although I haven”t used that one yet as I always use boost threads or posix threads on linux.)