World.java

jmud-0.11/src/World.java · 18.3 KB

From the archive jmud-0_11.tgz

Download the archive   « Back to the archive contents

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

import util.file.InvalidFileFormatException;
import util.nice.NiceVector;
import util.list.List;
import util.list.Vector;
import util.nice.Niceable;
import util.nice.NiceEnumeration;
import util.nice.Sorter;
import util.nice.Searcher;
import util.nice.NiceKey;
import misc.Separators;
import string.StrUtil;
import util.log.Log;

class World {

  private Manager    theManager     = null;
  private Config     theConfig      = null;
  private NiceVector theZones       = new NiceVector();
  private NiceVector theRooms       = new NiceVector();
  private List       thePlayers     = new List();
  private List       theChars       = new List();
  private NiceVector theItemProtos  = new NiceVector();
  private List       theItems       = new List();
  private NiceVector theCreatProtos = new NiceVector();
  private List       theCreatures   = new List();
    private Vector     theShops       = new Vector();

    private Vector      boards          = new Vector();

  private int    theId;
  private String theTitle = null;

    static final int B_ADMIN    = 0;
    static final int B_IMMORTAL = 1;
    static final int B_SOCIAL   = 2;

  
  World(Manager aManager, Config aConfig) {
    theManager     = aManager;
    theConfig      = aConfig;

    String worldFileName = aConfig.getWorldDir() + aConfig.getWorldFileName();

    BufferedReader worldFile = null;
    try {
      worldFile = new BufferedReader(new FileReader(worldFileName));

      theId = Integer.parseInt(worldFile.readLine().substring(1));
      theTitle = worldFile.readLine();

      Log.log("Mundo: " + theTitle);

      while (worldFile.ready()) {
	StringTokenizer tok = new StringTokenizer(worldFile.readLine());

	String zoneName = tok.nextToken();
	String zoneDir = theConfig.getWorldDir() + (tok.hasMoreTokens() ? tok.nextToken() : "");

	if (zoneName.startsWith(Separators.EOR))
	  break;
	try {
	  theZones.insert(new Zone(this, zoneName, zoneDir));
	}
	catch(InvalidFileFormatException e) {
	  Log.abort("Formato inválido do arquivo de zona: " + zoneName);
	}
      }

      try {
	  Room rm = findRoomById(0);
	  Log.warn("Suprimindo geração interna de sala inicial");
      }
      catch(NoSuchElementException e) {
	  Log.log("Inserindo sala inicial internamente");
	  insertRoom(new Room(null, 0, 0, "Limbo", "limbo", "Aqui é o limbo.\r\n"));
      }

      Log.log("Comprimindo vetor de salas");
      theRooms.trim();
      Log.log("Ordenando salas");
      Sorter.quickSort(theRooms);

      while (worldFile.ready()) {
	String line = worldFile.readLine();
	if (line.startsWith(Separators.EOF))
	  break;
	StringTokenizer tok = new StringTokenizer(line);

	String dir  = tok.nextToken(); 
	int srcZone = Integer.parseInt(tok.nextToken());
	int srcRoom = Integer.parseInt(tok.nextToken());
	int trgZone = Integer.parseInt(tok.nextToken());
	int trgRoom = Integer.parseInt(tok.nextToken());
	
	Zone z1 = findZoneById(srcZone);
	Room r1 = findRoomById(srcRoom + z1.getBase());
	Zone z2 = findZoneById(trgZone);

	Log.log("Porta interzona: " + line);

	if (r1.doorExists(dir))
	  Log.err("Colisão de porta inter-zonas: " + line);
	else {
	    try {
		r1.insertDoor(new Door(z2.getBase(), dir, trgRoom));
	    }
	    catch(NoSuchElementException e) {
		Log.err("Porta inter-zona com direção inválida: " + line);
	    }
	}
      }

      worldFile.close();

      Log.log("Comprimindo vetor de zonas");
      theZones.trim();
      Log.log("Ordenando zonas");
      Sorter.quickSort(theZones);

      Log.log("Comprimindo vetor de ítens");
      theItemProtos.trim();
      Log.log("Ordenando ítens");
      Sorter.quickSort(theItemProtos);

      Log.log("Comprimindo vetor de criaturas");
      theCreatProtos.trim();
      Log.log("Ordenando criaturas");
      Sorter.quickSort(theCreatProtos);

      Log.log("Comprimindo vetor de lojas");
      theShops.trim();

      adjustDoors();
      checkExits();
      checkReaching();

      /*
      Log.info("Vinculando vendedores a lojas");
      bindShops();
      */
    }
    catch(FileNotFoundException e) {
      Log.abort("Arquivo de mundo não encontrado: " + worldFileName);
    }
    catch(IOException e) {
      Log.abort("Falha de E/S ao ler arquivo de mundo: " + worldFileName);
    }

    loadBoards();

  }

