c# - 如何比较列表中两个类属性的两个数据?
问题描述
嘿伙计们,我正在创建一个即时游戏,需要一些帮助。检查玩家是否踩到地图位置的最佳方法是什么?这是我的课:
class MapInfo
{
public int PosX { get; set; }
public int PosY { get; set; }
public int Terrain { get; set; }
}
class PlayerInfo
{
public int PosX { get; set; }
public int PosY { get; set; }
}
- 玩家走了,我得到了 X 和 Y 的位置。
- 如果在我生成一个地形信息之前从未踩过 X 和 Y 位置(比如有一个箱子,只有沙子或怪物)。
- 如果玩家之前曾沉浸在该地图位置,我会加载保存的数据信息。
做这个的最好方式是什么?我尝试为 KnownPlaces 创建一个列表,但是如果我尝试执行 foreach 并比较从玩家位置到地图位置的值,我不知道如何只搜索一次相等的值。
解决方案
根据我对您的问题的理解;2个类,其中一个用于查询另一个的历史,这是您需要做的。
高层总结:
您需要有一个存储位置信息的类 ( MapInfo
)。这些位置的过去记录需要存储在某个地方 ( KnownPlaces
)。然后您需要记录您当前的位置 ( PlayerInfo
),并使用它来查询已知地点列表。如果没有匹配,您将需要创建并存储新记录。
在我的示例中,我为您提供了所有这些类的框架。但是,何时添加新位置、何时查询它们等等的逻辑取决于您。因为你是游戏的创造者。
class MapInfo
{
public int PosX { get; set; }
public int PosY { get; set; }
public int Terrain { get; set; }
public bool alreadyVisited { get; set; }
// Anything else you want to record
// … …
}
class PlayerInfo
{
public int currentPosX { get; set; }
public int currentPosY { get; set; }
public MapInfo currentMapInfo { get; set; }
public void getCurrentMapInfo()
{
currentMapInfo = KnownPlaces.GetMapInfo(currentPosX, currentPosY);
}
}
public class KnownPlaces
{
public static List<MapInfo> AllKnownPlaces = new List<MapInfo>();
public static MapInfo GetMapInfo(int posX, int posY)
{
MapInfo place = KnownPlaces.AllKnownPlaces.FirstOrDefault(n => n.PosX == posX && n.PosY == posY);
return place;
}
Public static void CreateNewMapInfo(int posX, int posY, //… other stuff you want to record)
{
MapInfo newMapInfo = new MapInfo();
newMapInfo.PosX = posX;
newMapInfo.PosY = posY;
// Anything else that you want to record.
KnownPlaces.AllKnownPlaces.Add(newMapInfo);
}
}
推荐阅读
- docker - docker 图像标签的含义:'onbuild'、'jessie'、'stretch'
- angular - 安装 npm 依赖项时出错:在 '...ories":{},"dist":{"in' 附近解析时 JSON 输入意外结束
- linear-programming - 收到错误 - Minizinc 建模语言上的“数量超出限制”
- laravel - 如何从之前填充的数组中填充空值?
- r - 每个 data.table 行与另一个 data.table 行的相关性
- php - I want customize Output from hasMany() in my API
- c - How to create an array literal of struct literals in C?
- vue.js - FileReader method does not update data property (vue.js)
- angular - Angular Material 日期选择器输入将日期视为美国格式
- php - 删除远程用户的会话 - 在 PHP 中远程注销 - Codeigniter