Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Don't forget to read Tuesday's email newsletter for your chance to win a free copy of Construct 2!


Am I over engineering? A generalized Game Action framework


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
10 replies to this topic

#1 fourvector   Members   -  Reputation: 120

Like
0Likes
Like

Posted 16 May 2012 - 03:03 PM

I'm writing a roguelike in Java, using an entity-component architecture I put together. I want to develop a framework for defining game actions that entities can take, and can be taken on, for instance "pick up", "attack", "eat" etc.

My design followed from the premise that the definition of every action can be thought of as a triplet consisting of a subject, verb, and object. So for instance, Hand - pick up - item. So I defined three interfaces:
Action
,
CanAct<type extends Action>
,
CanBeActedUpon<type extends Action>
.
Then what I would do would be to define a new action class, such as
Class PickUp implements Action{
	 PickUp(CanPickUp, CanBePickedUp){..}
}
, with two interfaces
CanPickUp extends CanAct<PickUp>
and
CanBePickedUp extends CanBeActedUpon<PickUp>

The idea was that with this framework I could assign different components different CanAct interfaces, and then if an entity lost the component, for instance your hands are cut off, they would lose the ability to take actions, unless of course they had other components which also performed those actions. In addition, I could create menus of possible actions on the fly, since all I'd have to do was take the main entity, compile a list of all it's possible actions (for component in entity, if component instanceof CanAct, component.getType()), then look at it's surroundings for other entities with components that have CanBeActedUpon of that type. Meanwhile the action would provide it's own name, so the menu code could be completely oblivious.

The problem is that Java won't allow an object to inherit two interfaces from the same base interface. So for instance, if I add Hands, I want them to be able to PickUp, Equip, Attack, and Open. CanPickUp extends CanAct<PickUp>,CanEquip extends CanAct<Equip>. My Hands object can't implement both.

Additionally, it gets very messy for some reason. Because everything that handles these actions has to be type agnostic, I end up doing a lot of strange typecasting that I don't fully understand. For example:

public static CanAct<?> canActor(GameObject g, Class<? extends Action> actionType){
  for(Part p : g.allParts){
   if(p instanceof CanAct<?>){
	CanAct<?> CA=(CanAct<?>)p;
	if(CA.actionType()==actionType){
	 return CA;
	}
   }
  }
  return null;
}

Where for this code I should point out that both the CanAct and CanBeActedUpon interface have the function actionType() which returns a Class<? extends Action>, and then CanPickUp for instance would return PickUp.class . I haven't been able to figure out how to do this in a more elegant way... Not to mention having to iterate through all the parts in the Entity.


I suppose my question is, does anyone have any suggestions for me? Am I over engineering my problem? Is there an easier approach? Is there a pattern I've not tried here? Or am I on the right track, and if so, what is my work around for implementing two of the same interfaces with different types?

Sponsor:

#2 ApochPiQ   Moderators   -  Reputation: 16069

Like
3Likes
Like

Posted 16 May 2012 - 03:22 PM

This feels to me like the kind of thing you should implement as data, not code structure.

Build a list of nouns and verbs, then a list of "valid phrases" - noun/verb/object triplets, as you described. All this can be done with a couple of containers easily enough.

Then have your game objects hold a tag as to what noun they are. Do a simple search through the phrase list to build up lists of valid pairings, and you're all set.

#3 6510   Members   -  Reputation: 151

Like
0Likes
Like

Posted 17 May 2012 - 12:56 AM

The problem is that Java won't allow an object to inherit two interfaces from the same base interface.

That is very well possible - if I understand correctly what you mean.

The approach seems weird to me.
Using instanceof is sometimes a valid shortcut to working code, but using it in the first place is an indicator of something's going on wrong.
Does an action know what it can do ? The actor should know about it. Then, there is also a backwards dependency from Can* to Action.
It is hard to understand - which is a sign to redesign.

#4 fourvector   Members   -  Reputation: 120

Like
0Likes
Like

Posted 17 May 2012 - 02:48 AM

ApochPiQ
I considered implementing it as data, but I wanted different CanAct and CanBeActedUpon objects to be able to modify the Action. So for instance this is PickUp:

