Contents:
Introduction to Tetris
Design
Implementation
- Is this a game of chance?
- Not the way I play it, no.
- W.C. Fields
Writing a game is the best ways to test your understanding of GUI programming, because it covers three important user interface areas: forms, structured graphics, and animation. In this chapter, we build the popular game of Tetris and reward ourselves with hours of unproductive fun afterward. These are the specific bits of Tk knowledge that we will exercise in this chapter:
Using canvas tags to efficiently move or delete groups of canvas items.
Using the timer to control pieces of animation: moving the blocks and shooting them. (Yes, we will add a cheesy arcade style shooting of the blocks too!)
Using pack effectively for form layout. This chapter just has two buttons and a canvas widget, so this is a very minor exercise.
It is estimated (or commonly quoted, at least) that most applications with a user interface devote around 70% of their code in GUI-specific details. In this chapter, you'll see how Tk reduces the burden to, say, a 30% effort, even in an application as GUI-intensive as a game.
Tetris hit the PC world in 1985 when its creators, Alexey Paszhitnov, Dmitry Pavlovsky, and Vadim Gerasimov, ported the game to the IBM PC. Shortly thereafter, Nintendo converted it into a huge success by implementing it on their Gameboy line of hand-held computer games. The continued availability of the line at a time when Nintendo is marketing 64-bit systems is a testimony to the game's appeal.
If you have never played the game, I suggest you play it a few times to get a feel for it.[ 1 ] In each iteration, a block[ 2 ] falls down from the top (ticking along one row at a time), and finally merges with the heap at the bottom (see Figure 15.1 ). At this point, Tetris collapses any row (of the heap) that has become full; that is, it deletes that row and moves all the heap rows above it one row down. Then the next iteration starts, this time possibly with a differently shaped block. The object of the game is to keep the heap from piling up all the way to the top. To do this, you can move the block to the left and right (using the keys "j" and "l") and rotate it (using "k") as it falls such that you can get the rows to fill up and collapse frequently. If you press the spacebar, the block falls down to the heap instantly (instead of gradually ticking along) and is merged with the heap.
[1] The complete code is available as tetris.pl at the O'Reilly FTP site.
[2] Consisting of four tiles, hence the name of the game.
Copyright © 2001 O'Reilly & Associates. All rights reserved.