【发布时间】:2011-11-20 15:17:29
【问题描述】:
我最近开始接触 C++;我是一个业余程序员,我懂一点 Python。
我编写了一条小蛇。我想插入另一条由计算机引导的蛇。
我决定将蛇可以采取的可能方向放在一个枚举中:
enum directions{UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW,NONE};
void fill_map(std::map<directions,V4> &map_vec);
void fill_map(std::map<int, directions*> &map_dir);
void fill_map(std::map<directions,directions> &map);
并为所需函数映射枚举:
void fill_map(std::map<directions,V4> &map_vec){
map_vec[UP] = V4(0,1,0,0);
map_vec[DOWN] = V4(0,-1,0,0);
//others
}
void fill_map(std::map<directions, directions> &map){
map[UP]= DOWN;
map[DOWN]= UP;
//others
}
void fill_map_axis(std::map<int, directions*> &map_dir){
directions array_x[2] = {RIGHT,LEFT};
map_dir[0] = array_x;
directions array_y[2] = {UP,DOWN};//store the array
map_dir[1] = array_y;
directions array_z[2] = {FW,RW};//store the array
map_dir[2] = array_z;
directions array_w[2] = {IN,OUT};//store the array
map_dir[3] = array_w;
}
在蛇构造函数中调用 fill_map 函数。
基本上我想要在 fill_map_axis 中做的是映射一个与坐标索引相对应的整数(0 coord x,1 coord y 等)并映射沿这些轴移动的两个方向。
所以我存储了一个包含两个方向的数组。
现在我调用函数:
directions SnakeCPU::find_dir(V4 point){
//point is the target point
directions dir;
int index = get_coord_index(point); //get the index where to move
double diff = head_pos[index]-point[index]; //find the difference between the head and the target point
directions* axis = dir_coords[index]; //call the map containing the directions stored in an array.
if(diff<0.){
dir = *axis; //use the first
}
else if(diff>0.) {
axis++;
dir = *axis; //use the second
}
else{
dir = NONE;
}
return dir;
}
虽然在Snake构造函数中初始化了map,但是从指针轴返回的值似乎是一个随机内存块。
所以我的问题是:你看到代码中有错误吗?我是否使用了有感觉的指针轴?
我真的不是指针专家;在 Python 中,地图是用这样的字典实例化的:
dir_coords = {0:[LEFT,RIGHT], ...}
所以我只需要调用它:
axis = dir_coords[index]
dir = axis[0]
#or
dir = axis[1]
编辑:
Snake 构造函数:
Snake::Snake()
{
fill_map(dir_vectors);
fill_map(dir_coords);
fill_map(opposite_dir);
head_pos = V4(0.,0.,0.,0.);
//other stuff...
}
【问题讨论】:
-
您的
array_x等是局部变量,您只是插入指向这些数组的指针。函数作用域退出后,这些指针不再有效。简而言之,一切都在上升。我建议在您的地图中存储std::pair<direction, direction>。 -
SnakeCPU构造函数的代码在哪里?
-
head_pos[] and point[]是什么?此外,axis++; dir = *axis;可以替换为dir = '*(++axis); -
@Kerrek,回答一下。
-
我想,很好 :D 什么是 std::pair?我把它叫做pair[0]和pair[1]?