Char.java

jmud-0.11/src/Char.java · 31.8 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

import java.io.IOException;
import java.util.Enumeration;
import java.util.NoSuchElementException;

import string.StrUtil;
import misc.Separators;
import util.log.Log;
import util.list.List;
import util.list.Iterator;
import util.nice.Searcher;
import util.nice.NiceKey;
import util.nice.NiceQueue;
import util.nice.Niceable;
import util.nice.NiceEnumeration;
import util.bit.Bit;
import clone.Clone;
import clone.CloneList;
import clone.CloneAlgo;
import integer.IntUtil;

abstract class Char implements Owner, Sheetable, Affectable, Clone, Niceable {

  static private Manager theManager = null;
  static protected World   theWorld   = null;
  
  static void setManager(Manager mgr) {
    theManager = mgr;
  }

  static void setWorld(World wld) {
    theWorld = wld;
  }

  static final int R_DISABLED  = 0;
  static final int R_GUEST     = 1;
  static final int R_NEWBIE    = 2;
  static final int R_CITIZEN   = 3;
  static final int R_SENIOR    = 4;
  static final int R_HERO      = 5;
  static final int R_LORD      = 6;
  static final int R_IMMORTAL  = 7;
  static final int R_GOD       = 8;
  static final int R_MONITOR   = 9;
  static final int R_THRESHOLD = 10;

  static final String rankNames[] = {
    "nenhum",
    "visitante",
    "iniciante",
    "cidadão",
    "sênior",
    "herói",
    "lorde",
    "imortal",
    "deus",
    "monitor",
    "limiar"
  };

    static final int S_NEUTRAL = 0;
    static final int S_MALE    = 1;
    static final int S_FEMALE  = 2;

    static final String sexLabels[] = {
	"neutro",
	"macho",
	"fêmea"
    };

    static final int P_DISABLED      = 0;
    static final int P_DEAD          = 1;
    static final int P_UNCONSCIOUS   = 2;
    static final int P_INCAPACITATED = 3;
    static final int P_ASLEEP        = 4;
    static final int P_RESTING       = 5;
    static final int P_SITTING       = 6;
    static final int P_STANDING      = 7;
    static final int P_AWARE         = 8;
    static final int P_FIGHTING      = 9;

    static final String positionLabels[] = {
	"desabilitad*",
	"mort*",
	"inconsciente",
	"incapacitad*",
	"dormindo",
	"descansando",
	"sentad*",
	"levantad*",
	"em guarda",
	"lutando"
    };

    protected Client    theClient       = null;
    protected String    theName         = null;
    protected String    theDescription  = "";
    protected Place     thePlace        = null;
    protected CloneList theItems        = new CloneList();
    protected int       theLevel        = 0;
    protected List      theEffects      = new List();
    protected int       thePosition     = P_STANDING;
    protected int       sex             = S_NEUTRAL;
    
    protected int       experience      = 0;
    protected int       totalExperience = 0;

    protected int       fights          = 0;
    protected int       kills           = 0;
    protected int       flees           = 0;
    protected int       deaths          = 0;
    
    protected Char      enemy           = null;
    protected int       localDamage     = 0;

  protected Item      theEq[] = {
    null, // 0
    null,
    null,
    null,
    null,
    null, // 5
    null,
    null,
    null,
    null,
    null, // 10
    null,
    null,
    null,
    null,
    null, // 15
    null,
    null,
    null,
    null,
    null, // 21
    null
  };

  static final int C_PHY = 0;
  static final int C_MEN = 1;
  static final int C_MYS = 2;
  static final int C_SOC = 3;

  static final int R_PER = 0;
  static final int R_AGI = 1;
  static final int R_ACT = 2;
  static final int R_RES = 3;
  static final int R_VIT = 4;

  static final int A_SEN = 0;
  static final int A_ALE = 1;
  static final int A_AWA = 2;
  static final int A_SLY = 3;
  static final int A_DEX = 4;
  static final int A_WIT = 5;
  static final int A_GHO = 6;
  static final int A_MAN = 7;
  static final int A_STR = 8;
  static final int A_INT = 9;
  static final int A_AUR = 10;
  static final int A_CHA = 11;
  static final int A_BOD = 12;
  static final int A_MIN = 13;
  static final int A_SPI = 14;
  static final int A_APP = 15;
  static final int A_STA = 16;
  static final int A_WIL = 17;
  static final int A_SOU = 18;
  static final int A_CON = 19;

    static final String attrLabels[] = {
	"sentidos", "atenção", "consciência", "malícia",
	"destreza", "raciocínio", "fantasma", "manipulação",
	"força", "inteligência", "aura", "carisma",
	"corpo", "mente", "espírito", "aparência",
	"vigor", "vontade", "alma", "confiança"
    };

