Player.java

jmud-0.11/src/Player.java · 12.7 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;

import util.file.InvalidFileFormatException;
import string.InvalidFlagException;
import string.StrUtil;
import misc.Separators;
import util.bit.Bit;
import util.log.Log;
import util.nice.NiceEnumeration;
import util.color.Color;

/*
  <nome>
  <descrição>
  ~
  <preferências>
  <sala>
  <posto> <nível>
  <posição> <sexo>
  <experiência> <experiência acumulada>
  <lutas>    <assassinatos> <mortes>        <fugas>
  <sentidos> <prontidão>    <sensitividade> <malícia>
  <destreza> <raciocínio>   <fantasma>      <manipulação>
  <força>    <inteligência> <aura>          <carisma>
  <corpo>    <mente>        <espírito>      <aparência>
  <vigor>    <vontado>      <alma>          <confiança>
  <t_vigor>  <t_vontade>    <t_alma>        <t_confiança>
  <ouro> <prata> <bronze>
 */

class Player extends Char {
  
    static final int P_DELETED = Bit.BIT0;
    static final int P_LOG     = Bit.BIT1;
    static final int P_COLOR   = Bit.BIT2;

    static final String prefLabels[] = {
	"apagado",
	"log",
	"cores"
    };

  private int theRank     = R_NEWBIE;
  private int preferences = 0;
  private int roomId;

  Player(Client aClient, String name) {
    theClient = aClient;
    theName   = name;
  }

  Player(Client aClient, String id, Config aConfig) 
    throws IOException, InvalidFileFormatException {

      theClient = aClient;

      BufferedReader reader = new BufferedReader(new FileReader(aConfig.getUserFilesDir() + id));
      
      theName        = reader.readLine();

      if (Debug.full)
	  Log.log("Carregando usuário: " + theName + " [" + id + "]");

      theDescription = StrUtil.readDescription(reader);

      try {
	preferences  = StrUtil.parseFlags(reader.readLine());
      }
      catch(InvalidFlagException e) {
	throw new InvalidFileFormatException();
      }

      roomId = Integer.parseInt(reader.readLine());

      try {
	StringTokenizer toker = new StringTokenizer(reader.readLine());

	theRank      = Integer.parseInt(toker.nextToken());
	theLevel     = Integer.parseInt(toker.nextToken());

	toker = new StringTokenizer(reader.readLine());

	thePosition  = Integer.parseInt(toker.nextToken());
	sex          = Integer.parseInt(toker.nextToken());

	toker = new StringTokenizer(reader.readLine());

	experience   = Integer.parseInt(toker.nextToken());
	totalExperience = Integer.parseInt(toker.nextToken());

	toker = new StringTokenizer(reader.readLine());

	fights       = Integer.parseInt(toker.nextToken());
	kills        = Integer.parseInt(toker.nextToken());
        flees        = Integer.parseInt(toker.nextToken());
        deaths       = Integer.parseInt(toker.nextToken());

      for (int r = 0; r < 5; ++r) {
	  toker = new StringTokenizer(reader.readLine());
	  for (int c = 0; c < 4; ++c)
	      realAttr[r * 4 + c] = Integer.parseInt(toker.nextToken());
      }
	
      for (int i = 0; i < 20; ++i)
	  attr[i] = realAttr[i];

	toker = new StringTokenizer(reader.readLine());
	stam = Integer.parseInt(toker.nextToken());
	will = Integer.parseInt(toker.nextToken());
	soul = Integer.parseInt(toker.nextToken());
	conf = Integer.parseInt(toker.nextToken());
      }
      catch(NumberFormatException e) {
	throw new InvalidFileFormatException();
      }

      try {
	  StringTokenizer tok = new StringTokenizer(reader.readLine());
	  if (!tok.hasMoreTokens())
	      throw new InvalidFileFormatException();
	  for (int i = 0; i < money.length; ++i)
	      money[i] = Integer.parseInt(tok.nextToken());
      }
      catch(NumberFormatException e) {
	  throw new InvalidFileFormatException();
      }
      
      String eof = reader.readLine();
      if (!eof.startsWith(Separators.EOF))
	throw new InvalidFileFormatException();

      reader.close();
  }

  void save(int id, Config aConfig) 
    throws IOException {
      BufferedWriter writer = new BufferedWriter(new FileWriter(aConfig.getUserFilesDir() + String.valueOf(id)));
      
      roomId    = thePlace.getId();
      
      writer.write(theName);                  writer.newLine();
      StrUtil.writeDescription(writer, theDescription);
      writer.write(StrUtil.makeFlags(preferences)); writer.newLine();
      writer.write(String.valueOf(roomId));   writer.newLine();

      writer.write(theRank + " " + theLevel);  writer.newLine();

      writer.write(thePosition + " " + sex); writer.newLine();

      writer.write(experience + " " + totalExperience); writer.newLine();

      writer.write(String.valueOf(fights) + " " + String.valueOf(kills) + " " + String.valueOf(deaths) + " " + String.valueOf(flees));   writer.newLine();

      for (int r = 0; r < 5; ++r) {
	  for (int c = 0; c < 4; ++c)
	      writer.write(realAttr[r * 4 + c] + " ");
	  writer.newLine();
      }

      writer.write(stam + " " + will + " " + soul + " " + conf); writer.newLine();

      for (int i = 0; i < money.length; ++i)
	  writer.write(money[i] + " ");
      writer.newLine();

      writer.write(Separators.EOF); writer.newLine();
      
      writer.close();
  }

