Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which class has the responsibility of setting Piece's pixels on a Board(2d matrix)? The Piece or the Board?

Tags:

java

c#

oop

So, I currently have a Board class that is composed of Pieces. Each Piece has a color and a string that describes the kind of piece. It also has a 2d matrix with bits either set on or off, that allows me to know which pixels to paint with the desired color or not.

My question is, which class should have the responsability to draw the pieces on the board? On one hand, I'd say the Piece class should do it. But to do it, I'd have to pass a Board as reference to Piece's Draw() method and although it's not terrible I find it kinda awkward. This raises the problem that Piece would have "to know" the Board class.

On the other hand, I could just have the Piece have a

Boolean[,] IsPixelSet(int x, int y)

and Board would then have a method of the form:

void DrawPieceOnBoard() {
    for (int y = 0; y < height; ++y) {
        for (int x = 0; x < width; ++x) {
            if (piece.IsPixelSet(x, y) {
                board.DrawPixelAt(x, y, piece.GetColor());
            }
        }
    }
}

How would you do it? And why? I can't see a clear winner in any of these approaches.

Thanks

edit

I'm not talking about actually drawing things on screen. What happens is that I'm implementing a Tetris game (currently, no GUI) and I need at every moment to set the Pixels of a Square on different positions on the board as it falls to the ground. The board basically only has an accessor and a mutator for each one of the (x, y) points. Let's now say I want to draw a Square(a type of Piece) on the Board. Should the Piece know of the board and its Draw() method make the changes to the Board, or should the Board access Piece's getter method and do it itself?

like image 703
devoured elysium Avatar asked Jul 28 '10 10:07

devoured elysium


3 Answers

FWIW, in general MVC theory, neither class should draw itself. Presentation would be a concern of a separate view.

like image 192
StuartLC Avatar answered Nov 20 '22 15:11

StuartLC


I'd say the Piece draws. For example, your function does not allow to enhance the Piece to allow them to have several colors.

The Piece does not have to know all the Board, just some method (maybe part of an interface) Draw(x,y,color).

like image 22
pascal Avatar answered Nov 20 '22 15:11

pascal


In my opinion the Piece should draw the piece and the Board should draw the board.

I would have something like this:

class Piece 
{
    Image Render(Rectangle bounds) { /*  */ }
}

class Board
{
    void Render(Graphics g)
    {
        //Draw the base

        foreach (piece in Pieces)
        {
            var rect = figureOutPosition(); //Positioning logic to 
            g.DrawImage(location, rect, piece.Render(rect));
        }

        //Draw any overlays

    }
}
like image 1
Pondidum Avatar answered Nov 20 '22 13:11

Pondidum