    static final String attrNames[] = {
	"sentidos", "atencao", "consciencia", "malicia",
	"destreza", "raciocinio", "fantasma", "manipulacao",
	"forca", "inteligencia", "aura", "carisma",
	"corpo", "mente", "espirito", "aparencia",
	"vigor", "vontade", "alma", "confianca"
    };


  /*           PHYSICAL  MENTAL       MYSTIC    SOCIAL
    PERCEPTION sense     alertness    awareness slyness
    AGILITY    dexterity witness      ghost     manipulation
    ACTION     strength  intelligence aura      charisma
    RESISTANCE body      mind         spirit    appearance
    VITALITY   stamina   will         soul      confidence
   */

    static final String attrRowNames[] = {
        "percepcao", "agilidade", "acao", "resistencia", "vitalidade"
    };
    
    static final String attrColumnNames[] = {
        "fisico", "mental", "mistico", "social"
    };
    
    static final String attrRowLabels[] = {
        "percepção", "agilidade", "ação", "resistência", "vitalidade"
    };
    
    static final String attrColumnLabels[] = {
        "físico", "mental", "místico", "social"
    };

  protected int realAttr[] = {
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1,
    1, 1, 1, 1
  };

  protected int attr[] = {
    1, 1, 1, 1,
    1, 1, 1, 1, 
    1, 1, 1, 1, 
    1, 1, 1, 1,
    1, 1, 1, 1
  };

  /* "fuel" */
  protected int stam = 1;
  protected int will = 1;
  protected int soul = 1;
  protected int conf = 1;

    // Modificados por equipamentos
    protected int attackPool[]     = { 0, 0, 0, 0 };
    protected int defensePool[]    = { 0, 0, 0, 0 };
    protected int damagePool[]     = { 0, 0, 0, 0 };
    protected int resistancePool[] = { 0, 0, 0, 0 };

    protected int money[] = {
	0,  // 0 - ouro
	0,  // 1 - prata
	0   // 2 - cobre
    };

    int getStam() {
	return stam;
    }

    int getWill() {
	return will;
    }

    int getSoul() {
	return soul;
    }

    int getConf() {
	return conf;
    }

    /////////////
    // Atributos:

    void attrToReal() {
	for (int i = 0; i < realAttr.length; ++i)
	    realAttr[i] = attr[i];
    }

    void attrFromReal() {
	for (int i = 0; i < realAttr.length; ++i)
	    attr[i] = realAttr[i];
    }

    // lendo:

    // Reais:

  int getRealAttr(int row, int column) {
    return realAttr[row * 4 + column];
  }

  int getRealAttr(int ind) {
    return realAttr[ind];
  }

    // Efetivos:

  int getAttr(int row, int column) {
    return attr[row * 4 + column];
  }

  int getAttr(int ind) {
    return attr[ind];
  }

    // mudando:

    // Reais:

    void setRealAttr(int row, int column, int val) {
        realAttr[row * 4 + column] = val;
    }
 
    void setRealAttr(int ind, int val) {
        realAttr[ind] = val;
    }
 
    void setRealAttrRow(int row, int val) {
        for (int i = 0; i < 4; ++i)
            setRealAttr(row, i, val);
    }
 
    void setRealAttrColumn(int column, int val) {
        for (int i = 0; i < 5; ++i)
            setRealAttr(i, column, val);
    }
 
    void setAllRealAttr(int v) {
        for (int i = 0; i < attr.length; ++i)
            realAttr[i] = v;
    }

    // Efetivos:

    void setAttr(int row, int column, int val) {
	attr[row * 4 + column] = val;
    }

    void setAttr(int ind, int val) {
	attr[ind] = val;
    }

    void setAttrRow(int row, int val) {
	for (int i = 0; i < 4; ++i)
	    setAttr(row, i, val);
    }

    void setAttrColumn(int column, int val) {
	for (int i = 0; i < 5; ++i)
	    setAttr(i, column, val);
    }

    void setAllAttr(int v) {
	for (int i = 0; i < attr.length; ++i)
	    attr[i] = v;
    }

    // incrementando:

    void addAttr(int row, int column, int val) {
	attr[row * 4 + column] += val;
    }

    void addAttr(int ind, int val) {
	attr[ind] += val;
    }

    void addAttrRow(int row, int val) {
	for (int c = 0; c < 4; ++c)
	    setAttr(row, c, getAttr(row, c) + val);
    }

    void addAttrColumn(int column, int val) {
	for (int r = 0; r < 5; ++r)
	    setAttr(r, column, getAttr(r, column) + val);
    }

