使用 Libtcod,如何控制台>打印具有动态颜色量的字符串?

Using Libtcod, how to console->print a string with a dynamic amount of colors?

本文关键字:动态 颜色 字符串 打印 Libtcod 控制台 gt 使用      更新时间:2023-10-16

我有一个助手函数,它接受一个字符串和一个颜色向量来格式化字符串,现在我的解决方案是手动检查颜色向量的大小,并使用相同数量的颜色调用控制台打印。

假设我有一个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循环计算,因为xpos2的函数。否则,所有内容都将保持在同一位置打印。:)应该是一个简单的改变。。。