我想动画一个40x20的字符块,我cout
。我想用system("cls");
清除控制台,然后立即显示下一个字符块。目前,下一个街区将采用打字机式。
对我的问题最简单的回答就是一次得到20行40字符的oss stream cout,而不是做打字机风格。
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();
}
答案 0 :(得分:2)
您可以在代码中维护两个2D数组,一个用屏幕上的当前字符块(让我们称之为cur
),另一个用下一个块(让我们称之为next
)。
假设cur
存储了当前屏幕上的块。通过写入next
数组设置下一个块。当您准备好将其放在屏幕上时,请同时循环浏览cur
和next
,仅针对不同的字符,使用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.
}
答案 1 :(得分:0)
您可以使用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