这里提供一个简单的未知环境机器人探索的代码示例:```c#include #include #include #define ROW 5 // 地图行数#define COL 5 // 地图列数typedef struct {int x; // 机器人当前所在的行int y; // 机器人当前所在的列} Robot;typedef struct {int x; // 物品所在的行int y; // 物品所在的列} Item;void init_map(int map[][COL], Robot *robot, Item *item);void print_map(int map[][COL], Robot *robot, Item *item);void move_up(int map[][COL], Robot *robot);void move_down(int map[][COL], Robot *robot);void move_left(int map[][COL], Robot *robot);void move_right(int map[][COL], Robot *robot);int main(void) {int map[ROW][COL] = {0}; // 地图,0 表示未探索的区域,1 表示已探索的区域Robot robot = {0}; // 机器人初始位置Item item = {0}; // 物品位置init_map(map, &robot, &item); // 初始化地图,机器人和物品的位置printf("Start exploring...\n");while (robot.x != item.x || robot.y != item.y) { // 当机器人找到物品时停止探索print_map(map, &robot, &item); // 输出当前地图状态int direction = rand() % 4; // 随机选择一个方向switch (direction) {case 0: move_up(map, &robot); break;case 1: move_down(map, &robot); break;case 2: move_left(map, &robot); break;case 3: move_right(map, &robot); break;default: break;}}printf("Find the item at (%d, %d)!\n", item.x, item.y);return 0;}// 初始化地图,机器人和物品的位置void init_map(int map[][COL], Robot *robot, Item *item) {srand((unsigned)time(NULL)); // 初始化随机数生成器int x, y;do {x = rand() % ROW; // 随机生成物品所在的行y = rand() % COL; // 随机生成物品所在的列} while (x == 0 && y == 0); // 物品位置不能与机器人初始位置重合map[x][y] = 1; // 标记物品所在位置已探索item->x = x;item->y = y;}// 输出当前地图状态void print_map(int map[][COL], Robot *robot, Item *item) {printf("Robot is at (%d, %d)\n", robot->x, robot->y);printf("Item is at (%d, %d)\n", item->x, item->y);printf("Current map:\n");for (int i = 0; i < ROW; i++) {for (int j = 0; j < COL; j++) {if (robot->x == i && robot->y == j) {printf("R "); // 机器人位置用 R 表示} else if (item->x == i && item->y == j) {printf("I "); // 物品位置用 I 表示} else if (map[i][j] == 1) {printf(". "); // 已探索的区域用 . 表示} else {printf("? "); // 未探索的区域用 ? 表示}}printf("\n");}}// 向上移动机器人void move_up(int map[][COL], Robot *robot) {if (robot->x > 0) { // 判断是否到达地图边界robot->x--;map[robot->x][robot->y] = 1; // 标记当前位置已探索}}// 向下移动机器人void move_down(int map[][COL], Robot *robot) {if (robot->x < ROW - 1) { // 判断是否到达地图边界robot->x++;map[robot->x][robot->y] = 1; // 标记当前位置已探索}}// 向左移动机器人void move_left(int map[][COL], Robot *robot) {if (robot->y > 0) { // 判断是否到达地图边界robot->y--;map[robot->x][robot->y] = 1; // 标记当前位置已探索}}// 向右移动机器人void move_right(int map[][COL], Robot *robot) {if (robot->y < COL - 1) { // 判断是否到达地图边界robot->y++;map[robot->x][robot->y] = 1; // 标记当前位置已探索}}```这个代码示例使用随机数生成器模拟机器人在未知环境中的探索过程,每次随机选择一个方向进行移动,直到机器人找到物品为止。在代码中,0 表示未探索的区域,1 表示已探索的区域,? 表示未知的区域,R 表示机器人的位置,I 表示物品的位置。可以根据实际需求进行修改和扩展。
未知环境探索(二)基于边界点的自主环境探索
未知环境探索(二)基于边界点的自主环境探索这里提供一个简单的未知环境机器人探索的代码示例:```c#include #include #include #define ROW 5 // 地图行数#define COL 5
发表评论