[英]2D arrays and Coordinates
I'm trying to just print space in my "canvas" ( with coordinates (2,2) for example) by editing my 80x20 grid made by █ blocks in the console window. 我试图通过在控制台窗口中编辑由█块组成的80x20网格,仅在“画布”中打印空间(例如,坐标为(2,2))。
Please suggest me better ways of creating the grid in the first place ( I've just learned for-each loops) 请首先建议我更好的创建网格的方法(我刚刚学习了for-each循环)
Why do I get those 3 characters after running the program ? 为什么在运行程序后得到这3个字符?
Why isn't the space on the (2,2) block but obviously on the first row somewhere in the mid ? 为什么(2,2)块上没有空格,但显然中间的第一行上没有空格?
Code : 代码:
#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;
}
Some issues: 一些问题:
for (int row = 0; row < 80; ++row)
. for (int row = 0; row < 80; ++row)
。 screen[2][2]=space
? screen[2][2]=space
呢? Since you're using C++, I'd probably write your code like this: 由于您使用的是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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.