Page 1 of 1

c# writing to the console help [SOLVED]

Posted: Fri Mar 16, 2012 2:24 am
by mattykins
So in a little console game i'm working on there is a draw board method that i use to draw all the tiles. it currently looks like this:

Code: Select all

 static public void boardWrite()
        {
            Console.Clear();
            
            for (int y = 0; y < 17; y++)
            {
                int i = 0;
                for (int x = 0; x < 80; x++)
                {
                    i++;
                    if (i < 80)
                    {
                        Console.Write(tiles[x, y]);
                    }
                    else
                    {
                        Console.Write("\n");
                        i = 0;
                    }
                }
            }

Each time the initial for loop iterates the second for loop iterates 80 times, or for each y value there are 80 x values making a 17 x 80 board of tiles. The glaring problem with this code is that it has to do 1,370 Console.Write's every time the board updates(which is everytime the player moves). My question is would there be a more efficient way to handle the writing of the board.

if it helps here is a link to where you can download the project, as of now the only thing that works is collision detection and movement(use WASD to move):
http://www.mediafire.com/?g4queiudjsrvaab

Re: c# writing to the console help

Posted: Fri Mar 16, 2012 4:08 am
by Jackolantern
Situations like this can be helped by the C# StringBuilder class. You could build up the string using StringBuilder in memory, and then output the whole constructed string at once, or maybe once for each line. Here is a tutorial about it as well. 8-)

Re: c# writing to the console help

Posted: Fri Mar 16, 2012 9:51 pm
by mattykins
That helped so much thanks! :)

The revised code looks like:

Code: Select all


        static public void boardWrite()
        {
            Console.Clear();
            board.Remove(0, board.Length);
            for (int y = 0; y < 17; y++)
            {
                int i = 0;
                for (int x = 0; x < 80; x++)
                {
                    i++;
                    if (i < 80)
                    {
                        board.Append(tiles[x, y]);
                    }
                    else
                    {
                        board.Append("\n");
                        i = 0;
                    }
                }
                
            }
            Console.Write(board);
        }
It is extremely smooth now there is no screen flashing or anything like that :)

Re: c# writing to the console help [SOLVED]

Posted: Fri Mar 16, 2012 11:59 pm
by Jackolantern
Awesome! Glad it helped out! :D