473,387 Members | 3,787 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

[Possibly OT] How to handle text parsing functions?

In my program I am accepting messages over the network and parsing them. I
find that the function that does this has gotten quite big, and so want to
break the if else code into functions. I started thinking of how to do
this, but came up with a number of ways and don't know what would be best,
and fit into the C++ idoism.

This is what I have now:

if ( ThisPlayer.Character.GMLevel == 100 && ( StrMessage == "/debugserver"
|| StrMessage == "/DEBUGSERVER" ) )
DebugMode = ! DebugMode;

else if ( StrMessage == "/list" || StrMessage == "/LIST" )
{
// lots of cod here
}

else if ( ThisPlayer.Character.GMLevel >= 50 && ( StrMessage.compare( 0, 8,
"/summon " ) == 0 || StrMessage.compare( 0, 8, "/SUMMON " ) == 0 ) )
{
// lots of code here
}

else if ( ThisPlayer.Character.GMLevel >= 50 && ( StrMessage.compare( 0, 8,
"/jumpto " ) == 0 || StrMessage.compare( 0, 8, "/JUMPTO " ) == 0 ) )
{
// lots of code here
}

etc.. There are actually 30 different else if's. As you can imagine, the
code is quite huge. The simplest thing would to take each // lots of code
here and make them functions and call them. But then I was thinking I could
just pass the GMLevel and StrMessage to the functions themselves. Then I
started thinking about maybe having some type of custom map type container
with the criteria (keyword and GMLevel) and a pointer to the function,
etc...

Over time this is just going to grow. This is the main text processing for
my online game and commands will only get added, not removed over time.

I can think of having a structure/class with Minimim GMLevel, keyword,
pointer to function call. There shouldn't be too much of a problem with
having to pass parameters to the class because of the game system constrains
I have a global structure that I can access what I need anyway.

What would be your suggestion?
Sep 25 '06 #1
4 1888
In a possible solution I am looking at this (something I just took 10
minutes to wrote but haven't tested yet). Any comments?

typedef bool (*CmdFuncPointer)( CPlayer& ThisPlayer, const std::string&
Message );

class CChatCommand
{
public:
unsigned int GMLevel; // minimum GMLevel
std::string Command; // Command string that calls (I.E. /kick)
CmdFuncPointer CmdFunc; // Command to process

CChatCommand( const unsigned int GMLevel, const std::string& Command,
const CmdFuncPointer CmdFunc ):
GMLevel( GMLevel ), Command( Command ), CmdFunc( CmdFunc ) {}
};

class CProcessChatMessage
{
public:
void AddCommand( const unsigned int GMLevel, const std::string& Command,
CmdFuncPointer CmdFunc )
{
Commands.push_back( CChatCommand( GMLevel, Command, CmdFunc ) );
}
bool ProcessMessage( CPlayer& ThisPlayer, const std::string& Message )
{
for ( std::vector<CChatCommand>::iterator it = Commands.begin(); it
!= Commands.end(); ++it )
{
if ( Message.compare( 0, (*it).Command.length(), (*it).Command )
== 0 &&
( (*it).Command[(*it).Command.length() - 1 ] != ' ' ||
Message.length() == (*it).Command.length() ) &&
ThisPlayer.Character.GMLevel >= (*it).GMLevel )
{
(*(*it).CmdFunc)( ThisPlayer, Message );
return true;
}
}
return false;
}
private:
std::vector<CChatCommandCommands;
};
Sep 25 '06 #2
Jim Langston <ta*******@rocketmail.comwrote:
In my program I am accepting messages over the network and parsing them. I
find that the function that does this has gotten quite big, and so want to
break the if else code into functions. I started thinking of how to do
this, but came up with a number of ways and don't know what would be best,
and fit into the C++ idoism.
This may not work for you since you are receiving the messages over the
network and they appear to be plain strings, but IMO the "idiomatic" way
to do it would be to have a "Command" base class with a virtual
"execute()" method or somesuch, and each specific command would be
derived from the Command base class. I believe there is a design
pattern for this.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
Sep 25 '06 #3

"Marcus Kwok" <ri******@gehennom.invalidwrote in message
news:ef**********@news-int2.gatech.edu...
Jim Langston <ta*******@rocketmail.comwrote:
In my program I am accepting messages over the network and parsing them.
I
find that the function that does this has gotten quite big, and so want
to
break the if else code into functions. I started thinking of how to do
this, but came up with a number of ways and don't know what would be
best,
and fit into the C++ idoism.

This may not work for you since you are receiving the messages over the
network and they appear to be plain strings, but IMO the "idiomatic" way
to do it would be to have a "Command" base class with a virtual
"execute()" method or somesuch, and each specific command would be
derived from the Command base class. I believe there is a design
pattern for this.

--
Marcus Kwok
Replace 'invalid' with 'net' to reply
You might want to look at the chain of command design pattern.

Each of you possibilities would be modelled as a separate subclass of a
common base class. You would register instances of these
classes to handle the messages. When a message arrives, you would iterate
through each of the instances
calling a virual function such as "execute()" . If the object handles that
message, it would process the message, then
return true, otherwise false, and you'd try the next object in the sequence.
You should check that you need to
continue processing after each "execute()" call .

The benefit of this approach is each object is simple and self contained.
Adding new messages is also very easy,
and the behavior can be dynamic, ie, messages handlers can be added or
removed as the situation requires.


Sep 26 '06 #4
In article <le**************@newsfe02.lga>, ta*******@rocketmail.com
says...
In my program I am accepting messages over the network and parsing them. I
find that the function that does this has gotten quite big, and so want to
break the if else code into functions. I started thinking of how to do
this, but came up with a number of ways and don't know what would be best,
and fit into the C++ idoism.
[ ... ]
Over time this is just going to grow. This is the main text processing for
my online game and commands will only get added, not removed over time.

I can think of having a structure/class with Minimim GMLevel, keyword,
pointer to function call. There shouldn't be too much of a problem with
having to pass parameters to the class because of the game system constrains
I have a global structure that I can access what I need anyway.

What would be your suggestion?
A couple of minor suggestions: first of all, instead of making the block
of code functions, I'd probably make them class objects. They give you
more flexibility in the long run. You might not need it now, but the
penalty is low (a couple extra lines of code for each) and in the long
run the flexibility is likely to pay off. For simplicity, I'd probably
derive them all from a fairly simple base class.

Second, instead of making the framework directly aware of the GMLevel,
I'd probably have each of those functors include a "check" function or
something like that, that could look at a player object to determine
whether the player can carry out that action. Make it a virtual
function, and have the base class version simply check whether the
player's GMLevel is high enough -- but someday, when you decide an
action requires GMLevel X _and_ the player to be carrying object Y (or
whatever) it'll be easy to handle. Again, the penalty now is minimal,
and the long-term payoff is potentially fairly high.

You also mentioned using a custom map type -- nothing you've said
convinces me that you need anything std::map doesn't provide. The
keyword is the key for your map, and the value type will be a pointer to
the "action" object. From what you've said so far, the base class would
look something like this:

class player;

class action {
int req_GMLevel;
public:
virtual bool check(player const &p) {
return p->GMLevel>= req_GMLevel;
}
virtual void exec() = 0;
}

From there your framework looks something like this:

// Do a case-insensitive comparison to avoid repeating comparisons,
// as well as allowing, e.g., "/List" along with "/list" and "/LIST"
//
struct cmp {
// Q&D case-insensitive comparison: convert a copy of each
// string to upper case, and compare those copies:
//
bool operator()(std::string a, std::string b) {
std::transform(a.begin(), a.end(), a.begin(), std::toupper);
std::transform(b.begin(), b.end(), a.begin(), std::toupper);
std::string::size_type len = b.size();
return a.compare(0, len, b) == 1;
}
};

// We'll be using this a couple of times and don't want to re-type it:
typedef std::map<std::string, action *, cmpactions_map;

// The actual map from command names to actions:
actions_map actions;

// Create our actual actions. Each must override execute().
// Each can override check() if more complex criteria ever arise
// for qualifying a player to carry out a particular action:
class lister : public action { /* ... */ } list;
class summoner: public action { /* ... */ } summon;
class jumper : public action { /* .. .*/ } jump;
// 27 more action classes here...

// Set up the map from commands to actions:
actions["/list"] = &list;
actions["/summon"] = &summon;
actions["/jumpto"] = &jump;
// 27 more command/action pairs here...

// Execute a command from the user:
//
// look the command up in the map
actions_map::iterator it = actions.find(strMessage);

// if it wasn't found, tell the user:
if (actions.end() == it)
std::cerr<<"Sorry, I don't understand: \""<< strMessage<<"\"\n";
// it was found; check whether the player can do that
else if (it->second.check(player)))
// and if so, do it.
it->second.execute();
else
// otherwise, tell them they can't.
std::cerr << "Sorry, you can't do that\n";

