Leser: 17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
package Polygon; sub new { bless [@_[1..$#_]], ref $_[0] || $_[0] } sub contains { my( $poly, $x, $y ) = @_; my $wn = 0; my( $x1, $y1 ) = @{ $poly->[-1] }; my( $x2, $y2 ) = @{ $poly->[ 0] }; my $start_over = $y1 >= $y; for ( 1 .. $#{ $poly } ) { my $end_over = $y2 >= $y; if ( $start_over != $end_over ) { if ( ($y2 - $y)*($x2 - $x1) <= ($y2 - $y1)*($x2 - $x) ) { $wn++ if $end_over; } else { $wn-- unless $end_over; } } # if $start_over = $end_over; ( $x1, $y1 ) = ( $x2, $y2 ); ( $x2, $y2 ) = @{ $poly->[$_] }; } # for return $wn != 0; # edit: war vorher $wn == 0, was natürlich falsch ist ;) } # contains
1 2 3 4 5
my $polygon = Polygon->new( [5,5], [5,20], [20,20], [20,5], [5,5] ); # edit . durch , ersetzt if ( $polygon->contains(10,10) ) { # 10,10 liegt im Polygon 5,5; 5,20; 20,20; 20,5; 5,5 } # if