Skip to main content
Engineering LibreTexts

8.35: Drawing a Piece on the Board or Elsewhere on the Screen

  • Page ID
  • def drawPiece(piece, pixelx=None, pixely=None):
        shapeToDraw = PIECES[piece['shape']][piece['rotation']]
        if pixelx == None and pixely == None:
            # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure
            pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])
        # draw each of the boxes that make up the piece
        for x in range(TEMPLATEWIDTH):
            for y in range(TEMPLATEHEIGHT):
                if shapeToDraw[y][x] != BLANK:
                    drawBox(None, None, piece['color'], pixelx + (x * BOXSIZE), pixely + (y * BOXSIZE))

    The drawPiece() function will draw the boxes of a piece according to the piece data structure that is passed to it. This function will be used to draw the falling piece and the "Next" piece. Since the piece data structure will contain all of the shape, position, rotation, and color information, nothing else besides the piece data structure needs to be passed to the function.

    However, the "Next" piece is not drawn on the board. In this case, we ignore the position information stored inside the piece data structure and instead let the caller of the drawPiece() function pass in arguments for the optional pixelx and pixely parameters to specify where exactly on the window the piece should be drawn.

    If no pixelx and pixely arguments are passed in, then lines 3 [484] and 5 [486] will overwrite those variables with the return values of convertToPixelCoords() call.

    The nested for loops on line 8 [489] and 9 [490] will then call drawBox() for each box of the piece that needs to be drawn.