  int getLoadRoom() {
    return roomId;
  }

  public String getBrief() {
    return getName() + " está aqui.";
  }

  String getPrompt() {
    return "ID:"+ theClient.getId() + " P:" + theRank + " " + super.getPrompt();	
  }

  boolean canExecute(Command cmd) {
    return theRank >= cmd.getMinRank();
  }

  boolean canCast(Magic mag) {
    return true;
  }

  boolean hasName(String name) {
    return theName.equalsIgnoreCase(name);
  }

    void turnPreference(int flag, boolean on) {
	if (on)
	    preferences = Bit.set(preferences, flag);
	else
	    preferences = Bit.reset(preferences, flag);
    }

    boolean queryPreference(int flag) {
	return Bit.isSet(preferences, flag);
    }

  void delete() {
    preferences = Bit.set(preferences, P_DELETED);
  }
  void undelete() {
    preferences = Bit.reset(preferences, P_DELETED);
  }
  boolean isDeleted() {
    return Bit.isSet(preferences, P_DELETED);
  }

  void startReceiveLog() {
      preferences = Bit.set(preferences, P_LOG);
  }
  void stopReceiveLog() {
      preferences = Bit.reset(preferences, P_LOG);
  }
  boolean isReceivingLog() {
      return Bit.isSet(preferences, P_LOG);
  }

    void colorOn() {
	turnPreference(P_COLOR, true);
    }

    void colorOff() {
	turnPreference(P_COLOR, false);
    }

    boolean useColor() {
	return queryPreference(P_COLOR);
    }

    String getColor(int color) {
	return useColor() ? Color.getVT100(color) : "";
    }

    String buildColor(int colorVector) {
	return useColor() ? Color.buildVT100(colorVector) : "";
    }

    String getNormalColor() {
	return useColor() ? Color.FORCE_NORMAL : "";
    }

  boolean isFirstMonitor() {
    return theClient.getId() == 0;
  }

  boolean hasId(int id) {
    return id == getId();
  }

  int getRank() {
    return theRank;
  }

  void promote(int aRank) {
    theRank = aRank;
  }

    /*
  boolean isCloneOf(Clone cl) {
    return false;
  }
    */

  boolean isPlayer() {
    return true;
  }

  /////////
  // Owner:

  public int getId() {
    return theClient.getId();
  }

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

  //
  /////////

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

  public String getSheet() {
      String prefs = StrUtil.listFlags(preferences, prefLabels);
      
    return "JOGADOR - ID: [" + getId() + "]  Posto: " + rankNames[getRank()] +  " [" + getRank() + "]  Nível: [" + theLevel  + "]"+ Separators.NL +
      "Nome: [" + theName + "]  Domínio: [" + theClient.getHostName() + "]" + Separators.NL +
	"Preferências: " + (prefs == "" ? "Nenhuma" : prefs) + Separators.NL +
      "Onde: " + thePlace.getTitle() + " (" + thePlace.getPlaceType() + " [" + thePlace.getId() + "])" + Separators.NL + super.getSheet();
  }

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

    void saveItemVerbatim(Item curr, BufferedWriter writer) 
	throws IOException {
	if (curr.isVolatile()) {
	    Log.info("Item VOLÁTIL não salvo [" + curr.getId() + "] para: " + getName(), Debug.full);
	    return;
	}

	if (curr.isStatic()) {
	    Log.info("Item estático salvo [" + curr.getId() + "] para: " + getName(), Debug.full);
	    writer.write(Separators.BOR + curr.getId()); writer.newLine();
	}
	else {
	    Log.info("Item salvo [" + curr.getId() + "] para: " + getName(), Debug.full);
	    curr.save(writer);
	}

	writer.write(Separators.EOR); writer.newLine();
    }

    void saveItemContents(Item curr, BufferedWriter writer) 
	throws IOException {
	Owner ow = curr.getContainer();
	if (ow != null)
	    for (NiceEnumeration itemEnum = ow.getContents(); itemEnum.hasMoreElements(); ) {
		Item it = (Item) itemEnum.nextElement();
		saveItem(it, writer);
	    }
    }

    void saveItem(Item curr, BufferedWriter writer)
	throws IOException {
	saveItemVerbatim(curr, writer);
	saveItemContents(curr, writer);
    }

