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

标签 c++ libtcod

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

假设我有一个颜色 vector 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 种颜色等。

我尝试为 vector 中的每种颜色执行 sprintf,将其添加到 out_string 并重复。我尝试用 ostringstream 做同样的事情。我尝试在 "%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++;
    }
}

我想我应该提到,我的代码有问题。每次通过 while 循环都需要计算第二个 print 语句中的 x 值,因为 x 作为 pos2 的函数而变化。否则,所有内容都会继续在同一个位置打印。 :) 应该是一个简单的改变......

关于c++ - 使用 Libtcod,如何控制台->打印具有动态颜色量的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23162382/

相关文章:

rust - 如果 `char` 不能容纳 >=256 的数字,我该如何使用 libTCOD 图形 block ?

c - libtcod - 移动功能不响应输入

c++ - 真的需要 constexpr 吗?

c++ - 在 C++ 中线程完成后将新任务分配给线程

c# - VB 中的 DLL 函数签名

python - 将变量分配给列表中的元组

C++:如何在函数中使用 %i?

C++ 异常访问冲突

c++ - 为什么我在 QtCreator 中收到 undefined reference 错误?