Implementation

We will focus only on those routines that either are central to the game or illustrate Tk in action.

The main program simply consists of the two calls to init() and MainLoop(). init creates the screen, sets up the key bindings, and configures a timer to call tick. Let us jump into the meat of the action by starting with this procedure.

tick moves the block down and then reloads the timer, specifying itself as a callback:

sub tick {
    return if ($state == $PAUSED);
    if (!@block_cells) {
        if (!create_random_block()) {
            game_over();           # Heap is full:could not place block
            return;                # at next tick interval
        }
        $w_top->after($interval, \&tick);
        return;
    }
    move_down();                      # move the block down
    $w_top->after($interval, \&tick); # reload timer for nex
}

fall() is called when the space bar is hit; it keeps moving the block down until it hits any tile in the heap or hits bottom. move_down returns a false when either of these happens.

sub fall {                 # Called when spacebar hit
    return if (!@block_cells);   # Return if not initialized
    1 while (move_down()); # Move down until it hits heap or bottom.
}

move_down() simply adds $MAX_COLS to each of the block tile’s cell positions to effectively move it one row down. It then checks whether any of these new positions touch the bottom of the grid or intersect with any preexisting heap tile’s cell position. If so, it calls the merge_block_and_heap routine and returns a false value. If not, it simply remembers the set of new positions and uses the move method to ...

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.