控制台coutanimation – C ++

我想animation一个40×20的字符块,我正在计算。 我想用system("cls");清除控制台system("cls"); 然后在angular色的下一个块立即出现。 目前下一个街区是打字机风格。

对我的问题最简单的答案就是一次只能有一个20行,40个字符的ossstreamcout,而不是打字机的风格。

Main.cpp的:

  mazeCreator.cout(); Sleep(5000); system("cls"); 

COUT()

 void MazeCreator::cout() { char wallChar = (char) 219; char pavedChar = (char) 176; char lightChar = ' '; char startChar = 'S'; char finishChar = 'F'; char errorChar = '!'; char removedWallChar = 'R'; char landmarkLocationChar = 'L'; ostringstream oss; for (int row = 0; row < rows; row++) { oss << " "; for (int col = 0; col < columns; col++) { if (mazeArray[row][col] == wall) oss << wallChar; else if (mazeArray[row][col] == paved) oss << pavedChar; else if (mazeArray[row][col] == light) oss << lightChar; else if (mazeArray[row][col] == start) oss << startChar; else if (mazeArray[row][col] == finish) oss << finishChar; else if (mazeArray[row][col] == removedWall) oss << removedWallChar; else if (mazeArray[row][col] == landmarkLocation) oss << landmarkLocationChar; else oss << errorChar; } oss << "\n"; } oss << "\n\n"; cout << oss.str(); } 

你可以在你的代码中维护两个二维数组,一个是当前屏幕上的字符块(我们称之为cur ),另一个是下一个块(我们next调用它)。

假设cur存储在屏幕上的块。 通过写入next数组来设置下一个块。 当你准备好把它放在屏幕上时,同时循环curnext ,并且只对不同的字符 ,使用SetConsoleCursorPosition跳转到该位置并写入新的字符。

完成之后,将next内容复制到cur并移到下一个块。

更新 :这是一个例子:

 class console_buffer { public: console_buffer(int rows, int columns) // start out with spaces : cur(rows, vector<char>(columns, ' ')), next(rows, vector<char>(columns, ' ')) { } void sync() { // Loop over all positions for (int row = 0; row < cur.size(); ++row) for (int col = 0; col < cur[row].size(); ++col) // If the character at this position has changed if (cur[row][col] != next[row][col]) { // Move cursor to position COORD c = {row, col}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c); // Overwrite character cout.put(next[row][col]); } // 'next' is the new 'cur' cur = next; } void put(char c, int row, int col) { next[row][col] = c; } private: vector<vector<char> > cur; vector<vector<char> > next; }; ... int main() { console_buffer buf(40, 20); // set up first block ... some calls to buf.put() ... // make first block appear on screen buf.sync(); // set up next block ... some calls to buf.put() // make next block appear on screen buf.sync(); // etc. } 

您可以使用CreateConsoleScreenBuffer实现双缓冲。 沿着这些线应该工作。 一段时间以前我曾用过这个,所以可能不完美。

 HANDLE current = GetStdHandle (STD_OUTPUT_HANDLE); HANDLE buffer = CreateConsoleScreenBuffer ( GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL ); WriteConsole (/*fill with what you're drawing*/); system ("cls"); //clear this screen before swapping SetConsoleActiveScreenBuffer (buffer); WriteConsole (/*do it to the other one now*/); system ("cls"); SetConsoleActiveScreenBuffer (current); //swap again //repeat as needed CloseHandle (buffer); //clean up