Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (527)
Games in Android Showcase (127)
games submitted by our members
Games in WIP (593)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Creating a Text Parser  (Read 1628 times)
0 Members and 1 Guest are viewing this topic.
Offline Gannin

Senior Newbie





« Posted 2006-03-02 22:43:04 »

Greetings everyone Smiley.  I'd like to create a simple text adventure game in Java.  I've done a lot of Java application programming, and I already have the GUI for the game set up, but I'm clueless about creating a text parser to interpret the typed commands.  Can anyone point me in the right direction?  Thanks Smiley.
Offline oNyx

JGO Coder


Medals: 2


pixels! :x


« Reply #1 - Posted 2006-03-02 22:54:04 »

There is StringTokenizer, String.split(1.5), Scanner (1.5)... and there is String.equalsIgnoreCase...

I think thats pretty much everything you need.

弾幕 ☆ @mahonnaiseblog
Offline Gannin

Senior Newbie





« Reply #2 - Posted 2006-03-02 23:01:11 »

So if you're programming for a 1.4.2 target, then basically you're left with StringTokenizer and a whole bunch of if statements?
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline oNyx

JGO Coder


Medals: 2


pixels! :x


« Reply #3 - Posted 2006-03-02 23:21:22 »

The first step is making a String array out of that other String.

You can do that for example with something like:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
String cmd="foo bar \"foo bar\" foo";
[...]
ArrayList commands = new ArrayList();
char[] chars = cmd.toCharArray();
boolean open = false;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
   if (chars[i] == '\"') {
      open = !open;
   } else if (chars[i] == ' ' && !open) {
      commands.add(sb.toString());
      sb = new StringBuffer();
   } else {
      sb.append(chars[i]);
   }
}
if (sb.length() > 0) {
   commands.add(sb.toString());
}

String[] pieces = new String[commands.size()];
commands.toArray(pieces);


The pieces array then contains "foo", "bar", "foo bar", "foo"... all whats left is looping over it (for example).

弾幕 ☆ @mahonnaiseblog
Offline cylab

JGO Ninja


Medals: 55



« Reply #4 - Posted 2006-03-03 00:04:42 »

You could use HashSets and HashMaps for interpretation. In a simple example theres just one Set with all known verbs and one Set with all known objects. Use StringTokenizer, String.toLower() and String.replaceAll() to create normalized tokens and test them against the verbs and objects to sort out unnecessary/unknown words. Now create a command-key in the form "<verb>/<object1>/<...>/<objectN>" and use this to look up a command object in a HashMap. Such a HashMap could look like this:

1  
2  
3  
4  
HashMap commands= new HashMap();
commands.put("open/door", new Command(){ execute(String[] args){ openDoor(); } });
commands.put("connect/camera/tv", new Command(){ execute(String[] args){ connectCameraToTV(); } });
// etc.


notice the parameter args to the execute function. In most cases you don't want to create an extra method for each combination of objects, so you can test for the HashMap key in a loop, starting with the longest key "<verb>/<object1>/<obect2>", test with one segment shorter, if you had no match: "<verb>/<object1>" and pass that <obect2> as a parameter. This way you can make somewhat generic commands that take additional tokens as parameters. Instead of a inline Command instance you could also use method names as strings and use the reflection class Method to execute these. This will create a more compact mapping, but I like the advantage of the compiler checking for typos when using inline objects.

You can extend the above in arbitrary ways like using two sets for level1 objects and level2 objects to define some sort of argument order (you will have to sort the possible token order in some way to reduce combinations) or adding other grammar types than verbs and objects like adverbs, conjunctions, etc. Also some more parameters (e.g. the current room) might make sense. This is just an example to get you thinking.

Essentially you are creating a syntax tree by specifying the keys in the described form. Abusing a "flat" HashMap is just the fastest approach to create such a mapping. it is not the fastest or best approach to process it.

