Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I want to build a generic rule parser for pen and paper style RPG systems. A rule can involve usually 1 to N entities 1 to N roles of a dice and calculating values based on multiple attributes of an entity.

For example:

Player has STR 18, his currently equipped weapon gives him a bonus of +1 STR but a malus of DEX -1. He attacks a monster entity and the game logic now is required to run a set of rules or actions:

Player rolls the dice, if he gets for example 8 or more (base attack value he needs to pass is one of his base attributes!) his attack is successfull. The monster then rolls the dice to calculate if the attack goes through it's armor. If yes the damage is taken if not the attack was blocked.

Besides simple math rules can also have constraints like applying only to a certain class of user (warrior vs wizard for example) or any other attribute. So this is not just limited to mathematical operations.

If you're familiar with RPG systems like Dungeon and Dragons you'll know what I'm up to.

My issue is now that I have no clue how to exactly build this the best possible way. I want people to be able to set up any kind of rule and later simply do an action like selecting a player and a monster and run an action (set of rules like an attack).

I'm asking less for help with the database side of things but more about how to come up with a structure and a parser for it to keep my rules flexible. The language of choice for this is php by the way.

Edit I:

Let me refine my goal: I want to create a user friendly interface (that does not require somebody to learn a programming language) to build more or less complex game rules. The simple reason: Personal use to not need to remember all the rules all the time, we simply do not play that often and it's a stopper to look them up each time. Also: Looks like a fun task to do and learn something. :)

What I've tried so far: Just thinking about a concept instead of wasting time building a wrong architecture. So far I have the idea to allow a user to create as many attributes as they want and then assign as many attributes as they want to any kind of entity. An entity can be a player, a monster, an item, anything. Now when calculating something the data is made available to the rule parser so that the rule parser should be able to do things like if Player.base_attack + dice(1x6) > Monster.armor_check then Monster.health - 1; The question here is about how to create that parser.

Edit II:

Here is an example of pretty basic value but to calculate it properly there are lots of different things and variables to take into account:

Base Attack Bonus (Term) Your base attack bonus (commonly referred to as BAB by the d20 community) is an attack roll bonus derived from character class and level. Base attack bonuses increase at different rates for different character classes. A character gains a second attack per round when his base attack bonus reaches +6, a third with a base attack bonus of +11 or higher, and a fourth with a base attack bonus of +16 or higher. Base attack bonuses gained from different classes, such as for a multiclass character, stack. A character’s base attack bonus does not grant any more attacks after reaching +16, cannot be less than +0, and does not increase due to class levels after character level reaches 20th. A minimum base attack bonus is required for certain feats.

You can read it here http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) including the links to classes and feats which have again their own rules to calculate the values that are required for the base attack.

I began to think that keeping it as generic as possible will also make it pretty hard to get a good rule parser done.

share|improve this question
3  
what have you tried so far? –  gnat Oct 22 '12 at 12:42
2  
I was actually thinking about exactly this type of problem this morning (not related to RPG, but rules processing engines) and trying to think of non-state machine approaches to rules processing and how combinatory parsers are so effective at completing a task usually done by state machines. I think there is a rich possibility for monadic combinators to approach most state machine problems more cleanly. That may sound like gibberish but I think there's something to this idea, just my 2 cents. RPG systems are a classic fun practice problem I like coding, perhaps I'll try this approach out. –  Jimmy Hoffa Oct 22 '12 at 15:43
1  
@jk. that article reminds me of a pattern I've liked for command line program argument parsing, using a dictionary of Funcs which initialize the program state based on the arguments as keys to the dictionary. Surprised I never found that post from Yegge before, very cool, thanks for pointing it out. –  Jimmy Hoffa Oct 22 '12 at 15:49
4  
I'm not really sure why this was closed as "not a real question". Its a higher level "whiteboard" question about how to architect an application that has a specific set of requirements (RPG rules system). I've voted to reopen it, but it will still need 4 other reopen votes to get reopened. –  Rachel Oct 22 '12 at 19:50
1  
Honestly I thought this site is exactly for this kind of conceptual questions while stackoverflow.com is thought for code / implementation problems. –  burzum Oct 23 '12 at 17:30

4 Answers 4

up vote 8 down vote accepted

