Simulation of Robot Motion Gaming Project in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
#include <iostream> // Class to represent a robot class Robot { public: Robot(int x = 0, int y = 0) : x(x), y(y) {} // Move the robot based on the given direction void move(char direction) { switch (direction) { case 'U': // Move up y++; break; case 'D': // Move down y--; break; case 'L': // Move left x--; break; case 'R': // Move right x++; break; default: std::cout << "Invalid direction! Use 'U', 'D', 'L', or 'R'.\n"; } } // Print the current position of the robot void printPosition() const { std::cout << "Robot position: (" << x << ", " << y << ")\n"; } private: int x, y; // Coordinates of the robot }; int main() { Robot robot; // Create a robot at the origin (0, 0) char command; std::cout << "Control the robot with 'U' (up), 'D' (down), 'L' (left), 'R' (right).\n"; std::cout << "Enter 'Q' to quit.\n"; while (true) { robot.printPosition(); std::cout << "Enter command: "; std::cin >> command; if (command == 'Q' || command == 'q') { break; } robot.move(command); } std::cout << "Simulation ended.\n"; robot.printPosition(); return 0; } |
Explanation Robot Class: Attributes: x, y: Coordinates of the robot on a 2D grid. Methods: move(char direction): Updates the robot’s position based on the direction command. ‘U’: Moves the robot up by incrementing the y-coordinate. ‘D’: Moves the robot down by decrementing the y-coordinate. ‘L’: Moves the robot left by decrementing the x-coordinate. ‘R’: …
Simulation of Robot Motion Gaming Project in C++ Read More »