Text Wrapping C# Console Game

Started by
1 comment, last by DennisterBeest 12 years, 1 month ago
Hi there, im working on my game called 'AI.You' which is all text based, right now though I think im going to need some text wrapping since it looks silly breaking the middle of words etc like it does right now.

The code I have so far for the text wrapping method is:


private static void textWrapper(string line)
{
//Split the string into an array.
string[] sentances = line.Split('\n');
//Wordwrap each sentance that is longer than the window width at the space before the last word on that line.
foreach(string sentance in sentances)
{
if (sentance.Length > Console.WindowWidth)
{
}
}
}


What I want to do next is check where the last space ' ' happens and then create a new line there. It would then however need to check the rest of the line to make sure it hasn't done the same thing again and this is why I'm confused I don't really know how to set this up.

Any help would be great (simple where possible as im just starting out ;P)
Advertisement
Are you drawing your text with a spritefont?
sentence.length gives the length of the sentence in characters, not in pixels.
so if you are using a spritefont you can use the spriteFont.MeasureString(sentence) to give you the actual pixel length of the sentence

When you know the pixel length you can iterate through the individual words of the line until the length of the first line is smaller than the width of the Console. You can simply place the words in a seperate string. Rinse and repeat as they say, until you have a series of strings that are all shorter than the length of the console window
did some playing around and got this working, i know it is not the most elegant way, but it works. it's up to you to make it pretty :)



private string[] DoWordWrap(string input, SpriteFont f)
{
string[] words = input.Split(new char[] { ' ' });
float strLen = f.MeasureString(input).X;
string[] result = new string[(int)(strLen / Window.ClientBounds.Width) + 1];
int count = 0;
int currentLine = 0;
float lineLen = 0;
float wordLen = f.MeasureString(words[0]).X;
while (count < words.Length)
{
while (lineLen < Window.ClientBounds.Width - wordLen && count < words.Length)
{
result[currentLine] += words[count] + " ";
count++;
if (count < words.Length)
{
wordLen = f.MeasureString(words[count]).X;
lineLen = f.MeasureString(result[currentLine]).X;
}
}
lineLen = 0;
result[currentLine] = result[currentLine].TrimEnd();
currentLine++;
}

return result;
}

This topic is closed to new replies.

Advertisement