使用 Libtcod,如何控制台>打印具有动态颜色量的字符串?
Using Libtcod, how to console->print a string with a dynamic amount of colors?
我有一个助手函数,它接受一个字符串和一个颜色向量来格式化字符串,现在我的解决方案是手动检查颜色向量的大小,并使用相同数量的颜色调用控制台打印。
假设我有一个4的颜色向量,在代码中它会做一些类似的事情:
void helper_func(TCODConsole* con, std::string msg_str, std::vector<TCOD_colctrl_t> color_vector)
{
char* message = msg_str.c_str();
//this is repeated 1 through 16, adding another color_vector.at(n) for each.
...
else if (color_vector.size() == 2)
//message might be "%cHello%c was in red"
console->print(x, y, message, color_vector.at(0), color_vector.at(1))
...
else if (color_vector.size() == 4)
//message might be "%cThe octopus%c shimmers at %cnight%c"
console->print(x, y, message, color_vector.at(0), color_vector.at(1), color_vector.at(2), color_vector.at(3))
...
}
虽然这很有效,但它很糟糕,我正在寻找不同的方法来实现它,允许超过16种颜色,等等。
我试着为向量中的每种颜色做一个sprintf
,将其添加到out_string并重复。我试过用鸵鸟做同样的事。我尝试过在"%c"
上拆分msg_str,然后在为每个字符串添加颜色后加入结果字符串。它从来没有成功过,总是使用第一种颜色,然后使用随机字符,而不是从那时起的颜色。
我希望上面的任何一个都能工作,因为简单地sprintf(out_char, format_msg, TCOD_COLCTRL_1)
打印到控制台(使用console->print(out_char)
)就可以了。
我的问题是:有没有一种好的方法可以将不同数量的颜色传递到控制台->打印功能,并使其准确显示这些颜色,而不会出现严重的代码冗余
作为后备,我可以打印出字符串的一部分,直到第一种颜色,计算其大小,将x
移动那么多,然后打印下一部分,但这并不理想。
我想这个问题也可以推广到对具有替换的正则printf
提出同样的问题。
变量函数的一种可能的替代方案可能涉及解析"%c"的msg_str,并根据color_vector以正确的颜色迭代打印字符串的每个段。我不确定下面的代码是否会编译——我在记事本上写的,所以可能需要一些工作。希望你能领会我的建议。
void helper_func(TCODConsole* con, std::string msg_str, std::vector<TCOD_colctrl_t> color_vector)
{
std::string str2;
std::size_t pos;
std::size_t pos2;
pos = msg_str.find("%c");
if (pos != std::string::npos)
str2 = msg_str.substr(0,pos);
else
str2 = msg_str;
console->print(x, y, str2.c_str());
int n = 0;
while (pos != std::string::npos) {
pos2 = msg_str.find("%c",pos+1);
if (pos2 != std::string::npos)
str2 = msg_str.substr(pos+2,pos2);
else
str2 = msg_str.substr(pos2+2,msg_str.length()-pos2+2);
console->print(x, y, str2.c_str(),color_vector.at(n));
pos = pos2;
n++;
}
}
我想我应该提一下,我的代码中有一个问题。第二个打印语句中的x值每次都需要通过while循环计算,因为x是pos2的函数。否则,所有内容都将保持在同一位置打印。:)应该是一个简单的改变。。。
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 输出没有重复元素的动态数组(收缩数组)C++
- 如何在内核C++中使用1920x1080x16M图形或类似的16M颜色?(VGA)
- 如何在24位SDL_Surface上设置像素的颜色
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- C++中的动态对象与非动态对象
- 如何在动态数组上使用搜索函数
- glFrambufferTexture动态颜色附件
- 使用 Libtcod,如何控制台>打印具有动态颜色量的字符串?