我的目标是开发一个功能,允许我在简单的JS / HTML5游戏的上下文中在任意两个项目集合之间交换任何项目。
逻辑如下所示,变量是硬编码的,而不是定义为函数参数。
function InventoryToWarehouse(draggedItemID) {
var howMany = prompt("How many items do you want to store in the warehouse?",0);
if(Game.heroInventory.hasItem(draggedItemID,howMany)) {
Game.heroInventory.removeItem(draggedItemID,howMany, "inventory");
Game.warehouse.addItem(draggedItemID,howMany,"warehouse");
} else { alert("Not enough items in the inventory!");
}
该功能利用库存管理系统中的三个较小功能:hasItem,addItem和removeItem。代码如下:
Inventory = function(){
var self = {
items:[] //{id:"itemId",quantity:1}
}
self.addItem = function(id,quantity,whereToRender){
for(var i = 0 ; i < self.items.length; i++){
if(self.items[i].id === id){
self.items[i].quantity += quantity;
self.refreshRender(whereToRender);
return;
}
}
self.items.push({id:id,quantity:quantity});
self.refreshRender(whereToRender);
}
self.removeItem = function(id,quantity,whereToRender){
for(var i = 0 ; i < self.items.length; i++){
if(self.items[i].id === id){
self.items[i].quantity -= quantity;
if(self.items[i].quantity <= 0)
self.items.splice(i,1);
self.refreshRender(whereToRender);
return;
}
}
}
self.hasItem = function(id,quantity){
for(var i = 0 ; i < self.items.length; i++){
if(self.items[i].id === id){
return self.items[i].quantity >= quantity;
}
}
return false;
}
self.refreshRender = function(whereToRender){
var str = "";
for(var i = 0 ; i < self.items.length; i++){
let item = Item.List[self.items[i].id];
let onclick = "Item.List['" + item.id + "'].event()";
str += "<button onclick=\"" + onclick + "\">" + item.name + " x" + self.items[i].quantity + "</button><br>";
}
if(whereToRender=="inventory"){document.getElementById("inventory").innerHTML = str;}
}
return self;
}
他们的库存管理功能只要对其执行的对象进行硬编码就完美地工作 - 就像上面的InventoryToWarehouse()一样。
有没有办法创建InventoryToWarehouse()函数的更通用/可自定义的版本?一个,其参数决定哪个项目集合应该发生交换?
我尝试了以下方法 - 但它无效:
function exchangeItemsBetweenCollections(collectionGiving, collectionReceiving) {
var howMany = prompt("How many items do you want to store in the warehouse?",0);
if(collectionGiving.hasItem(draggedItemID,howMany)) {
collectionGiving.removeItem(draggedItemID,howMany, "inventory");
collectionReceiving.addItem(draggedItemID,howMany,"warehouse");
} else {alert("Not enough items in the inventory!")}
}
我一直收到的错误是: collectionGiving.hasItem不是函数。 请有人关心: