19

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.

smci
  • 139
  • 10
floriank
  • 471
  • 2
  • 16
  • perhaps http://steve-yegge.blogspot.co.uk/2008/10/universal-design-pattern.html – jk. Oct 22 '12 at 11:54
  • Do you want some sort of user interface to enter these rules or did you consider using some scripting language? WoW for example uses Lua: http://www.wowwiki.com/Lua – sebastiangeiger Oct 22 '12 at 13:17
  • What about creating something like public events that get run at each interval, and let any entity attach to these events and run some code. For example with your attack, run a `BeforeAttack` event that the equipment and character class can hook into and update the values before the actual rolls occur. Or a `BeforeRoll` event that occurs before any dice roll that allows any dice roll modifiers to hook into. – Rachel Oct 22 '12 at 13:30
  • 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 `Func`s 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
  • 5
    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
  • @Rachel - now it needs just one more reopen vote. I agree that this should be reopened. At first I wasn't certain there was a solid answer to this. However, I like the countering answers provided so far. Your approach and the DSL route are good approaches that have different benefits to them. –  Oct 22 '12 at 21:18
  • 3
    Honestly I thought this site is exactly for this kind of conceptual questions while stackoverflow.com is thought for code / implementation problems. – floriank Oct 23 '12 at 17:30
  • @burzum You are correct, that is what this site is _currently_ about. Programmers.SE is in a 3 (or more) way tug-of-war on what it's supposed to be about, because of how the focus has changed since it was created... – Izkata Oct 23 '12 at 20:59
  • Tell us the most challenging examples of *"class-specific constraints (warrior vs wizard for example)"*. It won't be just about modying base stats, it'll be about special or forbidden types of actions, etc. Anyway, this is super-broad but will affect your decomposition into (software) classes, subclasses, attributes, methods, inheritance etc. – smci Jul 01 '23 at 22:01

4 Answers4

11

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.

Jon Purdy
  • 20,437
  • 7
  • 63
  • 95
  • 5
    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
  • 1
    @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... – floriank Oct 23 '12 at 17:26
  • 1
    @burzum: What about having your interface generate the lua scripts? – TMN Oct 23 '12 at 21:04
  • It would be easier to save the generated form data serialized and run the parser on that in the language the app is using instead of using another language. But with lua I could - in theory - set vars to lua, eval that script with my set vars and type cast the result, it might be safe this way. – floriank Oct 24 '12 at 01:16
4

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 :)

Rachel
  • 23,979
  • 16
  • 91
  • 159
  • 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. :) – floriank 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](http://rachel53461.wordpress.com/tag/math-converter/) 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 https://github.com/bobthecow/Ruler or that https://github.com/Trismegiste/PhpRules. – floriank Oct 25 '12 at 08:19
  • @burzum In the previous comment, I was thinking more like a drag/drop calculator that had entities instead of numbers, and you would be responsible for entering entity parameters through the UI. Maybe include some common formulas templates too, such as the standard attack formula. Its hard to know if that will actually work or not without knowing the exact rules of your game though. :) – Rachel Oct 25 '12 at 11:34
  • Check this out http://www.dandwiki.com/wiki/Base_Attack_Bonus_(Term) but the idea is to be able to implement different rule sets for different game systems. I think I'll need something that describes the game system and then a parser that will understand the game system and its rules and a parser that will run the game actions based on that ruleset. – floriank Oct 25 '12 at 15:28
  • @burzum Your link says "There is currently no text in this page. You can search for this page title in other pages, search the related logs, or edit this page" :) That's fine though, I was only trying to give a general idea of how it could be done, not actually figure out how to implement all the details (that's your responsibility) :) – Rachel Oct 25 '12 at 15:34
  • The reason for this is that programmers.se does not auto link the url properly, the link is misssing the ). – floriank Oct 27 '12 at 17:00
1

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.

Philip
  • 6,742
  • 27
  • 43
0

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.

Peter Kelley
  • 101
  • 2