Dadex
Dadex

Reputation: 129

Is there a faster way to clear the Console?

I'm developing some simple 2D array-based games. Their main feature is a bouncing "ball" (simply a char ball_char='O') in a box. The structure BALL has 2 variables: X and Y which rapresent its array positions. Every clock (a Sleep(milliseconds)) a procedure changes its X and Y (for example +1), clears the console's window and then draws all the array again simulating the ball's movement.

Here's part of the code:

#include <iostream.h> //cout
#include <windows.h> //Sleep(ms) and clearscreen()

#define H 51
#define W 51
char box[H][W];

struct ball
{
      char ball_char;
      int x, y, movx, movy;
}b;

void clearscreen() //MY TEACHER SUGGESTED ME THIS CODE TO "CLEAR" THE SCREEN
{
    HANDLE hOut;
    COORD Position;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);                          

    Position.X = 0;
    Position.Y = 0;
    SetConsoleCursorPosition(hOut, Position);
}

void draw() //here comes the bad "graphic engine" lol
{   
    int i;
    clearscreen();
    for(i=0;i<H;i++)
    {
        for(int j=0;j<W;j++)
            cout<<box[i][j];
        cout<<"|"<<endl; //DRAWING EDGES <---this is on the right side
    }

    for(i=0;i<W;i++)
        cout<<"-"; //this is on the bottom side
}

As you can see, the larger the box, the longer it takes to draw the whole array again. As I commented, I mentioned this project to my professor which suggested me that code to clear the console. But it isn't a real cleaning but, as far I can see, it only places the cursor at the beginning.

Main code:

main()
{
    b.ball_char='O';
    b.x=10;
    b.y=0;
    b.movx=1;
    b.movy=1;

    do //this is what I call "the clock"
    {
        move() //my procedure to simulate the ball movements (it simply adds movements force to their coordinates with some controls etc.)
        draw();
        Sleep(100);
    }while(1);
}

So the question is: do you know any faster way to clean the console? I already know that system("cls") is to be avoided.

Upvotes: 2

Views: 4971

Answers (2)

Limtis
Limtis

Reputation: 115

Works really well:

#include <windows.h>

void clearscreen()
{
    HANDLE hOut;
    COORD Position;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    Position.X = 0;
    Position.Y = 0;
    SetConsoleCursorPosition(hOut, Position);
}

Upvotes: 2

Leopoldo Negro
Leopoldo Negro

Reputation: 46

Here you can check different methods for clearing the screen, I recommend writting multiple blank lines as an easy solution and probably enough for your application.

Upvotes: 0

Related Questions