gpt4 book ai didi

c++ - 创建一个可变方 block 大小的棋盘

转载 作者:行者123 更新时间:2023-11-27 23:57:07 24 4
gpt4 key购买 nike

我在 C++ 中有一个名为 Image 的类,其中我有一个宽度、高度和一个长 vector ,它以某种方式存储所有像素值,它迭代第一列,然后向下移动一行,迭代通过第二列等。(0 是黑色,255 是白色)

现在我已经编写了一个函数 void chess (),它以这样一种方式转换像素值,使其具有基本的国际象棋图案,当您把它发出来。

我的下一个想法是制作不同尺寸的棋盘,例如宽 8,高 8,棋盘的每个方格都是 2x2 像素而不是1x1

现在,如果我尝试实现它,我唯一的“想法”是使用 2 个计数器,一个用于跟踪它不是在每个像素之后,而是在新的像素大小之后从白色变为黑色。此外,你必须有第二个计数器来跟踪,在你必须反转多少行之后,所以你从黑色开始,而不是白色。

但我还是想不通,我最终得到了太多的 If 语句和 for 和 while 循环,结果总是一团糟。必须有一个明显更简单的方法。有人有什么想法吗?

class Image
{
public:
typedef uint16_t PixelType;

private:
int width_;
int height_;
std::vector<PixelType> data_;

public:
// Standardkonstruktor: initialisiere Bild mit Groesse (0,0)
Image()
: width_(0)
, height_(0)
{}

Image(unsigned int width, unsigned int height)
: width_(width)
, height_(height)
{
int size = width * height;

for(int j=0; j < height; j++)
{
for(int i=0; i < width; i++)
{
data_.push_back(0);
}
}
}

void chess() // change an image to chess board pattern
{
data_.clear();
int width = (*this).width();
int height = (*this).height();

for(int w=0; w < width; w++)
{
for(int h=1; h <= height; h++)
{
/*std::cout << "P=("+ std::to_string(w) + "," + std::to_string(h) + ")" << std::endl;
std::cout << std::to_string(h%2) <<std::endl;
for testing purposes only */
if(w%2==0)
{
if( !(h%2==0) )
{
data_.push_back(255);
}
else
{
data_.push_back(0);
}
}
else
{
if( !(h%2==0) )
{
data_.push_back(0);
} else
{
data_.push_back(255);
}

}
}
}
}
};

最佳答案

您可以尝试根据 w 和 h 的奇偶性为矩阵着色。如果 w+h 为黑色,否则为白色。 h 和 w 从 0 开始。

关于c++ - 创建一个可变方 block 大小的棋盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com