我在为什么是基本概念而挣扎,但你能看看我的问题吗?
我有这样的代码: ai移动球棒,高度=显示的总高度,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;
}
}
}上面的这些都是我想要做的。球棒向上移动,当它到达屏幕顶部时,它会打印控制台线,并停止球拍。同样的情况也发生在屏幕的底部。它打印控制台,并停止蝙蝠。它每次都这样做,没有任何问题。
现在,如果我稍微修改代码:
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和更大的屏幕高度。
我确实有这样的理论,你不能嵌套一个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蝙蝠增加一些机会。有时速度快,有时速度慢。
提前谢谢你,
发布于 2013-10-28 23:33:02
您来自远方的代码如下所示:
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放在它的前面,因为它只应该输入一个:)
https://stackoverflow.com/questions/19643400
复制相似问题