0

I am working on a game in C#.

I have a list of events, that can happen. E.g

List<Event> _events = new List<Event>(); _events.Add(new Event("A goblin approaches", 2)); _events.Add(new Event("A gang of thieves approaches", 3)); _events.Add(new Event("Some money has been stolen", 3)); _events.Add(new Event("Three goblins approach", 4)); _events.Add(new Event("A guard dies of unknown causes",4));

The string in the Event constructor is the event name and the number is the difficulty.

I was wondering if I could also add code into the constructor that can be run later on if the event is called. I'd like different code in each event.

Something like

_events.Add(new Event("Some money has been stolen", 3, "Supply.Gold = Supply.Gold -50")); _events[2].runcode

I hope this makes sense, thanks

3
  • Why you can't dispatch fired event and execute your code from dispatcher? Or subclass Event and add virtual DoGood() method which will perform appropriate action? Commented Apr 7, 2015 at 12:45
  • @deeptowncitizen how can I pass a function into a constructor? Commented Apr 7, 2015 at 12:51
  • You can use delegates. Watch for C# Action Commented Apr 7, 2015 at 12:53

1 Answer 1

1

With this approach you can create events with simple implementation. And also difficult events with a lot of code (by extending Event class).

public class EventContext
{
    public int Gold { get; set; }
}

public interface IEvent
{
    void Do(EventContext context);
}

public abstract class Event : IEvent
{
    protected Event(string title, int difficulty)
    {
        Title = title;
        Difficulty = difficulty;
    }

    public string Title { get; private set; }
    public int Difficulty { get; private set; }


    public abstract void Do(EventContext context);
}

public class SimpleEvent : Event
{
    private readonly Action<EventContext> _callback;

    public SimpleEvent(string title, int difficulty, Action<EventContext> callback)
        : base(title, difficulty)
    {
        _callback = callback;
    }

    public override void Do(EventContext context)
    {
        _callback(context);
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        var gameContext = new EventContext {Gold = 100};
        var events = new List<IEvent>();
        events.Add(new SimpleEvent("Some money has been stolen", 3, context => context.Gold -= 10));

        events.First().Do(gameContext);
    }
}

But I believe it can be better to separate event type and event handler.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your time and help. I have not used actions before. I will definitely have a read up. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.