Skip to content

Instantly share code, notes, and snippets.

@maraoz
Created November 8, 2012 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraoz/4040993 to your computer and use it in GitHub Desktop.
Save maraoz/4040993 to your computer and use it in GitHub Desktop.
/**
* Creates the delta that would take this state to the newer state
*/
public GameStateDelta getDeltaTo(GameState newer) {
GameStateDelta delta = new GameStateDelta();
Set<GameObject> dissapeared = Sets.difference(this.getGameObjects(), newer.getGameObjects());
Set<GameObject> appeared = Sets.difference(newer.getGameObjects(), this.getGameObjects());
Set<Long> continued = Sets.intersection(this.getGameObjectIds(), newer.getGameObjectIds());
// objects existing in this state and not existing in new state
for (GameObject gameObject : dissapeared) {
delta.addObjectChange(GameObjectDelta.destroyDeltaFor(gameObject));
}
// objects not existing in this state and existing in new state
for (GameObject gameObject : appeared) {
delta.addNewObject(gameObject);
}
// objects which may have suffered changes in their fields
for (Long id: continued) {
GameObject current = this.getGameObject(id);
GameObject future = newer.getGameObject(id);
Preconditions.checkNotNull(current);
Preconditions.checkNotNull(future);
Class<? extends GameObject> type = current.getClass();
List<Field> networkedFields = GameObjectInspector.getNetworkedFields(type);
boolean changed = false;
GameObjectDelta objectDelta = new GameObjectDelta(type, id);
for (Field f : networkedFields) {
Object currentValue;
Object futureValue;
try {
currentValue = f.get(current);
futureValue = f.get(future);
if (!currentValue.equals(futureValue)) {
changed = true;
objectDelta.addFieldChange(new GameObjectFieldChange(f.getName(), futureValue));
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (changed) {
delta.addObjectChange(objectDelta);
}
}
return delta;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment