I want to create this function:
void drawSquare(int x) {
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
}
However, I get that the identifier "tortuga" is undefined.
I tried to modify the function like this:
void drawSquare(int x) {
ct::TurtleScreen scr;
scr.bgcolor({ "white" });
ct::Turtle tortuga(scr);
Home(tortuga);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.pencolor({ "red" });
tortuga.speed(ct::TS_FASTEST);
scr.exitonclick();
}
I get that the identifier "tortuga" is defined now, which seems to work.However, 20ish windows appeared where in each window, the turtle only drew three sides of a square like the following image: image I expected a spiral to be drawn.
Here is all the program:
#include"CTurtle.hpp"
#include <iostream>
using namespace std;
#define Home(x) x.left(90)
namespace ct = cturtle;
int shellSize;
int initialShellSize;
void drawSquare(int x) {
ct::TurtleScreen scr;
scr.bgcolor({ "white" });
ct::Turtle tortuga(scr);
Home(tortuga);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.pencolor({ "red" });
tortuga.speed(ct::TS_FASTEST);
scr.exitonclick();
}
int main(int argc, char** argv) {
std::cout << "Type the size of the outershell of the spiral: "; // Type a number and press enter
std::cin >> shellSize; // Get user input from the keyboard
initialShellSize = shellSize;
for (int i = 10; i <= initialShellSize; i = i 10)
{
shellSize = initialShellSize - (initialShellSize/i);
drawSquare(shellSize);
}
return 0;
}
CodePudding user response:
I've never used this library before, but it seems all you need to do is add a turtle parameter to your function and pass the turtle object to the function. This is not dissimilar to what you've already done with the x
parameter. Parameter passing is a basic technique of the C language (and pretty much any programming language).
void drawSquare(ct::Turtle& tortuga, int x) {
Home(tortuga);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
tortuga.right(90);
tortuga.forward(x);
}
int main(int argc, char** argv) {
std::cout << "Type the size of the outershell of the spiral: "; // Type a number and press enter
std::cin >> shellSize; // Get user input from the keyboard
initialShellSize = shellSize;
ct::TurtleScreen scr;
scr.bgcolor({ "white" });
ct::Turtle tortuga(scr);
for (int i = 10; i <= initialShellSize; i = i 10)
{
shellSize = initialShellSize - (initialShellSize/i);
drawSquare(tortuga, shellSize);
}
return 0;
}
I've used a reference ct::Turtle& tortuga
instead of ct::Turtle tortuga
. I'm guessing that is right, but as I said I've never used this library before.
And as already mentioned to get a square I'm guessing you need to call forward
four times.
I've also put the call to Home
inside the function, you might disagree.