-
Notifications
You must be signed in to change notification settings - Fork 34
/
Turtle.pm
80 lines (62 loc) · 1.91 KB
/
Turtle.pm
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package Turtle {
use 5.010;
use strict;
use warnings;
# Written by [email protected], adapted by John Cristy.
# Later adopted and improved by Daniel "Trizen" Șuteu.
sub new {
my $class = shift;
my %opt;
@opt{qw(x y theta mirror)} = @_;
# Create the main image
my $im = Image::Magick->new(size => $opt{x} . 'x' . $opt{y});
$im->ReadImage('canvas:white');
$opt{im} = $im;
bless \%opt, $class;
}
sub forward {
my ($self, $r, $opt) = @_;
my ($newx, $newy) = ($self->{x} + $r * sin($self->{theta}), $self->{y} + $r * -cos($self->{theta}));
$self->draw(
primitive => 'line',
points => join(' ',
$self->{x} * $opt->{scale} + $opt->{xoff},
$self->{y} * $opt->{scale} + $opt->{yoff},
$newx * $opt->{scale} + $opt->{xoff},
$newy * $opt->{scale} + $opt->{yoff},
),
stroke => $opt->{color},
strokewidth => 1
);
($self->{x}, $self->{y}) = ($newx, $newy); # change the old coords
}
sub draw {
my ($self, %opt) = @_;
$self->{im}->Draw(%opt);
}
sub composite {
my ($self, %opt) = @_;
$self->{im}->Composite(%opt);
}
sub save_as {
my ($self, $filename) = @_;
$self->{im}->Write($filename);
}
sub turn {
my ($self, $dtheta) = @_;
$self->{theta} += $dtheta * $self->{mirror};
}
sub state {
my ($self) = @_;
@{$self}{qw(x y theta mirror)};
}
sub setstate {
my $self = shift;
@{$self}{qw(x y theta mirror)} = @_;
}
sub mirror {
my ($self) = @_;
$self->{mirror} *= -1;
}
}
1;