简体   繁体   中英

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

Hey guys I'm creating a prompt game and need some help. What is the best way to check if a player have stepped on a map position? Here is my class:

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; }
}
  • The player walks and I got the X and Y position.
  • If the X and Y position are never stepped before I generate one terrain info (Like if have a chest, only sand or a monster).
  • If the player had steeped in that map position before, I load the saved data info.

What is the best way to do this? I tried creating a list to KnownPlaces but if I try do a foreach and compare the values from player position to map position I dont know how to search only the equal value one time.

Based on my understanding of your problem; 2 classes where one is used to query the history of the other, here is what you would need to do.

High level summary:

You need to have one class that stores location information ( MapInfo ). Past records of theses locations need to be stored somewhere ( KnownPlaces ). You then need to record your current position ( PlayerInfo ), and use it to query the list of known places. If there is no match, you will need to create and store the new record.

In my example I give you the framework for all these classes. But the logic for when to add new locations, when to query them, and so on, are up to you. Since you are the game creator.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM