Creating a flexible parsing/scripting engine

Started by
0 comments, last by xor 16 years, 1 month ago
I have a game that has many tokens, each with its own gametext. I need a way to process this gametext and allow additional tokens to be added later without hard-coding. Let's take a simple fireball as an example. The token's game text may read something like "Fireball does 3 dmg to target character". Seems simple, but the program has to understand what is targetable, damage type, how many targets, how much damage etc. So the token has a field that looks like this: ["direct", "Fireball", "fire", character, 1, 3] Which declares the name of the token is "Fireball" which does 3 points of direct fire damage to one character target. We create a damage object out of this that holds these attributes and then call the directDamage method:

	// Calculate damage to all targets
	public static void directDamage(Token source, Damage damage, ArrayList<Token> targets)
	{
		Iterator<Token> it = targets.iterator();
		while (it.hasNext())
		{
			processDamage(source, damage, it.next());
		}
	}
	
	// Alter Hit Points
	private static void processDamage(Token source, Damage damage, Token target)
	{
		int newHP = target.getAvatar().getHitPoints() - getDamage(source, damage, target.getDefense());
		target.getAvatar().setHitPoints(newHP);
	}
	
	// Determine how damage is affected by defense
	private static int getDamage(Token source, Damage damage, Defense defense)
	{
		if (defense == null)
			return damage.getDamageNumber();
		else
		{
			// Determine if defense is against damage type
			if (defense.getDefenseType().equalsIgnoreCase(damage.getDamageType()))
			{
				return 0; // assume immunity for now 
			}
			else
				return damage.getDamageNumber();
		}
	}

I can see additional parameters having to be added later but is this a reasonable start? I've never tried to code anything that has to be so flexible with the English language and I'm a bit unsure where to start.
Check out my current project on Kickstarter: Genegrafter
Advertisement
Maybe you could use, instead of that token, two objects, one with all the basic information that EVERY token has, or that you just know it won't need to be flexible, and another object with specific information about that token.

These two objects would be passed to a method that would handle all the basic information right there and would pass the object with the more specific information to a specific method to handle it.

If you use just one object you'd have to have lots of methods to handle all the types of tokens supported creating lots of duplicated code, with two, you have one central method to handle the common stuff, that by itself might even be enough for some simple tokens, and you have another set of methods to handle the rest, without much code duplication.

This topic is closed to new replies.

Advertisement