0

I have a java game that I have been working on for a while, and now I would like to revamp my debugging system.

At this moment you press the Tilde key and then type in a range of commands: Heal, Ammo, etc. I later added a spawn command for the zombie enemy. The command is as follows. ~spawn.zombie.100(x-coord).100(y-coord). The following code runs which splits the command into parameters for spawning.

        public void cheat(String code) {
    String[] tokens = code.substring(1).toLowerCase().split("\\.");
    switch (tokens[0]) {
    case "spawn":
        switch (tokens[1]) {
        case "zombie":
            game.cubes.add(new EnemyZombie(game, Integer
                    .parseInt(tokens[2]), Integer.parseInt(tokens[2])));
            break;
        case "health":
            game.cubes.add(new PowerUpHealth(game, Integer
                    .parseInt(tokens[2]), Integer.parseInt(tokens[2])));
            break;
        }
        break;
    default:
        break;
    }

    game.start();
}

How could I implement a syntax similar to that of Java? I would like to be able to type zombie.spawn().setX(100).setY(100).setHealth(1) and have those parameters passed.

piechesse
  • 39
  • 1
  • 7
  • Just use Java. And then use an existing tool for it. See something like [BeanShell](http://www.beanshell.org/intro.html) that can "run small snippets of Java directly". Or embed any other number of existing runtimes with evaluation support and a "similar syntax" (e.g. Groovey or Scala). Or create a lexer/parser, and use reflection across types that support a "Builder Pattern" .. this latter suggestion is *not* what I would do, as it involves much more work. – user2864740 Oct 15 '13 at 23:24

2 Answers2

0

Based on your description, that would probably take a good amount of code to implement.

However, if you're looking for a way to chain method calls together like that, you might want to have a look at the builder pattern. Check this post out:

When would you use the Builder Pattern?

Community
  • 1
  • 1
yamafontes
  • 5,552
  • 1
  • 18
  • 18
  • Similar to chaining methods, but I would like a system of splitting the presented string while the program runs. – piechesse Oct 15 '13 at 23:20
0

You can simply invoke a method at runtime using reflection. It looks like this:

this.getClass().getDeclaredMethod("myMethod").invoke(this);

You can, of course, call method with parameters as well. However, you'll need to write some parser for that and also you'll need to ensure you're calling methods in right order. To implement system, which will be able to proceed command you've written above, it'd take about 30 minutes.

tzima
  • 1,285
  • 1
  • 10
  • 23