gpt4 book ai didi

c - 机器人以相反的顺序遵循网格

转载 作者:行者123 更新时间:2023-11-30 14:30:10 26 4
gpt4 key购买 nike

我应该只用 C 语言编写一个程序。这是网格追随者的代码。

我定义了网格的坐标系(0-5,0-5)。还定义了机器人方向(+y、-y、+x、-x)和位置。 (我欢迎有关如何为此编写良好代码的提示。)

现在,当我的机器人穿过网格并通过某条路径到达网格中的某个坐标(x,y)时。仅允许 90 度和 180 度转弯。

如何沿着相同的路径到达(0,0),即起点?如何使用 C 代码反转方向并给出适当的转动指令?

最佳答案

这可以清理很多,但它应该是理解概念的一个很好的框架。我们基本上所做的就是保存每一步,然后简单地回溯它。

#include <stdio.h>

#define MAX_STEPS 256

enum CARDINAL_DIRECTIONS { N = 0, W, S, E };

struct _s_robot {
int x;
int y;
int orientation;
int step;
int x_history[MAX_STEPS];
int y_history[MAX_STEPS];
int turn_history[MAX_STEPS];
} MY_LITTLE_ROBOT = {0, 0, 0, 0, {0}, {0}, {0}};

void robot_go() {
switch(MY_LITTLE_ROBOT.orientation) {
case N:
++MY_LITTLE_ROBOT.y;
break;
case W:
--MY_LITTLE_ROBOT.x;
break;
case S:
--MY_LITTLE_ROBOT.y;
break;
case E:
++MY_LITTLE_ROBOT.x;
break;
}
MY_LITTLE_ROBOT.x_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.x;
MY_LITTLE_ROBOT.y_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.y;
MY_LITTLE_ROBOT.turn_history[MY_LITTLE_ROBOT.step] = MY_LITTLE_ROBOT.orientation;
++MY_LITTLE_ROBOT.step;
}

void robot_change_orientation(int _orientation) {
MY_LITTLE_ROBOT.orientation = _orientation;
}

void robot_reverse_orientation(int _orientation) {
if (_orientation == N) MY_LITTLE_ROBOT.orientation = S;
else if (_orientation == W) MY_LITTLE_ROBOT.orientation = E;
else if (_orientation == S) MY_LITTLE_ROBOT.orientation = N;
else if (_orientation == E) MY_LITTLE_ROBOT.orientation = W;
}

void robot_backtrack() {
int i;
printf("MY_LITTLE_ROBOT wants to turn around, currently at: %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
robot_reverse_orientation(MY_LITTLE_ROBOT.orientation);
for (i = MY_LITTLE_ROBOT.step-1; i >= 0; --i) {
printf("Robot is @ %i, %i, with an orientation of: %i \n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y, MY_LITTLE_ROBOT.orientation );
robot_reverse_orientation(MY_LITTLE_ROBOT.turn_history[i]);
robot_go();
}
}

void dump_history() {
int i;
for (i = MY_LITTLE_ROBOT.step-1; i >= 0; --i) {
printf("Robot is @ %i, %i, with an orientation of: %i \n", MY_LITTLE_ROBOT.x_history[i], MY_LITTLE_ROBOT.y_history[i], MY_LITTLE_ROBOT.turn_history[i] );
}
}

int main() {
printf("***START: Robot is @ %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
robot_go();
robot_go();
robot_go();
robot_change_orientation(S);
robot_go();
robot_go();
robot_change_orientation(W);
robot_go();
robot_go();
robot_go();
robot_change_orientation(N);
robot_go();
dump_history();
robot_backtrack();
printf("***FINISH: Robot is @ %i, %i\n", MY_LITTLE_ROBOT.x, MY_LITTLE_ROBOT.y);
return 0;
}

要反复使用机器人,您可能需要在原路返回后重置所有旅行历史记录,这应该是微不足道的。为了冗长和简单起见,我故意避免了 malloc 和其他使程序真正有用的令人困惑的方面。希望它能有所帮助。

我还假设您不需要真正的寻路算法(例如 A*),因为那完全是不同的游戏。

关于c - 机器人以相反的顺序遵循网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3743525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com