Skip to content

Instantly share code, notes, and snippets.

@darkwave
Created August 3, 2014 09:47
Show Gist options
  • Save darkwave/fcaa8ccd1fe8fb2121ba to your computer and use it in GitHub Desktop.
Save darkwave/fcaa8ccd1fe8fb2121ba to your computer and use it in GitHub Desktop.
Prototype for a game engine based on JSON and Reflection using Processing
import java.lang.reflect.*;
import java.util.Map;
import java.util.Map.Entry;
int availableIndex = 0;
int generateID() {
return availableIndex++;
}
class Game {
PApplet parent;
ArrayList<Entity> entities = new ArrayList<Entity>();
Map<String, Method> systems = new HashMap<String, Method>();
Game(PApplet parent) {
this.parent = parent;
}
void add(Entity e) {
entities.add(e);
}
void addComponent(Entity e, String name, String comp) {
Method commandMethod;
try {
commandMethod = parent.getClass().getMethod(name,
new Class[] {
Entity.class
}
);
}
catch (Exception ex) {
// no such method, or an error.. which is fine, just ignore
commandMethod = null;
PApplet.println("Please implement a " + name
+ "(Entity) method in your main sketch if you want to change "+ name + " properties");
}
if (commandMethod != null) {
systems.put(name, commandMethod);
}
e.setComponent(name, comp);
}
void run() {
for (Entry<String, Method> entry : systems.entrySet ()) {
String compName = entry.getKey();
Method m = entry.getValue();
try {
for (Entity e : entities) {
if (e.hasComponent(compName))
m.invoke(parent, e);
}
}
catch (Exception e) {
// TODO Auto-generated catch block
println("ahh");
}
}
}
}
class Entity {
public int id;
JSONObject components = new JSONObject();
public Entity() {
id = generateID();
components.setInt("id", id);
}
@Override
public String toString() {
return components.toString();
}
public void setComponent(String name, String json) {
JSONObject newComp = JSONObject.parse(json);
components.setJSONObject(name, newComp);
}
public boolean hasComponent(String comp) {
return components.hasKey(comp);
}
public JSONObject getComponent(String comp) {
return components.getJSONObject(comp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment