我有一个程序,该程序从文本文件中读取地图(障碍物,怪物,宝藏,玩家的出生点),然后玩家可以通过WASD键移动到宝藏,并带有怪物M和障碍物#。

有些地图有3个或更多的怪物。

为什么怪物“ obj”在同一坐标下不吃掉玩家?

        if (obj->x == player->x && obj->y == player->y) {


似乎不适合进行坐标比较

void move_monsters() {
    list_node *monster = monster_position;
    list_node *treasure = treasure_position;
    game_object *obj;
    game_object *obj2;
    while (monster) {
        unsigned possibilities[4][2];
        int position_count = 0;

        obj = monster->object;
        obj2 = treasure->object;

        if (isMovable(obj, obj->x + 1, obj->y)) {
            possibilities[position_count][0] = obj->x + 1;
            possibilities[position_count][1] = obj->y;
            position_count++;
        }
        if (isMovable(obj, obj->x - 1, obj->y)) {
            possibilities[position_count][0] = obj->x - 1;
            possibilities[position_count][1] = obj->y;
            position_count++;
        }
        if (isMovable(obj, obj->x, obj->y + 1)) {
            possibilities[position_count][0] = obj->x;
            possibilities[position_count][1] = obj->y + 1;
            position_count++;
        }
        if (isMovable(obj, obj->x, obj->y - 1)) {
            possibilities[position_count][0] = obj->x;
            possibilities[position_count][1] = obj->y - 1;
            position_count++;
        }
        // If the monster (obj) eats the treasure (obj2), the game is over.
        if (obj->x == obj2->x && obj->y == obj2->y) {
            printf("GAME OVER\n");
            free_memory();
            printf(KNRM);
            exit(0);
        }

        // If the monster (obj) eats the player, the game is over.
        if (obj->x == player->x && obj->y == player->y) {
            printf("GAME OVER\n");
            free_memory();
            printf(KNRM);
            exit(0);
        }

        // Do nothing if no moves are available.
        if (position_count) {
            int target = rand() % position_count;
            move_object(monster->object, possibilities[target][0], possibilities[target][1]);
        }
        monster = monster->next;
    }
}

最佳答案

这些怪物非常愚蠢:当其中任何一个都只有一步之遥时,它们就不会动静地吃掉宝藏或玩家。玩家与任何一个怪物之间的碰撞都是偶然的,玩家可以在下一次迭代中被怪物吞噬之前摆脱危险。

如果这从未发生,我怀疑玩家永远不会自愿遇到怪物,并且isMovable()函数认为玩家的位置不可用,从而阻止了怪物进食玩家。

09-30 11:17