O'Reilly logo

Mastering Perl/Tk by Nancy Walsh, Stephen Lidie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

tkhanoi.ppl

This next PPL program is a classic Tower of Hanoi game.

#!/usr/local/bin/perl -w # # Towers of Hanoi, Perl/Tk style. 2000/06/14, sol0@Lehigh.EDU # Global package, subroutine and data declarations. use Tk; use Tk::Dialog; use subs qw/do_hanoi fini hanoi init move_ring/; use strict; my $canvas; # the Hanoi playing field my @colors; # 24 graduated ring colors my $fly_y; # canvas Y-coord along which rings fly my $max_rings; # be nice and keep @colors count-consistent my $num_moves; # total ring moves my %pole; # tracks pole X-coord and ring count my %ring; # tracks ring canvas ID, width and pole my $ring_base; # canvas Y-coord of base of ring pile my $ring_spacing; # pixels between adjacent rings my $stopped; # 1 IFF simulation is stopped my $velocity; # pixel delta the rings move while flying my $version = '1.0, 2000/06/14'; # Main. my $mw = MainWindow->new(-use => $Plugin::brinfo{xwindow_id}); init; MainLoop; sub do_hanoi { # Initialize for a new simulation. my($n) = @_; # number of rings return unless $stopped; $stopped = 0; # start ... $num_moves = 0; # ... new simulation my $ring_height = 26; $ring_spacing = 0.67 * $ring_height; my $ring_width = 96 + $n * 12; my $canvas_width = 3 * $ring_width + 4 * 12; my $canvas_height = $ring_spacing * $n + $fly_y + 2 * $ring_height; $ring_base = $canvas_height - 32; # Remove all rings from the previous run and resize the canvas. for (my $i = 0; $i < $max_rings; $i++) { $canvas->delete($ring{$i, 'id'}) if defined $ring{$i, 'id'}; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required