我正在學習Java,我知道關於新手程序員的一個大抱怨是我們製作了很長時間且涉及的方法,應該將其分解爲幾個。那麼這裏是我寫的一個例子。 :-D。在Java中重構此功能
public void buildBall(){
/* sets the x and y value for the center of the canvas */
double i = ((getWidth()/2));
double j = ((getHeight()/2));
/* randomizes the start speed of the ball */
vy = 3.0;
vx = rgen.nextDouble(1.0, 3.0);
if (rgen.nextBoolean(.05)) vx = -vx;
/* creates the ball */
GOval ball = new GOval(i,j,(2 *BALL_RADIUS),(2 * BALL_RADIUS));
ball.setFilled(true);
ball.setFillColor(Color.RED);
add(ball);
/* animates the ball */
while(true){
i = (i + (vx* 2));
j = (j + (vy* 2));
if (i > APPLICATION_WIDTH-(2 * BALL_RADIUS)){
vx = -vx;
}
if (j > APPLICATION_HEIGHT-(2 * BALL_RADIUS)){
vy = -vy;
}
if (i < 0){
vx = -vx;
}
if (j < 0){
vy = -vy;
}
ball.move(vx + vx, vy + vy);
pause(10);
/* checks the edges of the ball to see if it hits an object */
colider = getElementAt(i, j);
if (colider == null){
colider = getElementAt(i + (2*BALL_RADIUS), j);
}
if (colider == null){
colider = getElementAt(i + (2*BALL_RADIUS), j + (2*BALL_RADIUS));
}
if (colider == null){
colider = getElementAt(i, j + (2*BALL_RADIUS));
}
/* If the ball hits an object it reverses direction */
if (colider != null){
vy = -vy;
/* removes bricks when hit but not the paddle */
if (j < (getHeight() -(PADDLE_Y_OFFSET + PADDLE_HEIGHT))){
remove(colider);
}
}
}
你可以從方法的標題看到,我開始時有着「造球」的好意。
有我撞到的幾個問題:
的問題是,然後我需要移動球,所以我創建了一個while循環。我沒有看到任何其他的方式去做,除了保持「真實」,所以這意味着我在這個循環下創建的任何其他代碼都不會發生。我沒有讓while循環變成一個不同的函數,因爲我使用了這些變量i and j
。
所以我沒有看到我可以重構這個循環之外。
所以我的主要問題是:
我將如何傳遞的i and j
值,以一種新的方法:「animateBall」和我將如何使用新的方法 ball.move(vx + vx, vy + vy);
如果球已經在buildBall方法被宣佈?
我理解這可能是更好的理解變量的作用域和參數傳遞一個簡單的事情,但我還沒有應用...
嗯...這個詞是拼寫爲 「撞機」 而不是 「colider」。你的代碼有很多風格問題。 – 2010-03-10 07:01:48
恩,謝謝你的幫助? – Joel 2010-03-10 07:07:46
作爲一個你真正想要處理'球'對象的人,你能說得更具體嗎?比如說,你有一個球形物體,你覺得它有多棒,比如球形物體應該採用什麼方法?這樣提供解決方案會更容易。 – Zaki 2010-03-10 07:17:17