让捕食者吃掉猎物

时间:2014-04-03 21:23:37

标签: c++

我正在用c ++做一个蚂蚁和bug游戏。我在bug.cpp中的move函数有一些问题,名为Bug :: move() 在我添加了if-s以查找蚂蚁是否在下一个网格之后,我的程序崩溃了,所以错误是如何吃掉蚂蚁的错误。 GetAt返回给定坐标处的生物体。 getType返回,如果它是一个bug或和 setAt将有机体组织设置在位置(x,y)。

void Bug::move()
{

if(world->getAt(x, y + 1)->getType() == ANT)
{
    world->setAt(x, y, NULL);
    world->setAt(x, y + 1, this);
    breedTicks = 0;
    setMoved(true);
}
else if(world->getAt(x, y - 1)->getType() == ANT)
{
    world->setAt(x, y, NULL);
    world->setAt(x, y - 1, this);
    breedTicks = 0;
    setMoved(true);
}
else if(world->getAt(x - 1, y)->getType() == ANT)
{
    world->setAt(x, y, NULL);
    world->setAt(x - 1, y, this);
    breedTicks = 0;
    setMoved(true);
}
else if(world->getAt(x + 1, y)->getType() == ANT)
{
    world->setAt(x, y, NULL);
    world->setAt(x + 1, y, this);
    breedTicks = 0;
    setMoved(true);
}

else
{
    Move randomMove = world->randomMove();

    if((randomMove == UP) && (y < WORLDSIZE - 1) && (world->getAt(x, y + 1) == NULL))
    {   
        movesTo(x, y + 1);
    }
    if((randomMove == DOWN) && (y > 0) && (world->getAt(x, y - 1) == NULL))
    {
        movesTo(x, y - 1);
    }
    if((randomMove == LEFT) && (x > 0) && (world->getAt(x - 1, y) == NULL))
    {
        movesTo(x - 1, y);
    }
    if((randomMove == RIGHT) && (x < WORLDSIZE - 1) && (world->getAt(x + 1, y) == NULL))
    {
        movesTo(x + 1, y);
    }
}
breedTicks++;
}

1 个答案:

答案 0 :(得分:0)

如果您仍然需要答案..

&#xA;&#xA;

您需要首先检查网格中是否有NULL。您可以这样做:

&#xA;&#xA;
  if(world-&gt; getAt(x,y + 1)!= NULL&amp;&amp; world-&gt; getAt(x,y + 1) - &gt; getType()== ANT)&#xA; {&#XA; world-&gt; setAt(x,y,NULL);&#xA; world-&gt; setAt(x  -  1,y,this);&#xA; breedTicks = 0;&#xA; setMoved(真);&#XA; }&#xA;  
&#xA;&#xA;

这样你就不会得到NULL指针引用,程序就崩溃了。

&#xA;