NPC Plugin refactoring

This commit is contained in:
simon 2018-12-22 15:29:58 -05:00
parent e4a06e79d4
commit b361f87154
14 changed files with 146 additions and 101 deletions

View File

@ -18,8 +18,7 @@ import java.awt.*;
import java.util.List;
import java.util.*;
public class Cubot extends GameObject implements Updatable, ControllableUnit, MessageReceiver,
Attackable, Rechargeable, HardwareHost {
public class Cubot extends GameObject implements Updatable, ControllableUnit, MessageReceiver {
private static final char MAP_INFO = 0x0200;

View File

@ -0,0 +1,38 @@
package net.simon987.npcplugin;
import net.simon987.server.GameServer;
import net.simon987.server.game.objects.Action;
public class ExecuteCpuTask extends NPCTask {
private static final int MAX_EXEC_TIME = GameServer.INSTANCE.getConfig().getInt("npc_exec_time");
@Override
public boolean checkCompleted() {
return false;
}
@Override
public void tick(NonPlayerCharacter npc) {
HackedNPC hNpc = (HackedNPC) npc;
//Execute code
int timeout = Math.min(hNpc.getEnergy(), MAX_EXEC_TIME);
hNpc.getCpu().reset();
int cost = hNpc.getCpu().execute(timeout);
hNpc.spendEnergy(cost);
if (hNpc.getCurrentAction() == Action.WALKING) {
if (hNpc.spendEnergy(100)) {
if (hNpc.incrementLocation()) {
//Couldn't walk
hNpc.setCurrentAction(Action.IDLE);
}
} else {
hNpc.setCurrentAction(Action.IDLE);
}
}
}
}

View File

@ -41,6 +41,8 @@ public class Factory extends Structure implements Updatable, MessageReceiver {
private char[] program;
private int programIndex = 0;
private static final int PROGRAM_SIZE = GameServer.INSTANCE.getConfig().getInt("factory_program_size");
public Factory() {
super(2, 2);
}
@ -83,47 +85,57 @@ public class Factory extends Structure implements Updatable, MessageReceiver {
private NonPlayerCharacter spawnNPC(Point p) {
NonPlayerCharacter npc;
if (programIndex == 0) {
npc = new HarvesterNPC();
npc.setWorld(getWorld());
npc.setObjectId(new ObjectId());
npc.setX(p.x);
npc.setY(p.y);
getWorld().addObject(npc);
getWorld().incUpdatable();
npc = spawnRandomNpc(p);
} else {
npc = new HackedNPC(program);
npc.setWorld(getWorld());
npc.setObjectId(new ObjectId());
npc.setX(p.x);
npc.setY(p.y);
getWorld().addObject(npc);
getWorld().incUpdatable();
System.out.println("NEW HACKED NPC");
this.locked = true;
npc = spawnHackedNpc(p);
}
return npc;
}
private NonPlayerCharacter spawnRandomNpc(Point p) {
NonPlayerCharacter npc;
npc = new HarvesterNPC();
npc.setWorld(getWorld());
npc.setObjectId(new ObjectId());
npc.setX(p.x);
npc.setY(p.y);
getWorld().addObject(npc);
getWorld().incUpdatable();
return npc;
}
private NonPlayerCharacter spawnHackedNpc(Point p) {
NonPlayerCharacter npc;
npc = new HackedNPC(program);
npc.setWorld(getWorld());
npc.setObjectId(new ObjectId());
npc.setX(p.x);
npc.setY(p.y);
getWorld().addObject(npc);
getWorld().incUpdatable();
this.locked = true;
this.programIndex = 0;
return npc;
}
@Override
public boolean sendMessage(char[] message) {
String strMessage = String.valueOf(message);
System.out.println("Received message " + strMessage);
if (locked) {
Settlement settlement = NpcPlugin.settlementMap.get(getWorld().getId());
if (Arrays.equals(settlement.getPassword(), message)) {
System.out.println("Factory unlock");
this.locked = false;
return true;
}
System.out.println("Wrong password, " + strMessage + "!=" + String.valueOf(settlement.getPassword()));
} else if (programIndex <= 2048) { //todo config
if (programIndex == 0) {
@ -131,13 +143,11 @@ public class Factory extends Structure implements Updatable, MessageReceiver {
}
System.arraycopy(message, 0, program, programIndex, message.length);
System.out.println("Factory append code: " + strMessage);
System.out.println("Wrote " + message.length + " chars");
programIndex += message.length;
return true;
}
return false;
return true;
}
}

View File

@ -7,7 +7,7 @@ import net.simon987.server.game.item.ItemVoid;
import net.simon987.server.game.objects.Action;
import net.simon987.server.game.objects.ControllableUnit;
import net.simon987.server.game.objects.Direction;
import net.simon987.server.game.objects.HardwareHost;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User;
import org.bson.Document;
import org.json.simple.JSONObject;
@ -17,9 +17,10 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, HardwareHost {
public class HackedNPC extends NonPlayerCharacter implements ControllableUnit {
private static final int MEM_SIZE = GameServer.INSTANCE.getConfig().getInt("hacked_npc_mem_size");
private static final boolean DIE_ON_NO_ENERGY = GameServer.INSTANCE.getConfig().getInt("hacked_npc_die_on_no_energy") != 0;
private CPU cpu;
/**
@ -39,15 +40,15 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
cpu.setMemory(new Memory(MEM_SIZE));
cpu.setHardwareHost(this);
//Write program
boolean write = cpu.getMemory().write(0, program, 0, program.length);
System.out.println("Write " + write);
cpu.getMemory().write(0, program, 0, program.length);
for (Object serialisedHw : (List) NpcPlugin.DEFAULT_HACKED_NPC.get("hardware")) {
HardwareModule hardware = GameServer.INSTANCE.getRegistry().deserializeHardware((Document) serialisedHw, this);
hardware.setCpu(cpu);
attachHardware(hardware, ((Document) serialisedHw).getInteger("address"));
}
setTask(new ExecuteCpuTask());
}
public HackedNPC(Document document) {
@ -68,37 +69,14 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
hardware.setCpu(cpu);
attachHardware(hardware, ((Document) serialisedHw).getInteger("address"));
}
setTask(new ExecuteCpuTask());
}
@Override
public void update() {
super.update();
System.out.println(Util.toHex(cpu.getMemory().getBytes()));
//Execute code
System.out.println("HACKED NPC " + this.getObjectId());
int timeout = Math.min(getEnergy(), 30); //todo get from config
cpu.reset();
int cost = cpu.execute(timeout);
spendEnergy(cost);
if (currentAction == Action.WALKING) {
if (spendEnergy(100)) {
if (!incrementLocation()) {
//Couldn't walk
currentAction = Action.IDLE;
}
} else {
currentAction = Action.IDLE;
}
}
/*
* CurrentAction is set during the code execution and this function is called right after
* If no action as been set, the action sent to the client is the action in currentAction that
* was set last tick (IDLE)
*/
lastAction = currentAction;
currentAction = Action.IDLE;
@ -108,32 +86,49 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
for (HardwareModule module : hardwareAddresses.values()) {
module.update();
}
//Don't bother calling checkCompleted()
getTask().tick(this);
}
@Override
public void setKeyboardBuffer(ArrayList<Integer> kbBuffer) {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has no keyboard module" +
"@HackedNPC::setKeyBoardBuffer()");
Thread.dumpStack();
}
@Override
public void setParent(User user) {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has no parent" +
"@HackedNPC::setParent()");
Thread.dumpStack();
}
@Override
public User getParent() {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has no parent" +
"@HackedNPC::getParent()");
Thread.dumpStack();
return null;
}
@Override
public ArrayList<Integer> getKeyboardBuffer() {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has no keyboard module" +
"@HackedNPC::getKeyBoardBuffer()");
Thread.dumpStack();
return null;
}
@Override
public Memory getFloppyData() {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has floppy data." +
"@HackedNPC::getFloppyData()");
Thread.dumpStack();
return null;
}
@Override
public void setAction(Action action) {
currentAction = action;
@ -141,11 +136,14 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
@Override
public ArrayList<char[]> getConsoleMessagesBuffer() {
return null;
return lastConsoleMessagesBuffer;
}
@Override
public int getConsoleMode() {
LogManager.LOGGER.warning("Something went wrong here: Hacked NPC has no console UI." +
"@HackedNPC::getConsoleMode()");
Thread.dumpStack();
return 0;
}
@ -210,6 +208,10 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
public void setEnergy(int energy) {
NpcBattery battery = (NpcBattery) getHardware(NpcBattery.class);
battery.setEnergy(energy);
if (energy == 0 && DIE_ON_NO_ENERGY) {
setDead(true);
}
}
public boolean spendEnergy(int amount) {
@ -217,6 +219,9 @@ public class HackedNPC extends NonPlayerCharacter implements ControllableUnit, H
NpcBattery battery = (NpcBattery) getHardware(NpcBattery.class);
if (battery.getEnergy() - amount < 0) {
if (DIE_ON_NO_ENERGY) {
setDead(true);
}
return false;
} else {
battery.setEnergy(battery.getEnergy() - amount);

View File

@ -30,7 +30,6 @@ public class HarvesterNPC extends NonPlayerCharacter {
@Override
public void update() {
super.update();
if (getSettlement() != null) {

View File

@ -30,7 +30,7 @@ public class NpcPlugin extends ServerPlugin {
ServerConfiguration configuration = gameServer.getConfig();
GameRegistry registry = gameServer.getRegistry();
listeners.add(new WorldCreationListener(configuration.getInt("factory_spawn_rate")));
listeners.add(new WorldCreationListener(configuration.getInt("settlement_spawn_rate")));
listeners.add(new CpuInitialisationListener());
listeners.add(new VaultWorldUpdateListener(configuration));
listeners.add(new VaultCompleteListener());
@ -54,6 +54,8 @@ public class NpcPlugin extends ServerPlugin {
settlementMap = new ConcurrentHashMap<>();
LogManager.LOGGER.fine("(NPC Plugin) Loading default HackedNPC settings from" +
" defaultHackedCubotHardware.json");
InputStream is = getClass().getClassLoader().getResourceAsStream("defaultHackedCubotHardware.json");
Scanner scanner = new Scanner(is).useDelimiter("\\A");
String json = scanner.next();

View File

@ -55,8 +55,6 @@ public class Settlement implements MongoSerializable {
public Settlement(World world) throws WorldGenerationException {
System.out.println("SETTLING");
this.world = world;
this.difficultyLevel = DifficultyLevel.NORMAL; //TODO randomize ?
this.password = "12345678".toCharArray();

View File

@ -10,7 +10,7 @@ import org.bson.types.ObjectId;
import java.awt.*;
import java.util.ArrayList;
public interface ControllableUnit extends MessageReceiver, Rechargeable, Attackable {
public interface ControllableUnit extends MessageReceiver, Rechargeable, Attackable, HardwareHost {
ObjectId getObjectId();

View File

@ -138,9 +138,9 @@ public class SocketServer {
} else {
ControllableUnit unit = user.getUser().getControlledUnit();
json.put("c", charArraysToJSON(unit.getConsoleMessagesBuffer()));
json.put("console_message_buffer", charArraysToJSON(unit.getConsoleMessagesBuffer()));
json.put("keys", intListToJSON(unit.getKeyboardBuffer()));
json.put("cm", unit.getConsoleMode());
json.put("console_mode", unit.getConsoleMode());
sendJSONObject(user, json);
}

View File

@ -66,12 +66,15 @@ shield_energy_cost=50
npc_lifetime=1024
npc_max_factory_distance=3
factory_max_npc_count=16
factory_spawn_rate=5
factory_program_size=1024
settlement_spawn_rate=5
harvester_hp_max=100
harvester_regen=5
harvester_biomass_drop_count=8
radio_tower_range=3
hacked_npc_mem_size=5120
npc_exec_time=5
hacked_npc_die_on_no_energy=1
#Vaults
vault_door_open_time=4
min_electric_box_count=1

View File

@ -276,6 +276,9 @@ var config = {
lowEnergy: 100,
otherCubotAlpha: 0.6,
},
hackedNpc: {
tint: 0xE040FB,
},
biomass: {
tint: 0x63B85F,
tintHover: 0x00FF00,
@ -537,9 +540,9 @@ var TickListener = (function () {
mar.client.keyboardBuffer.keys = message.keys;
}
if (message.c != undefined) {
mar.client.consoleScreen.handleConsoleBufferUpdate(message.c, message.cm);
mar.client.consoleScreen.handleConsoleBufferUpdate(message.console_message_buffer, message.console_mode);
if (DEBUG) {
console.log("[MAR] Received " + message.c.length + " console message(s)");
console.log("[MAR] Received " + message.console_message_buffer.length + " console message(s)");
}
}
};
@ -921,6 +924,7 @@ var Cubot = (function (_super) {
_this.direction = json.direction;
_this.action = json.action;
_this.energy = _this.getEnergy(json);
_this.baseTint = config.cubot.tint;
_this.cubotSprite = mar.game.make.sprite(0, 0, "sheet", null);
_this.cubotSprite.anchor.set(0.5, 0);
_this.addChild(_this.cubotSprite);
@ -952,7 +956,6 @@ var Cubot = (function (_super) {
_this.setShield(false);
return _this;
}
Cubot.prototype.getEnergy = function (json) {
return json["net.simon987.cubotplugin.CubotBattery"].energy;
};
@ -963,11 +966,11 @@ var Cubot = (function (_super) {
Cubot.prototype.onTileHover = function () {
mar.game.add.tween(this).to({ isoZ: 45 }, 200, Phaser.Easing.Quadratic.InOut, true);
mar.game.add.tween(this.scale).to({ x: 1.2, y: 1.2 }, 200, Phaser.Easing.Linear.None, true);
this.cubotSprite.tint = config.cubot.hoverTint;
if (this.text !== undefined) {
this.text.visible = true;
}
this.hovered = true;
this.cubotSprite.tint = this.getTint();
};
Cubot.prototype.onTileExit = function () {
mar.game.add.tween(this).to({ isoZ: 15 }, 400, Phaser.Easing.Bounce.Out, true);
@ -1007,7 +1010,7 @@ var Cubot = (function (_super) {
return config.cubot.lowEnergyTint;
}
else {
return config.cubot.tint;
return this.baseTint;
}
}
else {
@ -1195,9 +1198,6 @@ var HarvesterNPC = (function (_super) {
_this.text.visible = false;
return _this;
}
HarvesterNPC.prototype.getTint = function () {
return config.cubot.tint;
};
HarvesterNPC.prototype.updateDirection = function () {
switch (this.direction) {
case Direction.NORTH:
@ -1218,7 +1218,7 @@ var HarvesterNPC = (function (_super) {
if (json.hasOwnProperty("net.simon987.npcplugin.NpcBattery")) {
return json["net.simon987.npcplugin.NpcBattery"].energy;
} else {
return 0;
return 1000;
}
};
HarvesterNPC.prototype.updateObject = function (json) {
@ -1242,24 +1242,20 @@ var HarvesterNPC = (function (_super) {
}(Cubot));
var HackedNPC = (function (_super) {
__extends(HackedNPC, _super);
function HackedNPC(json) {
var _this = _super.call(this, json) || this;
_this.updateDirection();
_this.setText("Hacked NPC");
_this.text.visible = false;
_this.tint = 0xE040FB;
_this.baseTint = config.hackedNpc.tint;
_this.cubotSprite.tint = _this.baseTint;
return _this;
}
HackedNPC.prototype.updateObject = function (json) {
_super.prototype.updateObject.call(this, json);
var holoHw = json["net.simon987.cubotplugin.CubotHologram"];
this.updateHologram(holoHw.mode, holoHw.color, holoHw.value, holoHw.string);
};
HackedNPC.prototype.getEnergy = function (json) {
return json["net.simon987.npcplugin.NpcBattery"].energy;
};
return HackedNPC;
}(HarvesterNPC));
var BiomassBlob = (function (_super) {

View File

@ -85,10 +85,12 @@ class TickListener implements MessageListener {
//Update console screen
if (message.c != undefined) {
mar.client.consoleScreen.handleConsoleBufferUpdate(message.c, message.cm as ConsoleMode);
mar.client.consoleScreen.handleConsoleBufferUpdate(
message.console_message_buffer,
message.console_mode as ConsoleMode);
if (DEBUG) {
console.log("[MAR] Received " + message.c.length + " console message(s)")
console.log("[MAR] Received " + message.console_message_buffer.length + " console message(s)")
}
}
}

View File

@ -138,6 +138,7 @@ class Cubot extends GameObject {
protected cubotSprite: Phaser.Sprite;
private shieldBackSprite: Phaser.Sprite;
private shieldFrontSprite: Phaser.Sprite;
protected baseTint: number;
constructor(json) {
//workaround for topological sort, needs sprite dimensions
@ -158,6 +159,7 @@ class Cubot extends GameObject {
this.direction = json.direction;
this.action = json.action;
this.energy = this.getEnergy(json);
this.baseTint = config.cubot.tint;
this.cubotSprite = mar.game.make.sprite(0, 0, "sheet", null);
this.cubotSprite.anchor.set(0.5, 0);
@ -213,13 +215,12 @@ class Cubot extends GameObject {
mar.game.add.tween(this).to({isoZ: 45}, 200, Phaser.Easing.Quadratic.InOut, true);
mar.game.add.tween(this.scale).to({x: 1.2, y: 1.2}, 200, Phaser.Easing.Linear.None, true);
this.cubotSprite.tint = config.cubot.hoverTint;
if (this.text !== undefined) {
this.text.visible = true;
}
this.hovered = true;
this.cubotSprite.tint = this.getTint();
}
@ -269,7 +270,7 @@ class Cubot extends GameObject {
if (this.energy <= config.cubot.lowEnergy) {
return config.cubot.lowEnergyTint;
} else {
return config.cubot.tint;
return this.baseTint;
}
} else {
return config.cubot.hoverTint;
@ -530,13 +531,6 @@ class HarvesterNPC extends Cubot {
this.text.visible = false;
}
/**
* Needs to be overridden because Cubot() calls getTint() when initialised
*/
public getTint() {
return config.cubot.tint;
}
public updateDirection() {
switch (this.direction) {
case Direction.NORTH:
@ -558,7 +552,7 @@ class HarvesterNPC extends Cubot {
if (json.hasOwnProperty("net.simon987.npcplugin.NpcBattery")) {
return json["net.simon987.npcplugin.NpcBattery"].energy;
} else {
return 0;
return 1000; //arbitrary number so that the lowEnergy color thresh doesn't trigger
}
}
@ -600,7 +594,8 @@ class HackedNPC extends HarvesterNPC {
this.updateDirection();
this.setText("Hacked NPC");
this.text.visible = false;
this.tint = 0xE040FB;
this.baseTint = config.hackedNpc.tint;
this.cubotSprite.tint = this.baseTint;
}
updateObject(json) {
@ -609,11 +604,6 @@ class HackedNPC extends HarvesterNPC {
let holoHw = json["net.simon987.cubotplugin.CubotHologram"];
this.updateHologram(holoHw.mode, holoHw.color, holoHw.value, holoHw.string);
}
protected getEnergy(json): number {
return json["net.simon987.npcplugin.NpcBattery"].energy
}
}

View File

@ -18,6 +18,9 @@ let config = {
lowEnergy: 100, //Low energy threshold to change color
otherCubotAlpha: 0.6,
},
hackedNpc: {
tint: 0xE040FB,
},
biomass: {
tint: 0x63B85F,
tintHover: 0x00FF00,