簡體   English   中英

如何比較列表中兩個類屬性的兩個數據?

[英]How to compare two datas from two class property in a list?

嘿伙計們,我正在創建一個提示游戲,需要一些幫助。 檢查玩家是否踩到地圖位置的最佳方法是什么? 這是我的課:

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);
    }   
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM