什么是存储颜色的好方法?

Kri*_*iso 2 c++ colors

我开始制作"生命游戏",我想,如果我的状态可以超过1或0,那该怎么办?

但后来我需要不同的颜色.我希望颜色链接到网格/对象(网格是一个类).

什么是一种优质/体面的方式来存储彩色托盘以便快速/轻松访问?

我目前不太理想的解决方案是每个红色,绿色,蓝色和alpha值有4个内存指针.

在我的课上,我有一个函数将值的颜色设置v为rgba:

SetColor(v, r, g, b, a) //Set v to the appropriate color values
Run Code Online (Sandbox Code Playgroud)

我想保持此功能以轻松修改颜色.

Gui*_*cot 6

我使用的是非常简单的东西:4个漂浮物

struct Color {
    float r, g, b, a;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以拥有类似彩色托盘的东西:

// a Palette of 8 colors:
using palette_t = std::array<Color, 8>

palette_t myPalette { /* ... */ };
Run Code Online (Sandbox Code Playgroud)

然后,在您的网格或对象类中,您可以使用索引引用颜色:

struct Grid {
    // lot's of code

private:
    std::size_t colorIndex = 0;
};
Run Code Online (Sandbox Code Playgroud)

但后来你问如何轻松访问颜色(我想这是从Grid课堂上轻松访问)

有很多解决方案可以存在,而且大多数都取决于您的项目结构.这是其他许多想法.我希望它会激励你.

您可以存储返回正确颜色的函数:

struct Grid {
    // lot's of code

private:
    std::size_t colorIndex = 0;
    std::function<Color(std::size_t)> color;
};
Run Code Online (Sandbox Code Playgroud)

然后,有一些能够正确创建网格的东西:

struct GridCreator {
    GridCreator(const palette_t& aPalette) : palette{aPalette} {}

    Grid create(std::size_t color) const {
        Grid grid;

        // create the grid

        grid.color = [this](std::size_t index) {
            return palette[index];
        };

        return grid;
    }

private:
    const palette_t& palette;
};
Run Code Online (Sandbox Code Playgroud)

然后,您可以自由访问您的调色板,而无需直接知道Grid该类中的调色板.