What you’re asking for is essentially a domain-specific language—a small programming language for a narrow purpose, in this case defining P&P RPG rules. Designing a language is in principle not difficult, but there is a considerable amount of up-front knowledge that you must gain in order to be at all productive. Unfortunately, there is no central reference for this stuff—you’ve got to pick it up through trial, error, and lots of research.

First, find a set of primitive operations whereby other operations can be implemented. For example:

  • Get or set a property of the player, an NPC, or a monster

  • Get the result of a die roll

  • Evaluate arithmetic expressions

  • Evaluate conditional expressions

  • Perform conditional branching

Design a syntax that expresses your primitives. How will you represent numbers? What does a statement look like? Are statements semicolon-terminated? Newline-terminated? Is there block structure? How will you indicate it: through symbols or indentation? Are there variables? What constitutes a legal variable name? Are variables mutable? How will you access properties of objects? Are objects first-class? Can you create them yourself?

Write a parser that turns your program into an abstract syntax tree (AST). Learn about parsing statements with a recursive descent parser. Learn about how parsing arithmetic expressions with recursive descent is annoying, and a top-down operator precedence parser (Pratt parser) can make your life easier and your code shorter.

Write an interpreter that evaluates your AST. It can simply read each node in the tree and do what it says: a = b becomes new Assignment("a", "b") becomes vars["a"] = vars["b"];. If it makes your life easier, convert the AST into a simpler form before evaluation.

I recommend designing the simplest thing that will work and remain readable. Here’s an example of what a language might look like. Your design will necessarily differ based on your specific needs and preferences.

ATK = D20
if ATK >= player.ATK
    DEF = D20
    if DEF < monster.DEF
        monster.HP -= ATK
        if monster.HP < 0
            monster.ALIVE = 0
        end
    end
end

Alternatively, learn how to embed an existing scripting language such as Python or Lua into your application, and use that. The downside of using a general-purpose language for a domain-specific task is that the abstraction is leaky: all the features and gotchas of the language are still present. The upside is you don’t have to implement it yourself—and that is a significant upside. Consider it.

share|improve this answer
2  
Not a bad approach but I'm consistently skeptical of DSL's, they're a lot of work to get right (especially if you're talking about a true DSL with custom syntax and all, as opposed to just some fluent API which people have started calling "DSL"s), so you better be sure you're going to use the heck out of it, if you are then it's worth it. Often times I think people want to attempt a DSL where they're only going to use it for a small rules engine. Here's my rule of thumb: If the DSL implementation + usage is less code than no DSL, go for it, I don't think that would be so in this case. –  Jimmy Hoffa Oct 22 '12 at 16:39
    
@JimmyHoffa: Fair enough. It’s just in my nature to reach for language-based solutions, especially for games. I probably underestimate the difficulty of making something small and functional because I’ve done it many times. Still, it seems like an appropriate recommendation in this case. –  Jon Purdy Oct 22 '12 at 17:03
    
I guess I should say it is the right approach to this sort of problem, but that's predicated on the person doing the implementation being someone with sufficient skill. For learning, DSL's are great for juniors, but for actual releasable product I would never want to see anyone below senior level writing a DSL, and for a junior a DSL solveable problem should be solved in a different way. –  Jimmy Hoffa Oct 22 '12 at 17:58
    
After reading this I think I could simply eval lua scripts for that. The downside here would be that a user has to be capable of writing lua scripts. My personal goal is to write an interface that can be used without programming knowledge, like the rule builder in magento (ecommerce app). Because I want people to be able to add their own rules. I'm not implementing anything commercial, just a tool to let me and my friends enter the rules of RPG system we play on an irregular base and getting back to the rules and to apply them is a pain after some time... –  burzum Oct 23 '12 at 17:26
    
@burzum: What about having your interface generate the lua scripts? –  TMN Oct 23 '12 at 21:04

I would start by determining the different "Phases" of each action.

For example, a Combat Phase might involve:

GetPlayerCombatStats();
GetEnemyCombatStats();
GetDiceRoll();
CalculateDamage();

Each of these methods would have access to some fairly generic objects, such as the Player and the Monster, and would perform some fairly generic checks that other entities can use to modify the values.

For example, you might have something that looks like this included in your GetPlayerCombatStats() method:

GetPlayerCombatStats()
{
    Stats tempStats = player.BaseStats;

    player.GetCombatStats(player, monster, tempStats);

    foreach(var item in Player.EquippedItems)
        item.GetCombatStats(player, monster, tempStats);
}

