Sir Maxwell Sir Maxwell - 1 year ago 75
C# Question

Adding elements(text, events) based on player location

I'm creating a framework for my personal use, which allows me to create environments, entities, items etc...
Now, I wanna be able to retrieve the location that I just created and do something with it. Like a said location must have that types of monsters, there might be a blacksmith to help me forge new weapons, and since it's a text-based game, I wanna link some text to those locations.

I've got a list that's populated in a World class like so:

Environment.Environments.Add(new Environment("Dark Forest", "A very dark... very frightening place...", true, true));

Here's the big bad code:

class Environment
public string Name { get; private set; }
public string Description { get; private set; }
public bool ContainsItems { get; set; }
public bool ContainsEntities { get; set; }
public static List<Environment> Environments = new List<Environment>();

public Environment(string name, string description, bool containsItems, bool containEntities)
Name = name;
Description = description;
ContainsItems = containsItems;
ContainsEntities = containEntities;

public void SetLocation()
Console.ForegroundColor = ConsoleColor.Cyan;
DisplayText("You arrived at {0}", Name);

if (ContainsItems)
Console.ForegroundColor = ConsoleColor.Yellow;
DisplayText("If you look carefully, you might find something valuable!");
Console.ForegroundColor = ConsoleColor.Red;
DisplayText("Proceed with caution, some monsters hides here!");
Console.ForegroundColor = ConsoleColor.White;

I tried different things, like adding events that are linked to one of my command "Look", but I'm not sure if it's the right tool for my needs and I must say, I never used events till now! So if you were to implement something like this, how would you go about it?!

Answer Source

I would create a grid system with locations. Give an x/y coordinate, with collections of details (Items and Creatures (don't use "entity" it has its own meaning)).

public class Environment
   public List<Location> Locations {set; get;}
   public Location CurrentLocation {get; set;}
   public Environment()
       Locations = new List<Locations> {...} //set up Locations in a grid
       public Location Move(string direction)
        //check to see if there is a location in the direction the user wants to move
        //if so, load the new Location into CurrentLocation. If not, throw an exception

public class Location
   public List<Item> Items {set; get;}
   public List<Item> Creatures {set; get;}
   public int X {get; set;} 
   public int Y {get; set;}
   public void OnLoaded()
       //here is where you check if there are items, or creatures, etc, simply by counting the list...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download