-3

我在使用这段代码时遇到了问题,如果有人能指出我正确的方向,我将不胜感激。已经卡了好几天了!!

基本上,我试图阻止船在到达边界后移动。边界是 6 和 -6。

这是代码。谢谢 :)

public void move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5)
    {
        .... ?? What to write here?

    }
    else if (position < -5)
    {
        .... ?? What to write here?

    }

    position = position + direction;
    gun1.move(direction);
    gun2.move(direction);

}
4

3 回答 3

2

即使他试图移出边界,这也会让玩家保持在边界

public void move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5)
    {
        position = 5;

    }
    else if (position < -5)
    {
        position = -5;

    }

    position = position + direction;
    gun1.move(direction);
    gun2.move(direction);

}
于 2013-09-18T05:12:36.150 回答
2

问题取决于。如果您想在对象到达其边界时停止它,那么诸如...

// Move first
position = position + direction;

// Boundary check second...
if (position > 5)
{
     position = 5;
}
else if (position < -5)
{
     position = -5;
}

gun1.move(direction);
gun2.move(direction);

如果你想“反弹”墙壁......

// Move first
position = position + direction;

// Boundary check second...
if (position > 5)
{
     position = 5;
     direction *= -1
}
else if (position < -5)
{
     position = -5;
     direction *= -1
}

gun1.move(direction);
gun2.move(direction);

可能会奏效-没有更多上下文就很难说...

于 2013-09-18T05:11:44.387 回答
0

您的方法必须将状态(已移动或未移动)传达给调用代码。你可以通过两种方式做到这一点:

1 返回状态码

public int move (int direction) //if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5 || position <-5)
    {
        return -1;   //status code for no movement

    }

2 当船不能移动时抛出异常

public void move (int direction) throws InvalidArgumentException//if position exceeds 5 then playership will 
                                 //no long move in that direction.
{
    if (position > 5 || position <-5)
    {
        throw new InvalidArgumentException("Cannot move!");   //status code for no movement

    }

调用代码可以处理它认为合适的状态代码/异常。

于 2013-09-18T05:15:14.243 回答