    void loadBoards() {

	boards.insert(new Board(B_ADMIN, "Administrativo", Char.R_DISABLED, Char.R_DISABLED, Char.R_MONITOR, theConfig));
	boards.insert(new Board(B_IMMORTAL, "Divino", Char.R_IMMORTAL, Char.R_IMMORTAL, Char.R_IMMORTAL, theConfig));
	boards.insert(new Board(B_SOCIAL, "Social", Char.R_GUEST, Char.R_NEWBIE, Char.R_IMMORTAL, theConfig));
	boards.trim();
    }

    void saveBoards() {
	if (Debug.full)
	    Log.log("Gravando quadros");

	for (int i = 0; i < boards.getSize(); ++i)
	    ((Board) boards.getElementAt(i)).save(theConfig);
    }

    Board findBoardById(int id) throws NoSuchElementException {
	for (Enumeration enum = boards.elements(); enum.hasMoreElements(); ) {
	    Board be = (Board) enum.nextElement();
	    if (be.getId() == id)
		return be;
	}

	throw new NoSuchElementException();
    }

  void resetZones() {
    Log.log("Automatizando mundo");
    for (NiceEnumeration zones = theZones.elements(); zones.hasMoreElements(); ) {
      Zone curr = (Zone) zones.nextElement();
      curr.reset();
    }
  }

    void checkResets() {
	for (NiceEnumeration zones = theZones.elements(); zones.hasMoreElements(); ) {
	    Zone curr = (Zone) zones.nextElement();
	    curr.tick();
	    if (curr.isTimeToReset())
		curr.reset();
	}
    }


  Zone findZoneById(int zoneId) 
    throws NoSuchElementException {
      for (NiceEnumeration zones = theZones.elements(); zones.hasMoreElements(); ) {
	Zone curr = (Zone) zones.nextElement();
	if (curr.getId() == zoneId)
	  return curr;
      }
      throw new NoSuchElementException();
  }

  String getZoneSheet() {
    String list = "";
    for (NiceEnumeration zones = theZones.elements(); zones.hasMoreElements(); ) {
      Zone curr = (Zone) zones.nextElement();
      list += Separators.NL + curr.getSheet();
    }
    return list;
  }

  void sendToOpenPlace(String msg) {
    for (Enumeration enum = thePlayers.elements(); enum.hasMoreElements(); ) {
      Char ch = (Char) enum.nextElement();
      if (ch.getPlace().isOpen())
	ch.send(msg);
    }
  }

  void sendToPlayers(String msg) {
      for (Enumeration enum = thePlayers.elements(); enum.hasMoreElements(); ) {
	  Char ch = (Char) enum.nextElement();
	  ch.send(msg);
      }      
  }

  void insertRoom(Room newRoom) {
    theRooms.insert(newRoom);
  }

  Room findRoomById(int roomId) throws NoSuchElementException {
    return (Room) theRooms.getElementAt(Searcher.binarySearch(theRooms, new NiceKey(roomId)));
  }

  String listRoomsById(int firstId, int lastId) {
    String list = "";
    for (NiceEnumeration rooms = theRooms.elements(); rooms.hasMoreElements(); ) {
      Room curr = (Room) rooms.nextElement();
      int id = curr.getId();
      if (id >= firstId && id <= lastId)
	list += Separators.NL + StrUtil.formatNumber(curr.getId(), 5, ' ') + " " + curr.getTitle();
    }
    return list;
  }

  String listRoomsByName(String name) {
    String list = "";
    for (NiceEnumeration rooms = theRooms.elements(); rooms.hasMoreElements(); ) {
      Room curr = (Room) rooms.nextElement();
      if (curr.hasName(name))
	list += Separators.NL + StrUtil.formatNumber(curr.getId(), 5, ' ') + " " + curr.getTitle();
    }
    return list;
  }

  void insertItemProto(ItemProto itemProto) {
    theItemProtos.insert(itemProto);
  }

  ItemProto findItemProtoById(int itemId)
    throws NoSuchElementException {
      for (NiceEnumeration items = theItemProtos.elements(); items.hasMoreElements(); ) {
	ItemProto currItem = (ItemProto) items.nextElement();
	if (currItem.hasId(itemId))
	  return currItem;
      }
      throw new NoSuchElementException();
  }

  String getItemProtosByName(String name) {
    String list = "";
    for (NiceEnumeration items = theItemProtos.elements(); items.hasMoreElements(); ) {
      ItemProto curr = (ItemProto) items.nextElement();
      if (curr.hasName(name))
	list += Separators.NL + StrUtil.formatNumber(curr.getId(), 5, ' ') + " " + StrUtil.rightPad(curr.getItemProtoType(), 23) +
	  " " + curr.getName();
    }
    return list;
  }

