Hi! I'm new here.
I'm reading a book about C++ so I'm quite new to the language.
An exercise asks to write a simple "Turtle Graphics" program.
This program should be able to simulates very simple graphics thanks to the following commands:
Command Meaning
1 - Pen up
2 - Pen down
3 - Turn right
4 - Turn left
5 , n - Move forward n spaces
6 - Print 20-by-20 array
9 - End of data (sentinel)
Now, before I post my code, my questions:
- is the code clear? I'm not very happy about the two switch I use to decide the command and the direction (in the move function).
- I wasn't able to implement the fifth command in one line, I mean you have to write 5, ENTER and than the N. The exercise asks to do it in one line. How can I achieve that?
Thank you for any suggestion and please don't be gentle: I want to learn :)
My code:
#include <iostream>
using namespace std;
void printMap(void);
void printCommands(void);
void move(int);
const int END = 9;
const int commands[7] = { 0, 1, 2, 3, 4, 5, 6 };
int map[20][20] = { 0 };
bool penDown = false;
int x = 0;
int y = 0;
int dir = 0; // 0 = N, 1 = E, 2 = S, 3 = O
int main() {
cout << "Welcome to the Turtle Graphics! Here's the list of commmands:" << endl;
printCommands();
int command;
int args;
cout << "Enter a command: ";
cin >> command;
if (command == 5) cin >> args;
while (command != END) {
switch (command) {
// print commands
case 0:
printCommands();
break;
// set the pen down
case 1:
if (penDown) penDown = false;
else cout << "The pen is already up." << endl;
break;
// pen up
case 2:
if (!penDown) penDown = true;
else cout << "The pen is already down." << endl;
break;
// turn right
case 4:
dir = (dir + 1) % 4;
cout << "The new direction is " << dir << endl;
break;
// turn left
case 3:
dir -= 1;
if (dir < 0) dir = 3;
cout << "The new direction is " << dir << endl;
break;
// move forward
case 5:
cout << "Moving forward by " << args << endl;
move(args);
break;
// show the map
case 6:
printMap();
break;
}
cout << "Enter a command (0 to show commands): ";
cin >> command;
if (command == 5) cin >> args;
}
cout << "Bye bye!" << endl;
return 0;
}
void move(int steps) {
while (steps-- > 0) {
switch (dir) {
// N
case 0:
if (y > 0) y--;
break;
// E
case 1:
if (x < 20) x++;
break;
// S
case 2:
if (y < 19) y++;
break;
// O
case 3:
if (x > 0) x--;
break;
}
if (penDown) map[y][x] = 1;
}
}
void printMap() {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (x == j && y == i) cout << "X";
else if (map[i][j] == 0) cout << " ";
else cout << "*";
}
cout << endl;
}
}
void printCommands() {
cout << "0 - Show the commands available\n"
<< "1 - Turn up the pen\n"
<< "2 - Turn down the pen\n"
<< "3 - Turn left\n"
<< "4 - Turn right\n"
<< "5, n - Move therd of n tiles\n"
<< "6 - Show the drawing\n"
<< "9 - Exit program" << endl;
}