c++ - 生命游戏 - 打印板到相同位置

标签 c++

#include <iostream>
using namespace std;

int board[10][10] = {{0,1,0,0,0,1,1,0,0,0},
                     {0,0,0,0,0,1,1,1,0,0},
                     {0,0,1,0,0,1,0,1,0,1},
                     {0,1,0,0,0,1,1,0,0,0},
                     {0,0,0,0,0,0,0,0,0,0},
                     {0,1,0,0,0,1,1,0,0,0},
                     {0,0,0,0,0,1,1,1,0,0},
                     {0,0,1,0,0,1,0,1,0,1},
                     {0,1,0,0,0,1,1,0,0,0},
                     {0,0,0,0,0,0,0,0,0,0}};

void PrintBoard()
{
    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            if(board[i][j] == 1)
            {
                cout << '*';
            }
            else
            {
                cout << '-';
            }
        }
        cout << endl;
    }
}

int main()
{
    bool done = false;
    while(!done)
    {
        done = false;
        PrintBoard();
        int i = 0;
        i++;
        cout << i;
    }
}

我的问题是将电路板打印到控制台上的相同位置。通过这种方式,它可以在控制台上向下打印成一行的数百个板。我希望它现在是一个无限循环,因为当我让后代部分开始工作时,它将像您期望的程序那样流畅地移动。

最佳答案

如果您使用的是 Windows 终端,则显示 http://en.wikipedia.org/wiki/ANSI_escape_code#Windows_and_DOS 会有帮助。

char csi_esc = 27;
char csi_begin = '[';
// clear screen and reposition cursor
cout<<csi_esc<<csi_begin<< "2J]";

可以作为一个开始。 (未经测试,我无法访问 Windows 终端)。

糟糕,我读维基文章很差。

The Win32 console does not natively support ANSI escape sequences at all. Software such as ANSICON[7] can act as a wrapper around the standard Win32 console and add support for ANSI escape sequences. Otherwise software must manipulate the console with the ioctl-like Console API[8] interlaced with the text output. Some software internally interprets ANSI escape sequences in text being printed and translates them to these calls.[9]

因此,您应该使用常规的 WinAPI 调用。

#include<windows.h>

void PrintBoard(){
    // Position cursor at 0,0
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD coord;
    coord.X = coord.Y = 0;
    SetConsoleCursorPosition( console, coord );
    // Draw the rest of the stuff. 
}

参见 Using High Level Input and Output FunctionsAPI reference

如果您在基于 unix 的系统中的终端中,只需

#include<ncurses.h>

并链接库

g++ -o life life.cpp -lncurses

关于c++ - 生命游戏 - 打印板到相同位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24292357/

相关文章:

C++/QT - QFileDialog::getOpenFileName 过滤器 *.xml 禁用名称中包含日文字符的文件

c++ - 类成员和成员函数内存位置

android - 如何使用 perror() 但将提示输出到文件

c++ - Windows 和 Linux 之间的程序输出不同。为什么?

c++ - 为什么初始化列表中的自初始化引用不是错误?

c++ - 枚举类型作为soapcpp2中的返回值

c++ - OpenGL 深度不工作,三角形消失

c++ - mingw 5 std::this_thread 未定义

c++ - 具有不完全整数类型的结构和枚举

c++ - 为 OSI 第 2 层流量生成器寻找 OSS