Search code examples
ctreeartificial-intelligenceminimax

Building tree in Nim game


I want to create a game like Nim.

The player can take 1 or M (defined) cubes and the winner is the player who takes the last cube. I will also create a minimax function, so the MAX player (always plays first) is making the best move. I started writing my program but I have trouble creating the tree game. Here is my code:

#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();
    }
}

I'm getting an error at these lines and I can't figure out what's wrong:

cube->left = buildGameTree();
cube->right = buildGameTree();

Can anyone help me with this function?


Solution

  • Your buildGameTree should be:

    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);
    }
    

    That is:

    • allocate memory for the cube;
    • return the allocated cube at end of function.

    Some questions remain about what this function is to do, as it receives no parameters. Since cube->numCubes is always M, there will be an infinite recursion on if (cube->numCubes >= 1).