我想创建像Nim这样的游戏。
玩家可以使用1个或M个(已定义的)多维数据集,而获胜者是获取最后一个多维数据集的玩家。我还将创建一个minimax函数,因此MAX播放器(始终首先播放)正在做出最佳动作。我开始编写我的程序,但是我在创建树游戏时遇到了麻烦。这是我的代码:
#define M 30
#define K 4
char player[3] = "MAX";
int cubesCounter = M;
struct Node {
int value;
int numCubes;
struct Node *left;
struct Node *right;
};
char switchPlayer() {
if (strcmp(player, "MAX") == 0) {
strcpy(player, "MIN");
} else {
strcpy(player, "MAX");
}
}
struct Node buildGameTree() {
struct Node *cube;
cube->numCubes = M;
cube->left = NULL;
cube->right = NULL;
if (cube->numCubes >= 1) {
cube->numCubes = cube->numCubes - 1;
cube->left = buildGameTree();
}
if (cube->numCubes >= M) {
cube->numCubes = cube->numCubes - M;
cube->right = buildGameTree();
}
}
我在这些方面遇到错误,我无法弄清楚出了什么问题:
cube->left = buildGameTree();
cube->right = buildGameTree();
任何人都可以帮我这个功能吗?
答案 0 :(得分:0)
您的buildGameTree
应该是:
struct Node *buildGameTree(){
struct Node *cube= calloc(1,sizeof(struct Node));
cube->numCubes = M;
cube->left = NULL;
cube->right = NULL;
if (cube->numCubes >= 1){
cube->numCubes = cube->numCubes - 1;
cube->left = buildGameTree();
}
if (cube->numCubes >= M){
cube->numCubes = cube->numCubes - M;
cube->right = buildGameTree();
}
return (cube);
}
那是:
关于这个函数要做什么仍然存在一些问题,因为它没有接收任何参数。由于cube->numCubes
始终为M
,因此if (cube->numCubes >= 1)
会有无限递归。
答案 1 :(得分:0)
我更改了代码,现在是:
struct Node *buildGameTree(int ncubes){
struct Node *cube = calloc(1, sizeof(struct Node));
cube->cubesRemaining = ncubes;
if (cube->cubesRemaining >= 1){
cube->left = buildGameTree(ncubes - 1);
switchPlayer();
}
if (cube->cubesRemaining >= M){
cube->right = buildGameTree(ncubes - M);
switchPlayer();
}
return (cube);
}
编译代码我不会遇到错误问题。当我完成我的课程时,我会对此进行测试。