我正在開發一款遊戲,它有一個字落在屏幕底部,用戶在觸及底部之前鍵入該字。所以你可以在單詞下降時輸入輸入。現在我有一個計時器,等待5秒鐘,打印單詞,再次運行計時器,清除屏幕,並打印10個單位的單詞。控制檯C++中的多線程定時器和I/O
int main()
{
for (int i = 0; i < 6; i++)
{
movexy(x, y);
cout << "hello\n";
y = y + 10;
wordTimer();
}
}
非常基本,我知道。這就是爲什麼我認爲多線程會是一個好主意,這樣我就可以讓這個詞下降,而我仍然在底部輸入輸入。這是我當時的嘗試至今:
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();
}
然而,這僅打印打招呼4倍到屏幕上,然後打印55,然後打印您好再次,然後計算下3次以上。那麼關於如何正確地做到這一點的任何建議?我已經完成了研究。短短几年我檢查了鏈接沒有幫助:
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
編輯: 這裏是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;
}
這也是必要的wordTimer()
unsigned int elapsed_ms(_timeb* start, _timeb* end)
{
return (end->millitm - start->millitm) + 1000 * (end->time - start->time);
}
和任務1
void task1(string msg)
{
movexy(x, y);
cout << msg;
y = y + 10;
}
和無效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
);
}
什麼是'task1'?那是'詞霸'?請張貼您的問題的代碼示例,我們可以自己編譯。 –
@Marinos_K對不起><任務1改變光標位置,並接受一個字符串,它將顯示,然後將10加到y單位。 WordTimer打印倒計時5秒 – user2073308
「這隻會在屏幕上打印4次問候,然後打印55,然後再次打印問候,然後倒計數3次。「 - 你期待它做什麼? – immibis