Create a Pen class and integrate it into Turtle

조회 수: 3 (최근 30일)
Estefania Dimas Martinez
Estefania Dimas Martinez 2016년 10월 17일
답변: David Davis 2017년 3월 2일
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
Estefania Dimas Martinez 2016년 10월 18일
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에서 App Building에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by