javascript - 如何根据填充数组动态填充值数组?

标签 javascript arrays

我已经研究这个问题有一段时间了,所以我决定从 nodejs 转向 jsfiddle,看看你们是否可以提供一些启发。

代码如下:

 inventory = [ // 50 Slot inventory 10 HORIZONTAL / 5 SLOTS VERTICAL
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0
 ]
 items = {
    "1": {
        name: "Short Sword",
        slot_position: 5,
        slot_size: [1, 3]
    },
    "2": {
        name: "Heavy Leather Boots",
        slot_position: 1,
        slot_size: [2, 2]
    },
    "3": {
        name: "Potion 1",
        slot_position: 26,
        slot_size: [1, 1]
    }
 }

 for (i in items) {
    inventory[items[i].slot_position] = 1; // Fill in the used inventory slots to 1 (The easy part)

    if (items[i].slot_size) {
        if (items[i].slot_size[0] > 1) {
            /*
            The X slot_size has to be greater than '1' because we already filled in their current positon.
            Now I need to fill in the inventory slots based on their item_slot_size [X,Y] values... (I'm              stuck here)
            */



        }
    }


 }

 console.log(inventory);
 console.log(inventory.length); // 50 is correct.

还有 jsfiddle:http://jsfiddle.net/68w1w0s8/8/

在第 42 行,我被困在这里,因为我需要根据商品 slot_size 尺寸将库存中的插槽动态填充到 1

例如,短剑的 slot_size 为 [1,3](向下 3 个方 block ),那么我如何在我的 库存中动态填写适当的值 数组?

如何使用我的 slot_size 数组的示例最好通过我的图表来查看:enter image description here

最佳答案

首先,您的库存应该是一个矩阵(集合的集合)

 inventory = [ // 50 Slot inventory 10 HORIZONTAL / 5 SLOTS VERTICAL (HARDCODE) 
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 ]

然后您可以使用您的插槽大小进行迭代。此外,插槽位置应存储在坐标中:

 items = {
    "1": {
        name: "Short Sword",
        slot_position: [5,0],
        slot_size: [1, 3]
    },
    "2": {
        name: "Heavy Leather Boots",
        slot_position: [1,0],
        slot_size: [2, 2]
    },
    "3": {
        name: "Potion 1",
        slot_position: [6,2],
        slot_size: [1, 1]
    }
 }

 for (i in items) {
    var item = items[i];
    if (item.slot_size) {
            for (var x = 0; x < item.slot_size[0]; x++) {
                for (y = 0; y < item.slot_size[1]; y++) { 
                     inventory[y+item.slot_position[1]][x+item.slot_position[0]] = item;               
            }
        }
    }
 }

JSfiddle

关于javascript - 如何根据填充数组动态填充值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30419825/

相关文章:

javascript - div 的背景不透明度而不影响所有子项

javascript - 如何将我的 HTML 表单提交与我的 JavaScript 表单更新分开?

php - 根据表jquery中的数据填充多维数组

C: scanf() 接受的参数多于应有的参数

c# - 将 OnClick 事件附加到现有 JavaScript 按钮

javascript - 单击按钮时放置和删除背景颜色

java - 为什么java中的double if语句返回数组中的空搜索

apache-flex - AS3 中的多维向量

c# - 如何以只读方式传递字节数组?

javascript - 尝试通过将鼠标悬停在一个 div 上来向多个 div 添加类