  void insertCreatProto(CreatureProto creatProto) {
    theCreatProtos.insert(creatProto);
  }

    void insertShop(Shop sh) {
	theShops.insert(sh);
    }

    Shop findShopById(int shId) throws NoSuchElementException {
	for (Enumeration shops = theShops.elements(); shops.hasMoreElements(); ) {
	    Shop sh = (Shop) shops.nextElement();
	    if (sh.hasId(shId))
		return sh;
	}
	throw new NoSuchElementException();
    }
    
    Shop findShopByKeeperId(int keeperId) {
	for (Enumeration shops = theShops.elements(); shops.hasMoreElements(); ) {
	    Shop sh = (Shop) shops.nextElement();
	    if (sh.getKeeperId() == keeperId)
		return sh;
	}
	return null;
    }

    String getShopList() {
	String list = "";
	for (Enumeration shops = theShops.elements(); shops.hasMoreElements(); ) {
	    Shop sh = (Shop) shops.nextElement();
	    list += Separators.NL + sh.getShortSheet();
	}    
	return list;
    }

    /*
    void bindShops() {
	for (Enumeration shops = theShops.elements(); shops.hasMoreElements(); ) {
	    Shop sh = (Shop) shops.nextElement();
	    int keeperId = sh.getKeeperId();
	    try {
		Char ch = findCharById(keeperId);
		if (!(ch instanceof ShopCreature))
		    Log.err("Criatura [" + keeperId + "] não é vendedor da loja: " + 
			    sh.getId());
		else
		    ((ShopCreature) ch).bindShop(sh);	    
	    }
	    catch(NoSuchElementException e) {
		Log.warn("Vendedor [" + keeperId + "] não encontrado para loja: " + 
			 sh.getId());
	    }
	    
	}    
    }
    */

  CreatureProto findCreatProtoById(int creatId)
    throws NoSuchElementException {
      for (NiceEnumeration creats = theCreatProtos.elements(); creats.hasMoreElements(); ) {
	CreatureProto currCreat = (CreatureProto) creats.nextElement();
	if (currCreat.hasId(creatId))
	  return currCreat;
      }
      throw new NoSuchElementException();
  }

  String getCreatProtosByName(String name) {
    String list = "";
    for (NiceEnumeration creats = theCreatProtos.elements(); creats.hasMoreElements(); ) {
      CreatureProto curr = (CreatureProto) creats.nextElement();
      if (curr.hasName(name))
	list += Separators.NL + StrUtil.formatNumber(curr.getId(), 5, ' ') + " " + curr.getName();
    }
    return list;
  }

  void adjustDoors() {
    Log.log("Ajustando portas");

    for (NiceEnumeration sourceRooms = theRooms.elements(); sourceRooms.hasMoreElements(); ) {
      Room currRoom = (Room) sourceRooms.nextElement();
      for (NiceEnumeration doors = currRoom.getExits(); doors.hasMoreElements(); ) {
	Door currDoor = (Door) doors.nextElement();
	try {
	  currDoor.adjust((Room) theRooms.getElementAt(Searcher.binarySearch(theRooms, new NiceKey(currDoor.getDestinationId()))));
	}
	catch(NoSuchElementException e) {
	  Log.err("Porta " + currDoor.getDirectionName() + " da sala " + currRoom.getId() + " conduz a sala inexistente: " + currDoor.getDestinationId());
	  currDoor.setError();
	}
      }
    }
  }

  void checkExits() {
    Log.log("Verificando saídas");

    for (NiceEnumeration rooms = theRooms.elements(); rooms.hasMoreElements(); ) {
      Room curr = (Room) rooms.nextElement();
      NiceEnumeration doors = curr.getExits();
      if (!doors.hasMoreElements())
	Log.warn("Sala sem saída: " + curr.getId());
    }
  }

  void checkReaching() {
    Log.log("Verificando alcançabilidade das salas");
    
    for (NiceEnumeration trgRooms = theRooms.elements(); trgRooms.hasMoreElements(); ) {
      Room trg = (Room) trgRooms.nextElement();
    Ok: {
	for (NiceEnumeration srcRooms = theRooms.elements(); srcRooms.hasMoreElements(); ) {
	  Room src = (Room) srcRooms.nextElement();
	  for (NiceEnumeration doors = src.getExits(); doors.hasMoreElements(); ) {
	    Door dr = (Door) doors.nextElement();
	    if (dr.getDestinationRoom() == trg)
	      break Ok;
	  }
	}
	Log.warn("Sala não alcançável: " + trg.getId());
      } // Ok
    }
  }

  void insertChar(Char aChar, Place plc) {
    theChars.insert(aChar);
    aChar.enterPlace(plc);
  }

