package Minesweeper; use strict; use warnings; use Exporter qw; our @EXPORT_OK = qw; sub annotate { my ($minefield) = @_; my @heatmap; # array storing our final answer # check for no rows return $minefield if @{ $minefield } == 0; # check for no columns return $minefield if $minefield->[0] eq ""; # read in minefield spaces and mines into array # append an extra column with 'X' at the end my @field = map { [split ( //, $_ ), 'X'] } @{ $minefield }; my $columns = @{ $field[0] } - 1; # subtract extra column we added my $rows = @field; # add an extra row of 'X' to the end push @field => [ ('X') x ($columns + 1) ]; # need that extra column back # go through the minefield, first by rows then columns foreach my $row (0 .. $rows - 1) { my $row_buildup = ""; # this represents each row we add to @heatmap foreach my $column (0 .. $columns - 1) { my $mine_count; if ( $field[$row][$column] eq '*' ) { $mine_count = '*'; # replace mine with mine } else { # count number of mines in the 8 adjacent spaces, including diagonally foreach my $offset ([ 0, -1], [ 0, 1], [-1, 0], [ 1, 0], [-1, -1], [-1, 1], [ 1, -1], [ 1, 1]) { if ( $field[$row + $offset->[0]][$column + $offset->[1]] eq '*' ) { $mine_count++; } } # end foreach my $offset # if count is greater than zero, insert the count # otherwise, we just insert a space $mine_count = $mine_count ? $mine_count : ' '; } # end else $row_buildup .= $mine_count; } # end foreach my $column push @heatmap => $row_buildup; # add the row to our answer } # end foreach my $row return \@heatmap; } 1;