4

We are working on a game and looking to develop a functionality which will allow us to mix various items in a manner similar to "alchemy" game. The main idea is that we have a number of elements, which can be split into three groups: basic, intermediate and final. Basic resources can be merged together and make an intermediate resource, intermediate resources can be merged with intermediate and basic resources and make final and so on.

So, we are thinking about having 2 HashMaps: one would have a indicate what each resource is combinable with, second one would map what each resource would be made of. Is there a better way to do this? Any data structure that we are not aware of?

Thanks

4
  • It's hard to visualize what you are asking for. Can you show some pseudo code or a flow chart of what you are wanting?
    – yams
    Jun 28, 2013 at 15:28
  • Why not use basic OOP, have a class for elements. 3 types of classes for basic intermediate and advanced that override this, and then override those for each element. Jun 28, 2013 at 15:29
  • I can come up with a Category class and a Resource class that has a Category and List<Resource> requirements field. Jun 28, 2013 at 15:30
  • more important to know on how you should represent your data is how it will be used. Ok, you say basic elements combine into an intermediate element and intermediate elements combine into final elements. But what are the constraints? Can you give some depth on your use case? Jun 28, 2013 at 17:34

5 Answers 5

6

Just write your own Datastructure like this

public class Element {
 enum Type{BASIC, INTERMEDIATE, FINAL};
 private Type type;
 private String name;
 private List<Element> combinable;
}
11
  • Basically what I would've said. Except I would make the combinable into a HashMap<Element, Element>, where the key is what can be combined, and the value is what they combine into.
    – asteri
    Jun 28, 2013 at 15:34
  • Yes, that is something we were also looking at, wasn't sure if there is something exists though. That is really useful. Thanks
    – El_o.di
    Jun 28, 2013 at 15:37
  • maybe add another List<Element> called components to show what Elements this Element is made of (if type != BASIC), to answer the other half of the question Jun 28, 2013 at 15:38
  • Encapsuling data inside such custom datatypes is a basic concept of OOP. Jun 28, 2013 at 15:40
  • 1
    Side note : It should be INTERMEDIATE instead of IMMEDIATE. Jun 28, 2013 at 15:47
1

What you want is an enum containing all your elements, with a couple of methods. Here is an example, feel free to use it if it suites your needs.
If desired, you can also make a second enum for Type (as Templar suggested) and add it as a field in you Element enum.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public enum Element {
    //Example instances, replace with what is appropriate for your game.
    WATER, // Basic
    WOOD, // Basic
    IRON, // Basic
    STONE, // Basic
    FIRE, // Basic
    CARBON(WOOD, FIRE), //Intermediate
    FORGE(STONE, IRON), // Intermediate
    STEEL(FORGE, IRON); // Final

    private Element[] parts;

    private Element() {
        //instantiates parts to prevent NullPointerException
        this.parts = new Element[0];
    }

    private Element(Element... parts) {
        this.parts = parts;
    }

    /**
     * return all the parts of this Element.
     * @return
     */
    public List<Element> getParts() {
        return Arrays.asList(parts);
    }

    /**
     * find all elements that have this Element listed as one of their parts.
     * 
     * @param part
     * @return
     */
    public List<Element> getComposites() {
        List<Element> composites = new ArrayList<Element>();
        // Iterate through all Elements
        for (Element composite : Element.values()) {
            // Iterate through each Element's parts
            for (Element part : composite.parts) {
                // If the element has a part equal to the argument,
                // Add the element to the list of composites.
                if (part == this) {
                    composites.add(composite);
                }
            }
        }

        return composites;
    }

}
0

You should use the Composite design pattern. In your case BasicResource is a leaf class. intermediate and final are composites.

2
  • 1
    I don't think Composite is a good match here. Composite works well for things where you want to arbitrarily compose items to make new items—but in this case there are restrictions (which elements can be combined), and the resulting elements should also have specific names (e.g. iron + carbon = steel, not "iron-carbon").
    – DaoWen
    Jun 28, 2013 at 15:38
  • I see, maybe I should play a game of alchemy first :-)
    – avidD
    Jun 28, 2013 at 15:40
0

I would actually separate elements and their combinability - if each element has to contain a list of elements it's combinable with, whenever you want to add a new element you have to go back and add it to all old elements you want it to combine with.

I'd separate the concept out into something like "Elements" and "Formulas" -

class Element { 
     enum Type{NULL, BASIC, INTERMEDIATE, FINAL};         
     private Type type;
     private String name;
     // ....
} 

class Formula {
    private List<Element> requires = new ArrayList<Element>();
    private Element produces;

    public Formula(List<Element> requires, Element produces) {
        Collections.copy(requires, this.requires);
        this.produces = produces;
    }

    public final List<Element> requiredElements() {
        return Collections.unmodifiableList(requires);
    }

    public final boolean applyFormula(List<Element> ingredients) {
        for (Element e : requires) {
            if (!ingredients.contains(e)) {
                // ingredients doesn't contain a required element - return early.
                return false;
            }
        }
        for (Element e : requires) {
            ingredients.remove(e);
        }
        ingredients.add(produces);
        return true;
    }
}
0

If you're creating a game, having this data hard-coded in your Java source code is going to make things a pain. You'll have to recompile every time you want to add a new element, change a relationship (what is composed of what), etc.

Instead, I'd recommend storing all of your element information in an external source and then reading it in / accessing it from your program. You could do this with a database, but I have a feeling that's a little bit overkill (at least for now). Instead, you could use a nice readable, plain-text, standardized format like JSON to define your elements and their relationships externally, and then import all the data using a library (I'd suggest GSon) for easy access in your program.

As for the data structure, I think your choice of HashMaps would work just fine. Since JSON is built on two basic types of data structures—lists [] and maps {}—that's what Gson would convert things to anyway. Here's a very simple example of what how I'd envision your element specification:

{
  "elements" : {
    "iron" : "basic",
    "carbon" : "basic",
    "steel" : "intermediate"
  },
  "formulae" : {
    "steel" : [ "iron", "carbon" ]
  }
}

You could read that in with Gson (or whatever JSON library you choose), and then build whatever other data structures you need from that. If you can figure out how to get Gson to create the data structures you want directly (I know this is possible, but I don't remember how hard it is to do the configuration), then that would be even better. For example, if you could turn the "formulae" value into a BidiMap (the Apache Commons bi-directional map) then that might be very useful (but you'd also need to turn the components list into a set to keep it order-agnostic, e.g. iron+carbon is the same as carbon+iron).

For even more dynamic behavior, you could add a feature into your program to allow you to reload all of your elements data while your game is still running! (This might make debugging easier.)

I know this isn't exactly what you were asking, but I hope you find my suggestions helpful anyway!

Not the answer you're looking for? Browse other questions tagged or ask your own question.