如何使用 gotoxy 函数代替 clrscr

how to use gotoxy function instead of clrscr

做第一个项目是俄罗斯方块; 现在我在做动画部分,但是清屏有问题,我试过了:

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

它工作了,但它一直在闪烁屏幕,有没有办法使用 gotoxy 函数而不是 clrscr 来达到同样的目的?

我在 visual studio 2008 年使用 windows 控制台系统 32。

system("cls") 执行 shell 命令来清除屏幕。这是非常低效的,而且绝对不适合游戏编程。

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

  • 如果你有一个函数gotoxy(),就可以一行接一行地打印很多空格。它不是超高性能,但它是一种方法。此 SO question 提供 gotoxy() 替代方案,因为它是一个非标准函数。

  • microsoft support recommendation provides a more performant alternative to clear the screen on Windows, using the winapi console functions例如GetConsoleScreenBufferInfo()FillConsoleOutputCharacter()SetConsoleCursorPosition()

编辑:

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

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

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
}

编辑 2:

此外,这里有两个可以与标准 cout 输出混合的光标定位函数:

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;
}