我试图在我的"画布中打印空间" (例如坐标(2,2))通过在控制台窗口中编辑由█块制作的80x20网格。
请首先建议我更好的方法来创建网格 (我刚刚学会了 - 每个循环)
为什么我在运行程序后会得到这3个字符?
为什么不在(2,2)区块上的空间,但显然是在中间某个位置的第一行?
代码:
#include <iostream>
int main()
{
uint8_t block {219}; // █
uint8_t space {32}; // ' '
uint8_t screen[80][20] {};
for (auto &row : screen) // make the "canvas"
for (auto &col : row)
col = block;
for (int row = 1; row <= 80; ++row)
{
for (int col = 1; col <= 20; ++col)
{
if (col == 2 && row == 2)
screen[row][col] = space;
}
}
std::cout << *screen;
return 0;
}
答案 0 :(得分:2)
一些问题:
for (int row = 0; row < 80; ++row)
。screen[2][2]=space
?由于您使用的是C ++,我可能会编写如下代码:
#include <iostream>
#include <vector>
class Screen {
public:
typedef uint8_t schar;
std::vector<schar> data; //Store data in a flat array: increases speed by improving caching
int width;
int height;
Screen(int width, int height, schar initchar){
this->width = width; //'this' refers to the current instantiation of this object
this->height = height;
data.resize(width*height,initchar); //Resize vector and set its values
}
schar& operator()(int x, int y){
return data[y*width+x];
}
void setAll(schar initchar){
std::fill(data.begin(),data.end(),initchar);
}
void print() const {
std::cout<<"\033[2J"; //ANSI command: clears the screen, moves cursor to upper left
for(int y=0;y<height;y++){
for(int x=0;x<width;x++)
std::cout<<data[y*width+x];
std::cout<<"\n"; //Much faster than std::endl
}
std::cout<<std::flush; //Needed to guarantee screen displays
}
};
int main(){
const int WIDTH = 80;
const int HEIGHT = 20;
uint8_t block {219}; // █
uint8_t space {32}; // ' '
Screen screen(WIDTH,HEIGHT,block);
screen(2,2) = space;
screen.print();
return 0;
}