How to integrate a Pen class into a Turtle
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I must create a Pen class which has properties color and width, and then use that in my Turtle3 class by using a setPen() method on it This is what I have so far:
1)My Pen Class
classdef Pen
properties
color
width
end
methods
function obj=Pen()
end
function obj=setColor(obj,newColor)
obj.color= newColor
end
function obj=setWidth(obj,newWidth)
obj.width= newWidth
end
end
end
2) My Turtle3 class
classdef Turtle3
%TURTLE Turtle with a pen
%Turtle with a pen
properties
%location of turtle
x
y
%0 is E, 90 is N, 180 is W, 270 is S
heading
%pen status
pen_on_paper
%pen
pen
end
methods
function obj=Turtle()
%make a new Turtle
obj.x=0;
obj.y=0;
obj.heading=90;
obj.pen_on_paper= true;
obj.pen = true;
obj.pen = true;
end
function obj=forward(obj,distance)
%move forward in current heading given distance
x2=obj.x+distance*cosd(obj.heading);
y2=obj.y+distance*sind(obj.heading);
if obj.pen_on_paper
%draw line
hold on
l= line([obj.x x2], [obj.y y2]);
l.Color='black';
l.LineWidth=1;
hold off
pause(0.1)
end
%update location
obj.x=x2;
obj.y=y2;
end
function obj = rotate(obj,angle)
% rotate CCW by given angle
obj.heading = mod(obj.heading + angle,360);
end
function obj = penUp(obj)
obj.pen_on_paper = false;
end
function obj = penDown(obj)
obj.pen_on_paper = true;
end
function obj = setPen(obj, s)
obj.pen= Pen();
end
end
end
I tried to run it using the following code:
thick_red = Pen();
thick_red = thick_red.setColor('red');
thick_red = thick_red.setWidth(5);
thin_blue = Pen();
thin_blue = thin_blue.setColor('blue');
thin_blue = thin_blue.setWidth(1);
turtle = Turtle3.setPen(thick_red);
The error that I am getting says "The class Turtle3 has no Constant property or Static method named 'setPen'.
Error in Triangle (line 16)
turtle = Turtle3.setPen(thick_red);"
Antworten (2)
Soma Ardhanareeswaran
am 21 Okt. 2016
'setPen' is a member function and not static. Invoke it using the object of the Turtle3 class.
2 Kommentare
David Davis
am 2 Mär. 2017
your setPen function is wrong. it Should look like this
function obj = setPen(obj,pen) obj.pen = pen; end
and then once you have done this you do what the person above says. You create a pen, establish its properties, create a turtle and then set the pen variable to be the turtles pen. Ex:
t = Turtle();
p = Pen();
red = p.setPen('red',2); % note I did both width and color in the same function
t.setPen(red);
Now your turtle will have a red pen.
0 Kommentare
Siehe auch
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!