3
\$\begingroup\$

I'm building a game in C++ (using SDL) for a college project, I'm trying to figure out how to script events that happens when a player does something, or some time passes etc.

I have a and idea of how to do it but I don't want to go against how it's commonly done.


Right now I have a class called Obj from where enemies, items and the player are child classes, my idea is to add 3 public variables to it like this:

class Obj{
    int eventDeath,eventTouch,eventTalk,eventMeet;
}

Then I could create an Obj with eventDeath=1 and when it died it would fire event(1). event() would be something like this:

void event(int n){
   switch(n){
   case 1: 
      dialog("I'm dying");
      break;   
   }
}

I could also add invisible "Obj" in specific places for when a player walks over a certain place. I don't know if this is a good idea but I can't think of other means to do it. How is it commonly done? Also how do I keep track of events that already happened?

\$\endgroup\$
  • \$\begingroup\$ What you are looking for are event handlers, which often take the form of Functors in C++. Google Functors, and evaluate their use for your project. You may also be able to get away with function pointers or member function pointers, depending on your needs. \$\endgroup\$ – PlayDeezGames Oct 7 '13 at 18:39
2
\$\begingroup\$

Then I'd recommend creating a new class for each type of message (with a common Message base), since different messages will typically need different bits of data in them. You can then use over-loading of methods to make delivery of events simple and easy. Something like:

// messages.h
class Object;

struct IMessage {
  virtual void dispatch(Object& obj) const = 0;
};

struct DeathMessage : public IMessage {
  void dispatch(Object& obj) const;
};

/* more messages */

// object.h
#include "messages.h"

class Object {
public:
  virtual void onDeath(const DeathMessage&) { }
  /* other handles here */

  void onMessage(const IMessage& msg) { msg.dispatch(*this); }

// messages.cpp
#include "messages.h"

void DeathMessage::dispatch(Object& obj) {
  obj.onDeath(*this);
}

Now your Object subclasses can override onDeath or onCreate or onDamage or whatever as desired. Different messages can have additional data, e.g DamageMessage can include how much damage was caused, what type of damage, who the source of the damage is, etc.

So far as making events trigger once, just add a boolean to the class. The first time you process the message, set it to true. Ignore repeats if it's not false.

You can generalize the system further once you have more experience with the language and programming concepts.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.