To map the structure more appropriate, you could create a nested HashMap tree, where all branching nodes are HashMaps and each leaf is a Command object. This way, you do not have to append your tokens to a single string key, but use the first token (e.g. the verb) to query the root-level HashMap. If the result is a Command, call execute on it and pass the remaining tokens as parameters. If it is a HashMap, use the second token to query the next deeper Command or HashMap, etc.


Mathias - I Know What [you] Did Last Summer!
Offline Jeff

JGO Coder




Got any cats?


« Reply #5 - Posted 2006-03-03 00:10:52 »

If you have regexp, you can also "explode" a tring this way.

This particualr exploder will group anything between " "  as a single element though it doesnt
have logic for escaped quotes so you cannot otherwise use quotes...

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
        static final Pattern splitPattern = 
      Pattern.compile("(?:\"([^\"]*+)\")|(\\S+)");

   public static String[] explode(String text) {
      Matcher m = splitPattern.matcher(text);
      List<String> list = new ArrayList<String>();
      while (m.find()){  
         String tok = m.group(1);
         if (tok == null){
            tok = m.group(2);
         }
         list.add(tok);
      }
      String[] out = new String[list.size()];
      return list.toArray(out);
   }




Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Offline Gannin

Senior Newbie





« Reply #6 - Posted 2006-03-03 00:25:12 »

Thanks for all of the replies so far.  I see that String.split is actually part of 1.4, so it can still be used when you're developing for a 1.4.2 platform.

I'm going to have to study all of these replies I've received so far, and if anyone would like to, please feel free to continue to reply.  The more information the better.  Thanks Smiley.
Offline oNyx

JGO Coder


Medals: 2


pixels! :x


« Reply #7 - Posted 2006-03-03 02:49:26 »

>see that String.split is actually part of 1.4

Ooops... my bad. I actually wrote "1.4" first, but changed it to "1.5" for some reason.

弾幕 ☆ @mahonnaiseblog
Offline nonnus29

Senior Devvie




Giving Java a second chance after ludumdare fiasco


« Reply #8 - Posted 2006-03-04 01:34:12 »

Quote
I'm going to have to study all of these replies I've received so far, and if anyone would like to, please feel free to continue to reply.  The more information the better.

Tokenizing input and parsing tokens is part of what compilers do so you might research that area; finite state machines, regular expressions, context free grammars, BNF form, syntax trees.  I found this document to be very informative (it's about c/lex/yacc but it has good theory discussion):

http://epaperpress.com/lexandyacc/
Offline swpalmer

JGO Coder


Exp: 12 years


Where's the Kaboom?


« Reply #9 - Posted 2006-03-04 03:19:04 »

I think BNF is no good in this context.

For a text adventure you want a natural language parser.

Some resources linked here: http://web.syr.edu/~mdtaffet/nlp_sites.html

One that I've been wanting to port to Java is http://www.link.cs.cmu.edu/link/submit-sentence-4.html

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Jeff

JGO Coder




Got any cats?


« Reply #10 - Posted 2006-03-06 02:41:26 »

While BNF and RDPs are a very inetresting (and fun) topic I agree that here they are over-kill.

His syntax is not likely to be more complex then noun-verb, or noun-verb-indirect object at most.

Most MUDs use one for or another of regexp if they need anything more varied.


Got a question about Java and game programming?  Just new to the Java Game Development Community?  Try my FAQ.  Its likely you'll learn something!

http://wiki.java.net/bin/view/Games/JeffFAQ
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

PocketCrafter7 (12 views)
2014-11-28 16:25:35

PocketCrafter7 (7 views)
2014-11-28 16:25:09

PocketCrafter7 (8 views)
2014-11-28 16:24:29

toopeicgaming1999 (75 views)
2014-11-26 15:22:04

toopeicgaming1999 (65 views)
2014-11-26 15:20:36

toopeicgaming1999 (15 views)
2014-11-26 15:20:08

SHC (29 views)
2014-11-25 12:00:59

SHC (27 views)
2014-11-25 11:53:45

Norakomi (32 views)
2014-11-25 11:26:43

Gibbo3771 (28 views)
2014-11-24 19:59:16
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!