Skip to content

Instantly share code, notes, and snippets.

@spoike
Created February 24, 2013 07:43
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 spoike/5023039 to your computer and use it in GitHub Desktop.
Save spoike/5023039 to your computer and use it in GitHub Desktop.
package javaapplication2;
public class BodyPart {
private int health = 100;
private String bodyPartName;
public BodyPart(String bodyPartName, int health) {
this.health = health;
this.bodyPartName = bodyPartName;
}
public int getHealth() { return health; }
public void setHealth(int health) { this.health = health; }
String getBodyPartName() {
return bodyPartName;
}
}
package javaapplication2;
import java.util.HashMap;
class Creature {
public HashMap<String, BodyPart> bodyparts = new HashMap<String, BodyPart>();
// The hashmap is for quickly retrieve bodypart that the user wants
public Creature() {
}
public void addBodyPart(BodyPart bodyPart) {
bodyparts.put(bodyPart.getBodyPartName(), bodyPart);
}
public void hit(String bodyPartName, int decrement) {
BodyPart bp = bodyparts.get(bodyPartName);
int newHealth = bp.getHealth() - decrement;
bp.setHealth(newHealth);
}
}
package javaapplication2;
public class CreatureBuilder {
public Creature GetCreature() {
Creature c = new Creature();
c.addBodyPart(new BodyPart("head", 100));
c.addBodyPart(new BodyPart("torso", 100));
c.addBodyPart(new BodyPart("arms", 100));
c.addBodyPart(new BodyPart("legs", 100));
return c;
}
}
package javaapplication2;
public class JavaApplication2 {
public static void main(String[] args) {
CreatureBuilder builder = new CreatureBuilder();
Creature c = builder.GetCreature();
listCreatureBodyParts(c);
// take a hit to the head
c.hit("head", 25);
System.out.println("------------------");
listCreatureBodyParts(c);
}
public static void listCreatureBodyParts(Creature c) {
for (BodyPart bodyPart : c.bodyparts.values()) {
System.out.println(bodyPart.getBodyPartName() + ": " + bodyPart.getHealth());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment