0

在我的 Gridworld 程序中,我有一个像虫子一样行动的公民,以及一个将公民变成受害者的罪犯。我的警察演员虽然没有完全完成,但目前正在帮助受害者。但是,在有界网格中,它不识别下一个位置是无效的。这是我的代码。

public void act()
{
    Grid<Actor> gr = getGrid();
    Location loca = getLocation();
    Location next = loca.getAdjacentLocation(getDirection());
    Actor neighbor = gr.get(next);

    if (gr.isValid(next))
    {
        ArrayList<Location> locs = getGrid().getOccupiedLocations();
        for(Location loc: locs) 
        {
            if (getGrid().get(loc) instanceof Victim)
            {
                Location prev = loc.getAdjacentLocation(getDirection()-180);
                moveTo(prev);
            }
            else if( neighbor instanceof Victim || neighbor instanceof Citizen)
                turn();
            else  
                moveTo(next);
        }
    }
    else
        turn();
}
4

1 回答 1

0

尝试Actor neighbor = gr.get(next);在 if 语句之后移动。

if (gr.isValid(next))
{
    Actor neighbor = gr.get(next);
    ArrayList<Location> locs = getGrid().getOccupiedLocations();

    for(Location loc: locs)
        ...

这样next,在尝试从那里获取位置之前,会检查您的位置以确保它在网格Actor中。

另一件事,在您调用的第二个 if 语句中getGrid().get(next),但您已经拥有gr当前网格,因此您可以使用gr.get(next). 没有理由创建变量而不使用它。

于 2014-04-11T17:04:46.063 回答