I’ve written a fair few articles on using console apps, especially for the purpose of writing games. This post, for example, is the start of a series on creating a snake game using a C# console app.
Disclaimer: this post is largely just bringing together the information listed at the bottom of this article into a single place. I take no credit for the code herein (with the exception of the rectangle itself).
One thing that used to be common knowledge, back when I wrote games and apps in Turbo Pascal and C, was that you could use the extended character set in order to create a rudimentary set of graphics. In this post, I’m going to cover my re-discovery of those characters. We’ll draw a rectangle in a console app.
Back in the Borland days, the way to add these to your program was to hold Alt-Gr and then type the ASCII code. In .Net Framework, these were, broadly, included; however, in .Net Core+, you need to add a NuGet package:
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" />
Once you’ve done this, you need the following magic line to allow you to actually use the code pages:
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Before we get into using this, let’s see what’s available. Firstly, this is how you would list the code pages:
var encs = CodePagesEncodingProvider.Instance.GetEncodings();
foreach (var enc in encs.OrderBy(a => a.Name))
{
Console.WriteLine($"{enc.Name} {enc.CodePage}");
}
The specific code page that we’re interested in is IBM437:
Encoding cp437 = Encoding.GetEncoding("IBM437");
byte[] source = new byte[1];
for (byte i = 0x20; i < 0xFE; i++)
{
source[0] = i;
Console.WriteLine($"{i}, {cp437.GetString(source)}");
}
We can display a single character like this:
Console.WriteLine($"{cp437.GetString(new byte[1] { 217 })}");
Okay, so we now have all the tools, it’s just assembling them in the right order:
Console.Write($"{cp437.GetString(new byte[1] { 218 })}");
for (int i = 1; i < 20; i++)
{
Console.Write($"{cp437.GetString(new byte[1] { 196 })}");
}
Console.WriteLine($"{cp437.GetString(new byte[1] { 191 })}");
for (int i = 1; i < 5; i++)
{
Console.Write($"{cp437.GetString(new byte[1] { 179 })}");
Console.Write(new String(' ', 19));
Console.WriteLine($"{cp437.GetString(new byte[1] { 179 })}");
}
Console.Write($"{cp437.GetString(new byte[1] { 192 })}");
for (int i = 1; i < 20; i++)
{
Console.Write($"{cp437.GetString(new byte[1] { 196 })}");
}
Console.WriteLine($"{cp437.GetString(new byte[1] { 217 })}");
References
https://stackoverflow.com/questions/58439415/visual-studio-2019-dont-recognize-ascii-characters
https://stackoverflow.com/questions/17619279/extended-ascii-in-c-sharp