|
实验内容 机器人搬盒子问题。一个机器人ROBOT,一个壁橱ALCOVE,一个积木块BOX,两个桌子A和B。开始时机器人ROBOT在壁橱ALCOVE旁边,两手空空。桌子A上放着积木块BOX.桌子B是空着的,机器人把积木块BOX从桌子A上搬到桌子B上,然后回到壁橱旁。用归结原理求解问题。 | ||||||||||||
|
实验原理及流程图 归结原理(Resolution Principle) 1)基本思想:通过逻辑推理验证目标是否可从初始状态和规则集合中推出。 2)核心步骤:
3)步骤流程:
4)流程图
|
#python实现
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
class Robot:
def __init__(self):
self.location = "ALCOVE"
self.hands_empty = True
self.box_location = "A"
self.target_location = "B"
# 坐标系统 (x, y)
self.positions = {
"ALCOVE": (1, 0.5),
"A": (3, 0.5),
"B": (5, 0.5)
}
self.current_pos = self.positions[self.location]
self.frames = []
def record_frame(self):
frame = {
"robot_pos": self.current_pos,
"box_pos": self.box_location,
"hands_empty": self.hands_empty,
"location": self.location
}
self.frames.append(frame)
def move(self, destination):
print(f"机器人从 {self.location} 移动到 {destination}")
start_pos = self.current_pos
end_pos = self.positions[destination]
steps = 10
for i in range(steps + 1):
progress = i / steps
x = start_pos[0] + (end_pos[0] - start_pos[0]) * progress
y = start_pos[1] + (end_pos[1] - start_pos[1]) * progress
self.current_pos = (x, y)
self.record_frame()
time.sleep(0.1)
self.location = destination
self.current_pos = self.positions[destination]
self.record_frame()
def pick_up(self):
if self.location == self.box_location and self.hands_empty:
print(f"机器人在 {self.location} 拿起积木块")
self.hands_empty = False
for _ in range(5):
self.record_frame()
time.sleep(0.1)
else:
print("拿起失败!")
def put_down(self):
if not self.hands_empty:
print(f"机器人在 {self.location} 放下积木块")
self.box_location = self.location
self.hands_empty = True
# 放下动作需要多帧表现
for _ in range(5):
self.record_frame()
time.sleep(0.1)
else:
print("放下失败!")
def solve_problem(self):
print("开始解决问题...")
self.record_frame() # 初始状态
self.move("A")
self.pick_up()
self.move("B")
self.put_down()
self.move("ALCOVE")
print("问题解决!")
class Visualizer:
def __init__(self, robot):
self.fig, self.ax = plt.subplots(figsize=(10, 5))
self.robot = robot
self.ani = None
def init_plot(self):
self.ax.clear()
self.ax.set_xlim(0, 6)
self.ax.set_ylim(0, 1.5)
self.ax.set_title("机器人搬盒子问题 - 完整动画演示")
self.ax.axis('off')
# 绘制固定物体
for name, pos in self.robot.positions.items():
self.ax.text(pos[0], 1.2, name, ha='center', fontsize=12)
self.ax.plot([pos[0] - 0.3, pos[0] + 0.3], [1.0, 1.0], 'k-', linewidth=3)
return []
def update_frame(self, frame_num):
self.ax.clear()
self.init_plot()
frame = self.robot.frames[frame_num]
# 绘制机器人
robot_x, robot_y = frame["robot_pos"]
self.ax.plot(robot_x, robot_y, 'bo', markersize=20)
self.ax.text(robot_x, robot_y + 0.1, "ROBOT", ha='center', fontsize=10)
# 绘制积木块
if frame["hands_empty"]:
box_pos = self.robot.positions[frame["box_pos"]]
self.ax.plot(box_pos[0], 1.0, 'rs', markersize=15)
self.ax.text(box_pos[0], 0.95, "BOX", ha='center', color='white')
else:
# 手持状态
self.ax.plot(robot_x, robot_y + 0.2, 'rs', markersize=12)
# 显示当前步骤
step_text = f"步骤 {frame_num + 1}/{len(self.robot.frames)}"
self.ax.text(0.5, 0.2, step_text, fontsize=12, bbox=dict(facecolor='lightyellow'))
return []
def animate(self):
self.ani = animation.FuncAnimation(
self.fig, self.update_frame,
frames=len(self.robot.frames),
init_func=self.init_plot,
interval=300, # 每帧间隔(毫秒)
blit=False,
repeat=False
)
plt.show()
if __name__ == "__main__":
# 创建机器人和可视化器
robot = Robot()
visualizer = Visualizer(robot)
# 解决问题并记录所有帧
robot.solve_problem()
# 显示完整动画
visualizer.animate()
# 保持窗口打开
plt.show()



