根据OOP设计,最佳的RPG编码实践是什么?

时间:2019-09-25 17:35:33

标签: java oop

我正在做一个RPG游戏,有一个Player和一个Equipment班。我应该在mountEquipment()类中实现Player方法,还是类似

public class Player {
    private ArrayList<Equipment> equipments;

    public void mountEquipment(Equipment e){
        // how can i know what attributes
        // Equipment will change in Player?
        equipments.add(e);
    }
}

或者我应该在Equipment类中实现,该类将是

public class Equipment {

    public void mountEquipment(Player p){
        // here i can access all Player attributes
        p.addStrength(50);
        p.addHP(100);
        p.addEquipment(this);
    }
}

访问Player类中定义mountEquipment的{​​{1}}属性比较容易,但是我认为在Equipment类中使用mountEquipment更有意义很难更改Player属性。例如,Player可以改变力量,Sword可以改变力量和运气。

在这种情况下,我应该在哪里实现此类?

1 个答案:

答案 0 :(得分:1)

在简单的情况下,玩家的数据基本上只是其基本数据+装备数据的总和。

似乎是共享界面的机会:

public interface StatProvider {
    int health();

    int intellect();
}

public class Ring implements StatProvider {
    @Override
    public int health() {
        return 0;
    }

    @Override
    public int intellect() {
        return 5;
    }
}

public class Mage implements StatProvider {

    private final int baseHealth = 100;
    private final int baseIntellect = 20;

    private List<StatProvider> equipment;

    @Override
    public int health() {
        return baseHealth + equipment.stream().mapToInt(StatProvider::health).sum();
    }

    @Override
    public int intellect() {
        return baseIntellect + equipment.stream().mapToInt(StatProvider::intellect).sum();
    }
}

也许也可以与装饰器模式配合使用

public class HealthDoublingEnchantment implements StatProvider {
    private final StatProvider delegate;

    public HealthDoublingEnchantment(StatProvider delegate) {
        this.delegate = delegate;
    }

    @Override
    public int health() {
        return delegate.health() * 2;
    }

    @Override
    public int intellect() {
        return delegate.intellect();
    }
}

例如

new HealthDoublingEnchantment(new Ring());