Calling a Draw() function from multiple struct instances

  ascii, c++, game-development

I’m working on a console, ASCII game and I need the text output to display the player, enemies, and map. In order to make multiple enemies AND have them accessible, I stored the functions that change and read their values within an entity structure.

struct entity
{
    int hp, atk, x, y;
    bool isPlayer;
    void Draw();
    void Setup();
    void Input();
    void Logic();
};

and here is the Draw() function:

void entity::Draw()
{
    system("cls");  // Screen clear

    for (int i = 0; i < WIDTH; i++) // Top frame
        cout << "#";

    cout << endl;

    for (int i = 1; i < HEIGHT; i++)
    {
        for (int j = 0; j < WIDTH; j++)
        {
            if (j == 0 || j == WIDTH - 1)   // Middle frame
                cout << "#";

            else if (j == x && i == y)      // Player character display
            {
                if (isPlayer)
                    cout << "@";
                else                        // Enemy display
                    cout << "D";
            }
            else
                cout << " ";                // Empty space
        }
        cout << endl;
    }

    for (int i = 0; i < WIDTH; i++) // Bottom frame
        cout << "#";
}

The issue arises in execution, where Draw() and the other 3 functions are run in a while loop, with one for each entity instance.

int main()
{
    entity player = entity();
    player.isPlayer = true;
    player.Setup();

    entity dummy = entity();
    dummy.Setup();
    while (!gameOver)   // Main Game Loop
    {
        player.Draw();
        dummy.Draw();
        player.Input();
        player.Logic();
        dummy.Logic();
        Sleep(10);
    }
}

Since the dummy Draw() runs last, it overlaps the previous, effectively rendering the player invisible. This also slows the game down a lot by having to redraw the screen once for each entity.

Would there be a way to only have to call the function once? Or maybe there’s a deeper flaw?

And yes, I know system("cls") is a cardinal sin.

Source: Windows Questions C++

LEAVE A COMMENT