public class PickUp implements Action{

CanPickUp subject;
CanBePickedUp object;

public PickUp(CanPickUp subject,CanBePickedUp object){
  this.object=object;
  this.subject=subject;
}

public void Act(){
  //iff the subject can pickup
  if(subject.isInReach(object) && subject.add(object)){
   //remove the object from the region
   object.removeFromWorld();
  }
}


public String getName(){
  return "Pick Up "+object.getGameObject().name;
}
}

With the CanPickUp and CanBePickedUp interfaces having the functions implied here. Now different components can implement these interfaces in different ways. For instance a land mine, when it is "removeFromWorld()" might, in addition to leaving the world, also do a test to see if it explodes, or something to that effect. In general it makes sense to me that different nouns should modify the action. With a data implementation, I'd have to construct some kind of huge case structure to account for different functionality.

6510
Is using instanceof expensive, or is it just considered bad form? To me it seems like the right thing to do. I use it frequently for my event distribution system to my components, since it seems more type safe than having some kind of string as an ID, which could be tricked, for instance, I could send a RegionChanged event, any component listening for RegionChanged events would check the type and respond in the right way.

#5 6510   Members   -  Reputation: 151

Like
0Likes
Like

Posted 17 May 2012 - 03:00 AM

Is using instanceof expensive, or is it just considered bad form? To me it seems like the right thing to do. I use it frequently for my event distribution system to my components, since it seems more type safe than having some kind of string as an ID, which could be tricked, for instance, I could send a RegionChanged event, any component listening for RegionChanged events would check the type and respond in the right way.

Good or bad... it is a warning indicator of incomplete OOP design, of lacking polymorphism, most probably if used frequently.
When dealing with various kind of events, you would rather have different event handler implementations as well.

#6 ApochPiQ   Moderators   -  Reputation: 16069

Like
0Likes
Like

Posted 17 May 2012 - 05:32 AM

With a data implementation, I'd have to construct some kind of huge case structure to account for different functionality.


Isn't that exactly the kind of structure you're going to wind up creating with this approach?


In my proposal, you implement your verbs as code, and everything else as data. You still get the ability to do things like your "pick up" example, you just eliminate a lot of boilerplate for all the nouns.

All actions derive from a base interface, which has a single method: Act. Act accepts two Noun parameters, a subject and an object. So you get something like this:

if(Phrases.CanUsePhrase(SomeVerbTag, SomeSubject.GetNoun(), SomeObject.GetNoun()))
{
    Verbs.Get(SomeVerbTag).Act(SomeSubject, SomeObject);
}
else
{
    ShowUIMessage("I'm sorry Dave, I'm afraid I can't let you do that.");
}

// Elsewhere, we implement a verb, such as Pick Up:
void Act(Noun subject, Noun object)
{
    if(subject.CanReach(object))
    {
        if(subject.Add(object))
        {
            World.Remove(object);
            ShowUIMessage("You got the " + object.GetName());
        }
    }
    else
    {
        ShowUIMessage("Almost... there...");
    }
}


#7 fourvector   Members   -  Reputation: 120

Like
0Likes
Like

Posted 17 May 2012 - 06:48 AM

ApochPiQ,

Perhaps I am confused about what you mean by data. Data wouldn't have any functionality besides getters and setters and such. I would imagine here that the noun data would just be an enum, : {CanPickUp, CanBePickedUp, etc...}. But then in the example you've given, we have a function like subject.CanReach(object). How are these functions defined? Additionally, does every Noun need to have a CanReach(object) function, shouldn't only the ones that CanPickUp? I appreciate your help, I just feel like I must not be understanding something that you're trying to say.

#8 ApochPiQ   Moderators   -  Reputation: 16069

Like
5Likes
Like

Posted 17 May 2012 - 10:34 AM

There's a middle ground here that it seems like you might be overlooking; on one extreme you have code for everything ("hard coding") where everything is specifically accomplished by some piece of code. This is actually the road you're headed down with your design, even though it may not seem like it just yet. The other extreme is "logic-less" for lack of a better word; where all you have is data values but they don't do anything interesting.

Neither extreme is healthy.

What you want is to create a generalized "Noun" class that handles all the different logic that nouns can have in your game; they have a "tag" (such as "hands" or "sword"), they have a location in the world or some container, they have the ability to interact with other nouns (provided the right Phrase exists to permit that) and so on.