//Java实现
class Robot {
private String location;
private boolean holdingBox;
public Robot(String location) {
this.location = location;
this.holdingBox = false;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public boolean isHoldingBox() {
return holdingBox;
}
public void setHoldingBox(boolean holdingBox) {
this.holdingBox = holdingBox;
}
public void move(String toLocation) {
System.out.println("Robot moves from " + location + " to " + toLocation);
location = toLocation;
}
public void grab(Box box) {
if (box.getLocation().equals(location) && !holdingBox) {
System.out.println("Robot grabs the box from " + location);
box.setLocation("held by robot");
holdingBox = true;
}
}
public void drop(Box box, Table table) {
if (table.getLocation().equals(location) && holdingBox) {
System.out.println("Robot drops the box on " + table.getName());
box.setLocation(table.getName());
holdingBox = false;
}
}
}
class Box {
private String location;
public Box(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
class Table {
private String name;
private String location;
public Table(String name, String location) {
this.name = name;
this.location = location;
}
public String getName() {
return name;
}
public String getLocation() {
return location;
}
}
public class RobotBox {
public static void main(String[] args) {
Robot robot = new Robot("ALCOVE");
Box box = new Box("TABLE_A");
Table tableA = new Table("TABLE_A", "TABLE_A");
Table tableB = new Table("TABLE_B", "TABLE_B");
// Inference process
robot.move("TABLE_A");
robot.grab(box);
robot.move("TABLE_B");
robot.drop(box, tableB);
robot.move("ALCOVE");
}
}

//c++实现
#include <iostream>
#include <string>
class Box {
private:
std::string location;
public:
Box(const std::string& location) : location(location) {}
std::string getLocation() const {
return location;
}
void setLocation(const std::string& location) {
this->location = location;
}
};
class Table {
private:
std::string name;
std::string location;
public:
Table(const std::string& name, const std::string& location) : name(name), location(location) {}
std::string getName() const {
return name;
}
std::string getLocation() const {
return location;
}
};
class Robot {
private:
std::string location;
bool holdingBox;
public:
Robot(const std::string& location) : location(location), holdingBox(false) {}
std::string getLocation() const {
return location;
}
void setLocation(const std::string& location) {
this->location = location;
}
bool isHoldingBox() const {
return holdingBox;
}
void setHoldingBox(bool holdingBox) {
this->holdingBox = holdingBox;
}
void move(const std::string& toLocation) {
std::cout << "Robot moves from " << location << " to " << toLocation << std::endl;
location = toLocation;
}
void grab(Box& box) {
if (box.getLocation() == location && !holdingBox) {
std::cout << "Robot grabs the box from " << location << std::endl;
box.setLocation("held by robot");
holdingBox = true;
}
}
void drop(Box& box, Table& table) {
if (table.getLocation() == location && holdingBox) {
std::cout << "Robot drops the box on " << table.getName() << std::endl;
box.setLocation(table.getName());
holdingBox = false;
}
}
};
int main() {
Robot robot("ALCOVE");
Box box("TABLE_A");
Table tableA("TABLE_A", "TABLE_A");
Table tableB("TABLE_B", "TABLE_B");
// Inference process
robot.move("TABLE_A");
robot.grab(box);
robot.move("TABLE_B");
robot.drop(box, tableB);
robot.move("ALCOVE");
return 0;
}

|
实验心得及体会 通过这次实验,我深刻理解了如何使用面向对象编程来模拟现实世界的问题。Java、C++和Python三种不同语言的实现虽然语法上有所差异,但它们的核心思想是一致的:通过类和对象来表示实体(如机器人、箱子和桌子),并通过方法来定义这些实体的行为。在Java和C++的实现中,主要关注的是基本的面向对象特性,如封装、继承和多态的应用。这两个版本的代码结构清晰,易于理解和维护,适合处理简单的逻辑控制。而Python的实现则更进一步,利用matplotlib库实现了动画效果,使得问题的解决过程可视化。 |

7617

被折叠的 条评论
为什么被折叠?



