Design

Let us look at the design of the user interface (specifically, our strategy for using the canvas widget effectively) and the data structures that record the state of the game and are not dependent on the user interface.

User Interface

Tetris’s screen layout, shown in Figure 15.1, is straightforward. You need two button widgets for “Start/Pause” and “Quit,” a canvas widget for the graphics, and a main window to contain all this stuff.

The grid and the blocks are drawn on the canvas. Each block is composed of several square tiles moving as one unit. The heap is a similar collection of tiles. Each tile is a canvas item. An alternative for drawing the block is a filled polygon, but the tiled version is much simpler to implement. The block’s tiles are tagged with the string “block,” so it is easy to move them around as one unit, using the canvas’s move method. We also remember each tile’s canvas item ID so that they can be individually deleted or moved.

One concern with animation is flicker when the monitor’s periodic refresh picks up changes to video memory as they are happening. To prevent flicker, you need to resort to double-buffering: first render the new animation frame into a pixmap and then copy that pixmap quickly into video memory. Fortunately, the canvas widget already does double-buffering, so we can simply move canvas items around without fear of flicker.

Data Structures

Both the block and the heap carry two pieces of information for each tile: its position on the grid ...

Get Advanced Perl Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.