施工期间如何交换对象信息?

时间:2018-07-07 10:39:28

标签: javascript object

作为一个学习javascript的项目,我正在做一个小型游戏。在这个游戏中有资源和机器。购买机器需要花费一种或多种资源,并且每台机器都会产生一种或多种资源。机器也可以有输入(例如能量)来保持生产。

由于资源和机器如何相互缠绕,我不确定如何在它们之间交换信息。为了计算每个资源的秒数,我不想遍历所有机器以检查其输出是否包含该资源。我宁愿以仅检查产生此资源的机器的方式构造对象。

我想到了一种方法,方法是让Machine构造函数在其输出对象中循环,然后将其名称推送到资源对象中的数组。但是以某种方式,这感觉更像是黑客,而不是可靠的解决方案。除此之外,我还想提出一种解决方案,使尚未解决的游戏机制可以轻松,动态地应用新机器,(临时)生产提升或折扣。可以按资源,按机器或所有资源/机器进行提升和折扣的地方。

下面是我当前为资源和机器定义对象的方式。

请问您有什么建议或提示吗?

Game.objectConstructor.Resource = function(id, name) {

    var instance = {};
    instance.id = id;
    instance.name = name;
    instance.category = 'resource';

    var private = {};
    private.production = {
        perSecond: function() {
            // Go over all machines producing id and calculate
        },
        current: 0,
        update: function() {
            var now = new Date().getTime();
            // Cap current storage by the maximum storage we have.
            private.production.current = Math.min(private.perSecond()/1000*(now-private.lastUpdate), private.storage.current());
        },
        lastUpdate: new Date().getTime(),
    },
    private.storage = {
        level: 1,
        baseCapacity: 50,
        discount: 0.00,
        upgradeCost: function() {
            var result = {};
            result[private.name] = private.storage.current()*(1-private.storage.discount);
            result['somethingelse'] = private.storage.current()*0.25*(1-private.storage.discount);
            return result;
        },
        current: function() {return Math.pow(private.storage.baseCapacity, private.storage.level);}
    }

    this.perSecond = function() {
        return private.production.perSecond();
    }

    return instance;
};

Game.materials.entries.metal = new Game.objectConstructor.Resource('metal', 'Metal');

Game.objectConstructor.Machine = function(id, name, cost, input, output) {

    var instance = {};
    instance.id = id;
    instance.name = name;
    instance.category = 'machine';

    var private = {};
    private.cost = cost;
    private.input = input;
    private.output = output;

    this.isAffordable = function() {
        if (Object.keys(private.cost).every(c => (c.current - cost[c]) > 0)) {
            return true;
        }
        return false;
    }

    return instance;
}
Game.machines.entries.metalGrinder = new Game.objectConstructor.Machine('grinder', 'Grinder', {metal: 10}, {}, {metal: 1})

0 个答案:

没有答案
相关问题