Я использовал какой-то код из другого вопроса, чтобы заставить перенос слов влиять на целые слова, а не разбивать их.
Я хотел бы включить дополнительные строки, которые содержат форматирование, но я не смог выяснить это или найти что-нибудь на машине Google.
Смотрите код ниже.
using System;
using System.Collections.Generic;
/// <summary>
/// Writes the specified data, followed by the current line terminator,
/// to the standard output stream, while wrapping lines that would otherwise
/// break words.
/// </summary>
/// <param name="paragraph">The value to write.</param>
/// <param name="tabSize">The value that indicates the column width of tab
/// characters.</param>
public static void WordWrap(string paragraph, int tabSize = 8)
{
string[] lines = paragraph
.Replace("\t", new String(' ', tabSize))
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++) {
string process = lines[i];
List<String> wrapped = new List<string>();
while (process.Length > Console.WindowWidth) {
int wrapAt = process.LastIndexOf(' ', Math.Min(Console.WindowWidth - 1, process.Length));
if (wrapAt <= 0) break;
wrapped.Add(process.Substring(0, wrapAt));
process = process.Remove(0, wrapAt + 1);
}
foreach (string wrap in wrapped) {
Console.WriteLine(wrap);
}
Console.WriteLine(process);
}
}
Форматирование, которое я хотел бы использовать, - это просто изменение цвета для диалога, когда кто-то говорит, или для определенных ключевых слов (названий мест, предметов и имен персонажей и т.д.).
Смотрите код ниже.
public static void townName(string town)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Game.WordWrap(town);
Console.ResetColor();
}
public static void Dialog(string message)
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
Game.WordWrap(message);
Console.ResetColor();
}
public static void Villain()
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Game.WordWrap("Zanbar Bone");
Console.ResetColor();
}
Любая помощь очень ценится, будь осторожен со мной, хотя я все еще учусь. Обыкновенные термины были бы очень полезны :)
Итак, мы собираемся писать построчно по мере необходимости для цвета, а затем заканчивать абзацы вручную.
//keep track of the end width right here
static int endWidth = 0;
public static void WordWrap(string paragraph, int tabSize = 8)
{
//were only doing one bit at a time
string process = paragraph;
List<String> wrapped = new List<string>();
//if were going to pass the end
while (process.Length + endWidth > Console.WindowWidth)
{
//reduce the wrapping in the first line by the ending with
int wrapAt = process.LastIndexOf(' ', Math.Min(Console.WindowWidth - 1 - endWidth, process.Length));
//if there no space
if (wrapAt == -1)
{
//if the next bit won't take up the whole next line
if (process.Length < Console.WindowWidth - 1)
{
//this will give us a new line
wrapped.Add("");
//reset the width
endWidth = 0;
//stop looping
break;
}
else
{
//otherwise just wrap the max possible
wrapAt = Console.WindowWidth - 1 - endWidth;
}
}
//add the next string as normal
wrapped.Add(process.Substring(0, wrapAt));
//shorten the process string
process = process.Remove(0, wrapAt + 1);
//now reset that to zero for any other line in this group
endWidth = 0;
}
//write a line for each wrapped line
foreach (string wrap in wrapped)
{
Console.WriteLine(wrap);
}
//don't write line, just write. You can add a new line later if you need it,
//but if you do, reset endWidth to zero
Console.Write(process);
//endWidth will now be the lenght of the last line.
//if this didn't go to another line, you need to add the old endWidth
endWidth = process.Length + endWidth;
}
//use this to end a paragraph
static void EndParagraph()
{
Console.WriteLine();
endWidth = 0;
}
Вот пример использования этого:
Console.BackgroundColor = ConsoleColor.Blue;
WordWrap("First Line. ");
Console.BackgroundColor = ConsoleColor.Red;
WordWrap("This is a much longer line. There are many lines like it but this one is my line "+
"which is a very long line that wraps.");
EndParagraph();
WordWrap("Next Paragraph");
Вы видите, что мы пишем линию, меняем цвет, пишем еще одну строку. Мы должны заканчивать абзацы вручную, а не как часть текстового блока.
Существуют и другие стратегии, но эта позволяет использовать большую часть вашего кода.