Jump to content
  • Advertisement
Sign in to follow this  
TheTroll

Parsing a string

This topic is 4561 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am trying to figure out the best way to parse a string that I use to roll dice in a RPG. Anyone who plays will know what I am talking about. ie. d4, 2d8, 4d6+6 and 2(d20+2)+6. Any suggestions would be helpful. Thanks. theTroll

Share this post


Link to post
Share on other sites
Advertisement
You haven't mentioned what programming language you want to use. I recently did something similar in Prolog which was loads of fun.

Anyway, the basics are the following:
  • You need to define the basic terms of which your string is comprised. Judging by the content, these will either be a die string or a number.

  • Afterwards, implement a recursive method which will build a binary tree out of your string. The tree's nodes will be composite terms, which are defined as any valid expression built from basic terms. The tree's leaves must be basic terms.

  • Each parent node will define an operation on his children. In this case, either addition or multiplication

  • Evaluation of the expression in the root will involve traversing the tree


EDIT: The above just might be overkill.

Share this post


Link to post
Share on other sites
The die and the multiplier are pretty easy. The biggest problem I am having is figuring out the parenthesis, a single parenthesis is pretty easy but once I get into multiples then it starts getting complicated.

theTroll

Share this post


Link to post
Share on other sites
I would build a tree out of it.

Ex: 2(d20+2)+6


ADD
/ \
MULT 6
/ \
2 ADD
/ \
d20 2




Then build the result from the bottom up.

Share this post


Link to post
Share on other sites
Regular expressions and compiler theory. There's plenty of tools that generate those for you. Lex/Yacc, Bison, and I simply forgot the other alternatives right now.

My personal tool of choice is Lex/Yacc combo, since I never had problems finding it's port to any language/platform I used.

In addition, I prefer to let them generate the optimal syntax/parse tree, then I hand-code the state machine for minimum clutter. A typical state machine for parsing this will be under 100 lines of code.

And since you mentioned C#, look at this: http://fisheye1.cenqua.com/viewrep/~raw,r=1.4/d20sharp/d20Sharp/Dice.cs

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!