    void saveInventory(BufferedWriter writer) 
	throws IOException {
	for (NiceEnumeration items = theItems.elements(); items.hasMoreElements(); ) {
	    Item curr = (Item) items.nextElement();
	    saveItem(curr, writer);
	}
    }

    void saveEquipment(BufferedWriter writer) 
	throws IOException {

	// visitar todas as posicoes de equipamento
	int wearFlags = 0;
	int currFlag  = 1;
	for (int i = 0; i < Item.WEAR_POSITIONS; ++i, currFlag <<= 1)

	    // so' interessa se estiver ocupada e ainda nao visitada
	    if (theEq[i] != null && !Bit.isSet(wearFlags, currFlag)) {

		// salvo o equipamento
		saveItem(theEq[i], writer);

		// marco como posicao visitada
		wearFlags = Bit.set(wearFlags, currFlag);

		// verifico se pode estar em multiplas posicoes
		if (theEq[i].wearAll()) {
		    int auxFlag = currFlag << 1;

		    // marco cada posicao que ocupa
		    for (int j = i + 1; j < Item.WEAR_POSITIONS; ++j, auxFlag <<= 1)
			if (theEq[j] == theEq[i])
			    wearFlags = Bit.set(wearFlags, auxFlag);
		}
	    }
    }

    void saveItems(BufferedWriter writer)
	throws IOException {
	saveInventory(writer);
	saveEquipment(writer);
	writer.write(Separators.EOF); writer.newLine();
    }

    void saveItems(String fileName) {
	BufferedWriter itemFile = null;

	try {
	    itemFile = new BufferedWriter(new FileWriter(fileName));
	}
	catch(IOException e) {
	    Log.err("Falha ao criar arquivo de itens: " + fileName);
	    return;
	}

	try {
	    saveItems(itemFile);
	}
	catch(IOException e) {
	    Log.err("Falha ao gravar arquivo de itens: " + fileName);
	}

	try {
	    itemFile.close();
	}
	catch(IOException e) {
	    Log.warn("Falha ao fechar arquivo de itens: " + fileName);
	}
    }

    void saveItems(Config cfg) {
	saveItems(cfg.getItemFilesDir() + getId());
    }

    void loadItems(BufferedReader reader) 
	throws InvalidFileFormatException, IOException {

	FOR: for ( ; ; ) {
	    if (!reader.ready())
		throw new InvalidFileFormatException();

	    String itemId = reader.readLine();
	    ItemProto itPro = null;
	    int id = -1;

	    boolean next;

	    do {
		next = false;

		if (itemId.startsWith(Separators.EOF))
		    break FOR;
		if (!itemId.startsWith(Separators.BOR))
		    throw new InvalidFileFormatException();

		id = Integer.parseInt(itemId.substring(1));
				
		try {
		    itPro = theWorld.findItemProtoById(id);
		}
		catch(NoSuchElementException e) {
		    Log.warn("Ignorando item sem protótipo [" + id + "] carregado para: " + getName());

		    // ignora todas as linhas ate' o comeco do proximo item
		    for ( ; ; ) {
			if (!reader.ready())
			    throw new InvalidFileFormatException();

			itemId = reader.readLine();
			if (itemId.startsWith(Separators.EOF) || !itemId.startsWith(Separators.BOR)) {
			    next = true;
			    break;
			}
		    }
		    
		}
	    } while (next);

	    Item it = null;

	    if (itPro != null)
		if (itPro.isVolatile()) {
		    Log.warn("Ignorando item volátil [" + id + "] carregado para: " + getName());
		}
		else if (itPro.isStatic()) {
		    it = itPro.create();
		}
		else {
		    it = Item.load(id, reader, itPro);
		}

	    // Entrega o item para o usuario
	    if (it != null)
		theWorld.insertItem(it, this);

	    String eor = reader.readLine();
	    if (!eor.startsWith(Separators.EOR))
		throw new InvalidFileFormatException();
	}
    }

    void loadItems(String fileName) {
	BufferedReader itemFile = null;
	try {
	    itemFile = new BufferedReader(new FileReader(fileName));
	}
	catch(FileNotFoundException e) {
	    Log.warn("Arquivo de items não encontrado: " + fileName);
	    return;
	}

	try {
	    loadItems(itemFile);
	}
	catch(InvalidFileFormatException e) {
	    Log.err("Arquivo de itens com formato inválido: " + fileName);
	}
	catch(IOException e) {
	    Log.err("Falha ao carregar arquivo de itens: " + fileName);
	}

	try {
	    itemFile.close();
	}
	catch(IOException e) {
	    Log.warn("Falha ao fechar arquivo de itens: " + fileName);
	}
    }

    void loadItems(Config cfg) {
	loadItems(cfg.getItemFilesDir() + getId());
    }
}

Site Stats

Snippets: 1791
Codebases: 571