坦克大战(一期)-设计模式-责任链应用1.2

DesignPatterns
bingor 3 years ago
parent 20e075db3c
commit d09a6719d7

@ -20,7 +20,7 @@ import java.util.List;
*@Date 2022/10/11 17:55 *@Date 2022/10/11 17:55
*@Version 3.0 *@Version 3.0
*/ */
public class ColliderChain { public class ColliderChain implements Collider {
List<Collider> colliders = new LinkedList<>(); List<Collider> colliders = new LinkedList<>();
public ColliderChain() { public ColliderChain() {
@ -36,9 +36,11 @@ public class ColliderChain {
return colliders; return colliders;
} }
public void collide(GameObject o1, GameObject o2) { @Override
public boolean collide(GameObject o1, GameObject o2) {
for (Collider collider : colliders) { for (Collider collider : colliders) {
collider.collide(o1, o2); if( ! collider.collide(o1, o2)) return false;
} }
return true;
} }
} }

@ -9,5 +9,5 @@ import com.msb.model.abstracts.GameObject;
* @Version: 1.0 * @Version: 1.0
*/ */
public interface Collider { public interface Collider {
public void collide(GameObject o1, GameObject o2); public boolean collide(GameObject o1, GameObject o2);
} }

@ -19,20 +19,21 @@ import com.msb.model.abstracts.GameObject;
*/ */
public class BulletTankCollider implements Collider { public class BulletTankCollider implements Collider {
@Override @Override
public void collide(GameObject o1, GameObject o2) { public boolean collide(GameObject o1, GameObject o2) {
if(o1 instanceof Bullet && o2 instanceof Tank) { if(o1 instanceof Bullet && o2 instanceof Tank) {
Bullet bullet = (Bullet) o1; Bullet bullet = (Bullet) o1;
Tank tank = (Tank) o2; Tank tank = (Tank) o2;
if(bullet.getGroup() == tank.getGroup()) return; if(bullet.getGroup() == tank.getGroup()) return true; //没有撞继续执行
if(bullet.getRectangle().intersects(tank.getRectangle())) { if(bullet.getRectangle().intersects(tank.getRectangle())) {
bullet.die(); bullet.die();
tank.die(); tank.die();
} }
return false; //撞上就不再向下执行了
} else if (o1 instanceof Tank && o2 instanceof Bullet) { } else if (o1 instanceof Tank && o2 instanceof Bullet) {
collide(o2, o1); return collide(o2, o1);
} else { } else {
return; return true;
} }
} }
} }

@ -18,7 +18,7 @@ import com.msb.model.abstracts.GameObject;
*/ */
public class TankTankCollider implements Collider { public class TankTankCollider implements Collider {
@Override @Override
public void collide(GameObject o1, GameObject o2) { public boolean collide(GameObject o1, GameObject o2) {
if(o1 instanceof Tank && o2 instanceof Tank) { if(o1 instanceof Tank && o2 instanceof Tank) {
Tank tank1 = (Tank) o1; Tank tank1 = (Tank) o1;
Tank tank2 = (Tank) o2; Tank tank2 = (Tank) o2;
@ -26,8 +26,9 @@ public class TankTankCollider implements Collider {
tank1.goBack(); tank1.goBack();
tank2.goBack(); tank2.goBack();
} }
return true; //坦克与坦克相撞,坦克不会消失,所以责任链应该继续
} else { } else {
return; return true;
} }
} }
} }

Loading…
Cancel
Save