0

我正在为大学课程做作业,我和我的伙伴遇到了问题。我们正在制作的程序是一个游戏。

我们有几个类,它们都继承自基类,称为 Creature。这些都是玩家需要处理的敌人,他们都运行自己的 AI。有 4 种不同类型的子类,都在命名空间 Creature(包括父级、Creature)中,其中一个类具有只有它需要的特殊功能。这个班级被称为兔子。

现在,我的工作是根据需要调用 AI 函数。问题是,当我要求游戏板告诉我我得到什么生物时,我并不总是知道我在呼唤什么类。

所有敌人都保存为指针,如下所示,在游戏板方块中:

    struct Square
    {   
        // Pointers to Morso class, where the enemy is saved
        Creature::Creature* creature;
        //Undeeded stuff removed

    };

现在,这一切都很好,直到我们需要访问特殊功能。如果满足某些条件,Pupu会成倍增加。因此,在 Pupu 中,我需要调用的函数很少,以确保它正确执行。

然而,问题来了。

我打电话给我们的棋盘类,把我给它的坐标中的生物给我。

void GameEngine::GameEngine::runAI()
{
    Creature::Creature* creature= NULL;

    for(unsigned int y = 0; y < dimY; y++)
    {
        for(unsigned int x = 0; x < dimX; x++)
        {
            Coordinate target;

            target.setX(x);
            target.setY(y);

            creature= board_->returnCreature(target);

            //If there is a creature in the target, run its AI
            if(creature!= NULL)
            {

                //If it is, check special procedures
                if(creature->returnType() == "bunny")
                {
                    bunnyReproduce(creature);
                }

                creature->ai();
            }

        }//for x

    }//for y
}

现在, :

void GameEngine::GameEngine::bunnyReproduce(Ccreature::Creature* creature)
{

//Checks that it really is a bunny
if( creature->returnType() != "bunny"){ return; }

//Check is there another bunny near
creature->checkForMate();


}

问题是,在这一点上,生物不能调用 checkForMate,它是 Bunny 的公共成员,而不是 Creature。我们需要把虚函数变成Creature吗?

我尝试将 checkForMate 设置为 Creature::Bunny,但由于我尝试赋予它的原始值是 Creature 类,所以我不能这样做。我们是否需要在 Creature 类中创建一个空的虚函数,然后覆盖它 Bunnyclass?

我正在运行带有 QT 5.0.2 的 Qt Creator 2.7.0。

4

2 回答 2

3

您应该将函数添加reproduceCreature类中并在Bunny您以后可能添加到游戏中的任何其他生物中实现它。这样任何生物都会以自己的方式繁殖自己。在这种情况下,你甚至不需要检查生物类型。因为如果你有一些不可复制的生物,你可能只是实现reproduce为空的方法,它什么都不做。

于 2013-04-25T10:54:47.023 回答
1

理想情况下,您的引擎根本不需要关心它正在使用哪种生物。

如果你想让兔子在每一步都重现ai(),为什么不在兔子那里做呢ai()
毕竟,决定什么时候繁殖不应该是兔子的责任,而不是一些万能的外部引擎吗?

void Creature::Bunny::ai()
{
    if (niceMateNearby())
        reproduce();
    else
        eatCarrotsAndJumpAround();
}
于 2013-04-25T11:18:09.377 回答