    void addAllAttr(int val) {
	for (int i = 0; i < attr.length; ++i)
	    attr[i] += val;
    }

    //
    ///////////////

  public void send(String msg) {
    if (theClient != null)
      theClient.send(msg);
  }

  void enterPlace(Place target) {
    thePlace = target;
    thePlace.insertChar(this);
  }

  void leavePlace() {
    try {
      thePlace.removeChar(this);
    }
    catch(NoSuchElementException e) {
      Log.log("Personagem '" + getName() + "' não encontrado ao ser removido de: " + thePlace.getOwnerType() + " [" + thePlace.getId() + "]");
    }
    thePlace = null;
  }

  void moveTo(Place target) {
    leavePlace();
    enterPlace(target);
  }

  void moveTo(String doorName) 
    throws NoSuchElementException {
      moveTo(thePlace.findDoorByName(doorName).getDestinationRoom());
  }

    void walkTo(Place target, int dir) {
	Place oldPlace = getPlace();
	moveTo(target);
	oldPlace.actionNotToChar("$p saiu para " + Door.getDirectionName(dir) + ".", true, this);
	getPlace().actionNotToChar("$p chegou.", true, this);
	look();
    }
  
  static final String SEE_NOTHING = "Você não vê nada de especial...";
  static final String YOU_SEE     = "Você vê:" + Separators.NL;
 
  void lookAt(Char ch) {
    send(YOU_SEE + ch.getFullDescription());
  }
 
  void lookAt(Item it) {
    send(YOU_SEE + it.getFullDescription());
  }

  String getFullDescription() {
    return (((theDescription.length() == 0) ? SEE_NOTHING : theDescription) + getEqList());
  }

  void lookAt(Place aPlace) {
    send(aPlace.getFullDescription(this));
  }

  void look() {
    lookAt(thePlace);
  }

  public String getName() {
    return theName;
  }

    int getLevel() {
	return theLevel;
    }

    int getExp() {
	return experience;
    }

    int getTotalExp() {
	return totalExperience;
    }

    int getPosition() {
	return isFighting() ? P_FIGHTING : thePosition;
    }

    void setPosition(int pos) {
	thePosition = pos;
    }

    boolean isFemale() {
	return sex == S_FEMALE;
    }

    String getPositionLabel() {
	return StrUtil.adjustSex(positionLabels[getPosition()], isFemale());
    }

  void setDescription(String desc) {
    theDescription = desc;
  }
 
  String getDescription() {
    return theDescription;
  }

  boolean canSee(Char ch) {
    return ch != null;
  }

  boolean canSee(Item it) {
    return it != null;
  }

  boolean canSeeAnyOf(Char ch, Char vict, Item it1, Item it2) {
    return canSee(ch) || canSee(vict) || canSee(it1) || canSee(it2);
  }

  String replaceCharName(String act, String simb, Char ch) {
    return StrUtil.replace(act, simb, canSee(ch) ? ((ch == this) ? "você" : ch.getName()) : "alguém");
  }

  String replaceItemName(String act, String simb, Item it) {
    return StrUtil.replace(act, simb, canSee(it) ? it.getName() : "algo");
  }

  /*
    act = cadeia de caracteres podendo conter os seguintes símbolos:
    $p - personagem agente da ação - ch
    $P - personagem vítima da ação - vict
    $i - item primário             - it1
    $I - item secundário           - it2
    hide = esconder ação se ela não puder ser enxergada
  */

  // 2 personagens e 2 itens
  void action(String act, boolean hide,
	      Char ch, Char vict,
	      Item it1, Item it2) {
    if (hide && !canSeeAnyOf(ch, vict, it1, it2))
      return;

    String ac = new String(act);
    ac = replaceCharName(ac, "$p", ch);
    ac = replaceCharName(ac, "$P", vict);
    ac = replaceItemName(ac, "$i", it1);
    ac = replaceItemName(ac, "$I", it2);

    if (ac.length() > 0)
      send(Character.toUpperCase(ac.charAt(0)) + ac.substring(1));
  }

  // 2 personagens e 1 item
  void action(String act, boolean hide,
	      Char ch, Char vict,
	      Item it1) {
    action(act, hide, ch, vict, it1, null);
  }

  // 2 personagens e nenhum item
  void action(String act, boolean hide,
	      Char ch, Char vict) {
    action(act, hide, ch, vict, null, null);
  }

  // 1 personagem e 2 itens
  void action(String act, boolean hide,
	      Char ch,
	      Item it1, Item it2) {
    action(act, hide, ch, null, it1, it2);
  }

  // 1 personagem e 1 item
  void action(String act, boolean hide,
	      Char ch,
	      Item it) {
    action(act, hide, ch, null, it, null);
  }