  void insertChar(Char aChar, int roomId) 
    throws NoSuchElementException {
      insertChar(aChar, findRoomById(roomId));
  }
  

    public void insertChar(Char aChar) 	throws NoSuchElementException {
	
	Zone zn = findZoneById(theConfig.getStartZone());
	int roomId = zn.getBase() + theConfig.getStartRoom();
	
	insertChar(aChar, roomId);
    }
    
  public void removeChar(Char aChar) throws NoSuchElementException {
    aChar.leavePlace();
    theChars.remove(aChar);
  }

  // BeginTask
  public void insertPlayer(Char ch) {
    thePlayers.insert(ch);
  }

  // QuitTask
  public void removePlayer(Char ch) throws NoSuchElementException {
    thePlayers.remove(ch);
  }

  // destrói os items e equipamento do personagem antes de
  // remove-lo do mundo
  public void extractChar(Char ch) {
    ch.extractItems(); 
    ch.extractEqs(); 
    removeChar(ch);
  }

  public Char findCharByName(String name)
    throws NoSuchElementException {
      for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
	Char currChar = (Char) charEnum.nextElement();
	if (currChar.hasName(name))
	  return currChar;
      }    
      throw new NoSuchElementException();
  }

  public Char findCharById(int id)
    throws NoSuchElementException {
      for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
	Char currChar = (Char) charEnum.nextElement();
	if (currChar.hasId(id))
	  return currChar;
      }    
      throw new NoSuchElementException();
  }

  String getPlayerList() {
    String list = "";
    for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
      Char currChar = (Char) charEnum.nextElement();
      if (currChar.isPlayer())
	list += Separators.NL + currChar.getName();
    }    
    return list;
  }

  String getFullPlayerList() {
    String list = "";
    for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
      Char curr = (Char) charEnum.nextElement();
      if (curr.isPlayer()) {
	Place plc  = curr.getPlace();
	list += Separators.NL + 
	  StrUtil.formatNumber(curr.getId(), 5, ' ') + " " +
	  StrUtil.formatNumber(curr.getRank(), 5, ' ') + " " +
	  StrUtil.formatNumber(curr.getLevel(), 5, ' ') + " " +
	  StrUtil.rightPad(curr.getName(), 10) + " " +
	  curr.getClient().getHostName();
      }
    }    
    return list;
  }

  public void insertItem(Item it, Owner ow) {
    theItems.insert(it);
    it.giveTo(ow);
  }

  public void removeItem(Item it) throws NoSuchElementException {
    theItems.remove(it);
    it.drop();
  }

  // destrói os itens possivelmente contidos num
  // recipiente antes de removê-lo do mundo
  public void extractItem(Item it) {
    Owner ow = it.getContainer();
    if (ow != null)
      ow.extractItems();
    try { removeItem(it); /* drop, takeoffeq */ } catch(NoSuchElementException e) { }
  }

  public Item findItemById(int itemId) 
    throws NoSuchElementException {
      for (Enumeration itemEnum = theItems.elements(); itemEnum.hasMoreElements(); ) {
	Item currItem = (Item) itemEnum.nextElement();
	if (currItem.hasId(itemId))
	  return currItem;
      }    
      throw new NoSuchElementException();
  }
  
  public Item findItemByName(String name) 
    throws NoSuchElementException {
      for (Enumeration itemEnum = theItems.elements(); itemEnum.hasMoreElements(); ) {
	Item currItem = (Item) itemEnum.nextElement();
	if (currItem.hasName(name))
	  return currItem;
      }    
      throw new NoSuchElementException();
  }

  // 2 personagens e 2 itens
  public void action(String act, boolean hide,
	      Char ch, Char vict,
	      Item it1, Item it2) {
    for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
      Char currChar = (Char) charEnum.nextElement();
      currChar.action(act, hide, ch, vict, it1, it2);
    }    
  }

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

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


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

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

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

  // 2 personagens e 2 itens
  public void actionNotToChar(String act, boolean hide,
		  Char ch, Char vict,
		  Item it1, Item it2) {
    for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
      Char currChar = (Char) charEnum.nextElement();
      if (currChar != ch)
	currChar.action(act, hide, ch, vict, it1, it2);
    }    
  }

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

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

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

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

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

    ////
    //

    // chamado a cada hora do mundo
    void creatureAction() {

	Log.debug("Acionando criaturas andarilhas");

	for (Enumeration charEnum = theChars.elements(); charEnum.hasMoreElements(); ) {
	    Char currChar = (Char) charEnum.nextElement();
	    if (!currChar.isPlayer())
		((Creature) currChar).doAction();
	}    
    }
    
    //
    ///
}

Site Stats

Snippets: 1791
Codebases: 571