--
Later,
Jerry.

The universe is a figment of its own imagination.
Sep 27 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Rohit | last post by:
Hi, Threads in the .NET Framework 1.1 (and possibly in 1.0 also) leak "Event" handles, by Event handles I mean Win32 Event handles which can be monitored using the ProcessExplorer from...
2
by: Indiana Epilepsy and Child Neurology | last post by:
Before asking this questions I've spent literally _years_ reading (Meyer, Stroustrup, Holub), googling, asking more general design questions, and just plain thinking about it. I am truly unable to...
9
by: bobo | last post by:
Hi, I have table wich looks like that id detail 1 value1=15,value2=345,value3=2 2 value1=1523,value2=32,value3=2322 3 value1=2,value2=45,value3=34 How can I change it to this: ...
4
by: atv | last post by:
Whatis the proper way to handle errors from function calls? For example, i normally have a main function, with calls to mine or c functions. Should i check for errors in the functions called...
4
by: Hugh | last post by:
Hello, I am having some problems understanding (most likely), parsing a text file. I would like to parse a file like: block1 { stuff; ... stuffN; };
3
by: Richard | last post by:
I have a requirement to put a GDI style circle or rectangle border around the selected row of a datagrid/ It will overlap into the row above and below the selected row. Doing this in a the OnPaint...
6
by: Jacob Rael | last post by:
Hello, I have a simple script to parse a text file (a visual basic program) and convert key parts to tcl. Since I am only working on specific sections and I need it quick, I decided not to...
3
by: toton | last post by:
Hi, I have some ascii files, which are having some formatted text. I want to read some section only from the total file. For that what I am doing is indexing the sections (denoted by .START in...
13
by: charliefortune | last post by:
I am fetching some product feeds with PHP like this $merch = substr($key,1); $feed = file_get_contents($_POST); $fp = fopen("./feeds/feed".$merch.".txt","w+"); fwrite ($fp,$feed); fclose...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.