【发布时间】:2018-04-29 06:52:13
【问题描述】:
目前正在开发一个基本的 RPG 系统,但我遇到了一个方法错误。该方法旨在添加一个 item(代码中的类)和一个可选数量到玩家库存(一个 Item[] 数组)。
这是 item 类的代码:
public class Item
{
public string Name;
public int quantity;
public int maxstack;
public int[] stats = new int[5];
public Item(string name, int Amount = 1, int MaxStack = 10, int ATK = 0,
int DEF = 0, int MAT = 0, int MDF = 0, int SPD = 0)
{
Name = name;
quantity = Amount;
maxstack = MaxStack;
stats[0] = ATK;
stats[1] = DEF;
stats[2] = MAT;
stats[3] = MDF;
stats[4] = SPD;
}
}
关键变量是“数量”和“最大堆栈”。
现在,在将物品添加到玩家物品栏时,关于这些变量的问题出现了。 该方法在将物品添加到库存时,使用 Array.IndexOf();
搜索库存中的空槽和相同物品的任何堆栈这是 AddItem() 方法的代码:
public void AddItem(Item item, int Amount = 1)
{
for (int i = Amount; i > 0; i--)
{
int ItemIndex = Array.IndexOf(inv, item); // Searches for a matching item
int EmptySlot = Array.IndexOf(inv, null); // Searches for an empty slot
ItemCheck:
if (ItemIndex != -1) // ItemIndex will equal -1 if no matching item was found
{
if (inv[ItemIndex].quantity >= inv[ItemIndex].maxstack) // Is the quantity/stack of the found item equal to its maximum stackable value?
{
ItemIndex = Array.IndexOf(inv, item, ItemIndex + 1); // If yes, search for another index.
goto ItemCheck;
} else {
inv[ItemIndex].quantity++; // If the stack hasn't reached its max, increase it by one.
}
}
else
{
inv[EmptySlot] = item; // If no matching item was found, use an empty slot to create a new stack.
inv[EmptySlot].quantity = 1;
}
}
}
现在,假设我创建了一个名为“stick”的项目,它最多只能堆叠 3 个。当运行 AddItem(stick, 3) 并列出每个堆栈的数量时,控制台返回
Stick x1
Stick x1
谁能帮帮我?为什么我的代码将堆栈变回数量为 1?
编辑:
添加 1、2 或 3 根棍子会返回正确的数量,但只有在堆栈达到最大值后才添加更多棍子会引发错误的结果。
编辑:
添加 6 根棍子会返回 2 堆,每堆 3 件物品。添加 7 根棍子会返回 3 堆,每堆有 1 个物品。
【问题讨论】:
-
那么,什么是inv?
-
我会大胆猜测并说它可能不起作用,因为
Array.IndexOf在数组中找不到与您传递给函数的任何Item对象的值相等的项. -
盯着
goto......你知道SO人们希望我们对新人很好......但有时我觉得这很有挑战性:) -
@KeithNicholas 对于
goto导致不良代码流的原因,最好提供一个建设性的信息性理由;我们知道,但不是每个人都知道。 -
哦,我知道....我知道问题所在。
标签: c# visual-studio debugging