spoike
2/24/2013 - 7:43 AM

Simple getting started thing for http://stackoverflow.com/questions/15049510/how-could-i-implement-body-parts-in-a-java-roguelike

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());
        }
    }
}
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;

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 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;
    }
}