  // 1 personagem e nenhum item
  void action(String act, boolean hide,
	      Char ch) {
    action(act, hide, ch, null, null, null);
  }

  Place getPlace() {
    return thePlace;
  }

  Client getClient() {
    return theClient;
  }

    Item searchItem(String name, int ind) throws NoSuchElementException {
	try {
	    return findItemByName(name, ind);
	}
	catch(NoSuchElementException e) {
	}
	
	try {
	    return findEqByName(name, ind);
	}
	catch(NoSuchElementException e) {
	}
	
	return getPlace().findItemByName(name, ind);
    }

    static final String ROOM = "sala";
    static final String INVENTORY = "inventario";
    static final String EQUIPMENT = "equipamentos";

    Item searchItem(IndexParser ip) {
	if (ip.hasType()) {
	    if (INVENTORY.startsWith(ip.getType()))
		return findItemByName(ip);
	    if (EQUIPMENT.startsWith(ip.getType()))
		return findEqByName(ip.getWord(), ip.getIndex());
	    if (ROOM.startsWith(ip.getType()))
		return getPlace().findItemByName(ip.getWord(), ip.getIndex());
	}
	return searchItem(ip.getWord(), ip.getIndex());
    }

    BoardItem searchBoard() throws NoSuchElementException {
	try {
	    return findBoard();
	}
	catch(NoSuchElementException e) {
	    return getPlace().findBoard();
	}
    }

  //////////////
  // Equippable:

  public int findEqPositionByName(String name, int ind) throws NoSuchElementException {
    for (int i = 0; i < Item.WEAR_POSITIONS; ++i) { 
      Item it = theEq[i];
      if (it != null && it.hasName(name) && --ind == 0)
	return i;
    }
    throw new NoSuchElementException();
  }

  public Item findEqByName(String name, int ind) throws NoSuchElementException {
    return theEq[findEqPositionByName(name, ind)];
  }

  public int findEqPosition(Item it) throws NoSuchElementException {
    for (int i = 0; i < Item.WEAR_POSITIONS; ++i)
      if (theEq[i] == it)
	return i;
    throw new NoSuchElementException();
  }

    // apenas para itens que não sejam multi-veste
    public int findWearPosition(Item it) throws NoSuchElementException {
	for (int wearPos = 0; wearPos < Item.WEAR_POSITIONS; ++wearPos) 
	    if (canWearOn(it, wearPos))
		return wearPos;
	throw new NoSuchElementException();
    }
  
    public boolean canWear(Item it) {
	if (it.wearAll()) {
	    int currFlag = 1;
	    for (int i = 0; i < Item.WEAR_POSITIONS; ++i) {
		if (Bit.isSet(it.getWearVector(), currFlag) && theEq[i] != null)
		    return false;
		currFlag <<= 1;
	    }
	    return true;
	}

	try {
	    findWearPosition(it);
	    return true;
	}
	catch(NoSuchElementException e) {
	}
	
	return false;
    }

    public void wear(Item it) {
	if (!canWear(it)) {
	    Log.err("Tentativa de equipar item sem posição apropriada.");
	    return;
	}

	if (it.wearAll()) {
	    int currFlag = 1;
	    for (int i = 0; i < Item.WEAR_POSITIONS; ++i) {
		if (Bit.isSet(it.getWearVector(), currFlag))
		    theEq[i] = it;
		currFlag <<= 1;
	    }
	    affectPool(it);
	}
	else 
	    wearOn(it, findWearPosition(it));
		
    }

    // apenas para equipamentos que não sejam multi-veste
    public boolean canWearOn(Item it, int wearPos) {
	return !it.wearAll() && Bit.isSet(it.getWearVector(), 1 << wearPos) && theEq[wearPos] == null;
    }
    
    // apenas para equipamentos que não sejam multi-veste
    public void wearOn(Item it, int wearPos) {
	if (it.wearAll()) {
	    Log.err("Tentativa de equipar item multi-veste [" + it.getId()+ "] em uma posição específica: " + wearPos);
	    return;
	}
	
	if (!canWearOn(it, wearPos)) {
	    Log.err("Tentativa de vestir item em posição ocupada/inválida: " + wearPos);
	    return;
	}
	
	theEq[wearPos] = it;

	affectPool(it);
    }

    public void takeOffEq(int wearPos) throws NoSuchElementException {
	Item it = theEq[wearPos];

	if (it == null)
	    throw new NoSuchElementException();

	takeOffEq(it);
    }
    
    public void takeOffEq(Item it) {
	for (int i = 0; i < Item.WEAR_POSITIONS; ++i)
	    if (theEq[i] == it)
		theEq[i] = null;

	unnaffectPool(it);
    }
    