This allows you to easily add in any entity with specific rules, such as a Player Class, monster, or Equipment piece.

As another example, suppose you wanted a Sword of Slaying Everything Except Squid, which that gives you +4 against everything, unless that thing has tentacles, in which case you have to drop your sword and get a -10 in the combat.

Your equipment class for this sword might have an GetCombatStats that looks something like this:

GetCombatStats(Player player, Monster monster, Stats tmpStats)
{
    if (monster.Type == MonsterTypes.Tentacled)
    {
        player.Equipment.Drop(this);
        tmpStats.Attack -= 10;
    }
    else
    {
        tmpStats.Attack += 4;
    }
}

This allows you to easily modify the combat values without needing to know about the rest of the combat logic, and it allows you to easily add new pieces to the application because the details and implementation logic of your Equipment (or whatever entity it is) only need to exist in the entity class itself.

The key things to figure out is at what points can values change, and what elements influence those values. Once you have those, building out your individual components should be easy :)

share|improve this answer
    
That's the way to go. In most Pen&Paper RPGs, there are phases in calculations, that is generally written in guidebooks. You can also put the ordering of stage in an ordered list to make it more generic. –  Hakan Deryal Oct 22 '12 at 23:25
    
This sounds pretty static to me and does not allow an user to simply enter/build the required rules in an UI? What you describe sounds more like hardcoded rules. This should be also doable by having a list of nested rules. I do not want to hardcode any rules. If I could do everything in code I would not need to ask that question, that would be easy. :) –  burzum Oct 23 '12 at 18:25
    
@burzum Yes this means the rules would be defined by the code, however it makes it very extensible from the code. For example, if you wanted to add a new Class type, or a new Equipement piece, or a new Monster type, you just need to build the class objects for that entity and fill in the appropriate methods in your class with your logic. –  Rachel Oct 23 '12 at 19:31
    
@burzum I just read the edit to your question. If you want a rules engine only for UI use, I would consider making a pool of entities (Player, Monster, Dice, etc), and setting up something that allows users to drag/drop entity pieces into an "equation" area, filling in parameters of the entity (such as filling in player.base_attack), and specify simple operators as to how the pieces fit together. I actually have a something posted on my blog that parses a mathematical equation that you may be able to use. –  Rachel Oct 23 '12 at 19:36
    
@Rachel what you describe is dead easy OOP, there even many examples out in the wild that use RPG like stuff as examples to teach OOP. Having these objects and work with them is the easy part, I could build them on the fly based on data from the database. The issue in your approach are the hardcorded rules like GetEnemyCombatStats() whatever this method does would need to be defined somewhere via an UI and stored in a db. Your article seems to be similar to that github.com/bobthecow/Ruler or that github.com/Trismegiste/PhpRules. –  burzum Oct 25 '12 at 8:19

I'd take a look at maptool specifically Rumble's 4th ed framework. It's the best system I've seen for setting up what you're talking about. Unfortunately the best is still horribly crufty. Their "macro" system has... let's say... evolved over time.

As for a "rules parser" I'd just stick with whatever programming language you're comfortable with, even if that's PHP. There's not going to be any good way around encoding all the rules of your system.

Now, if you want your users to be able to write THEIR OWN ruleset, then you're looking at implementing your own scripting language. Users script their own high-level actions, your php interprets that into something that actually affect database values, and then it throws a bunch of errors because it's a horribly crufty system that's been shoe-horned into place over the years. Really, Jon Purdy's answer is right on the ball.

share|improve this answer

I think that you need to be able to be able to think abstractly about what things are going to be in your problem space, come up with some sort of model and then base your DSL on that.

For example you might have the entities entity, action and event at the top level. Die rolls would be events that occur as a result of actions. Actions would have conditions that determine whether they are available in a given situation and a "script" of things that occur when the action is taken. More complex things would be the ability to define a sequence of phases where different actions can occur.

Once you have some sort of conceptual model (and I suggest you write it down and/or draw diagrams to represent it) you can start to look at different means of implementing it.

One route is to define what is called an external DSL where you define your syntax and use a tool such as antlr to parse it and call your logic. Another route is to use the facilities present in a programming language to define your DSL. Languages such as Groovy and Ruby are particularly good in this space.

One trap you need to avoid is mixing your display logic with your implemented game model. I would vote to have the display read your model and display appropriately rather than mixing your display code intermixed with your model.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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