Create a Pen class and integrate it into Turtle

1 次查看(过去 30 天)
Give the Turtle a pen object to use. The Pen class should have properties color and width and methods Pen(), setColor(), setWidth().
Add a setPen() method to Turtle to handle changing the Turtle’s pen. You will also need to make small modifications to your other code to reflect the fact that the Turtle has a Pen object as a property.
You can now define Pens the Turtle can use.
For example:
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 = turtle.setPen(thick_red);
turtle = turtle.setPen(thin_blue);
This is what I have so far:
classdef Turtle
%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= Pen(color, width)
obj.pen= True
end
function obj= SetColor()
obj.pen= color
end
function obj= setWidth()
obj.pen = width
end
function obj = setPen(obj)
obj.pen= True
end
end
My code doesn't run, what should I do to give the color and width properties to my pen class?
end

回答(2 个)

Walter Roberson
Walter Roberson 2016-10-17
Why are you assigning to obj.pen multiple times, especially with different data types? Is obj.pen a color, a thickness, a logical value?
  2 个评论
Estefania Dimas Martinez
pen is an object used by the turtle and Pen should be a class with color and width properties
Walter Roberson
Walter Roberson 2016-10-18
You need to set the proper property of the object, not keep assigning to obj.pen
For example it might be obj.pen.color = color

请先登录,再进行评论。


David Davis
David Davis 2017-3-2
In your code you failed to make pen its own class. Pen should be an object like Turtle with its own properties.

类别

Help CenterFile Exchange 中查找有关 Assembly 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by