    public Item getEq(int ind) {
	return theEq[ind];
    }

    public String getEqList() {
	String eq = "";
	
	int wearFlags = 0;
	int currFlag  = 1; 
	for (int i = 0; i < Item.WEAR_POSITIONS; ++i) {
	    if (theEq[i] != null && !Bit.isSet(wearFlags, currFlag)) {
		wearFlags = Bit.set(wearFlags, currFlag);
		
		eq += Separators.NL + StrUtil.rightPad("<" + Item.wearPositions[i] + ">", 17) + theEq[i].getName();

		if (theEq[i].wearAll()) {
		    
		    int j = i + 1;
		    int auxFlag = currFlag << 1;
		    for (; j < Item.WEAR_POSITIONS; ++j) {
			if (theEq[j] == theEq[i] && !Bit.isSet(wearFlags, auxFlag)) {
			    wearFlags = Bit.set(wearFlags, auxFlag);
			    
			    eq += Separators.NL + StrUtil.rightPad("<" + Item.wearPositions[j] + ">", 17) + theEq[i].getName() + " *";
			    
			} // if
			auxFlag <<= 1;
		    } // for

		} // if wearAll
	    }

	    currFlag <<= 1;
	} // for
  
    
    return eq;
  }

  void extractEqs() {
    for (int i = 0; i < Item.WEAR_POSITIONS; ++i) 
      if (theEq[i] != null) {
	Owner ow = theEq[i].getContainer();
	if (ow != null)
	  ow.extractItems();
	theWorld.removeItem(theEq[i]); // faz drop, takeoffeq
      }
  }

  // Equippable
  /////////////

    String getPrompt() {
	return stam + "/" + getAttr(A_STA) + " " + will + "/" + getAttr(A_WIL) + " " + soul + "/" + getAttr(A_SOU) + " " + conf + "/" + getAttr(A_CON) + "> ";
    }

    abstract String getColor(int color);
    abstract String buildColor(int colorVector);
    abstract String getNormalColor();

  //////////////////////////
  // Implementação de Owner:

  abstract public int getId();

  public String getOwnerType() {
    return "personagem";
  }

  private void addLoadOf(Item it) {
  }

  private void subLoadOf(Item it) {
  }

  public void insertItem(Item it) {
    CloneAlgo.insert(theItems, it);
    addLoadOf(it);
  }

  public void removeItem(Item anItem) throws NoSuchElementException {
    theItems.remove(anItem);
    subLoadOf(anItem);
  }

  public Item findItemById(int itemId) throws NoSuchElementException {
    return (Item) Searcher.linearSearch(theItems, new NiceKey(itemId));
  }

  public Item findItemByName(IndexParser ip) throws NoSuchElementException {
    return (Item) Searcher.linearSearch(theItems, new NiceKey(ip.getWord()), ip.getIndex());
  }

  public Item findItemByName(String name, int ind) throws NoSuchElementException {
    return (Item) Searcher.linearSearch(theItems, new NiceKey(name), ind);
  }

  public NiceQueue findItemsByName(IndexParser ip) {
    return SearcherAdaptor.findItemsByName(theItems, ip);
  }

  public String getItemList() {
    return CloneAlgo.getList(theItems, null, CloneAlgo.F_NAME);
  }

  public boolean hasFreeLoad(int load) {
    return true;
  }

  public void extractItems() {
    for (NiceEnumeration items = theItems.elements(); items.hasMoreElements(); ) {
      Item curr = (Item) items.nextElement();
      Owner ow = curr.getContainer();
      if (ow != null)
	ow.extractItems();
      theWorld.removeItem(curr);
    }
  }

  public Owner getOwner() {
    return thePlace;
  }

   public BoardItem findBoard() throws NoSuchElementException {
       for (NiceEnumeration enum = theItems.elements(); enum.hasMoreElements(); ) {
	   Item it = (Item) enum.nextElement();
	   if (it instanceof BoardItem)
	       return (BoardItem) it;
       }

       throw new NoSuchElementException();
    }

    public NiceEnumeration getContents() {
	return theItems.elements();
    }

  //
  //////////////////////////

  abstract public String getBrief();

  abstract boolean hasId(int id);

  abstract boolean canExecute(Command cmd);

  abstract boolean canCast(Magic mag);

  abstract boolean hasName(String name);

  abstract boolean isFirstMonitor();
  
  abstract int getRank();

  abstract void promote(int aRank);

  abstract boolean isPlayer();

  abstract void save(int id, Config aConfig) throws IOException;

  /////////////////
  // Affectable:

  public void insertEffect(Effect eff) {
    theEffects.insert(eff);
  }

  public void removeEffect(Effect eff) {
    theEffects.remove(eff);
  }