There's two things to keep in mind here. One is that you don't want to hard-code everything in your logic, which is what my initial suggestion was meant to help with. The other, separate factor (which you've now touched on) is that you have more than just "nouns" - you have different kinds of nouns.

You have a couple of options here, but the best thing I would suggest would be to have a really basic stripped-down "Noun" class which holds references to "Capability" objects. There are two kinds of capabilities: CanBeSubjectOfVerb and CanBeObjectOfVerb. Both of these things should be data-driven, i.e. you don't have code that says "oh, this is a FooCapability, therefore it can work with these nouns blah blah blah." Instead, you simply maintain a list (which you can load from a file or whatever, doesn't matter) which indicates the capabilities that each noun in the world can have. A verb then lists the capabilities that it involves.

Then the example becomes a little more generalized. Inside of the CanUsePhrase implementation, you look at the verb provided and what capabilities it expects. Then you check those capabilities with each noun, seeing if they fit the CanBeSubjectOfVerb and CanBeObjectOfVerb slots. If everything passes, you return true; otherwise you return false. Then, as in the example code above, you invoke the verb itself.

This time, though, it'd look more like this:

// For each capability attached to the verb:
if(capability.CanPerformNow(subject, object))
    capability.Perform(subject, object);

Now you have a PickUp capability. Hands nouns have the PickUp capability listed in their CanBeSubjectOfVerb list. Swords have PickUp listed in their CanBeObjectOfVerb list. So far all we've done is look at data: what lists have what members? And the data indicates we can proceed.

Note that there isn't a Verb class anymore; there's no need! Verbs are entirely data now, i.e. they exist only in the sense that Phrases has a list of what verbs are allowed, and Nouns tell you what verbs they can interact with as subject and object.

So we've looked at our data and it says we can PickUp a Sword using our Hands. Now it's time to get to the actual logic/code part. Here's where you implement the PickUp capability as a class. PickUp simply looks like this:

bool CanPerformNow(Noun rawsubject, Noun rawobject)
{
    ContainerCapability subject = (ContainerCapability)rawsubject.GetCapability(CAPABILITY_CONTAINER);
    ItemCapability object = (ItemCapability)rawobject.GetCapability(CAPABILITY_ITEM);

    // Safety check; you might want to log an error, throw
    // an exception, or whatever else, to alert you as the
    // programmer to the fact that your data check allowed
    // this verb/noun combo through when it shouldn't.
    if(subject == null || object == null)
        return false;

    // Note that if you like you can replace this constant
    // with a member data variable in the Capability, that
    // tells you how far *this* instance of the Capability
    // can "reach." In this way, you can implement several
    // different "ranges" without needing more code.
    if(subject.Position().DistanceTo(object.Position()) > MAX_PICKUP_DISTANCE)
        return false;


    if(!subject.CanFit(object))
        return false;

    return true;
}

void Perform(Noun rawsubject, Noun rawobject)
{
    ContainerCapability subject = (ContainerCapability)rawsubject.GetCapability(CAPABILITY_CONTAINER);
    ItemCapability object = (ItemCapability)rawobject.GetCapability(CAPABILITY_ITEM);

    object.GetContainer().RemoveItem(object);
    subject.AddItem(object);    
}


I'm leaving out a lot of details of course, but that should hopefully illustrate the basic principles.

#9 fourvector   Members   -  Reputation: 120

Like
0Likes
Like

Posted 19 May 2012 - 09:11 AM

I'm still mulling over and playing with what you've said, ApochPiQ. I believe I understand and agree with what you've said about Data: turn CanPickUp into a piece of data instead of an interface, and you can move it around and use its functionality in a more versatile way.

I also like the idea of having Nouns as being a fundamental sort of object for storing these pieces of Data, because it closely mirrors the Entity-Component architecture.

I'm a bit confused about the distinction between a capability and a verb. It seems to me that in defining a capability, what you're really doing is implicitly defining a verb. This is how I understand what you're saying:

A capability has a perform() function, in which it does the thing which it is capable of doing, and a canPerform() function, in which it determines if it can do the thing it is capable of doing. In your example you include three capabilities:
PickUp, ContainerCapability, and ItemCapability.
In addition to their perform() and canPerform() functions, ContainerCapability and ItemCapability also have functions which are related to our understanding of how Containers and Items operate, such as Container.canFit(Item) or Item.getContainer(). I'll call functions of this type "the meat", they are what make the actual game behave in a specific fashion, as opposed to the bones, which is the scaffolding, like perform(). So capabilities hold the meat. This makes sense to me. After the meat has been defined in the capabilities, you can then construct a phrase list, with verbs being the linking up of two different capabilities. This linking defines the verb itself.

