15 Commits
v1.2a ... v1.3a

Author SHA1 Message Date
simon
2e9248ea2e Factory Integration, NPC improvements. #19 & #31. 2017-12-24 14:26:19 -05:00
simon
4f1342593f Added Factory object #31 2017-12-23 12:17:36 -05:00
simon
3548928218 Improved World update performance. Decreased save file size. Added Harvester NPC #19. 2017-12-16 15:40:03 -05:00
simon
cd41db9e58 Added Passive energy source for Cubots #14 2017-12-16 11:35:04 -05:00
simon
597118bd07 Removed files that I accidentally added 2017-12-09 10:52:13 -05:00
simon
9dd9b45d2d Added Day/Night Cycle #14 2017-12-09 10:50:37 -05:00
Simon Fortier
9597a80edf Merge pull request #30 from StevenBerdak/master
Keep backup of old saved files #8
2017-12-08 18:31:16 -05:00
Steven Robert Berdak
d24363fd82 Added file management
.
2017-12-04 17:25:55 -08:00
simon
be45979ed0 Added biomass respawn feature #22 2017-12-02 10:26:59 -05:00
simon
29cac77e79 Changed maven artifactID names 2017-11-22 17:05:50 -05:00
simon
6be2a496c6 Added maven framework support. Started working on NPCs #19 2017-11-21 20:22:11 -05:00
simon
12db25e726 Changed byte array in Memory to char array (+60% performance improvement) 2017-11-18 22:23:32 -05:00
simon
d004386b7b Bug fixes for various operands 2017-11-18 22:21:14 -05:00
simon
e09d2c1b16 Bug fix with [reg] as source operand 2017-11-16 18:41:57 -05:00
simon
c703dec3cf CPU execution time costs energy #16 2017-11-15 12:24:01 -05:00
181 changed files with 2237 additions and 733 deletions

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="Server" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.3.6" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.42" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
</component>
</module>

