Zone.java
jmud-0.11/src/Zone.java · 16.4 KB
From the archive jmud-0_11.tgz
Download the archive « Back to the archive contents
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
import java.util.Enumeration;
import util.file.InvalidFileFormatException;
import util.nice.Niceable;
import util.nice.NiceKey;
import misc.Separators;
import util.list.Queue;
import util.list.Vector;
import util.log.Log;
import string.StrUtil;
class Zone implements Niceable {
private int theId;
private String theTitle = null;
private String theName = null;
private int base;
private int range;
private int period;
private int remainingTime;
private World theWorld = null;
private Queue theResets = new Queue();
Zone(World aWorld, String zoneFileName, String zoneDir)
throws InvalidFileFormatException {
theWorld = aWorld;
String zone = zoneDir + zoneFileName;
BufferedReader zoneFile = null;
try {
zoneFile = new BufferedReader(new FileReader(zone));
String id = zoneFile.readLine();
if (!id.startsWith(Separators.BOR))
throw new InvalidFileFormatException();
theId = Integer.parseInt(id.substring(1));
theTitle = zoneFile.readLine();
theName = zoneFile.readLine().toLowerCase();
Log.log("Zona: " + theTitle);
StringTokenizer tok = new StringTokenizer(zoneFile.readLine());
if (!tok.hasMoreTokens())
throw new InvalidFileFormatException();
base = Integer.parseInt(tok.nextToken());
if (!tok.hasMoreTokens())
throw new InvalidFileFormatException();
range = Integer.parseInt(tok.nextToken());
if (!tok.hasMoreTokens())
throw new InvalidFileFormatException();
period = Integer.parseInt(tok.nextToken());
while (zoneFile.ready()) {
String fileName = zoneFile.readLine();
// Ignora linhas em branco e comentarios
if (fileName.length() == 0 || fileName.startsWith(Separators.REM))
continue;
if (fileName.startsWith(Separators.EOF))
break;
String name = zoneDir + fileName.substring(2);
switch(fileName.charAt(0)) {
case 's': loadRooms(name); break;
case 'i': loadItems(name); break;
case 'c': loadCreatures(name); break;
case 'a': loadResets(name); break;
case 'l': loadShops(name); break;
default: throw new InvalidFileFormatException();
}
}
zoneFile.close();
}
catch(FileNotFoundException e) {
Log.abort("Arquivo de zona não encontrado: " + zone);
}
catch(IOException e) {
Log.abort("Falha de I/O ao acessar arquivo de zona: " + zone);
}
}
////////////
// Niceable:
public boolean lessThan(Niceable n) {
return getId() < ((Zone) 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 Zone.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;
case NiceKey.K_STR:
result = theName.compareTo(key.getStrKey()) < 0;
break;
default:
Log.err("Tipo inválido de chave em Zone.keyLessThan(...): " + key.getKeyType());
}
return result;
}
//
////////////
boolean hasId(int id) {
return id == getId();
}
boolean hasName(String name) {
return theName.equals(name);
}
int getId() {
return theId;
}
String getTitle() {
return theTitle;
}
int getBase() {
return base;
}
void reset() {
Log.log("Automatizando zona: " + theTitle);
Reset.init();
for (Enumeration res = theResets.elements(); res.hasMoreElements(); ) {
Reset curr = (Reset) res.nextElement();
curr.perform(theWorld);
}
remainingTime = period;
}
void tick() {
if (remainingTime > 0)
--remainingTime;
}
boolean isTimeToReset() {
return remainingTime == 0;
}
void loadRooms(String rooms) {
BufferedReader roomFile = null;
try {
roomFile = new BufferedReader(new FileReader(rooms));
}
catch(FileNotFoundException e) {
Log.abort("Arquivo de salas não encontrado: " + rooms);
}
try {
while (roomFile.ready()) {
String roomId = roomFile.readLine();
if (roomId.startsWith(Separators.EOF))
break;
if (!roomId.startsWith(Separators.BOR))
throw new InvalidFileFormatException();
int id = Integer.parseInt(roomId.substring(1));
if (id >= range)
Log.abort("Sala com ID fora da faixa da zona: " + id);
theWorld.insertRoom(new Room(this, base, id, roomFile));
}
roomFile.close();
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de salas com formato inválido: " + rooms);
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de salas: " + rooms);
}
}
void loadItems(String items) {
BufferedReader itemFile = null;
try {
itemFile = new BufferedReader(new FileReader(items));
}
catch(FileNotFoundException e) {
Log.err("Arquivo de items não encontrado: " + items);
return;
}
try {
while (itemFile.ready()) {
String itemId = itemFile.readLine();
if (itemId.startsWith(Separators.EOF))
break;
if (!itemId.startsWith(Separators.BOR))
throw new InvalidFileFormatException();
int id = Integer.parseInt(itemId.substring(1));
if (id >= range)
Log.abort("Item com ID fora da faixa da zona: " + id);
theWorld.insertItemProto(ItemProto.load(id, base, itemFile));
String eor = itemFile.readLine();
if (!eor.startsWith(Separators.EOR))
throw new InvalidFileFormatException();
}
itemFile.close();
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de itens com formato inválido: " + items);
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de itens: " + items);
}
}
void loadCreatures(String creats) {
BufferedReader creatFile = null;
try {
creatFile = new BufferedReader(new FileReader(creats));
}
catch(FileNotFoundException e) {
Log.err("Arquivo de criaturas não encontrado: " + creats);
return;
}
try {
while (creatFile.ready()) {
String creatId = creatFile.readLine();
if (creatId.startsWith(Separators.EOF))
break;
if (!creatId.startsWith(Separators.BOR))
throw new InvalidFileFormatException();
int id = Integer.parseInt(creatId.substring(1));
if (id >= range)
Log.abort("Criatura com ID fora da faixa da zona: " + id);
int type = Integer.parseInt(creatFile.readLine());
theWorld.insertCreatProto(new CreatureProto(base, id, type, creatFile));
}
creatFile.close();
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de criaturas com formato inválido: " + creats);
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de criaturas: " + creats);
}
}
void loadResets(String resets) {
BufferedReader resetsFile = null;
try {
resetsFile = new BufferedReader(new FileReader(resets));
}
catch(FileNotFoundException e) {
Log.abort("Arquivo de salas não encontrado: " + resets);
}
try {
int count = 0;
while (resetsFile.ready()) {
++count;
String line = resetsFile.readLine();
if (line.startsWith(Separators.EOF))
break;
else if (line.startsWith(Separators.REM))
continue;
StringTokenizer tok = new StringTokenizer(line);
if (tok.hasMoreTokens()) {
try {
switch(tok.nextToken().charAt(0)) {
case 'c':
theResets.insert(new ResetCreat(base, tok));
break;
case 'i':
theResets.insert(new ResetItem(base, tok));
break;
case 'e':
theResets.insert(new ResetEquip(base, tok));
break;
case 'd':
theResets.insert(new ResetGive(base, tok));
break;
case 'p':
theResets.insert(new ResetPut(base, tok));
break;
default:
throw new InvalidFileFormatException();
}
if (tok.hasMoreTokens() && !tok.nextToken().startsWith(Separators.REM))
throw new InvalidFileFormatException(resets, "Zone.loadResets", "excesso de parâmetros na linha de automação", line, count);
}
catch(NoSuchElementException e) {
throw new InvalidFileFormatException();
}
catch(NumberFormatException e) {
throw new InvalidFileFormatException();
}
}
}
resetsFile.close();
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de itens com formato inválido: " + resets);
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de itens: " + resets);
}
}
void loadShops(String shops) {
BufferedReader shopFile = null;
try {
shopFile = new BufferedReader(new FileReader(shops));
}
catch(FileNotFoundException e) {
Log.err("Arquivo de lojas não encontrado: " + shops);
return;
}
try {
while (shopFile.ready()) {
String shopId = shopFile.readLine();
if (shopId.startsWith(Separators.EOF))
break;
if (!shopId.startsWith(Separators.BOR))
throw new InvalidFileFormatException();
int id = Integer.parseInt(shopId.substring(1));
if (id >= range)
Log.abort("Loja com ID fora da faixa da zona: " + id);
theWorld.insertShop(new Shop(base, id, shopFile));
}
shopFile.close();
}
catch(InvalidFileFormatException e) {
Log.err("Arquivo de lojas com formato inválido: " + shops);
}
catch(IOException e) {
Log.err("Falha de E/S ao ler arquivo de lojas: " + shops);
}
}
String getSheet() {
return StrUtil.formatNumber(theId, 5, ' ') + " " +
StrUtil.rightPad(theTitle, 31) + " " +
StrUtil.rightPad(theName, 16) + " " +
StrUtil.formatNumber(base, 5, ' ') + " " +
StrUtil.formatNumber(range, 5, ' ') + " " +
StrUtil.formatNumber(remainingTime, 5, ' ') + " " +
StrUtil.formatNumber(period, 5, ' ');
}
}
abstract class Reset {
static protected boolean last;
static void init() {
last = true;
}
protected boolean depend;
protected int max;
Reset(StringTokenizer tok) {
Log.log("Automação: genérico");
depend = Integer.parseInt(tok.nextToken()) != 0;
max = Integer.parseInt(tok.nextToken());
}
abstract void perform(World theWorld);
}
class ResetCreat extends Reset {
private int creatId;
private int roomId;
ResetCreat(int zoneBase, StringTokenizer tok) {
super(tok);
Log.log("Automação: criatura");
creatId = Integer.parseInt(tok.nextToken()) + zoneBase;
roomId = Integer.parseInt(tok.nextToken()) + zoneBase;
}
void perform(World theWorld) {
Log.log("Inserindo criatura " + creatId + " na sala " + roomId);
if (depend && !last) {
last = false;
return;
}
last = false;
CreatureProto cr;
try {
cr = theWorld.findCreatProtoById(creatId);
}
catch(NoSuchElementException e) {
Log.err("Criatura a ser criada não encontrada: " + creatId);
return;
}
Place pl;
try {
pl = theWorld.findRoomById(roomId);
}
catch(NoSuchElementException e) {
Log.err("Sala não encontrada: " + roomId);
return;
}
if (cr.getNumberOfCreatures() >= max)
return;
Creature newCr = (Creature) cr.create();
theWorld.insertChar(newCr, pl);
last = true;
Log.log("Inserindo criatura " + creatId + " na sala " + roomId + ": Ok");
}
}
class ResetItem extends Reset {
private int itemId;
private int roomId;
ResetItem(int zoneBase, StringTokenizer tok) {
super(tok);
Log.log("Automação: item");
itemId = Integer.parseInt(tok.nextToken()) + zoneBase;
roomId = Integer.parseInt(tok.nextToken()) + zoneBase;
}
void perform(World theWorld) {
Log.log("Inserindo item " + itemId + " na sala " + roomId);
if (depend && !last) {
last = false;
return;
}
last = false;
ItemProto it;
try {
it = theWorld.findItemProtoById(itemId);
}
catch(NoSuchElementException e) {
Log.err("Item a ser criado não encontrado: " + itemId);
return;
}
Place pl;
try {
pl = theWorld.findRoomById(roomId);
}
catch(NoSuchElementException e) {
Log.err("Sala não encontrada: " + roomId);
return;
}
if (it.getNumberOfItems() >= max)
return;
Item newIt = it.create();
theWorld.insertItem(newIt, pl);
last = true;
Log.log("Inserindo item " + itemId + " na sala " + roomId + ": Ok");
}
}
class ResetGive extends Reset {
private int itemId;
private int creatId;
ResetGive(int zoneBase, StringTokenizer tok) {
super(tok);
Log.log("Automação: entrega item");
itemId = Integer.parseInt(tok.nextToken()) + zoneBase;
creatId = Integer.parseInt(tok.nextToken()) + zoneBase;
}
void perform(World theWorld) {
Log.log("Entregando item " + itemId + " para criatura " + creatId);
if (depend && !last) {
last = false;
return;
}
last = false;
ItemProto it;
try {
it = theWorld.findItemProtoById(itemId);
}
catch(NoSuchElementException e) {
Log.err("Item a ser entregue não encontrado: " + itemId);
return;
}
Char ch;
try {
ch = theWorld.findCharById(creatId);
}
catch(NoSuchElementException e) {
Log.err("Criatura não encontrada: " + creatId);
return;
}
if (ch.isPlayer()) {
Log.warn("Jogador encontrado ao tentar entregar item " + itemId + " para criatura " + creatId);
return;
}
if (it.getNumberOfItems() >= max)
return;
Item newIt = it.create();
theWorld.insertItem(newIt, ch);
last = true;
Log.log("Entregando item " + itemId + " para criatura " + creatId + ": Ok");
}
}
class ResetEquip extends Reset {
private int itemId;
private int creatId;
ResetEquip(int zoneBase, StringTokenizer tok) {
super(tok);
Log.log("Automação: equipa item");
itemId = Integer.parseInt(tok.nextToken()) + zoneBase;
creatId = Integer.parseInt(tok.nextToken()) + zoneBase;
}
void perform(World theWorld) {
Log.log("Equipando criatura " + creatId + " com item " + itemId);
if (depend && !last) {
last = false;
return;
}
last = false;
ItemProto it;
try {
it = theWorld.findItemProtoById(itemId);
}
catch(NoSuchElementException e) {
Log.err("Item a ser equipado não encontrado: " + itemId);
return;
}
Char ch;
try {
ch = theWorld.findCharById(creatId);
}
catch(NoSuchElementException e) {
Log.err("Criatura não encontrada: " + creatId);
return;
}
if (ch.isPlayer()) {
Log.warn("Jogador encontrado ao tentar equipar item " + itemId + " na criatura " + creatId);
return;
}
if (it.getNumberOfItems() >= max)
return;
Item newIt = it.create();
int wearPos;
try {
wearPos = ch.findWearPosition(newIt);
}
catch(NoSuchElementException e) {
Log.err(creatId + " não tem onde equipar :" + itemId);
return;
}
theWorld.insertItem(newIt, ch);
newIt.equip(ch, wearPos);
last = true;
Log.log("Equipando criatura " + creatId + " com item " + itemId + ": Ok");
}
}
class ResetPut extends Reset {
private int itemId;
private int containerId;
ResetPut(int zoneBase, StringTokenizer tok) {
super(tok);
Log.log("Automação: coloca item");
itemId = Integer.parseInt(tok.nextToken()) + zoneBase;
containerId = Integer.parseInt(tok.nextToken()) + zoneBase;
}
void perform(World theWorld) {
Log.log("Colocando item " + itemId + " no recipiente " + containerId);
if (depend && !last) {
last = false;
return;
}
last = false;
ItemProto it;
try {
it = theWorld.findItemProtoById(itemId);
}
catch(NoSuchElementException e) {
Log.err("Item a ser inserido não encontrado: " + itemId);
return;
}
Item cnt;
try {
cnt = theWorld.findItemById(containerId);
}
catch(NoSuchElementException e) {
Log.err("Recipiente não encontrado: " + containerId);
return;
}
Owner ow = cnt.getContainer();
if (ow == null) {
Log.err("Item " + containerId + " não é um recipiente.");
return;
}
if (it.getNumberOfItems() >= max)
return;
Item newIt = it.create();
theWorld.insertItem(newIt, ow);
last = true;
Log.log("Colocando item " + itemId + " no recipiente " + containerId + ": Ok");
}
}