I attempted to implement this structure, but got stuck at what exactly the Container.perform() function should do. It seems as though the functionality of this function had been preempted by the PickUp.perform() function. It seems to me that Container.perform() should do what PickUp.perform() does, namely, cause an item to be contained by it. Here is where I realized that Container, in this scheme, implicitly defines a verb, namely "contain", through its perform() function. I would assume then that Item.perform() would do the exact same thing as Container.perform(), only maybe in a sort of converse way. We could really rename container and item to CanContain and CanBeContained, and the perform function on both of them does the same thing.

This implies that when we make our list of acceptable phrases, there's a natural verb that should be defined, namely contain, with the acceptable triplet being
[CanContain contain CanBeContained]

Which, when executed, does this: CanContain.perform(CanContain, CanBeContained), or CanBeContained.perform(CanContain, CanBeContained).

I suppose I'm stuck at this point. How might I define other verbs in my phrase list besides the natural verb implied by the perform() function? For instance, it makes sense that I should be able to remove an item from a container. But no combination of perform() calls from the two capabilities would implement that functionality. Do I create a CanRemove capability, with a perform() function that deals with the CanContain and CanBeContained capabilities, in a similar way to how the PickUp capability did before I subsumed it into my CanContain (Container) and CanBeContained (item) capabilities. Isn't this verging too closely on precisely what I was doing before?

I don't mean to be difficult, but I feel like I'm running around in circles in my head.


As an aside, I've been giving some thought to the kinds of functions I'd like to call on a general subject-verb-object structure. There are three groups:
Group A
boolean CanVerbNow(verb, subject, object);
boolean CanBeVerbedNow(verb, object, subject);
void do(verb, subject, object);
Group B
boolean CanVerb(verb, subject);
booean CanBeVerbed(verb,object);
Group C
set<Noun> getVerbed(verb, subject);
set<Noun> getVerbedBy(verb, object);
boolean isVerbed(verb, object);
boolean isVerbedBy(verb, subject)

Group A contains the meat, these are the functions that actually care about what the verb DOES

Group B only really care about what the verb does on a conceptual design level, but not on an actual functional programming level. They guarantee that the noun does these things, but they don't care what these things are.

Group C don't care at all what the verb does, but instead only care about semantic relationships. I've realized group C are actually questions about the topology of a directed graph, where nodes are nouns, and verbs are edges. I think it's a very interesting observation with bearing on how I should engineer my code.

A little bit of googling indicates that this problem is being though about, but maybe not much for game programming: http://en.wikipedia.org/wiki/Semantic_network

#10 ApochPiQ   Moderators   -  Reputation: 16069

Like
0Likes
Like

Posted 19 May 2012 - 01:44 PM

Consider: there is no such thing as "remove."

There is "take item from container A and put it in container B." That's it. A and B might be very different sorts of container (a dungeon floor and a backpack, for instance) but that's the only relationship you ever need to express: take it from one, put it in another.


Beyond that... I would encourage you to limit your noun/verb thinking to only things the player or AI can do. Supplemental stuff like spawning creatures, consuming items from your inventory, etc. should be hard-coded game logic. Otherwise you end up needing conditional clauses, or prepositional phrases ("consume Wand of Summoning from Backpack") or whatever else, and sooner or later you're on the road to implementing semantic networks and such which is massive overkill for a roguelike.


I respect that you want to engineer something generic, robust, and so forth, but be cautioned that this is a slippery slope. Premature generalization is a serious design sin. Design something that does what you need it to do, not something that does everything under the sun. Not all of your implementation detail has to be perfectly generalized and elegant and reusable and whatever else; as long as your one-off hard-coded stuff is genuinely one-off and not systematically duplicated all over the code base, you should be fine.

#11 fourvector   Members   -  Reputation: 120

Like
0Likes
Like

Posted 12 June 2012 - 07:44 AM

Hi ApochPiQ. I've taken your very last piece of advice and decided to do away with a generalized action framework. I've realized it's more important to write a specific piece of code to handle picking things up than a framework for doing EVERYTHING. At least for now, maybe when I've written some specific pieces of code for different actions I might more easily be able to recognize a common theme among the various actions.

Edited by fourvector, 12 June 2012 - 11:29 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS