【发布时间】:2011-01-25 18:44:06
【问题描述】:
我正在学习 Java,我知道对于新手程序员的一大抱怨是,我们编写的方法非常冗长且复杂,应该分成几个。好吧,这是我写的一个,是一个完美的例子。 :-D。
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 方法中声明了 ball ?
我知道这可能是更好地理解变量范围和传递参数的简单事情,但我还没有完全做到......
【问题讨论】:
-
嗯......这个词拼写为“collider”而不是“collider”。而且您的代码存在很多样式问题。
-
您能否更具体地说明您实际上要对“球”对象做什么?比如说,你有一个球对象,你希望它怎么处理,比如球对象应该有哪些方法?这样更容易提供解决方案。
-
@Zaki-saugata 说得对 1) 构建球 2) 让它四处移动 3) 检查它是否击中任何东西。