I'm developing a game that has a word falling to the bottom of the screen and the user typing that word before it hits the bottom. So you'll be able to type input while the word is falling. Right now I have a timer that waits 5 seconds, prints the word, runs timer again, clears the screen, and prints the word down 10 units.
int main()
{
for (int i = 0; i < 6; i++)
{
movexy(x, y);
cout << "hello\n";
y = y + 10;
wordTimer();
}
}
Very basic I know. Which is why I thought multithreading would be a good idea so that way I could have the word falling while I still type input at the bottom. This is my attempt at that so far:
vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.push_back(std::thread(task1, "hello\n"));
threads.push_back(std::thread(wordTimer));
}
for (auto& thread : threads) {
thread.join();
}
However this only prints hello 4 times to the screen, then prints 55, then prints hello again, then counts-down 3 more times. So any advice on how to correctly do this? I've already done research. Just a few of the links I checked out that didn't help:
C++11 Multithreading: Display to console
Render Buffer on Screen in Windows
Threading console application in c++
Create new console from console app? C++
https://msdn.microsoft.com/en-us/library/975t8ks0.aspx?f=255&MSPPError=-2147217396
http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm
EDIT: Here is wordTimer()
int wordTimer()
{
_timeb start_time;
_timeb current_time;
_ftime_s(&start_time);
int i = 5;
for (; i > 0; i--)
{
cout << i << endl;
current_time = start_time;
while (elapsed_ms(&start_time, ¤t_time) < 1000)
{
_ftime_s(¤t_time);
}
start_time = current_time;
}
cout << " 5 seconds have passed." << endl;
return 0;
}
this is also necessary for wordTimer()
unsigned int elapsed_ms(_timeb* start, _timeb* end)
{
return (end->millitm - start->millitm) + 1000 * (end->time - start->time);
}
and task1
void task1(string msg)
{
movexy(x, y);
cout << msg;
y = y + 10;
}
and void movexy(int x, int y)
void movexy(int column, int line)
{
COORD coord;
coord.X = column;
coord.Y = line;
SetConsoleCursorPosition(
GetStdHandle(STD_OUTPUT_HANDLE),
coord
);
}