道具合成

设计理念

我们的目标是设计一个直观的制作系统,以玩家背包中的物品作为输入原材料,制造产生新的物品。
制作系统的核心是一个简单的“配方,即需要特定数量的背包中的物品来制作一个物品。我们的实现涉及几个关键组件:

原材料

假设玩家收集的物品存储在背包中。每个物品都有一系列的属性,比如名称、数量、附加属性等。
对于一个简单的合成系统,这里我们只关注物品名称和数量,即有哪些东西,有多少。

制作规则

即配方,它说明了多少个什么东西,能合成多少个什么新东西,它需要包含的信息有:

  • 所需物品列表及其数量。
  • 制作完成后给予的新物品数量。

制作过程

即制作物品,需要干些什么,主要有以下这些步骤:

  1. 验证是否可以制作物品: 检查用来合成的原材料物品是否存在以及库存是否有足够。
  2. 消耗资源: 从背包库存中扣除所需数量的物品。
  3. 创建新物品: 将制作的物品添加回背包。

一个可用的代码片段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
let itemsInBag = []
var craftingRules = {
    plant: {
        requires: [
            { name: "flower", qty: 3 },
            { name: "wood", qty: 4 }
        ],
        gives: 1 // Quantity of new item produced
    }
};
function calculateItemsQtyInBag(){
    let result = {}
    for(var item in itemsInBag){
        result[item.id] = item.hold;
    }    
    return result;
}

function make(){
    let itemHold = calculateItemsQtyInBag();
   
}

function craftItem(itemName) {
    if (craftingRules.hasOwnProperty(itemName)) {
        var recipe = craftingRules[itemName];

        // Check if all required items are in inventory in sufficient quantities
        var canCraft = recipe.requires.every(function(requirement) {
            var item = inventory.find(function(item) {
                return item.name === requirement.name;
            });

            return item && item.qty >= requirement.qty;
        });

        if (canCraft) {
            // Deduct required items from inventory
            recipe.requires.forEach(function(requirement) {
                var item = inventory.find(function(item) {
                    return item.name === requirement.name;
                });

                if (item) {
                    item.qty -= requirement.qty;
                }
            });

            // Add new item to inventory
            var existingItem = inventory.find(function(item) {
                return item.name === itemName;
            });

            if (existingItem) {
                existingItem.qty += recipe.gives;
            } else {
                inventory.push({ id: new Date().getTime(), name: itemName, qty: recipe.gives });
            }

            console.log(itemName + " crafted successfully!");
            return true;
        } else {
            console.log("Not enough resources to craft " + itemName);
            return false;
        }
    } else {
        console.log("No such item exists to craft");
        return false;
    }
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

扫一扫,分享到微信

微信分享二维码

请我喝杯咖啡吧

微信