Search code examples
c++tetris

How to draw blocks in Tetris with less code?


Is there a way to do the print "0" part with less code? I tried various things, but I just crazy random prints. If I try a for loop with a variable that lets the BlockX array move up every time it prints a "0" it just flips out. even if I cap that variable at 3.

TIA

Edit: BlockX and BlockY are coordinates of blocks. Coordinates are defined somewhere else.

void Draw()
{

system("cls");
for (int i = 0; i < height + 1; i++)
{
    for (int j = 0; j < width + 1; j++)
    {
        if (j == 10)
        {
            cout << "|";
        }
        if (j == width)
        {
            cout << "|";
        }
        else if ((j == BlockX[0] && i == BlockY[0]) || (j == BlockX[1] && i == BlockY[1]) || (j == BlockX[2] && i == BlockY[2]) || (j == BlockX[3] && i == BlockY[3]))
        {
            cout << "0";                            
        }
        else
        {       
            cout << " ";
        }               
    }
    cout << endl;
}

Solution

  • To expand on Tas' thought, you could write a function to check those coordinates like this.

    bool isBlockCoordinate(int i, int j)
    {
        return ((j == BlockX[0] && i == BlockY[0]) ||
                (j == BlockX[1] && i == BlockY[1]) ||
                (j == BlockX[2] && i == BlockY[2]) ||
                (j == BlockX[3] && i == BlockY[3]));
    }
    

    And you could invoke it within your loop like this:

        if (j == width)
        {
            cout << "|";
        }
        else if (isBlockCoordinate(i, j))
        {
            cout << "0";                            
        }
        else
        {       
            cout << " ";
        }