python完整代码 实现简单火星探测机器人
时间: 2023-08-05 15:26:03 浏览: 359
好的,下面是一个简单的Python代码实现火星探测机器人的例子:
```python
import random
# 定义火星探测机器人类
class MarsRover:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
self.directions = ["N", "E", "S", "W"]
self.direction = random.choice(self.directions)
def move(self):
if self.direction == "N":
self.y += 1
elif self.direction == "E":
self.x += 1
elif self.direction == "S":
self.y -= 1
elif self.direction == "W":
self.x -= 1
def turn_left(self):
index = self.directions.index(self.direction)
self.direction = self.directions[(index - 1) % 4]
def turn_right(self):
index = self.directions.index(self.direction)
self.direction = self.directions[(index + 1) % 4]
def get_position(self):
return self.x, self.y, self.direction
def __str__(self):
return f"MarsRover({self.x}, {self.y}, {self.direction})"
# 测试
rover = MarsRover()
print(rover)
rover.move()
print(rover)
rover.turn_left()
print(rover)
rover.move()
print(rover)
rover.turn_right()
print(rover)
rover.move()
print(rover)
```
这个例子中定义了一个名为 `MarsRover` 的类,包含了机器人的坐标位置和朝向等属性,以及机器人的移动、转向和获取位置等方法。在测试部分,首先创建了一个默认坐标为 (0, 0) 的机器人,并随机指定了机器人的朝向。然后,机器人依次进行了移动、左转、移动和右转等操作,最后输出了机器人的当前位置和朝向。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)