  public void addStr(int value) {
    setAttr(A_STR, getAttr(A_STR) + value);
  }

  public void unnaffect() {
    for (Enumeration enum = theEffects.elements(); enum.hasMoreElements(); ) {
      Effect eff = (Effect) enum.nextElement();
      theManager.removeEffect(eff);
    }
  }

  //
  /////////////////


    // O equipamento ja' deve estar equipado
    private void affectPool(Item it) {
	it.affectEquipper(this);
    }

    // O equipamento ainda deve estar equipado
    private void unnaffectPool(Item it) {
	it.unnaffectEquipper(this);
    }

    void addToAttackPool(int col, int val) {
	attackPool[col] += val;
    }

    void addToDefensePool(int col, int val) {
	defensePool[col] += val;
    }

    void addToDamagePool(int col, int val) {
	damagePool[col] += val;
    }

    void addToResistancePool(int col, int val) {
	resistancePool[col] += val;
    }


  /////////////
  // Fightable:

    int getAttack(int col) {
	return getAttr(R_AGI, col) + attackPool[col];
    }

    int getDefense(int col) {
	return getAttr(R_AGI, col) + defensePool[col];
    }

    int getDamage(int col) {
	return getAttr(R_ACT, col) + damagePool[col];
    }

    int getResistance(int col) {
	return getAttr(R_RES, col) + resistancePool[col];
    }

  Char getEnemy() {
    return enemy;
  }

  void startFight(Char en) {
      if (isFighting())
	  return;

      getPlace().action("$p começa lutar com $P.", true, this, en);

      enemy = en;
      theManager.enterFight(this);
      ++fights;
      updatePosition();
  }

  void stopFight() {
      if (!isFighting())
	  return;

      enemy = null;
      theManager.leaveFight(this);
      updatePosition();
  }

    Item makeCorpse() {
	final int CORPSE_ID = 0;

	Item corpse = null;

	try {
	    corpse = theWorld.findItemProtoById(CORPSE_ID).create();
	    theWorld.insertItem(corpse, getPlace());
	}
	catch(NoSuchElementException e) {
	    Log.warn("Cadáver não encontrado: " + CORPSE_ID);
	}

	return corpse;
    }

    void transferItemsTo(Owner ow) {
	for (NiceEnumeration items = theItems.elements(); items.hasMoreElements(); ) {
	    Item it = (Item) items.nextElement();
	    it.transferTo(ow); // drop (remove ou solta), giveTo
	}
    }

    void transferEqsTo(Owner ow) {
	for (int i = 0; i < Item.WEAR_POSITIONS; ++i) {
	    Item it = theEq[i];
	    if (it != null) 
		it.transferTo(ow); // drop (remove ou solta), giveTo
	}
    }

    void transferAllItemsTo(Owner ow) {
	transferItemsTo(ow);
	transferEqsTo(ow);
    }

  void die() {
      if (isFighting())   // garante que existe um inimigo (enemy != null)
	  enemy.stopFight();

      stopFight();        // stopFight verifica se esta' lutando
      unnaffect();
      ++deaths;

      Item it = makeCorpse();
      if (it != null) {
	  Owner corpse = it.getContainer();
	  if (corpse == null)
	      Log.warn("Cadáver não é um recipiente: '" + it.getName() +"' [" + it.getId() + "]");
	  else
	      transferAllItemsTo(corpse);
      }

      getPlace().action("$p morre.", true, this);
  }

    void killedBy(Char en) {
	die();
	++en.kills;
    }

    // procura o inimigo na sala, para atacar
  void attack() {
      if (!isFighting())  // garante que nao vai atacar apos stopFight()
	  return;

      if (getEnemy().getPlace() == getPlace()) {
	  prepareToFight(); // tenta levantar para atacar
	  if (thePosition >= P_STANDING)
	      hitEnemy();
      }
      else
	  stopFight();
  }

  // ataca o respectivo inimigo
  void hitEnemy() {
      enemy.harmBy(this);   

      if (isFighting()) {
	  enemy.showCondition();
	  enemy.startFight(this);
      }
  }

    boolean isDeadlyHurt() {
	return -stam > getAttr(A_STA) || -will > getAttr(A_WIL) || -soul > getAttr(A_SOU);
    }

    boolean isCommatous() {
	return -stam > getAttr(A_STA) >> 1 || -will > getAttr(A_WIL) >> 1 || -soul > getAttr(A_SOU) >> 1;    }

    boolean isSpanked() {
	return stam < 0 || will < 0 || soul < 0;
    }

    void updatePosition() {
	if (isDeadlyHurt()) {
	    thePosition = P_DEAD;
	}
	else if (isCommatous()) {
	    thePosition = P_UNCONSCIOUS;
	}
	else if (isSpanked()) {
	    thePosition = P_INCAPACITATED;
	}
    }

