Console Screen Buffer

If you plan on making any console based games with the screen refreshing constantly you will find it flickers a lot unless you use what is known as a buffer. Here I show you a class that has a couple of functions to draw to, and then output the "image" to the console.

public class ScreenBuffer
    //initiate important variables
    public static char[,] screenBufferArray = new char[roomWidth,roomHeight]; //main buffer array
    public static string screenBuffer; //buffer as string (used when drawing)
    public static Char[] arr; //temporary array for drawing string
    public static int i = 0; //keeps track of the place in the array to draw to
    //this method takes a string, and a pair of coordinates and writes it to the buffer
    public static void Draw(string text, int x, int y)
        //split text into array
        arr = text.ToCharArray(0,text.Length);
        //iterate through the array, adding values to buffer 
        i = 0;
        foreach (char c in arr)
            screenBufferArray[x + i,y] = c;
    public static void DrawScreen()
        screenBuffer = "";
        //iterate through buffer, adding each value to screenBuffer
        for (int iy = 0; iy < roomHeight-1; iy++)
            for (int ix = 0; ix < roomWidth; ix++)
                screenBuffer += screenBufferArray[ix, iy];
    //set cursor position to top left and draw the string
        Console.SetCursorPosition(0, 0);
        screenBufferArray = new char[Game.roomWidth, Game.roomHeight];
    //note that the screen is NOT cleared at any point as this will simply overwrite the existing values on screen. Clearing will cause flickering again.

roomWidth and roomHeight are the width and height of your console screen respectively. This can easily be set using



Usage is very simple with this class. First of all you'll need to create the class by using

ScreenBuffer sb = new ScreenBuffer();

This simply create an instance of the ScreenBuffer class with the reference "sb" (you can change this to whatever you want).

To draw to it all you need to do is use the method Draw.

ScreenBuffer.Draw("text here",x,y);

Beware that this method will not handle new lines correctly. This could be easily added by using a check within the draw function, and if it detects \n simply jump the the next line in the array.

Now all you need to do is call the DrawScreen method at the end of the frame you are displaying and the array will be flushed onto the console screen, giving you a flicker free game!

~ knighty (Graeme Pollard - moc.liamg|33thgink#moc.liamg|33thgink)

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.