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’: Moves the robot right by incrementing the x-coordinate.
printPosition()
: Displays the current position of the robot.
- Attributes:
- Main Function:
- Robot Creation: Initializes a
Robot
object at the origin (0, 0). - Control Loop:
- Continuously prompts the user for a command to control the robot.
- Commands:
- ‘U’: Move up.
- ‘D’: Move down.
- ‘L’: Move left.
- ‘R’: Move right.
- ‘Q’: Quit the simulation.
- Position Update: Calls
move
method to update the robot’s position based on the command. - Simulation End: Prints the final position of the robot when the user quits.
- Robot Creation: Initializes a
Usage
- Robot Motion Simulation: Provides a basic simulation of robot movement on a grid using directional commands.
- Control Mechanism: Demonstrates simple user input handling to control the robot’s movement.