    // toma providencias referentes a ser espancado sem reagir
    void prepareToFight() {
	switch(thePosition) {
	case P_DISABLED:
	case P_DEAD:
	case P_UNCONSCIOUS:
	case P_INCAPACITATED:
	    break;
	case P_ASLEEP:
	    thePosition = P_RESTING;
	    getPlace().action("$p acorda.", true, this);
	    break;
	case P_RESTING:
	    thePosition = P_SITTING;
	    getPlace().action("$p senta-se.", true, this);
	    break;
	case P_SITTING:
	    thePosition = P_STANDING;
	    getPlace().action("$p levanta-se.", true, this);
	    break;
	case P_STANDING:
	    /* startFight(en); */
	    break;
	case P_AWARE:
	    /*
	    getPlace().action("$p reage violentamente!", true, this);
	    startFight(en);
	    hitEnemy();
	    */
	    break;
	default:
	    Log.err("Char.beenHitBy(...): personagem " + getName() + " com posição inválida: " + thePosition);
	}
    }

    // função de mais alto nível para tentar causar dano
    // faz todas as rolagens de dados necessárias
    // e, por fim, inflige o dano

    void harmBy(Char en) {
	acumulateDamage(en.rollDamage(this));

	inflictLocalDamage();

	// deve ficar apos o updatePosition (chamado por inflictLocalDamage)
	if (thePosition == P_DEAD)
	    killedBy(en);
    }

    private int rollDamage(Char vict) {

	int difference = vict.getDefense(C_PHY) - getAttack(C_PHY);

        int difficulty = (vict.thePosition >= P_STANDING) ? Sheet.getDifficulty(difference) : 1;

        int result     = Sheet.roll(difficulty);

	if (result == -1) 
	    {
		fall();
		return 0;
	    }

	if (result < difficulty)
	    {
		getPlace().action("$p erra $P.", true, this, vict);
		return 0;
	    }

	int bonus = Sheet.getBonus(result, difference);

	int damage = Sheet.getEffect(getDamage(C_PHY) - vict.getResistance(C_PHY), bonus);
	
	getPlace().action("$p causa " + damage + " pontos de dano em $P.", true, this, vict);
	return damage;
    }

    private void acumulateDamage(int damage) {
	localDamage += damage;
    }

    void inflictLocalDamage() {
	stam -= localDamage;
	localDamage = 0;
	updatePosition(); // atualiza posição devido a ferimentos
    }

    private void showCondition() {

	switch(thePosition) {
	case P_DEAD:
	    //showCondition("$p está mort*.");
	    Log.warn("showCondition() para personagem morto.");
	    break;
	case P_UNCONSCIOUS:
	    showCondition("$p está inconsciente.");
	    break;
	case P_INCAPACITATED:
	    showCondition("$p está incapacitad*.");
	    break;
	default:
	    if (isPrettyHurt())
		showCondition("$p está gravemente ferid*.");
	    else if (isHurt())
		showCondition("$p está muito ferid*.");
	    else if (isWounded())
		showCondition("$p está ferid*.");
	    else if (isBruised())
		showCondition("$p está escoriad*.");
	    else 
		showCondition("$p está em excelentes condições.");
	}
    }

    private void showCondition(String msg) {
	getPlace().action(StrUtil.adjustSex(msg, isFemale()), true, this);
    }


    boolean isPrettyHurt() {
	return stam < IntUtil.get1of4(getAttr(A_STA)) ||
	    will < IntUtil.get1of4(getAttr(A_WIL)) ||
	    soul < IntUtil.get1of4(getAttr(A_SOU));
    }

    boolean isHurt() {
	return stam < getAttr(A_STA) >> 1 || will < getAttr(A_WIL) >> 1 || soul < getAttr(A_SOU)>> 1;
    }

    boolean isWounded() {
	return stam < IntUtil.get3of4(getAttr(A_STA)) ||
	    will < IntUtil.get3of4(getAttr(A_WIL)) ||
	    soul < IntUtil.get3of4(getAttr(A_SOU));
    }

    boolean isBruised() {
	return stam < getAttr(A_STA) || will < getAttr(A_WIL) || soul < getAttr(A_SOU);
    }

  boolean isFighting() {
    return enemy != null;
  }

    void flee() {
	if (enemy.getEnemy() == this)
	  enemy.stopFight();
	stopFight();
	++flees;

	Place plc = getPlace();

	plc.action("$p tenta fugir em pânico!", true, this);
	NiceEnumeration enum = plc.getExits();

	if (enum.hasMoreElements()) {
	    Door d = (Door) enum.nextElement();
	    moveTo(d.getDestinationRoom());
	    plc.actionNotToChar("$p fugiu para " + d.getDirectionName() + ".", true, this);
	    look();
	    getPlace().actionNotToChar("$p chegou.", true, this);
	    return;
	}

	send("Impossível escapar!");
  }

