AutoHuntController(完整、可編譯版本)
package l1j.server.model.autohunt;import java.util.Collection;
import l1j.server.model.L1World;
import l1j.server.model.Instance.L1MonsterInstance;
import l1j.server.model.Instance.L1PcInstance;
import l1j.server.model.map.L1Map;
import l1j.server.model.L1Attack;
import l1j.server.model.skill.L1SkillUse;
public class AutoHuntController implements Runnable {
private final L1PcInstance _pc;
private Thread _thread;
private AutoHuntController(L1PcInstance pc) {
_pc = pc;
}
/**
* 對外唯一入口
*/
public static void start(L1PcInstance pc) {
AutoHuntController controller = new AutoHuntController(pc);
controller.startThread();
}
private void startThread() {
_thread = new Thread(this);
_thread.setDaemon(true);
_thread.start();
}
@Override
public void run() {
while (_pc.isAutoHunt()) {
try {
// 1. 基本檢查
if (_pc.isDead() || _pc.getNetConnection() == null) {
break;
}
// 2. 找最近怪物
L1MonsterInstance target = findNearestMonster();
if (target == null) {
Thread.sleep(1000);
continue;
}
// 3. 移動到攻擊距離
int distance = _pc.getLocation().getTileDistance(target.getLocation());
if (distance > 1) {
moveToTarget(target);
Thread.sleep(500);
continue;
}
// 4. 攻擊
attack(target);
Thread.sleep(800);
} catch (Exception e) {
e.printStackTrace();
break;
}
}
// 結束保險
_pc.setAutoHunt(false);
}
/**
* 找最近的怪
*/
private L1MonsterInstance findNearestMonster() {
Collection<L1MonsterInstance> list =
L1World.getInstance().getVisibleObjects(_pc, L1MonsterInstance.class);
L1MonsterInstance nearest = null;
int minDist = Integer.MAX_VALUE;
for (L1MonsterInstance mob : list) {
if (mob.isDead()) continue;
if (!mob.getMap().isPassable(mob.getX(), mob.getY())) continue;
int d = _pc.getLocation().getTileDistance(mob.getLocation());
if (d < minDist) {
minDist = d;
nearest = mob;
}
}
return nearest;
}
/**
* 移動到目標
*/
private void moveToTarget(L1MonsterInstance target) {
int dir = _pc.targetDirection(target.getX(), target.getY());
_pc.setHeading(dir);
_pc.getMoveState().setHeading(dir);
_pc.moveForward(dir);
}
/**
* 攻擊(使用既有戰鬥系統)
*/
private void attack(L1MonsterInstance target) {
L1Attack attack = new L1Attack(_pc, target);
attack.calcHit();
attack.calcDamage();
attack.action();
attack.commit();
}
}
頁:
[1]