gpt4 book ai didi

Java:我怎样才能让一个球表现得像一个有弹性的弹跳球?

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:41 25 4
gpt4 key购买 nike

我有两个类 BouncingBall 和另一个类 ElasticBall。这两个类都扩展了 BallImpl,它实现了一个名为 Ball 的接口(interface)。

public interface Ball {
int DEFAULT_RADIUS = 50;

int radius();
Point center();
void update();
}

public class BouncingBall extends BallImpl {
public static final int MOVEMENT_SPEED = 12;

static final int DOWN = 1;
static final int UP = -1;

private int direction;

BouncingBall(int x, int y, int direction) {
super(x, y);
this.direction = direction;
}

@Override
public void update() {
direction = reverseDirectionIfNecessary();
y = move();
}

private int reverseDirectionIfNecessary() {
if (movingTooHigh() || movingTooLow()) {
return switchDirection();
}

return this.direction;
}

private boolean movingTooLow() {
return y + radius >= BallWorld.BOX_HEIGHT && movingDown();
}

private boolean movingTooHigh() {
return y - radius <= 0 && movingUp();
}

private int switchDirection() {
return movingDown() ? UP : DOWN;
}

private int move() {
return y + (MOVEMENT_SPEED * direction);
}

private boolean movingDown() {
return direction == DOWN;
}

private boolean movingUp() {
return direction == UP;
}
}

public class ElasticBall extends BallImpl {
public static final int GROWTH_RATE = 2;

static final int GROW = 1;
static final int SHRINK = -1;

private int growthDirection;

ElasticBall(int x, int y, int radius, int growthDirection) {
super(x, y, radius);
this.growthDirection = growthDirection;
}

@Override
public void update() {
growthDirection = reverseGrowthDirectionIfNecessary();
radius = next();
}

private int reverseGrowthDirectionIfNecessary() {
if (growingTooBig() || shrinkingTooSmall()) {
return switchDirection();
}

return this.growthDirection;
}

private boolean shrinkingTooSmall() {
return radius <= 0 && shrinking();
}

private boolean growingTooBig() {
return radius >= Ball.DEFAULT_RADIUS && growing();
}

private int switchDirection() {
return growing() ? SHRINK : GROW;
}

private int next() {
return radius + (GROWTH_RATE * growthDirection);
}

private boolean shrinking() {
return growthDirection == SHRINK;
}

private boolean growing() {
return growthDirection == GROW;
}
}

我需要创建一个 BouncingElasticBall,它结合了 BouncingBallElasticBall 类的行为。我对OOP的了解很少,而且我知道Java不允许多重继承,那么我该如何解决这个问题?

提前致谢。

最佳答案

解决此问题的一种方法是不扩展 BallImpl,而是制作某种插件。像这样:

public class BallImpl implements Ball {
List<BallBehavior> behaviors = ...

@Override
public void update() {
behaviors.forEach(behavior -> behavior.update(this));
}
...
}

public interface BallBehavior {
void update(BallImpl ballImpl);
}

然后,只需将您的弹性和弹跳逻辑编写为行为

关于Java:我怎样才能让一个球表现得像一个有弹性的弹跳球?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35149228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com