2014-04-03 32 views
0

我正在用C++做一个蚂蚁和臭虫游戏。我在bug.cpp中的移动函数有一些问题,名为Bug :: move() 我添加了if-s来查找蚂蚁是否在下一个网格,所以它出错了,现在我的程序崩溃了虫子在吃蚂蚁。 GetAt返回给定坐标下的生物体。 如果getType为错误或者返回,则返回getAt将有机体组织置于位置(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++; 
} 
+0

什么'world-> getAt(...)'/'world-> setAt(...)'做索引超出界限? 'Bug-> movesTo(...)'相同。 – Deduplicator

+3

在家用电脑之前,我最喜欢的预测者是premacs。 –

+1

我现在的主要问题是如何找到一只蚂蚁,在得到正确答案之后,我会修复代码来吃掉蚂蚁。 – user3399655

回答

0

如果您仍需要一个答案..

您需要先检查电网有现货或NOT NULL。你能做到这一点,像这样:

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

这样你不会得到空指针引用,并在你的程序崩溃。