    void fall() {
	getPlace().action("$p cai!", true, this);
        thePosition = P_SITTING;
    }

  //
  /////////////


    void fullHeal() {
        stam = getAttr(A_STA);
        will = getAttr(A_WIL);
        soul = getAttr(A_SOU);
        conf = getAttr(A_CON);
        thePosition = P_STANDING;
    }

  /////////////
  // Sheetable:

    private String getSheetLine(int row) {
	String line = "";
	for (int c = 0; c < 4; ++c) {
	    int i = row * 4 + c;
	    line += StrUtil.leftWidth(attrLabels[i], 5) + ": " + StrUtil.formatNumber(getAttr(i), 3) + " (" + StrUtil.formatNumber(realAttr[i], 3) + ")  ";
	}
	return line;
    }

    private String listAttacks() {
	return StrUtil.formatNumber(getAttack(C_PHY), 3) + " " +
	    StrUtil.formatNumber(getAttack(C_MEN), 3) + " " + 
	    StrUtil.formatNumber(getAttack(C_MYS), 3);
    }

    private String listDefenses() {
 	return StrUtil.formatNumber(getDefense(C_PHY), 3) + " " +
	    StrUtil.formatNumber(getDefense(C_MEN), 3) + " " + 
	    StrUtil.formatNumber(getDefense(C_MYS), 3);
   }

    private String listDamages() {
	return StrUtil.formatNumber(getDamage(C_PHY), 3) + " " +
	    StrUtil.formatNumber(getDamage(C_MEN), 3) + " " + 
	    StrUtil.formatNumber(getDamage(C_MYS), 3);
    }

    private String listResistances() {
	return StrUtil.formatNumber(getResistance(C_PHY), 3) + " " +
	    StrUtil.formatNumber(getResistance(C_MEN), 3) + " " + 
	    StrUtil.formatNumber(getResistance(C_MYS), 3);
   }

    private String getConditions() {
	return getStam() + " " + getWill() + " " + getSoul() + " " + getConf();
    }

    private String getCharSheet() {
	String sh = "Sexo: " + sexLabels[sex] + Separators.NL + "Lutas: " + fights + "  Assassinatos: " + kills + "  Fugas: " + flees + "  Mortes: " + deaths + Separators.NL +
	    "Ataque: " + listAttacks() + 
	    "  Defesa:      " + listDefenses() + 
	    Separators.NL +
	    "Dano:   " + listDamages() + 
	    "  Resistência: " + listResistances();
	for (int r = 0; r < 5; ++r)
	    sh += Separators.NL + getSheetLine(r);
	sh += Separators.NL + "Condições: " + getConditions() + 
	    "  Posição: " + getPositionLabel() + Separators.NL + "Finanças: ";

	for (int i = 0; i < money.length; ++i)
	    sh += money[i] + " " + Currency.getKindAbbr(i) + "  ";
	sh += Separators.NL;

	return sh;
    }

    public String getSheet() {
	return getCharSheet();
    }

  //
  /////////////

    String getScore() {
	return "Personagem: " + getName() + "  Nível: " + getLevel() + "  Experiência: " + getExp() + " (" + getTotalExp() + ")" + Separators.NL +
	    getCharSheet();
    }
    
  /////////
  // Clone:

  public boolean isCloneOf(Clone cl) {
    return this instanceof Creature && cl instanceof Creature && getId() == ((Char) cl).getId();
  }

  // Clone
  /////////

  //////////////
  // Niceable:

  public boolean lessThan(Niceable n) {
    return getId() < ((Char) n).getId();
  }
  
  public boolean hasKey(NiceKey key) {
    boolean result = false;
    switch(key.getKeyType()) {
    case NiceKey.K_INT:
      result = hasId(key.getIntKey());
      break;
    case NiceKey.K_STR: 
      result = hasName(key.getStrKey());
      break;
    default:
      Log.err("Tipo inválido de chave em Char.hasKey(...): " + key.getKeyType());
    }
    
    return result;
  }

  public boolean keyLessThan(NiceKey key) {
    boolean result = false;
    switch(key.getKeyType()) {
    case NiceKey.K_INT:
      result = getId() < key.getIntKey();
      break;
    default:
      Log.err("Tipo inválido de chave em Char.keyLessThan(...): " + key.getKeyType());
    }
    return result;
  }
  
  //
  //////////////
}

Site Stats

Snippets: 1791
Codebases: 571