Create a Pen class and integrate it into Turtle
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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
0 comentarios
Respuestas (2)
Walter Roberson
el 17 de Oct. de 2016
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 comentarios
Walter Roberson
el 18 de Oct. de 2016
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
el 2 de Mzo. de 2017
In your code you failed to make pen its own class. Pen should be an object like Turtle with its own properties.
0 comentarios
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!