我需要使遊戲無法取勝,所以我使用此代碼來移動AI槳。乒乓遊戲 - AI槳搖搖欲墜
我的代碼起初可能有點難以理解,所以這裏有一個理論背後的原理:除非球比邊緣長度的一半更靠近邊緣,否則槳總是以中點擊球,然後槳停止以其一端接觸頂部或底部窗框移動。
if (ball.getY() < getHeight() - HEIGHT/2
&& ball.getY() > HEIGHT/2) {
paddleRight.setLocation(getWidth() - 3 * WIDTH, ball.getY()
- HEIGHT/2);
image2.setLocation(getWidth() - 3 * WIDTH, ball.getY() - HEIGHT
/2);
image2.sendToFront();
} else if (ball.getY() < HEIGHT/2) {
paddleRight.setLocation(getWidth() - 3 * WIDTH, 0);
image2.setLocation(getWidth() - 3 * WIDTH, 0);
image2.sendToFront();
} else {
paddleRight.setLocation(getWidth() - 3 * WIDTH, getHeight()
- HEIGHT);
image2.setLocation(getWidth() - 3 * WIDTH, getHeight() - HEIGHT);
image2.sendToFront();
}
我的球也是遊戲中隨機加速:
boolean bool = rand.nextBoolean();
if (bool)
if (dx > 0)
dx += 1;
else
dx -= 1;
else if (dy > 0)
dy += 0.5;
else
dy -= 0.5;
球運動包括X和Y軸移動
而在一些特定的速度,如果槳獲取到的一個角落開始在頂部和底部角落之間來回閃爍。我在代碼中找不到原因。
偏離主題,但是'bool'是這個變量的可怕名稱;例如,像'moveX'這樣的東西會更清晰一些。 –
'Ball.getY()'返回'int'嗎?你確定你的球位置報告正確嗎?如果'Ball.getY()'返回一個'float'或'double',你確定它永遠不會因爲其他地方的數學錯誤而意外地被設置爲Infinite/NaN? –
@JasonC是啊,我知道這是不好的,但我只會用它一次。 'ball.getY()'返回'double'。我應該將其轉換爲「int」嗎? – Asalas77