在前文中 如何设计一个背包系统的数据结构 我们已经定义了详细的背包数据逻辑,下面我们需要描述背包会是怎么工作的.
背包控制器
我们需要实现一个背包控制器来完成增删改查,并且存储数据。
实现背包储存
我们使用一个 readonly 的 Dictionary 来存储数据 key 是背包的 Name
public class BagController
{
public readonly Dictionary<string, Bag> Bags = new();
}
实现新增背包
下面我们要实现一个新增背包的功能,为了防止空,我们这边将所有的 BagItem 按照空初始化并循环设置到 bag.Items 里面即可。
private Bag CreateBag(int columnCount, int rowCount)
{
var items = new BagItem[columnCount, rowCount];
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < rowCount; j++)
{
items[i, j] = new BagItem();
}
}
return new Bag
{
Items = items,
ColumnCount = columnCount,
RowCount = rowCount,
};
}
注意 CreateBag 我们使用的是 private 因为不希望对外直接暴露,我们需要实现一个 AddBag 来对外并做一些简单的检测工作。
public void AddBag(string name, int columnCount, int rowCount)
{
if (Bags.ContainsKey(name))
{
GD.Print($"Bag {name} already exists.");
return;
}
var bag = CreateBag(columnCount, rowCount);
Bags.Add(name, bag);
}
查找物品
首先我们需要一个通过 ItemName 查找物品的 方法,这个在后面实现添加空物品和交换到其他背包时可能会更容易使用一点
private BagItem FindItemInBag(Bag bag, string itemName)
{
// 将二维数组转换为一维可迭代集合
var items = bag.Items.Cast<BagItem>();
// 使用LINQ查询来找到第一个匹配的项
return items.FirstOrDefault(item => item.Name == itemName);
}
private BagItem FindEmptySlotInBag(Bag bag)
{
var items = bag.Items.Cast<BagItem>();
return items.FirstOrDefault(item => item.IsEmpty);
}
获取某个指定的物品
一般而言在渲染物品时,我们需要去获取 BagItem 随后渲染到页面上,这个时候实现一个 GetBagItem 方法是一个不错的选项:
public BagItem GetBagItem(string name, int x, int y)
{
if (Bags.TryGetValue(name, out var bag))
{
return bag.Items[x, y];
}
return null;
}
删除背包
删除背包应该不是一个常用的操作,不过也一并补充了。
public void RemoveBag(string name)
{
if (Bags.ContainsKey(name))
{
Bags.Remove(name);
}
}
这样我们就实现了所有的背包处理逻辑,下面只需要把背包的处理逻辑和视图绑定即可。
本文标题:如何设计一个背包的控制逻辑
永久链接:https://iceprosurface.com/godot/bag-system/controller/
作者授权:本文由 icepro 原创编译并授权刊载发布。
版权声明:本文使用「署名-非商业性使用-相同方式共享 4.0 国际」创作共享协议,转载或使用请遵守署名协议。