Help on implementing how creatures and items interact in a computer role playing game

c#, class-design

Solution

This is a "double dispatch" problem. In regular OO programming, you "dispatch" the operation of a virtual method call to the concrete type of the class implementing the object instance you call against. A client doesn't need to know the actual implementation type, it is simply making a method call against an abstract type description. That's "single dispatch".

Most OO languages don't implement anything but single-dispatch. Double-dispatch is when the operation that needs to be called depends on two different objects. The standard mechanism for implementing double dispatch in OO languages without direct double-dispatch support is the "Visitor" design pattern. See the link for how to use this pattern.

Problem

I am programming a simple role playing game (to learn and for fun) and I'm at the point where I'm trying to come up with a way for game objects to interact with each other. There are two things I am trying to avoid. - Creating a gigantic game object that can be anything and do everything - Complexity - so I am staying away from a component based design like you see here So with those parameters in mind I need advice on a good way for game objects to perform actions on each other. For example - Creatures (Characters, Monsters, NPCs) can perform actions on Creatures or Items (weapons, potions, traps, doors) - Items can perform actions on Creatures or Items as well. An example would be a trap going off when a character tries to open a chest What I've come up with is a `PerformAction` method that can take Creatures or Items as parameters. Like this ``` PerformAction(Creature sourceC, Item sourceI, Creature targetC, Item targetI) // this will usually end up with 2 null params since // only 1 source and 1 target will be valid ``` Or should I do this instead? ``` PerformAction(Object source, Object target) // cast to correct types and continue ``` Or is there a completely different way I should be thinking about this?

Original source

Related problems