40
Plugin Cubot/pom.xml Normal file
View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.plugincubot</groupId>
<artifactId>plugin-cubot</artifactId>
<version>1.2a</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -2,10 +2,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Memory;
import net.simon987.server.game.ControllableUnit;
import net.simon987.server.game.Direction;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable;
import net.simon987.server.game.*;
import net.simon987.server.user.User;
import org.json.simple.JSONObject;
@@ -25,8 +22,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
private int hp;
private int heldItem;
private CubotAction currentAction = CubotAction.IDLE;
private CubotAction lastAction = CubotAction.IDLE;
private Action currentAction = Action.IDLE;
private Action lastAction = Action.IDLE;
private ArrayList<Integer> keyboardBuffer = new ArrayList<>();
@@ -37,6 +34,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
private int energy;
private int maxEnergy;
private static final float SOLAR_PANEL_MULTIPLIER = 1;
public Cubot() {
}
@@ -49,14 +48,16 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
@Override
public void update() {
if (currentAction == CubotAction.WALKING) {
storeEnergy((int) (SOLAR_PANEL_MULTIPLIER * GameServer.INSTANCE.getDayNightCycle().getSunIntensity()));
if (currentAction == Action.WALKING) {
if (spendEnergy(100)) {
if (!incrementLocation()) {
//Couldn't walk
currentAction = CubotAction.IDLE;
currentAction = Action.IDLE;
}
} else {
currentAction = CubotAction.IDLE;
currentAction = Action.IDLE;
}
}
@@ -66,7 +67,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
* was set last tick (IDLE)
*/
lastAction = currentAction;
currentAction = CubotAction.IDLE;
currentAction = Action.IDLE;
//Same principle for hologram
lastHologram = hologram;
@@ -76,8 +77,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("id", getObjectId());
json.put("type", ID);
json.put("i", getObjectId());
json.put("t", ID);
json.put("x", getX());
json.put("y", getY());
json.put("direction", getDirection().ordinal());
@@ -85,7 +86,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
json.put("hp", hp);
json.put("action", lastAction.ordinal());
json.put("holo", (int) lastHologram);
json.put("energy", (int) lastHologram);
json.put("energy", energy);
if (parent != null) {
json.put("parent", parent.getUsername()); //Only used client-side for now
@@ -97,12 +98,12 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
public static Cubot deserialize(JSONObject json) {
Cubot cubot = new Cubot();
cubot.setObjectId((int)(long)json.get("id"));
cubot.setX((int)(long)json.get("x"));
cubot.setY((int)(long)json.get("y"));
cubot.hp = (int)(long)json.get("hp");
cubot.setDirection(Direction.getDirection((int)(long)json.get("direction")));
cubot.heldItem = (int)(long)json.get("heldItem");
cubot.setObjectId((long) json.get("i"));
cubot.setX((int) (long) json.get("x"));
cubot.setY((int) (long) json.get("y"));
cubot.hp = (int) (long) json.get("hp");
cubot.setDirection(Direction.getDirection((int) (long) json.get("direction")));
cubot.heldItem = (int) (long) json.get("heldItem");
cubot.energy = (int) (long) json.get("energy");
cubot.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy");
@@ -128,11 +129,11 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
return keyboardBuffer;
}
public void clearKeyboardBuffer(){
public void clearKeyboardBuffer() {
keyboardBuffer.clear();
}
public void setCurrentAction(CubotAction currentAction) {
public void setCurrentAction(Action currentAction) {
this.currentAction = currentAction;
}
@@ -144,7 +145,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
this.parent = parent;
}
public CubotAction getAction() {
public Action getAction() {
return lastAction;
}
@@ -173,7 +174,11 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
energy -= spent;
return true;
}
}
public void storeEnergy(int qty) {
energy = Math.min(energy + qty, maxEnergy);
}
@@ -187,6 +192,13 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
@Override
public Memory getFloppyData() {
return ((CubotFloppyDrive) getParent().getCpu().getHardware(CubotFloppyDrive.DEFAULT_ADDRESS)).getFloppy().getMemory();
CubotFloppyDrive drive = ((CubotFloppyDrive) getParent().getCpu().getHardware(CubotFloppyDrive.DEFAULT_ADDRESS));
if (drive.getFloppy() != null) {
return drive.getFloppy().getMemory();
} else {
return null;
}
}
}

View File

@@ -3,6 +3,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.TileMap;
import org.json.simple.JSONObject;
@@ -41,16 +42,16 @@ public class CubotDrill extends CpuHardware {
} else if (a == GATHER_SLOW || a == GATHER_FAST) {
if (cubot.spendEnergy(1400)) {
if (cubot.getAction() == CubotAction.IDLE) {
if (cubot.getAction() == Action.IDLE) {
int tile = cubot.getWorld().getTileMap().getTileAt(cubot.getX(), cubot.getY());
if (tile == TileMap.IRON_TILE) {
cubot.setHeldItem(TileMap.ITEM_IRON);
cubot.setCurrentAction(CubotAction.DIGGING);
cubot.setCurrentAction(Action.DIGGING);
} else if (tile == TileMap.COPPER_TILE) {
cubot.setHeldItem(TileMap.ITEM_COPPER);
cubot.setCurrentAction(CubotAction.DIGGING);
cubot.setCurrentAction(Action.DIGGING);
}
}
@@ -69,7 +70,7 @@ public class CubotDrill extends CpuHardware {
return json;
}
public static CubotDrill deserialize(JSONObject hwJSON){
return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
public static CubotDrill deserialize(JSONObject hwJSON) {
return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -23,6 +23,8 @@ public class CubotFloppyDrive extends CpuHardware {
public CubotFloppyDrive(Cubot cubot) {
this.cubot = cubot;
floppyDisk = new FloppyDisk();
}
@Override
@@ -94,8 +96,6 @@ public class CubotFloppyDrive extends CpuHardware {
if (hwJSON.containsKey("floppy")) {
drive.floppyDisk = FloppyDisk.deserialise((JSONObject) hwJSON.get("floppy"));
} else {
drive.floppyDisk = new FloppyDisk();
}
return drive;

View File

@@ -33,7 +33,7 @@ public class CubotInventory extends CpuHardware {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if(a == POLL) {
if (a == POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getHeldItem());
@@ -55,7 +55,7 @@ public class CubotInventory extends CpuHardware {
return json;
}
public static CubotInventory deserialize(JSONObject hwJSON){
return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
public static CubotInventory deserialize(JSONObject hwJSON) {
return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -3,6 +3,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject;
@@ -41,14 +42,14 @@ public class CubotLaser extends CpuHardware {
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if(a == WITHDRAW) {
if (a == WITHDRAW) {
Point frontTile = cubot.getFrontTile();
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y);
if (cubot.getAction() != CubotAction.IDLE && objects.size() > 0) {
if (cubot.getAction() != Action.IDLE && objects.size() > 0) {
//FIXME: Problem here if more than 1 object
if (objects.get(0) instanceof InventoryHolder) {
if (((InventoryHolder) objects.get(0)).canTakeItem(b)) {
@@ -57,7 +58,7 @@ public class CubotLaser extends CpuHardware {
((InventoryHolder) objects.get(0)).takeItem(b);
cubot.setHeldItem(b);
cubot.setCurrentAction(CubotAction.WITHDRAWING);
cubot.setCurrentAction(Action.WITHDRAWING);
}
}
}
@@ -80,7 +81,7 @@ public class CubotLaser extends CpuHardware {
return json;
}
public static CubotLaser deserialize(JSONObject hwJSON){
return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
public static CubotLaser deserialize(JSONObject hwJSON) {
return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -3,6 +3,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.Direction;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
@@ -37,12 +38,12 @@ public class CubotLeg extends CpuHardware implements JSONSerialisable {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if(a == SET_DIR){
if (a == SET_DIR) {
Direction dir = Direction.getDirection(b);
if(dir != null){
if (dir != null) {
if (cubot.spendEnergy(20)) {
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
@@ -52,18 +53,18 @@ public class CubotLeg extends CpuHardware implements JSONSerialisable {
}
} else if(a == SET_DIR_AND_WALK){
} else if (a == SET_DIR_AND_WALK) {
Direction dir = Direction.getDirection(b);
if(dir != null){
if (dir != null) {
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
} else {
status.setErrorFlag(true);
}
cubot.setCurrentAction(CubotAction.WALKING);
cubot.setCurrentAction(Action.WALKING);
}
}
@@ -77,8 +78,8 @@ public class CubotLeg extends CpuHardware implements JSONSerialisable {
return json;
}
public static CubotLeg deserialize(JSONObject hwJSON){
return new CubotLeg((Cubot)GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
public static CubotLeg deserialize(JSONObject hwJSON) {
return new CubotLeg((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}

View File

@@ -2,6 +2,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Memory;
import net.simon987.server.assembly.Status;
import net.simon987.server.game.World;
import net.simon987.server.game.pathfinding.Node;
@@ -46,7 +47,7 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
switch (a){
switch (a) {
case GET_POS:
getCpu().getRegisterSet().getRegister("X").setValue(cubot.getX());
getCpu().getRegisterSet().getRegister("Y").setValue(cubot.getY());
@@ -62,7 +63,7 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
destX, destY, b);
//Write to memory
byte[] mem = getCpu().getMemory().getBytes();
Memory mem = getCpu().getMemory();
int counter = MEMORY_PATH_START;
@@ -80,32 +81,26 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
if (n.x < lastNode.x) {
//West
mem[counter++] = 0;
mem[counter++] = 3;
mem.set(counter++, 3);
} else if (n.x > lastNode.x) {
//East
mem[counter++] = 0;
mem[counter++] = 1;
mem.set(counter++, 1);
} else if (n.y < lastNode.y) {
//North
mem[counter++] = 0;
mem[counter++] = 0;
mem.set(counter++, 0);
} else if (n.y > lastNode.y) {
//South
mem[counter++] = 0;
mem[counter++] = 2;
mem.set(counter++, 2);
}
lastNode = n;
}
//Indicate end of path with 0xAAAA
mem[counter++] = -86;
mem[counter] = -86;
mem.set(counter, 0xAAAA);
} else {
//Indicate invalid path 0xFFFF
mem[counter++] = -1;
mem[counter] = -1;
mem.set(counter, 0xFFFF);
}
LogManager.LOGGER.fine("DEBUG: path to" + destX + "," + destY);

View File

@@ -2,6 +2,7 @@ package net.simon987.cubotplugin;
import net.simon987.cubotplugin.event.CpuInitialisationListener;
import net.simon987.cubotplugin.event.UserCreationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.CpuHardwareDeserializer;
@@ -10,11 +11,11 @@ import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer{
public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer {
@Override
public void init() {
public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener());
listeners.add(new UserCreationListener());
@@ -24,9 +25,9 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
@Override
public GameObject deserializeObject(JSONObject object) {
int objType = (int)(long)object.get("type");
int objType = (int) (long) object.get("t");
if(objType == Cubot.ID) {
if (objType == Cubot.ID) {
return Cubot.deserialize(object);
}
@@ -36,9 +37,9 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
@Override
public CpuHardware deserializeHardware(JSONObject hwJson) {
int hwid = (int)(long)hwJson.get("hwid");
int hwid = (int) (long) hwJson.get("hwid");
switch (hwid){
switch (hwid) {
case CubotLeg.HWID:
return CubotLeg.deserialize(hwJson);
case CubotLaser.HWID:

View File

@@ -25,7 +25,7 @@ public class FloppyDisk implements JSONSerialisable {
public FloppyDisk() {
this.memory = new Memory(1024 * 1440);
this.memory = new Memory(512 * 1440);
}
/**
@@ -39,7 +39,7 @@ public class FloppyDisk implements JSONSerialisable {
public boolean readSector(int sector, Memory cpuMemory, int ramAddress) {
if (sector <= 1440) {
cpuMemory.write(ramAddress, memory.getBytes(), sector * 1024, 1024);
cpuMemory.write(ramAddress, memory.getWords(), sector * 512, 512);
//Calculate seek time
int deltaTrack = (sector / 80) - rwHeadTrack;
@@ -66,7 +66,7 @@ public class FloppyDisk implements JSONSerialisable {
public boolean writeSector(int sector, Memory cpuMemory, int ramAddress) {
if (sector <= 1440) {
memory.write(sector * 512, cpuMemory.getBytes(), ramAddress * 2, 1024);
memory.write(sector * 512, cpuMemory.getWords(), ramAddress, 512);
//Calculate seek time
int deltaTrack = (sector / 80) - rwHeadTrack;

View File

@@ -11,7 +11,7 @@ public class Keyboard extends CpuHardware {
private static final int CLEAR_BUFFER = 0;
private static final int FETCH_KEY = 1;
/**
* Hardware ID (Should be unique)
*/
@@ -33,14 +33,14 @@ public class Keyboard extends CpuHardware {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if(a == CLEAR_BUFFER){
if (a == CLEAR_BUFFER) {
cubot.clearKeyboardBuffer();
} else if (a == FETCH_KEY){
} else if (a == FETCH_KEY) {
//pop
int key = 0;
if(cubot.getKeyboardBuffer().size() > 0){
if (cubot.getKeyboardBuffer().size() > 0) {
key = cubot.getKeyboardBuffer().get(0);
cubot.getKeyboardBuffer().remove(0);
}
@@ -61,7 +61,7 @@ public class Keyboard extends CpuHardware {
return json;
}
public static Keyboard deserialize(JSONObject hwJSON){
return new Keyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
public static Keyboard deserialize(JSONObject hwJSON) {
return new Keyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -18,8 +18,8 @@ public class CpuInitialisationListener implements GameEventListener {
public void handle(GameEvent event) {
LogManager.LOGGER.fine("(Plugin) Handled CPU Initialisation event (Cubot Plugin)");
CPU cpu = (CPU)event.getSource();
User user = ((CpuInitialisationEvent)event).getUser();
CPU cpu = (CPU) event.getSource();
User user = ((CpuInitialisationEvent) event).getUser();
CubotLeg legHw = new CubotLeg((Cubot) user.getControlledUnit());
legHw.setCpu(cpu);

View File

@@ -19,7 +19,7 @@ public class UserCreationListener implements GameEventListener {
@Override
public void handle(GameEvent event) {
User user = (User)event.getSource();
User user = (User) event.getSource();
LogManager.LOGGER.fine("(Plugin) Handled User creation event (Cubot Plugin)");
@@ -29,6 +29,7 @@ public class UserCreationListener implements GameEventListener {
GameServer.INSTANCE.getConfig().getInt("new_user_worldX"),
GameServer.INSTANCE.getConfig().getInt("new_user_worldY")));
cubot.getWorld().getGameObjects().add(cubot);
cubot.getWorld().incUpdatable();
cubot.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());

View File

@@ -1,3 +0,0 @@
classpath=net.simon987.kilnplugin.KilnPlugin
name=Kiln Plugin
version=1.0

View File

@@ -1,21 +0,0 @@
package net.simon987.kilnplugin;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class KilnPlugin extends ServerPlugin implements GameObjectDeserializer {
@Override
public void init() {
}
@Override
public GameObject deserializeObject(JSONObject object) {
return null;
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="Server" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.3.6" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.42" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
</component>
</module>

39
Plugin Misc HW/pom.xml Normal file
View File

@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.pluginmischw</groupId>
<artifactId>plugin-misc-hw</artifactId>
<version>1.2a</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,6 +1,7 @@
package net.simon987.mischwplugin;
import net.simon987.mischwplugin.event.CpuInitialisationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.logging.LogManager;
@@ -11,7 +12,7 @@ public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserialize
@Override
public void init() {
public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener());
LogManager.LOGGER.info("Initialised Misc Hardware Plugin");

21
Plugin NPC/Plugin NPC.iml Normal file
View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="module" module-name="Server" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.3.6" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.42" level="project" />
</component>
</module>

View File

@@ -0,0 +1,3 @@
classpath=net.simon987.npcplugin.NpcPlugin
name=NPC Plugin
version=1.0

36
Plugin NPC/pom.xml Normal file
View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.pluginnpc</groupId>
<artifactId>plugin-npc</artifactId>
<version>1.2a</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,184 @@
package net.simon987.npcplugin;
import net.simon987.server.GameServer;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.*;
import java.util.ArrayList;
public class Factory extends GameObject implements Updatable {
private static final int MAP_INFO = 0x0200;
static final int ID = 3;
private static final int MAX_NPC_COUNT = GameServer.INSTANCE.getConfig().getInt("factory_max_npc_count");
private static final int NPC_CREATION_COOLDOWN = NonPlayerCharacter.LIFETIME / MAX_NPC_COUNT;
private ArrayList<NonPlayerCharacter> npcs = new ArrayList<>();
/**
* Number of ticks to wait until the Factory can spawn a new NPC
*/
private int cooldown = 0;
/**
* Temporary NPC objectId array. The Factory links the NPCs to itself when initialised,
* at the first call of update().
*/
private Object[] tmpNpcArray = new Object[0];
/**
* Factory are uninitialised until the first update() call
*/
private boolean initialised = false;
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
if (!initialised) {
initialised = true;
for (Object id : tmpNpcArray) {
NonPlayerCharacter npc = (NonPlayerCharacter) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) id);
npc.setFactory(this);
npcs.add(npc);
}
} else {
if (cooldown == 0) {
if (npcs.size() < MAX_NPC_COUNT) {
Point p = getAdjacentTile();
if (p != null) {
NonPlayerCharacter npc = new HarvesterNPC();
npc.setWorld(getWorld());
npc.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
npc.setX(p.x);
npc.setY(p.y);
getWorld().getGameObjects().add(npc);
getWorld().incUpdatable();
npc.setFactory(this);
npcs.add(npc);
}
}
cooldown += NPC_CREATION_COOLDOWN;
} else {
cooldown--;
}
}
}
@Override
public boolean isAt(int x, int y) {
/*
* Object is 2x2 tiles, the (x,y) coordinates of the object being
* at top-left.
* # .
* . .
*/
return (x == getX() + 1 || x == getX()) && (y == getY() + 1 || y == getY());
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("i", getObjectId());
json.put("x", getX());
json.put("y", getY());
json.put("t", ID);
JSONArray tmpNpcArray = new JSONArray();
for (NonPlayerCharacter npc : npcs) {
tmpNpcArray.add(npc.getObjectId());
}
json.put("n", tmpNpcArray);
return json;
}
public static Factory deserialise(JSONObject json) {
Factory factory = new Factory();
factory.setObjectId((long) json.get("i"));
factory.setX((int) (long) json.get("x"));
factory.setY((int) (long) json.get("y"));
factory.tmpNpcArray = (Object[]) ((JSONArray) json.get("n")).toArray();
return factory;
}
/**
* Get the first non-blocked tile that is directly adjacent to the factory, starting from the north-east corner
* going clockwise.
*
* @return The coordinates of the first non-blocked tile, null otherwise.
*/
public Point getAdjacentTile() {
/*
* (2,0)
* (2,1)
* (1,2)
* (0,2)
* (-1,1)
* (-1,0)
* (0,-1)
* (1,-1)
*/
if (!getWorld().isTileBlocked(getX() + 2, getY())) {
return new Point(getX() + 2, getY());
} else if (!getWorld().isTileBlocked(getX() + 2, getY() + 1)) {
return new Point(getX() + 2, getY() + 1);
} else if (!getWorld().isTileBlocked(getX() + 1, getY() + 2)) {
return new Point(getX() + 1, getY() + 2);
} else if (!getWorld().isTileBlocked(getX(), getY() + 2)) {
return new Point(getX(), getY() + 2);
} else if (!getWorld().isTileBlocked(getX() + -1, getY() + 1)) {
return new Point(getX() + -1, getY() + 1);
} else if (!getWorld().isTileBlocked(getX() + -1, getY())) {
return new Point(getX() + -1, getY());
} else if (!getWorld().isTileBlocked(getX(), getY() + -1)) {
return new Point(getX(), getY() + -1);
} else if (!getWorld().isTileBlocked(getX() + 1, getY() + -1)) {
return new Point(getX() + 1, getY() + -1);
} else {
return null;
}
}
ArrayList<NonPlayerCharacter> getNpcs() {
return npcs;
}
}

View File

@@ -0,0 +1,105 @@
package net.simon987.npcplugin;
import net.simon987.server.assembly.Util;
import net.simon987.server.game.Direction;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder;
import net.simon987.server.logging.LogManager;
import java.util.ArrayList;
import java.util.Random;
public class HarvestTask extends NPCTask {
private Random random;
private int pause;
public HarvestTask() {
random = new Random();
pause = 0;
}
private Direction nextWorldDirection = null;
@Override
public boolean checkCompleted() {
return false;
}
@Override
public void tick(NonPlayerCharacter npc) {
if (pause == 0) {
//Get biomass
ArrayList<GameObject> biomass = new ArrayList<>(10);
for (GameObject object : npc.getWorld().getGameObjects()) {
//Plant MAP_INFO
if ((object.getMapInfo() & 0x4000) == 0x4000) {
biomass.add(object);
}
}
//Get closest one
int minDist = Integer.MAX_VALUE;
GameObject minBiomass = null;
for (GameObject plant : biomass) {
int dist = Util.manhattanDist(npc.getX(), npc.getY(), plant.getX(), plant.getY());
if (dist < minDist) {
minDist = dist;
minBiomass = plant;
}
}
//Move towards it
if (minBiomass != null && minDist == 1) {
//Reached biomass, change direction to face it
Direction newDirection = Direction.getFacing(npc.getX(), npc.getY(),
minBiomass.getX(), minBiomass.getY());
if (newDirection != null) {
npc.setDirection(newDirection);
//Reached biomass, harvest it
if (minBiomass instanceof InventoryHolder) {
((InventoryHolder) minBiomass).takeItem(1);
pause += 6;
}
} else {
LogManager.LOGGER.severe("FIXME: tick:HarvestTask, Direction is null");
}
nextWorldDirection = null;
} else if (minBiomass != null && npc.moveTo(minBiomass.getX(), minBiomass.getY(), 1)) {
//Moving towards biomass...
nextWorldDirection = null;
} else {
if (nextWorldDirection == null) {
while (!npc.gotoWorld(nextWorldDirection)) {
nextWorldDirection = Direction.getDirection(random.nextInt(4));
}
pause += 6;
} else {
npc.gotoWorld(nextWorldDirection);
}
}
} else {
pause--;
}
}
}

View File

@@ -0,0 +1,69 @@
package net.simon987.npcplugin;
import net.simon987.server.GameServer;
import net.simon987.server.game.Direction;
import org.json.simple.JSONObject;
public class HarvesterNPC extends NonPlayerCharacter {
public static final int ID = 10;
public HarvesterNPC() {
setTask(new HarvestTask());
hp = 10;
}
@Override
public void update() {
super.update();
if (getFactory() != null) {
if (getTask().checkCompleted()) {
setTask(new HarvestTask());
} else {
getTask().tick(this);
}
//Self-destroy when age limit is reached
if (getAge() >= NonPlayerCharacter.LIFETIME) {
setDead(true);
getFactory().getNpcs().remove(this);
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = super.serialise();
json.put("i", getObjectId());
json.put("x", getX());
json.put("y", getY());
json.put("direction", getDirection().ordinal());
json.put("hp", hp);
json.put("energy", energy);
json.put("action", getAction().ordinal());
json.put("t", ID);
return json;
}
public static HarvesterNPC deserialize(JSONObject json) {
HarvesterNPC npc = new HarvesterNPC();
npc.setObjectId((long) json.get("i"));
npc.setX((int) (long) json.get("x"));
npc.setY((int) (long) json.get("y"));
npc.hp = (int) (long) json.get("hp");
npc.setDirection(Direction.getDirection((int) (long) json.get("direction")));
npc.energy = (int) (long) json.get("energy");
npc.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy");
return npc;
}
}

View File

@@ -0,0 +1,10 @@
package net.simon987.npcplugin;
public abstract class NPCTask {
public abstract boolean checkCompleted();
public abstract void tick(NonPlayerCharacter npc);
}

View File

@@ -0,0 +1,184 @@
package net.simon987.npcplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Util;
import net.simon987.server.game.Action;
import net.simon987.server.game.Direction;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable;
import net.simon987.server.game.pathfinding.Node;
import net.simon987.server.game.pathfinding.Pathfinder;
import net.simon987.server.logging.LogManager;
import java.util.ArrayList;
public abstract class NonPlayerCharacter extends GameObject implements Updatable {
private static final int MAP_INFO = 0x0040;
private static final int MAX_FACTORY_DISTANCE = GameServer.INSTANCE.getConfig().getInt("npc_max_factory_distance");
public static final int LIFETIME = GameServer.INSTANCE.getConfig().getInt("npc_lifetime");
//Unused
int hp;
int energy;
int maxEnergy;
/**
* Current task
*/
private NPCTask task;
private Action lastAction = Action.IDLE;
/**
* Factory that created this NPC
*/
private Factory factory;
/**
* If set to true, the NPC will be destroyed next tick if it is
* not linked to a Factory
*/
private boolean selfDestroyNextTick = false;
/**
* Age of the npc, in ticks
*/
private int age = 0;
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
age++;
//Destroy NPCs that are not linked with a Factory
if (factory == null) {
if (selfDestroyNextTick) {
setDead(true);
}
selfDestroyNextTick = true;
}
}
/**
* Attempt to move the NPC to the specified coordinates
*
* @param range distance to the desired coordinates, in tiles
* @return true if the path is passable
*/
boolean moveTo(int x, int y, int range) {
ArrayList<Node> path = Pathfinder.findPath(getWorld(), getX(), getY(), x, y, range);
if (path != null && path.size() > 0) {
Node nextTile = path.get(1);
Direction newDirection = Direction.getFacing(getX(), getY(), nextTile.x, nextTile.y);
if (newDirection != null) {
setDirection(newDirection);
} else {
LogManager.LOGGER.severe("FIXME: moveTo:NonPlayerCharacter, Direction is null");
}
if (incrementLocation()) {
lastAction = Action.WALKING;
return true;
}
}
lastAction = Action.IDLE;
return false;
}
/**
* Go to the next World in the specified Direction.
*
* @return true if the World in the specified Direction is within the max. distance from the Factory
*/
boolean gotoWorld(Direction direction) {
if (direction == Direction.NORTH) {
if (Util.manhattanDist(factory.getWorld().getX(), factory.getWorld().getY(),
getWorld().getX(), getWorld().getY() - 1) <= MAX_FACTORY_DISTANCE) {
if (!moveTo(8, 0, 0)) {
setDirection(Direction.NORTH);
incrementLocation();
}
return true;
} else {
return false;
}
} else if (direction == Direction.EAST) {
if (Util.manhattanDist(factory.getWorld().getX(), factory.getWorld().getY(),
getWorld().getX() + 1, getWorld().getY()) <= MAX_FACTORY_DISTANCE) {
if (!moveTo(15, 7, 0)) {
setDirection(Direction.EAST);
incrementLocation();
}
return true;
} else {
return false;
}
} else if (direction == Direction.SOUTH) {
if (Util.manhattanDist(factory.getWorld().getX(), factory.getWorld().getY(),
getWorld().getX(), getWorld().getY() + 1) <= MAX_FACTORY_DISTANCE) {
if (!moveTo(8, 15, 0)) {
setDirection(Direction.SOUTH);
incrementLocation();
}
return true;
} else {
return false;
}
} else if (direction == Direction.WEST) {
if (Util.manhattanDist(factory.getWorld().getX(), factory.getWorld().getY(),
getWorld().getX() - 1, getWorld().getY()) <= MAX_FACTORY_DISTANCE) {
if (!moveTo(0, 7, 0)) {
setDirection(Direction.WEST);
incrementLocation();
}
return true;
} else {
return false;
}
} else {
return false;
}
}
public NPCTask getTask() {
return task;
}
public void setTask(NPCTask task) {
this.task = task;
}
public Action getAction() {
return lastAction;
}
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
public int getAge() {
return age;
}
}

View File

@@ -0,0 +1,35 @@
package net.simon987.npcplugin;
import net.simon987.npcplugin.event.WorldCreationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class NpcPlugin extends ServerPlugin implements GameObjectDeserializer {
@Override
public void init(ServerConfiguration configuration) {
listeners.add(new WorldCreationListener());
LogManager.LOGGER.info("Initialised NPC plugin");
}
@Override
public GameObject deserializeObject(JSONObject object) {
int objType = (int) (long) object.get("t");
if (objType == HarvesterNPC.ID) {
return HarvesterNPC.deserialize(object);
} else if (objType == Factory.ID) {
return Factory.deserialise(object);
}
return null;
}
}

View File

@@ -0,0 +1,64 @@
package net.simon987.npcplugin.event;
import net.simon987.npcplugin.Factory;
import net.simon987.server.GameServer;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.event.WorldGenerationEvent;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
import java.util.Random;
public class WorldCreationListener implements GameEventListener {
/**
* Spawn rate. Higher = rarer: A factory will be spawn about every FACTORY_SPAWN_RATE generated Worlds
*/
private static final int FACTORY_SPAWN_RATE = 35;
private Random random = new Random();
@Override
public Class getListenedEventType() {
return WorldGenerationEvent.class;
}
@Override
public void handle(GameEvent event) {
if (random.nextInt(FACTORY_SPAWN_RATE) == 0) {
World world = ((WorldGenerationEvent) event).getWorld();
for (int x = 2; x < 12; x++) {
for (int y = 2; y < 12; y++) {
if ((!world.isTileBlocked(x, y) && !world.isTileBlocked(x + 1, y) &&
!world.isTileBlocked(x, y + 1) && !world.isTileBlocked(x + 1, y + 1))) {
Factory factory = new Factory();
factory.setWorld(world);
factory.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
factory.setX(x);
factory.setY(y);
if (factory.getAdjacentTile() == null) {
//Factory has no non-blocked adjacent tiles
continue;
}
world.getGameObjects().add(factory);
world.incUpdatable();
LogManager.LOGGER.info("Spawned Factory at (" + world.getX() + ", " + world.getY() +
") (" + x + ", " + y + ")");
return;
}
}
}
}
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="module" module-name="Server" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.3.6" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.42" level="project" />
</component>
</module>

View File

@@ -1,3 +0,0 @@
classpath=net.simon987.plantplugin.PlantPlugin
name=Plant Plugin
version=1.0

36
Plugin Plant/pom.xml Normal file
View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.pluginplant</groupId>
<artifactId>plugin-biomassBlob</artifactId>
<version>1.2a</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,110 @@
package net.simon987.biomassplugin;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject;
public class BiomassBlob extends GameObject implements InventoryHolder {
private static final char MAP_INFO = 0x4000;
public static final int ID = 2;
/**
* Yield of the blob, in biomass units
*/
private int biomassCount;
/**
* Style of the blob (Only visual)
*/
// private int style;
private static final int ITM_BIOMASS = 1;
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("t", ID);
json.put("i", getObjectId());
json.put("x", getX());
json.put("y", getY());
json.put("b", biomassCount);
// json.put("style", style);
return json;
}
public int getBiomassCount() {
return biomassCount;
}
public void setBiomassCount(int biomassCount) {
this.biomassCount = biomassCount;
}
// public int getStyle() {
// return style;
// }
//
// public void setStyle(int style) {
// this.style = style;
// }
public static BiomassBlob deserialize(JSONObject json) {
BiomassBlob biomassBlob = new BiomassBlob();
biomassBlob.setObjectId((long) json.get("i"));
biomassBlob.setX((int) (long) json.get("x"));
biomassBlob.setY((int) (long) json.get("y"));
// biomassBlob.style = (int) (long) json.get("style");
biomassBlob.biomassCount = (int) (long) json.get("b");
return biomassBlob;
}
/**
* Called when an object attempts to place an item in this BiomassBlob
*
* @param item item id (see MarConstants.ITEM_*)
* @return Always returns false
*/
@Override
public boolean placeItem(int item) {
//Why would you want to place an item in a blob?
return false;
}
@Override
public boolean canTakeItem(int item) {
return item == ITM_BIOMASS && biomassCount >= 1;
}
/**
* Called when an object attempts to take an item from this BiomassBlob.
* If the object requests biomass, it will be subtracted from biomassCount, and
* if it reaches 0, the plant is deleted
*
* @param item item id (see MarConstants.ITEM_*)
*/
@Override
public void takeItem(int item) {
if (item == ITM_BIOMASS) {
if (biomassCount > 1) {
biomassCount--;
} else {
//Delete plant
setDead(true);
}
}
}
}

View File

@@ -0,0 +1,35 @@
package net.simon987.biomassplugin;
import net.simon987.biomassplugin.event.WorldCreationListener;
import net.simon987.biomassplugin.event.WorldUpdateListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class BiomassPlugin extends ServerPlugin implements GameObjectDeserializer {
@Override
public void init(ServerConfiguration config) {
listeners.add(new WorldCreationListener());
listeners.add(new WorldUpdateListener(config));
LogManager.LOGGER.info("Initialised Biomass plugin");
}
@Override
public GameObject deserializeObject(JSONObject object) {
int objType = (int) (long) object.get("t");
if (objType == BiomassBlob.ID) {
return BiomassBlob.deserialize(object);
}
return null;
}
}

View File

@@ -0,0 +1,81 @@
package net.simon987.biomassplugin;
import net.simon987.server.GameServer;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
public class WorldUtils {
/**
* Generate a list of biomass blobs for a world
*/
public static ArrayList<BiomassBlob> generateBlobs(World world, int minCount, int maxCount, int yield) {
Random random = new Random();
int blobCount = random.nextInt(maxCount - minCount) + minCount;
ArrayList<BiomassBlob> biomassBlobs = new ArrayList<>(maxCount);
//Count number of plain tiles. If there is less plain tiles than desired amount of blobs,
//set the desired amount of blobs to the plain tile count
int[][] tiles = world.getTileMap().getTiles();
int plainCount = 0;
for (int y = 0; y < World.WORLD_SIZE; y++) {
for (int x = 0; x < World.WORLD_SIZE; x++) {
if (tiles[x][y] == 0) {
plainCount++;
}
}
}
if (blobCount > plainCount) {
blobCount = plainCount;
}
outerLoop:
for (int i = 0; i < blobCount; i++) {
Point p = world.getTileMap().getRandomPlainTile();
if (p != null) {
//Don't block worlds
int counter = 0;
while (p.x == 0 || p.y == 0 || p.x == World.WORLD_SIZE - 1 || p.y == World.WORLD_SIZE - 1 ||
world.isTileBlocked(p.x, p.y)) {
p = world.getTileMap().getRandomPlainTile();
counter++;
if (counter > 25) {
continue outerLoop;
}
}
for (BiomassBlob biomassBlob : biomassBlobs) {
if (biomassBlob.getX() == p.x && biomassBlob.getY() == p.y) {
//There is already a blob here
continue outerLoop;
}
}
BiomassBlob biomassBlob = new BiomassBlob();
biomassBlob.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
// biomassBlob.setStyle(0); //TODO: set style depending on difficulty level? or random? from config?
biomassBlob.setBiomassCount(yield);
biomassBlob.setX(p.x);
biomassBlob.setY(p.y);
biomassBlob.setWorld(world);
biomassBlobs.add(biomassBlob);
}
}
LogManager.LOGGER.info("Generated " + biomassBlobs.size() + " biomassBlobs for World (" + world.getX() + ',' +
world.getY() + ')');
return biomassBlobs;
}
}

View File

@@ -0,0 +1,31 @@
package net.simon987.biomassplugin.event;
import net.simon987.biomassplugin.BiomassBlob;
import net.simon987.biomassplugin.WorldUtils;
import net.simon987.server.GameServer;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.event.WorldGenerationEvent;
import java.util.ArrayList;
public class WorldCreationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return WorldGenerationEvent.class;
}
@Override
public void handle(GameEvent event) {
int minCount = GameServer.INSTANCE.getConfig().getInt("minBiomassCount");
int maxCount = GameServer.INSTANCE.getConfig().getInt("maxBiomassCount");
int yield = GameServer.INSTANCE.getConfig().getInt("biomass_yield");
ArrayList<BiomassBlob> biomassBlobs = WorldUtils.generateBlobs(((WorldGenerationEvent) event).getWorld(),
minCount, maxCount, yield);
((WorldGenerationEvent) event).getWorld().getGameObjects().addAll(biomassBlobs);
}
}

View File

@@ -0,0 +1,72 @@
package net.simon987.biomassplugin.event;
import net.simon987.biomassplugin.BiomassBlob;
import net.simon987.biomassplugin.WorldUtils;
import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.event.WorldUpdateEvent;
import net.simon987.server.game.World;
import java.util.ArrayList;
import java.util.HashMap;
public class WorldUpdateListener implements GameEventListener {
private HashMap<World, Long> worldWaitMap = new HashMap<>(200);
private int minBlobCount;
private int maxBlobCount;
private int blobYield;
private int waitTime;
private int blobThreshold;
public WorldUpdateListener(ServerConfiguration config) {
minBlobCount = config.getInt("minBiomassRespawnCount");
maxBlobCount = config.getInt("maxBiomassRespawnCount");
waitTime = config.getInt("biomassRespawnTime");
blobThreshold = config.getInt("biomassRespawnThreshold");
blobYield = config.getInt("biomass_yield");
}
@Override
public Class getListenedEventType() {
return WorldUpdateEvent.class;
}
@Override
public void handle(GameEvent event) {
World world = ((WorldUpdateEvent) event).getWorld();
//If there is less than the respawn threshold,
if (world.getGameObjects(BiomassBlob.class).size() < blobThreshold) {
//Set a timer for respawn_time ticks
if (!worldWaitMap.containsKey(world) || worldWaitMap.get(world) == 0L) {
worldWaitMap.put(world, GameServer.INSTANCE.getGameUniverse().getTime() + waitTime);
} else {
long waitUntil = worldWaitMap.get(world);
if (GameServer.INSTANCE.getGameUniverse().getTime() >= waitUntil) {
//If the timer was set less than respawn_time ticks ago, respawn the blobs
ArrayList<BiomassBlob> newBlobs = WorldUtils.generateBlobs(world, minBlobCount,
maxBlobCount, blobYield);
world.getGameObjects().addAll(newBlobs);
//Set the 'waitUntil' time to 0 to indicate that we are not waiting
worldWaitMap.replace(world, 0L);
}
}
}
}
}

View File

@@ -0,0 +1,3 @@
classpath=net.simon987.biomassplugin.BiomassPlugin
name=Biomass Plugin
version=1.0

View File

@@ -1,160 +0,0 @@
package net.simon987.plantplugin;
import net.simon987.server.GameServer;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder;
import net.simon987.server.game.Updatable;
import org.json.simple.JSONObject;
public class Plant extends GameObject implements Updatable, InventoryHolder{
private static final char MAP_INFO = 0x4000;
public static final int ID = 2;
/**
* Grow time (see config.properties)
*/
private static final int GROW_TIME = GameServer.INSTANCE.getConfig().getInt("plant_grow_time");
/**
* Game time of the creation of this Plant
*/
private long creationTime;
/**
* Whether the plant is grown or not
*/
private boolean grown;
/**
* Yield of the plant, in biomass units
*/
private int biomassCount;
/**
* Style of the plant (Only visual)
*/
private int style;
private static final int ITM_BIOMASS = 1;
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("type", ID);
json.put("id", getObjectId());
json.put("x", getX());
json.put("y", getY());
json.put("creationTime", creationTime);
json.put("grown", grown);
json.put("biomassCount", biomassCount);
json.put("style", style);
return json;
}
/**
* Called every tick
*/
@Override
public void update() {
if (!grown) {
//Check grow
if (creationTime + GROW_TIME <= GameServer.INSTANCE.getGameUniverse().getTime()) {
grown = true;
biomassCount = GameServer.INSTANCE.getConfig().getInt("plant_yield");
}
}
}
public long getCreationTime() {
return creationTime;
}
public void setCreationTime(long creationTime) {
this.creationTime = creationTime;
}
public boolean isGrown() {
return grown;
}
public void setGrown(boolean grown) {
this.grown = grown;
}
public int getBiomassCount() {
return biomassCount;
}
public void setBiomassCount(int biomassCount) {
this.biomassCount = biomassCount;
}
public int getStyle() {
return style;
}
public void setStyle(int style) {
this.style = style;
}
public static Plant deserialize(JSONObject json){
Plant plant = new Plant();
plant.setObjectId((int)(long)json.get("id"));
plant.setX((int)(long)json.get("x"));
plant.setY((int)(long)json.get("y"));
plant.grown = (boolean)json.get("grown");
plant.creationTime = (long)json.get("creationTime");
plant.style = (int)(long)json.get("style");
plant.biomassCount = (int)(long)json.get("biomassCount");
return plant;
}
/**
* Called when an object attempts to place an item in this Plant
*
* @param item item id (see MarConstants.ITEM_*)
* @return Always returns false
*/
@Override
public boolean placeItem(int item) {
//Why would you want to place an item in a plant?
return false;
}
@Override
public boolean canTakeItem(int item) {
return item == ITM_BIOMASS && grown && biomassCount >= 1;
}
/**
* Called when an object attempts to take an item from this Plant.
* If the object requests biomass, it will be subtracted from biomassCount, and
* if it reaches 0, the plant is deleted
*
* @param item item id (see MarConstants.ITEM_*)
*/
@Override
public void takeItem(int item) {
if (item == ITM_BIOMASS) {
if (grown && biomassCount > 1) {
biomassCount--;
} else if (grown) {
//Delete plant
setDead(true);
}
}
}
}

View File

@@ -1,32 +0,0 @@
package net.simon987.plantplugin;
import net.simon987.plantplugin.event.WorldCreationListener;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class PlantPlugin extends ServerPlugin implements GameObjectDeserializer {
@Override
public void init() {
listeners.add(new WorldCreationListener());
LogManager.LOGGER.info("Initialised Plant plugin");
}
@Override
public GameObject deserializeObject(JSONObject object) {
int objType = (int)(long)object.get("type");
if(objType == Plant.ID) {
return Plant.deserialize(object);
}
return null;
}
}

View File

@@ -1,96 +0,0 @@
package net.simon987.plantplugin.event;
import net.simon987.plantplugin.Plant;
import net.simon987.server.GameServer;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.event.WorldGenerationEvent;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
public class WorldCreationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return WorldGenerationEvent.class;
}
@Override
public void handle(GameEvent event) {
ArrayList<Plant> plants = generatePlants(((WorldGenerationEvent)event).getWorld());
((WorldGenerationEvent)event).getWorld().getGameObjects().addAll(plants);
}
/**
* Generate a list of plants for a world
*/
public ArrayList<Plant> generatePlants(World world) {
int minTreeCount = GameServer.INSTANCE.getConfig().getInt("minTreeCount");
int maxTreeCount = GameServer.INSTANCE.getConfig().getInt("maxTreeCount");
int plant_yield = GameServer.INSTANCE.getConfig().getInt("plant_yield");
Random random = new Random();
int treeCount = random.nextInt(maxTreeCount - minTreeCount) + minTreeCount;
ArrayList<Plant> plants = new ArrayList<>(maxTreeCount);
//Count number of plain tiles. If there is less plain tiles than desired amount of trees,
//set the desired amount of trees to the plain tile count
int[][] tiles = world.getTileMap().getTiles();
int plainCount = 0;
for (int y = 0; y < World.WORLD_SIZE; y++) {
for (int x = 0; x < World.WORLD_SIZE; x++) {
if (tiles[x][y] == 0) {
plainCount++;
}
}
}
if (treeCount > plainCount) {
treeCount = plainCount;
}
outerLoop:
for (int i = 0; i < treeCount; i++) {
Point p = world.getTileMap().getRandomPlainTile();
if (p != null) {
//Don't block worlds
while (p.x == 0 || p.y == 0 || p.x == World.WORLD_SIZE - 1 || p.y == World.WORLD_SIZE - 1) {
p = world.getTileMap().getRandomPlainTile();
}
for (Plant plant : plants) {
if (plant.getX() == p.x && plant.getY() == p.y) {
//There is already a plant here
continue outerLoop;
}
}
Plant plant = new Plant();
plant.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
plant.setStyle(0); //TODO: set style depending on difficulty level? or random? from config?
plant.setBiomassCount(plant_yield);
plant.setCreationTime(0); // Plants generated by the world generator always have creationTime of 0
plant.setX(p.x);
plant.setY(p.y);
plant.setWorld(world);
plants.add(plant);
}
}
LogManager.LOGGER.info("Generated " + plants.size() + " plants for World (" + world.getX() + ',' +
world.getY() + ')');
return plants;
}
}

21
Server/Server.iml Normal file
View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="jdk" jdkName="1.8" jdkType="JavaSDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.java-websocket:Java-WebSocket:1.3.6" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.42" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
</component>
</module>

49
Server/pom.xml Normal file
View File

@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,9 +1,13 @@
package net.simon987.server;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventDispatcher;
import net.simon987.server.event.TickEvent;
import net.simon987.server.game.DayNightCycle;
import net.simon987.server.game.GameUniverse;
import net.simon987.server.game.World;
import net.simon987.server.io.FileUtils;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.PluginManager;
import net.simon987.server.plugin.ServerPlugin;
@@ -20,8 +24,9 @@ import java.util.ArrayList;
public class GameServer implements Runnable {
public final static GameServer INSTANCE = new GameServer();
private GameUniverse gameUniverse;
private final static String SAVE_JSON = "save.json";
private GameUniverse gameUniverse;
private GameEventDispatcher eventDispatcher;
private PluginManager pluginManager;
@@ -29,6 +34,10 @@ public class GameServer implements Runnable {
private SocketServer socketServer;
private int maxExecutionTime;
private DayNightCycle dayNightCycle;
public GameServer() {
this.config = new ServerConfiguration(new File("config.properties"));
@@ -36,25 +45,31 @@ public class GameServer implements Runnable {
gameUniverse = new GameUniverse(config);
pluginManager = new PluginManager();
maxExecutionTime = config.getInt("user_timeout");
dayNightCycle = new DayNightCycle();
//Load all plugins in plugins folder, if it doesn't exist, create it
File pluginDir = new File("plugins/");
File[] pluginDirListing = pluginDir.listFiles();
if(pluginDirListing != null) {
for(File pluginFile : pluginDirListing) {
if (pluginDirListing != null) {
for (File pluginFile : pluginDirListing) {
if(pluginFile.getName().endsWith(".jar")){
pluginManager.load(pluginFile);
if (pluginFile.getName().endsWith(".jar")) {
pluginManager.load(pluginFile, config);
}
}
} else {
if(!pluginDir.mkdir()) {
if (!pluginDir.mkdir()) {
LogManager.LOGGER.severe("Couldn't create plugin directory");
}
}
eventDispatcher = new GameEventDispatcher(pluginManager);
eventDispatcher.getListeners().add(dayNightCycle);
}
@@ -103,14 +118,24 @@ public class GameServer implements Runnable {
private void tick() {
gameUniverse.incrementTime();
//Dispatch tick event
GameEvent event = new TickEvent(gameUniverse.getTime());
eventDispatcher.dispatch(event); //Ignore cancellation
//Process user code
ArrayList<User> users_ = gameUniverse.getUsers();
for (User user : users_) {
if(user.getCpu() != null){
if (user.getCpu() != null) {
try {
int timeout = Math.min(user.getControlledUnit().getEnergy(), maxExecutionTime);
user.getCpu().reset();
user.getCpu().execute();
int cost = user.getCpu().execute(timeout);
user.getControlledUnit().spendEnergy(cost);
} catch (Exception e) {
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
e.printStackTrace();
@@ -122,25 +147,49 @@ public class GameServer implements Runnable {
//Process each worlds
//Avoid concurrent modification
ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds());
int updatedWorlds = 0;
for (World world : worlds) {
world.update();
if (world.shouldUpdate()) {
world.update();
updatedWorlds++;
}
}
//Save
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
save(new File("save.json"));
}
// Clean up history files
if(gameUniverse.getTime() % config.getInt("clean_interval") == 0) {
FileUtils.cleanHistory(config.getInt("history_size"));
}
socketServer.tick();
LogManager.LOGGER.info("Processed " + gameUniverse.getWorlds().size() + " worlds");
LogManager.LOGGER.info("Processed " + gameUniverse.getWorlds().size() + " worlds (" + updatedWorlds +
") updated");
}
/**
* Save game universe to file in JSON format
*
* @param file JSON file to save
*/
public void save(File file){
public void save(File file) {
boolean dirExists = FileUtils.prepDirectory(FileUtils.DIR_PATH);
if (new File(new File(SAVE_JSON).getAbsolutePath()).exists() && dirExists) {
byte[] data = FileUtils.bytifyFile(new File(SAVE_JSON).toPath());
try {
FileUtils.writeSaveToZip(SAVE_JSON, data);
} catch (IOException e) {
System.out.println("Failed to write " + SAVE_JSON + " to zip file");
e.printStackTrace();
}
}
try {
FileWriter fileWriter = new FileWriter(file);
@@ -148,7 +197,7 @@ public class GameServer implements Runnable {
JSONArray plugins = new JSONArray();
for(ServerPlugin plugin : pluginManager.getPlugins()){
for (ServerPlugin plugin : pluginManager.getPlugins()) {
plugins.add(plugin.serialise());
}
@@ -176,4 +225,8 @@ public class GameServer implements Runnable {
public void setSocketServer(SocketServer socketServer) {
this.socketServer = socketServer;
}
public DayNightCycle getDayNightCycle() {
return dayNightCycle;
}
}

View File

@@ -8,7 +8,7 @@ import java.net.InetSocketAddress;
public class Main {
public static void main(String[] args){
public static void main(String[] args) {
LogManager.initialize();
@@ -17,11 +17,13 @@ public class Main {
//Load
GameServer.INSTANCE.getGameUniverse().load(new File("save.json"));
SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"),
config.getInt("webSocket_port")), config);
GameServer.INSTANCE.setSocketServer(socketServer);
(new Thread(socketServer)).start();
(new Thread(GameServer.INSTANCE)).start();
}

View File

@@ -208,7 +208,7 @@ public class Assembler {
} else {
//Handle integer value
char s = (char)(int)Integer.decode(value);
char s = (char) (int) Integer.decode(value);
for (int i = 0; i < factor; i++) {
out.write(Util.getHigherByte(s));
@@ -253,6 +253,8 @@ public class Assembler {
} else if (tokens[0].toUpperCase().equals(".DATA")) {
LogManager.LOGGER.fine("DEBUG: .data @" + currentLine);
result.defineSegment(Segment.DATA, currentLine, currentOffset);
throw new PseudoInstructionException(currentLine);
}
@@ -279,7 +281,7 @@ public class Assembler {
if (tokens[1].toUpperCase().equals("EQU") && tokens.length == 3) {
try {
//Save value as a label
labels.put(tokens[0], (char)(int)Integer.decode(tokens[2]));
labels.put(tokens[0], (char) (int) Integer.decode(tokens[2]));
} catch (NumberFormatException e) {
throw new InvalidOperandException("Usage: constant_name EQU immediate_value", currentLine);
}

View File

@@ -3,7 +3,10 @@ package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.AssemblyException;
import net.simon987.server.assembly.exception.DuplicateSegmentException;
import net.simon987.server.logging.LogManager;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
@@ -77,6 +80,10 @@ public class AssemblyResult {
if (!codeSegmentSet) {
codeSegmentOffset = origin + currentOffset;
codeSegmentLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .text offset @" + codeSegmentOffset);
codeSegmentSet = true;
} else {
throw new DuplicateSegmentException(currentLine);
@@ -87,6 +94,9 @@ public class AssemblyResult {
if (!dataSegmentSet) {
dataSegmentOffset = origin + currentOffset;
dataSegmentLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .data offset @" + dataSegmentOffset);
dataSegmentSet = true;
} else {
throw new DuplicateSegmentException(currentLine);
@@ -96,4 +106,20 @@ public class AssemblyResult {
}
public char[] getWords() {
char[] assembledCode = new char[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(assembledCode);
return assembledCode;
}
public int getCodeSegmentOffset() {
if (codeSegmentSet) {
return codeSegmentOffset;
} else {
return origin;
}
}
}

View File

@@ -20,7 +20,7 @@ import java.util.HashMap;
* a Memory object and execute them. A CPU object holds registers objects &
* a Memory object.
*/
public class CPU implements JSONSerialisable{
public class CPU implements JSONSerialisable {
/**
*
@@ -60,22 +60,21 @@ public class CPU implements JSONSerialisable{
private ServerConfiguration config;
private long timeout;
private int registerSetSize;
private static final char EXECUTION_COST_ADDR = 0x0050;
private static final char EXECUTED_INS_ADDR = 0x0051;
/**
* Creates a new CPU
*/
public CPU(ServerConfiguration config, User user) throws CancelledException{
public CPU(ServerConfiguration config, User user) throws CancelledException {
this.config = config;
instructionSet = new DefaultInstructionSet();
registerSet = new DefaultRegisterSet();
attachedHardware = new HashMap<>();
codeSegmentOffset = config.getInt("org_offset");
timeout = config.getInt("user_timeout");
instructionSet.add(new JmpInstruction(this));
instructionSet.add(new JnzInstruction(this));
instructionSet.add(new JzInstruction(this));
@@ -104,7 +103,7 @@ public class CPU implements JSONSerialisable{
GameEvent event = new CpuInitialisationEvent(this, user);
GameServer.INSTANCE.getEventDispatcher().dispatch(event);
if(event.isCancelled()){
if (event.isCancelled()) {
throw new CancelledException();
}
}
@@ -116,7 +115,7 @@ public class CPU implements JSONSerialisable{
ip = codeSegmentOffset;
}
public void execute() {
public int execute(int timeout) {
long startTime = System.currentTimeMillis();
int counter = 0;
@@ -128,10 +127,16 @@ public class CPU implements JSONSerialisable{
while (!status.isBreakFlag()) {
counter++;
if(counter % 1000 == 0){
if (System.currentTimeMillis() >= (startTime + timeout)) {
if (counter % 10000 == 0) {
if (System.currentTimeMillis() > (startTime + timeout)) {
LogManager.LOGGER.fine("CPU Timeout " + this + " after " + counter + "instructions (" + timeout + "ms): " + (double) counter / ((double) timeout / 1000) / 1000000 + "MHz");
return;
//Write execution cost and instruction count to memory
memory.set(EXECUTION_COST_ADDR, timeout);
memory.set(EXECUTED_INS_ADDR, Util.getHigherWord(counter));
memory.set(EXECUTED_INS_ADDR + 1, Util.getLowerWord(counter));
return timeout;
}
}
@@ -151,8 +156,17 @@ public class CPU implements JSONSerialisable{
executeInstruction(instruction, source, destination);
// LogManager.LOGGER.info(instruction.getMnemonic());
}
double elapsed = (System.currentTimeMillis() - startTime);
int elapsed = (int) (System.currentTimeMillis() - startTime);
LogManager.LOGGER.fine(counter + " instruction in " + elapsed + "ms : " + (double) counter / (elapsed / 1000) / 1000000 + "MHz");
//Write execution cost and instruction count to memory
memory.set(EXECUTION_COST_ADDR, elapsed);
memory.set(EXECUTED_INS_ADDR, Util.getHigherWord(counter));
memory.set(EXECUTED_INS_ADDR + 1, Util.getLowerWord(counter));
return elapsed;
}
public void executeInstruction(Instruction instruction, int source, int destination) {
@@ -268,7 +282,7 @@ public class CPU implements JSONSerialisable{
if (destination == 0) {
//Single operand
ip++;
instruction.execute(memory, registerSet.get(source), status);
instruction.execute(memory, registerSet.get(source - registerSetSize), status);
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value
//this shouldn't happen
@@ -281,11 +295,11 @@ public class CPU implements JSONSerialisable{
} else if (destination <= registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, memory, registerSet.get(source), status);
instruction.execute(registerSet, destination, memory, registerSet.get(source - registerSetSize), status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), memory, registerSet.get(source), status);
instruction.execute(memory, registerSet.get(destination - registerSetSize), memory, registerSet.get(source - registerSetSize), status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
@@ -313,7 +327,7 @@ public class CPU implements JSONSerialisable{
ip += 2;
instruction.execute(memory, memory.get(ip - 1), memory,
registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
} else if (destination < registerSetSize) {
} else if (destination <= registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, memory,
@@ -344,7 +358,7 @@ public class CPU implements JSONSerialisable{
JSONArray hardwareList = new JSONArray();
for(Integer address : attachedHardware.keySet()){
for (Integer address : attachedHardware.keySet()) {
CpuHardware hardware = attachedHardware.get(address);
@@ -362,17 +376,17 @@ public class CPU implements JSONSerialisable{
CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user);
cpu.codeSegmentOffset = (int)(long)json.get("codeSegmentOffset");
cpu.codeSegmentOffset = (int) (long) json.get("codeSegmentOffset");
JSONArray hardwareList = (JSONArray)json.get("hardware");
JSONArray hardwareList = (JSONArray) json.get("hardware");
for(JSONObject serialisedHw : (ArrayList<JSONObject>)hardwareList){
for (JSONObject serialisedHw : (ArrayList<JSONObject>) hardwareList) {
CpuHardware hw = CpuHardware.deserialize(serialisedHw);
hw.setCpu(cpu);
cpu.attachHardware(hw, (int)(long)serialisedHw.get("address"));
cpu.attachHardware(hw, (int) (long) serialisedHw.get("address"));
}
cpu.memory = Memory.deserialize((JSONObject)json.get("memory"));
cpu.memory = Memory.deserialize((JSONObject) json.get("memory"));
cpu.registerSet = RegisterSet.deserialize((JSONObject) json.get("registerSet"));
return cpu;
@@ -407,18 +421,18 @@ public class CPU implements JSONSerialisable{
this.codeSegmentOffset = codeSegmentOffset;
}
public void attachHardware(CpuHardware hardware, int address){
public void attachHardware(CpuHardware hardware, int address) {
attachedHardware.put(address, hardware);
}
public void detachHardware(int address){
public void detachHardware(int address) {
attachedHardware.remove(address);
}
public boolean hardwareInterrupt(int address){
public boolean hardwareInterrupt(int address) {
CpuHardware hardware = attachedHardware.get(address);
if(hardware != null){
if (hardware != null) {
hardware.handleInterrupt(status);
return true;
} else {

View File

@@ -26,14 +26,14 @@ public abstract class CpuHardware implements JSONSerialisable {
public abstract char getId();
public static CpuHardware deserialize(JSONObject hwJson){
public static CpuHardware deserialize(JSONObject hwJson) {
for(ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()){
for (ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()) {
if(plugin instanceof CpuHardwareDeserializer){
if (plugin instanceof CpuHardwareDeserializer) {
CpuHardware hw = ((CpuHardwareDeserializer) plugin).deserializeHardware(hwJson);
if(hw != null){
if (hw != null) {
return hw;
}
}

View File

@@ -56,10 +56,10 @@ public class DefaultInstructionSet implements InstructionSet {
public Instruction get(int opcode) {
Instruction instruction = instructionMap.get(opcode);
if(instruction != null){
if (instruction != null) {
return instruction;
} else {
// System.out.println("Invalid instruction " + opcode);
// System.out.println("Invalid instruction " + opcode);
//Todo: Notify user? Set error flag?
return defaultInstruction;
}

View File

@@ -1,12 +1,15 @@
package net.simon987.server.assembly;
import net.simon987.server.GameServer;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Deflater;
@@ -23,7 +26,7 @@ public class Memory implements Target, JSONSerialisable {
/**
* Contents of the memory
*/
private byte[] bytes;
private char[] words;
/**
* Create an empty Memory object
@@ -31,7 +34,7 @@ public class Memory implements Target, JSONSerialisable {
* @param size Size of the memory, in words
*/
public Memory(int size) {
bytes = new byte[size];
words = new char[size];
}
/**
@@ -42,29 +45,26 @@ public class Memory implements Target, JSONSerialisable {
*/
@Override
public int get(int address) {
address = (char)address * 2; //Because our Memory is only divisible by 16bits
address = (char) address;
if (address < 0 || address + 2 > bytes.length) {
if (address >= words.length) {
LogManager.LOGGER.info("DEBUG: Trying to get memory out of bounds " + address);
return 0;
}
return (((bytes[address] & 0xFF) << 8) | (bytes[address + 1] & 0xFF));
return words[address];
}
/**
* Write x words from an array at an offset
*/
public boolean write(int offset, byte[] bytes, int srcOffset, int count) {
public boolean write(int offset, char[] src, int srcOffset, int count) {
offset = (char)offset * 2;
if (offset + count > this.bytes.length || count < 0 || offset < 0 || srcOffset >= bytes.length) {
if (offset + count > this.words.length || srcOffset >= src.length || count < 0 || offset < 0) {
return false;
}
System.arraycopy(bytes, srcOffset, this.bytes, offset, count);
System.arraycopy(src, srcOffset, this.words, offset, count);
return true;
}
@@ -76,30 +76,31 @@ public class Memory implements Target, JSONSerialisable {
*/
@Override
public void set(int address, int value) {
address = (char) address;
address = (char)address * 2;
if (address < 0 || address + 2 > bytes.length) {
if (address >= words.length) {
LogManager.LOGGER.info("DEBUG: Trying to set memory out of bounds: " + address);
return;
}
bytes[address] = (byte) ((value >> 8) & 0xFF);
bytes[address + 1] = (byte) (value & 0xFF);
words[address] = (char) value;
}
/**
* Fill the memory with 0s
*/
public void clear() {
Arrays.fill(bytes, (byte) 0);
Arrays.fill(words, (char) 0);
}
/**
* Get byte array of the Memory object
*/
public byte[] getBytes() {
byte[] bytes = new byte[words.length * 2];
ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asCharBuffer().put(words);
return bytes;
}
@@ -112,7 +113,7 @@ public class Memory implements Target, JSONSerialisable {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
deflaterOutputStream.write(bytes);
deflaterOutputStream.write(getBytes());
deflaterOutputStream.close();
byte[] compressedBytes = stream.toByteArray();
@@ -125,28 +126,42 @@ public class Memory implements Target, JSONSerialisable {
return json;
}
public static Memory deserialize(JSONObject json){
public static Memory deserialize(JSONObject json) {
Memory memory = new Memory(0);
byte[] compressedBytes = Base64.getDecoder().decode((String)json.get("zipBytes"));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
String zipBytesStr = (String) json.get("zipBytes");
memory.bytes = baos.toByteArray();
if (zipBytesStr != null) {
byte[] compressedBytes = Base64.getDecoder().decode((String) json.get("zipBytes"));
} catch (IOException e) {
e.printStackTrace();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
memory.setBytes(baos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} else {
LogManager.LOGGER.severe("Memory was manually deleted");
memory = new Memory(GameServer.INSTANCE.getConfig().getInt("memory_size"));
}
return memory;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
this.words = new char[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(this.words);
}
public char[] getWords() {
return words;
}
}

View File

@@ -87,7 +87,7 @@ public class RegisterSet implements Target, JSONSerialisable {
Register register = registers.get(address);
if(register != null){
if (register != null) {
return register.getValue();
} else {
return 0;
@@ -106,7 +106,7 @@ public class RegisterSet implements Target, JSONSerialisable {
Register register = registers.get(address);
if(register != null){
if (register != null) {
register.setValue(value);
} else {
LogManager.LOGGER.info("DEBUG: trying to set unknown reg index : " + address);
@@ -144,7 +144,7 @@ public class RegisterSet implements Target, JSONSerialisable {
@Override
public JSONObject serialise() {
JSONArray registers = new JSONArray();
for(Integer index : this.registers.keySet()){
for (Integer index : this.registers.keySet()) {
JSONObject register = new JSONObject();
register.put("index", index);
@@ -164,14 +164,14 @@ public class RegisterSet implements Target, JSONSerialisable {
RegisterSet registerSet = new RegisterSet();
JSONArray registers = (JSONArray)json.get("registers");
JSONArray registers = (JSONArray) json.get("registers");
for(JSONObject jsonRegister : (ArrayList<JSONObject>)registers){
for (JSONObject jsonRegister : (ArrayList<JSONObject>) registers) {
Register register = new Register((String)jsonRegister.get("name"));
register.setValue((int)(long)jsonRegister.get("value"));
Register register = new Register((String) jsonRegister.get("name"));
register.setValue((int) (long) jsonRegister.get("value"));
registerSet.registers.put((int)(long)jsonRegister.get("index"), register);
registerSet.registers.put((int) (long) jsonRegister.get("index"), register);
}
@@ -182,7 +182,7 @@ public class RegisterSet implements Target, JSONSerialisable {
public String toString() {
String str = "";
for(Integer index: registers.keySet()){
for (Integer index : registers.keySet()) {
str += index + " " + registers.get(index).getName() + "=" + Util.toHex(registers.get(index).getValue()) + "\n";
}

View File

@@ -41,7 +41,7 @@ public class Util {
return s & 0x0000FFFF;
}
public static String toHex(int a){
public static String toHex(int a) {
return String.format("%04X ", uShort(a));
}

View File

@@ -8,8 +8,8 @@ import net.simon987.server.assembly.Util;
/**
* Add two numbers together, the result is stored in the destination operand
* <p>
* ADD A, B
* A = A + B
* ADD A, B
* A = A + B
* </p>
*/
public class AddInstruction extends Instruction {
@@ -39,8 +39,8 @@ public class AddInstruction extends Instruction {
@Override
public Status execute(Target dst, int dstIndex, Target src, int srcIndex, Status status) {
int a = (char)dst.get(dstIndex);
int b = (char)src.get(srcIndex);
int a = (char) dst.get(dstIndex);
int b = (char) src.get(srcIndex);
return add(a, b, status, dst, dstIndex);
}
@@ -48,8 +48,8 @@ public class AddInstruction extends Instruction {
@Override
public Status execute(Target dst, int dstIndex, int src, Status status) {
int a = (char)dst.get(dstIndex);
int b = (char)src;
int a = (char) dst.get(dstIndex);
int b = (char) src;
return add(a, b, status, dst, dstIndex);
}

View File

@@ -8,8 +8,8 @@ import net.simon987.server.assembly.Util;
/**
* AND two numbers together, the result is stored in the destination operand
* <p>
* AND A, B
* A = A & B
* AND A, B
* A = A & B
* </p>
* FLAGS: OF=0 S=* Z=* X=0
*/
@@ -27,8 +27,8 @@ public class AndInstruction extends Instruction {
@Override
public Status execute(Target dst, int dstIndex, Target src, int srcIndex, Status status) {
int a =(char)dst.get(dstIndex);
int b = (char)src.get(srcIndex);
int a = (char) dst.get(dstIndex);
int b = (char) src.get(srcIndex);
int result = (a & b);
@@ -45,8 +45,8 @@ public class AndInstruction extends Instruction {
@Override
public Status execute(Target dst, int dstIndex, int src, Status status) {
int a = (char)dst.get(dstIndex);
int b = (char)src;
int a = (char) dst.get(dstIndex);
int b = (char) src;
int result = (a & b);

View File

@@ -23,8 +23,8 @@ public class CmpInstruction extends Instruction {
public Status execute(Target dst, int dstIndex, Target src, int srcIndex, Status status) {
int a = (char)dst.get(dstIndex);
int b = (char)src.get(srcIndex);
int a = (char) dst.get(dstIndex);
int b = (char) src.get(srcIndex);
int result = a - b;
@@ -40,8 +40,8 @@ public class CmpInstruction extends Instruction {
@Override
public Status execute(Target dst, int dstIndex, int src, Status status) {
int a = (char)dst.get(dstIndex);
int b = (char)src;
int a = (char) dst.get(dstIndex);
int b = (char) src;
int result = a - b;

View File

@@ -28,16 +28,16 @@ public class DivInstruction extends Instruction {
public Status execute(Target src, int srcIndex, Status status) {
//Source = Y:A
int source = ((((char)cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char)cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
int source = ((((char) cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char) cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
if (src.get(srcIndex) == 0) {
//Division by 0
status.setBreakFlag(true);
status.setErrorFlag(true);
} else {
cpu.getRegisterSet().getRegister("A").setValue((char)(source / (char)src.get(srcIndex)));
cpu.getRegisterSet().getRegister("Y").setValue((char)(source % (char)src.get(srcIndex)));
cpu.getRegisterSet().getRegister("A").setValue((char) (source / (char) src.get(srcIndex)));
cpu.getRegisterSet().getRegister("Y").setValue((char) (source % (char) src.get(srcIndex)));
}
return status;
@@ -48,16 +48,16 @@ public class DivInstruction extends Instruction {
//Source = Y:A
int source = ((((char)cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char)cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
int source = ((((char) cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char) cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
if (src == 0) {
//Division by 0
status.setBreakFlag(true);
status.setErrorFlag(true);
} else {
cpu.getRegisterSet().getRegister("A").setValue((char)(source / (char)src));
cpu.getRegisterSet().getRegister("Y").setValue((char)(source % (char)src));
cpu.getRegisterSet().getRegister("A").setValue((char) (source / (char) src));
cpu.getRegisterSet().getRegister("Y").setValue((char) (source % (char) src));
}

Some files were not shown because too many files have changed in this diff Show More