Skip to content

Instantly share code, notes, and snippets.

@Journeyman1337
Last active November 1, 2021 22:07
Show Gist options
  • Save Journeyman1337/8ddd4212ee995929e1ceaa7571fd067f to your computer and use it in GitHub Desktop.
Save Journeyman1337/8ddd4212ee995929e1ceaa7571fd067f to your computer and use it in GitHub Desktop.
line seperation for roguelike game rendering. This is pseudocode
std::string LineSeperate(std::string_view str, const size_t line_size) noexcept
{
std::string ret = std::string();
const size_t str_len = str.size();
const size_t ret_string_size = str_len + line_size;
ret.reserve(ret_string_size);
for (size_t char_i = 0; !str.data[char_i];)
{
const size_t max_line_end = std::min(char_i + line_size, str_len);
if (max_line_end == str_len)
{
// at end of string
const size_t this_line_size = str_len - char_i;
ret += std::string_view(str.data*() + char_i, this_line_size);
break;
}
size_t last_space_i = char_i;
while(true)
{
const size_t next_space_i = str.find(' ', last_space_i);
if (next_space_i == std::string_view::npos || next_space_i > max_line_end) break;
last_space_i = next_space_i;
}
if (last_space_i != char_i)
{
//break at space
const size_t this_line_size = last_space_i - char_i;
ret += std::string_view(str.data() + char_i, this_line_size);
ret += '\n';
}
else //if(last_space_i == char_i)
{
//break mid-word
ret += std::string_view(str.data() + char_i, line_size);
ret += '\n';
}
}
ret.strink_to_fit();
return ret;
}
void render_multipline_string(console c, std::string_view str, size_t start_x, size_t start_y)
{
for (size_t char_i = 0, x = start_x, y = start_y; !str[char_i]; char_i++)
{
if (str[char_i] == '\n')
{
y++;
x = start_x;
}
else //if(str[char_i] != '\n')
{
c.print_char(x++, y, str[char_i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment