如何使用gotoxy函数而不是clrscr

时间:2015-04-18 18:59:31

标签: c++ windows console tetris cls

做第一个项目及它的俄罗斯方块; 现在我正在制作动画部分,但我在清除屏幕方面遇到了问题,我已经尝试过:

void clrscr() 
{ 
  system("cls"); 
}

虽然有效,但屏幕一直闪烁,有没有办法使用gotoxy功能而不是clrscr用于同一目的?

我在visual studio 2008上使用Windows控制台系统32。

1 个答案:

答案 0 :(得分:3)

system("cls")执行shell命令以清除屏幕。这是非常有效的,并且绝对不适用于游戏编程。

不幸的是,屏幕I / O取决于系统。当你提到“cls”而不是“clear”时,我猜你正在使用windows console:

  • 如果您有一个函数gotoxy(),则可以在另一行上定位并打印大量空格。它不是超高性能,但它是一种方法。此SO question提供gotoxy()个替代品,因为它是非标准功能。

  • 使用GetConsoleScreenBufferInfo(),例如FillConsoleOutputCharacter()SetConsoleCursorPosition()void console_clear_region (int x, int y, int dx, int dy, char clearwith = ' ') { HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE); // get console handle CONSOLE_SCREEN_BUFFER_INFO csbi; // screen buffer information DWORD chars_written; // count successful output GetConsoleScreenBufferInfo(hc, &csbi); // Get screen info & size GetConsoleScreenBufferInfo(hc, &csbi); // Get current text display attributes if (x + dx > csbi.dwSize.X) // verify maximum width and height dx = csbi.dwSize.X - x; // and adjust if necessary if (y + dy > csbi.dwSize.Y) dy = csbi.dwSize.Y - y; for (int j = 0; j < dy; j++) { // loop for the lines COORD cursor = { x, y+j }; // start filling // Fill the line part with a char (blank by default) FillConsoleOutputCharacter(hc, TCHAR(clearwith), dx, cursor, &chars_written); // Change text attributes accordingly FillConsoleOutputAttribute(hc, csbi.wAttributes, dx, cursor, &chars_written); } COORD cursor = { x, y }; SetConsoleCursorPosition(hc, cursor); // set new cursor position } ,这个microsoft support recommendation提供了更高效的清除Windows屏幕的替代方法。 。

修改

我知道您使用基于字符的输出,因为您编写的是控制台应用程序,而不是功能齐全的win32图形应用程序。

然后,您可以通过仅清除控制台的一部分来调整上面提供的代码:

void console_gotoxy(int x, int y)
{
    HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE);  // get console handle 
    COORD cursor = { x, y };
    SetConsoleCursorPosition(hc, cursor);  // set new cursor position
}

void console_getxy(int& x, int& y)
{
    HANDLE hc = GetStdHandle(STD_OUTPUT_HANDLE);  // get console handle 
    CONSOLE_SCREEN_BUFFER_INFO csbi;        // screen buffer information
    GetConsoleScreenBufferInfo(hc, &csbi);      // Get screen info & size 
    x = csbi.dwCursorPosition.X;
    y = csbi.dwCursorPosition.Y;
}  

编辑2:

另外,这里有两个cusor定位功能,可以与标准cout输出混合使用:

{{1}}