#!/usr/bin/perl # http://perlmonks.org/?node_id=1170733 use strict; use warnings; my $sea = ((' ' x 10) . "\n") x 10; sub transpose { local $_ = $sea; tr/<>^v/^v<>/; $sea = ''; $sea .= "\n" while s/^(.)/ $sea .= $1; '' /gem; } for my $ship ( 4,3,3,2,2,2,1,1,1,1 ) { my @places; push @places, $-[0] while $sea =~ /(?= {$ship})/g; substr $sea, $places[rand @places], $ship, ('O', '<>', '<#>', '<##>' )[$ship - 1]; for (0, 9, 11, 0, 9, 11) { $sea =~ s/(?<=[<>^v#O].{$_}) | (?=.{$_}[<>^v#O])/~/gs; transpose; } rand > 0.5 and transpose; } tr/ /~/ for $sea; print $sea; my @chars = $sea =~ /./g; use Tk; # for http://perlmonks.org/?node_id=1170638 my $mw = MainWindow->new( -title => "Battleship" ); for my $y (0..9) { for my $x (0..9) { my ($char, $b) = shift @chars; $b = $mw->Button( -font => 'courier 24', -text => ' ', -command => sub {$b->configure(-text => $char) }, )->grid(-row => $y, -column => $x); } } MainLoop;