************For matlab************** This is the turtle class classdef Turtle %T
ID: 3803364 • Letter: #
Question
************For matlab**************
This is the turtle class
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
end
methods
function obj = Turtle()
% make a new Turtle
obj.x = 0;
obj.y = 0;
obj.heading = 90;
obj.pen_on_paper = true;
end
function obj = forward(obj,distance)
% move forward in current heading given distancd
x2 = obj.x + distance*cosd(obj.heading);
y2 = obj.y + distance*sind(obj.heading);
if obj.pen_on_paper
% draw a line
hold on
l = line([obj.x x2],[obj.y y2]);
l.Color = 'black';
l.LineWidth = 1;
hold off
pause(0.1) % can you guess what this does?
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
end
end
Explanation / Answer
According to the question, modify your Turtle class to allow the user to change the pen color and pen width. The initial color is ‘black’, and the initial width is 1. Test your code by drawing rainbow concentric boxes.
As per assignment says: I will need to add two methods to the Turtle class: obj = penColor(obj,new_color) – changes the pen color obj = penWidth(obj,new_width) – changes the pen width, so using this function I have added both the object.
classdef Turtle
properties
% location of turtle
x
y
% 0 is E, 90 is N, 180 is W, 270 is S
heading
% pen status
pen_on_paper
% width of pen
pen_width
% color of pen
pen_color
end
methods
function obj = Turtle() %constructor
% make a new turtle
obj.x = 0;
obj.y = 0;
obj.heading = 90;
obj.pen_on_paper = true;
obj.pen_width = [];
obj.pen_color = [];
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 a line
hold on
l = line([obj.x x2],[obj.y y2]);
l.Color = penColor;
l.penColor([1,0,0])
l.LineWidth = penWidth;
l.LineWidth = 1;
hold off
pause (0.1)
end
% update location
obj.x = x2;
obj.y = y2;
end
function obj = penWidth(obj, new _width)
new_width = [1,2,3,4];
obj.pen_width = rand(new_width);
end
function obj = penColor(obj,new_color)
new_color = ['yellow','red','blue','green','black','orange','purple'];
obj.pen_color = rand(new_color);
end
end
end
As per the question I have added below drawing rainbow concentric boxes.
Here I have added the code as per the assignments, if any doubt related to the code I am happy to give your answer ,please let me know for any doubt, my mail id pratap_mishra@outlook.com.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.