0

我正在为必须是一个基本概念而苦苦挣扎,但是你能看看我的问题吗?

我有代码,其中:ai 移动玩家球棒,HEIGHT = 显示的总高度,batHeight 是乒乓球拍/球拍的大小:

public void ai(int bally, int HEIGHT, int batHeight) {
    if (bally < this.y + ySize / 2) {
        if (this.y <= 0) {
            System.out.println("Upper Bound");
           y = 0;
        } else {
            y -= 2;
        }
    }
    if (bally > this.y + ySize / 2) {
        if (this.y >= HEIGHT - batHeight) {
            System.out.println("Lower Bounds");
            y = HEIGHT - batHeight;
        } else {
            y += 2;
        }
    }
}

以上正是我想要做的。Pong Bat 向上移动,当它碰到屏幕顶部时,它会打印控制台行并停止 Bat。完全相同的情况发生在屏幕底部。它打印控制台,并停止蝙蝠。它每次都这样做,没有问题。

现在,如果我稍微修改一下代码:

public void ai(int bally, int HEIGHT, int batHeight) {
    if (bally < this.y + ySize / 2) {
        if (this.y <= 0) {
            System.out.println("Upper Bound");
            y = 0;
        } else {
            if(rand.nextInt(2)+1 == 1){
                y -= 2;
            }else{
                y -=3;
            }
        }
    }
    if (bally > this.y + ySize / 2) {
        if (this.y >= HEIGHT - batHeight) {
            System.out.println("Lower Bounds");
            y = HEIGHT - batHeight;
        } else {
            y += 2;
        }
    }
}

它迭代一次,在顶部边界处停止,但随后它迷失了自己,忘记了边界,球棒从屏幕上移开。我有控制台打印 Bat y 位置,它可以毫无问题地跟踪,准确地显示它的 y 坐标,但是在第一次迭代之后,它变为负 y 并且大于屏幕高度。

我确实有这样的理论,即你不能在 ELSE 语句中嵌套一个 IF,所以我尝试移动它以便它读取:

if(this.y != 0){
    if(rand.nextInt(2) + 1 == 1){ 
        //move the paddle at speed 1
    } else {
        //move paddle at speed 2
    }
}else{
    //do not move the paddle
}

但这并没有什么不同。

代码背后的想法是为 AI 蝙蝠增加一些机会。有时它很快,有时它更慢。

提前致谢,

4

1 回答 1

0

你的代码从远处看起来是这样的:

for a given time:
if the ball is below the paddle {
    if the paddle is below the screen, put it back
    else move it down 2 or 3 units
}
if the ball is above the paddle {
    if the paddle is above the screen, put it back
    else move it up 2 units
}

想象一下球在​​ y = 1 并且球拍在 y = 2 的情况。第一个if语句会被触发 (1 < 2),球拍不在外面 (2 > 0),所以它向下移动 2 或 3单位。让我们说 3,为了争论。现在,桨在 y = -1 处,球仍然在 y = 1 处。现在,第二个大的条件为if真!所以我们输入它:桨不在上面,我们将它向上移动两个单位。现在,桨在 y = 1...

很明显,它不应该进入第二个循环。所以,else在它前面放一个,因为它应该只输入一个:)

于 2013-10-28T23:33:02.687 回答