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.GameServer;
import net.simon987.server.assembly.Memory; import net.simon987.server.assembly.Memory;
import net.simon987.server.game.ControllableUnit; import net.simon987.server.game.*;
import net.simon987.server.game.Direction;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@@ -25,8 +22,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
private int hp; private int hp;
private int heldItem; private int heldItem;
private CubotAction currentAction = CubotAction.IDLE; private Action currentAction = Action.IDLE;
private CubotAction lastAction = CubotAction.IDLE; private Action lastAction = Action.IDLE;
private ArrayList<Integer> keyboardBuffer = new ArrayList<>(); private ArrayList<Integer> keyboardBuffer = new ArrayList<>();
@@ -37,6 +34,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
private int energy; private int energy;
private int maxEnergy; private int maxEnergy;
private static final float SOLAR_PANEL_MULTIPLIER = 1;
public Cubot() { public Cubot() {
} }
@@ -49,14 +48,16 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
@Override @Override
public void update() { public void update() {
if (currentAction == CubotAction.WALKING) { storeEnergy((int) (SOLAR_PANEL_MULTIPLIER * GameServer.INSTANCE.getDayNightCycle().getSunIntensity()));
if (currentAction == Action.WALKING) {
if (spendEnergy(100)) { if (spendEnergy(100)) {
if (!incrementLocation()) { if (!incrementLocation()) {
//Couldn't walk //Couldn't walk
currentAction = CubotAction.IDLE; currentAction = Action.IDLE;
} }
} else { } else {
currentAction = CubotAction.IDLE; currentAction = Action.IDLE;
} }
} }
@@ -66,7 +67,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
* was set last tick (IDLE) * was set last tick (IDLE)
*/ */
lastAction = currentAction; lastAction = currentAction;
currentAction = CubotAction.IDLE; currentAction = Action.IDLE;
//Same principle for hologram //Same principle for hologram
lastHologram = hologram; lastHologram = hologram;
@@ -76,8 +77,8 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
@Override @Override
public JSONObject serialise() { public JSONObject serialise() {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put("id", getObjectId()); json.put("i", getObjectId());
json.put("type", ID); json.put("t", ID);
json.put("x", getX()); json.put("x", getX());
json.put("y", getY()); json.put("y", getY());
json.put("direction", getDirection().ordinal()); json.put("direction", getDirection().ordinal());
@@ -85,7 +86,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
json.put("hp", hp); json.put("hp", hp);
json.put("action", lastAction.ordinal()); json.put("action", lastAction.ordinal());
json.put("holo", (int) lastHologram); json.put("holo", (int) lastHologram);
json.put("energy", (int) lastHologram); json.put("energy", energy);
if (parent != null) { if (parent != null) {
json.put("parent", parent.getUsername()); //Only used client-side for now json.put("parent", parent.getUsername()); //Only used client-side for now
@@ -97,7 +98,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
public static Cubot deserialize(JSONObject json) { public static Cubot deserialize(JSONObject json) {
Cubot cubot = new Cubot(); Cubot cubot = new Cubot();
cubot.setObjectId((int)(long)json.get("id")); cubot.setObjectId((long) json.get("i"));
cubot.setX((int) (long) json.get("x")); cubot.setX((int) (long) json.get("x"));
cubot.setY((int) (long) json.get("y")); cubot.setY((int) (long) json.get("y"));
cubot.hp = (int) (long) json.get("hp"); cubot.hp = (int) (long) json.get("hp");
@@ -132,7 +133,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
keyboardBuffer.clear(); keyboardBuffer.clear();
} }
public void setCurrentAction(CubotAction currentAction) { public void setCurrentAction(Action currentAction) {
this.currentAction = currentAction; this.currentAction = currentAction;
} }
@@ -144,7 +145,7 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
this.parent = parent; this.parent = parent;
} }
public CubotAction getAction() { public Action getAction() {
return lastAction; return lastAction;
} }
@@ -173,7 +174,11 @@ public class Cubot extends GameObject implements Updatable, ControllableUnit {
energy -= spent; energy -= spent;
return true; 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 @Override
public Memory getFloppyData() { 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.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.TileMap; import net.simon987.server.game.TileMap;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@@ -41,16 +42,16 @@ public class CubotDrill extends CpuHardware {
} else if (a == GATHER_SLOW || a == GATHER_FAST) { } else if (a == GATHER_SLOW || a == GATHER_FAST) {
if (cubot.spendEnergy(1400)) { if (cubot.spendEnergy(1400)) {
if (cubot.getAction() == CubotAction.IDLE) { if (cubot.getAction() == Action.IDLE) {
int tile = cubot.getWorld().getTileMap().getTileAt(cubot.getX(), cubot.getY()); int tile = cubot.getWorld().getTileMap().getTileAt(cubot.getX(), cubot.getY());
if (tile == TileMap.IRON_TILE) { if (tile == TileMap.IRON_TILE) {
cubot.setHeldItem(TileMap.ITEM_IRON); cubot.setHeldItem(TileMap.ITEM_IRON);
cubot.setCurrentAction(CubotAction.DIGGING); cubot.setCurrentAction(Action.DIGGING);
} else if (tile == TileMap.COPPER_TILE) { } else if (tile == TileMap.COPPER_TILE) {
cubot.setHeldItem(TileMap.ITEM_COPPER); cubot.setHeldItem(TileMap.ITEM_COPPER);
cubot.setCurrentAction(CubotAction.DIGGING); cubot.setCurrentAction(Action.DIGGING);
} }
} }

View File

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

View File

@@ -3,6 +3,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder; import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@@ -48,7 +49,7 @@ public class CubotLaser extends CpuHardware {
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y); 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 //FIXME: Problem here if more than 1 object
if (objects.get(0) instanceof InventoryHolder) { if (objects.get(0) instanceof InventoryHolder) {
if (((InventoryHolder) objects.get(0)).canTakeItem(b)) { if (((InventoryHolder) objects.get(0)).canTakeItem(b)) {
@@ -57,7 +58,7 @@ public class CubotLaser extends CpuHardware {
((InventoryHolder) objects.get(0)).takeItem(b); ((InventoryHolder) objects.get(0)).takeItem(b);
cubot.setHeldItem(b); cubot.setHeldItem(b);
cubot.setCurrentAction(CubotAction.WITHDRAWING); cubot.setCurrentAction(Action.WITHDRAWING);
} }
} }
} }

View File

@@ -3,6 +3,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.Action;
import net.simon987.server.game.Direction; import net.simon987.server.game.Direction;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@@ -63,7 +64,7 @@ public class CubotLeg extends CpuHardware implements JSONSerialisable {
status.setErrorFlag(true); status.setErrorFlag(true);
} }
cubot.setCurrentAction(CubotAction.WALKING); cubot.setCurrentAction(Action.WALKING);
} }
} }

View File

@@ -2,6 +2,7 @@ package net.simon987.cubotplugin;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Memory;
import net.simon987.server.assembly.Status; import net.simon987.server.assembly.Status;
import net.simon987.server.game.World; import net.simon987.server.game.World;
import net.simon987.server.game.pathfinding.Node; import net.simon987.server.game.pathfinding.Node;
@@ -62,7 +63,7 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
destX, destY, b); destX, destY, b);
//Write to memory //Write to memory
byte[] mem = getCpu().getMemory().getBytes(); Memory mem = getCpu().getMemory();
int counter = MEMORY_PATH_START; int counter = MEMORY_PATH_START;
@@ -80,32 +81,26 @@ public class CubotLidar extends CpuHardware implements JSONSerialisable {
if (n.x < lastNode.x) { if (n.x < lastNode.x) {
//West //West
mem[counter++] = 0; mem.set(counter++, 3);
mem[counter++] = 3;
} else if (n.x > lastNode.x) { } else if (n.x > lastNode.x) {
//East //East
mem[counter++] = 0; mem.set(counter++, 1);
mem[counter++] = 1;
} else if (n.y < lastNode.y) { } else if (n.y < lastNode.y) {
//North //North
mem[counter++] = 0; mem.set(counter++, 0);
mem[counter++] = 0;
} else if (n.y > lastNode.y) { } else if (n.y > lastNode.y) {
//South //South
mem[counter++] = 0; mem.set(counter++, 2);
mem[counter++] = 2;
} }
lastNode = n; lastNode = n;
} }
//Indicate end of path with 0xAAAA //Indicate end of path with 0xAAAA
mem[counter++] = -86; mem.set(counter, 0xAAAA);
mem[counter] = -86;
} else { } else {
//Indicate invalid path 0xFFFF //Indicate invalid path 0xFFFF
mem[counter++] = -1; mem.set(counter, 0xFFFF);
mem[counter] = -1;
} }
LogManager.LOGGER.fine("DEBUG: path to" + destX + "," + destY); 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.CpuInitialisationListener;
import net.simon987.cubotplugin.event.UserCreationListener; import net.simon987.cubotplugin.event.UserCreationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.game.GameObject; import net.simon987.server.game.GameObject;
import net.simon987.server.io.CpuHardwareDeserializer; import net.simon987.server.io.CpuHardwareDeserializer;
@@ -14,7 +15,7 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
@Override @Override
public void init() { public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener()); listeners.add(new CpuInitialisationListener());
listeners.add(new UserCreationListener()); listeners.add(new UserCreationListener());
@@ -24,7 +25,7 @@ public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer,
@Override @Override
public GameObject deserializeObject(JSONObject object) { 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) {

View File

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

View File

@@ -29,6 +29,7 @@ public class UserCreationListener implements GameEventListener {
GameServer.INSTANCE.getConfig().getInt("new_user_worldX"), GameServer.INSTANCE.getConfig().getInt("new_user_worldX"),
GameServer.INSTANCE.getConfig().getInt("new_user_worldY"))); GameServer.INSTANCE.getConfig().getInt("new_user_worldY")));
cubot.getWorld().getGameObjects().add(cubot); cubot.getWorld().getGameObjects().add(cubot);
cubot.getWorld().incUpdatable();
cubot.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId()); 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; package net.simon987.mischwplugin;
import net.simon987.mischwplugin.event.CpuInitialisationListener; import net.simon987.mischwplugin.event.CpuInitialisationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware; import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.io.CpuHardwareDeserializer; import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
@@ -11,7 +12,7 @@ public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserialize
@Override @Override
public void init() { public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener()); listeners.add(new CpuInitialisationListener());
LogManager.LOGGER.info("Initialised Misc Hardware Plugin"); 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; package net.simon987.server;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventDispatcher; 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.GameUniverse;
import net.simon987.server.game.World; import net.simon987.server.game.World;
import net.simon987.server.io.FileUtils;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.PluginManager; import net.simon987.server.plugin.PluginManager;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
@@ -20,6 +24,7 @@ import java.util.ArrayList;
public class GameServer implements Runnable { public class GameServer implements Runnable {
public final static GameServer INSTANCE = new GameServer(); public final static GameServer INSTANCE = new GameServer();
private final static String SAVE_JSON = "save.json";
private GameUniverse gameUniverse; private GameUniverse gameUniverse;
private GameEventDispatcher eventDispatcher; private GameEventDispatcher eventDispatcher;
@@ -29,6 +34,10 @@ public class GameServer implements Runnable {
private SocketServer socketServer; private SocketServer socketServer;
private int maxExecutionTime;
private DayNightCycle dayNightCycle;
public GameServer() { public GameServer() {
this.config = new ServerConfiguration(new File("config.properties")); this.config = new ServerConfiguration(new File("config.properties"));
@@ -36,6 +45,11 @@ public class GameServer implements Runnable {
gameUniverse = new GameUniverse(config); gameUniverse = new GameUniverse(config);
pluginManager = new PluginManager(); pluginManager = new PluginManager();
maxExecutionTime = config.getInt("user_timeout");
dayNightCycle = new DayNightCycle();
//Load all plugins in plugins folder, if it doesn't exist, create it //Load all plugins in plugins folder, if it doesn't exist, create it
File pluginDir = new File("plugins/"); File pluginDir = new File("plugins/");
File[] pluginDirListing = pluginDir.listFiles(); File[] pluginDirListing = pluginDir.listFiles();
@@ -44,7 +58,7 @@ public class GameServer implements Runnable {
for (File pluginFile : pluginDirListing) { for (File pluginFile : pluginDirListing) {
if (pluginFile.getName().endsWith(".jar")) { if (pluginFile.getName().endsWith(".jar")) {
pluginManager.load(pluginFile); pluginManager.load(pluginFile, config);
} }
} }
@@ -55,6 +69,7 @@ public class GameServer implements Runnable {
} }
eventDispatcher = new GameEventDispatcher(pluginManager); eventDispatcher = new GameEventDispatcher(pluginManager);
eventDispatcher.getListeners().add(dayNightCycle);
} }
@@ -103,14 +118,24 @@ public class GameServer implements Runnable {
private void tick() { private void tick() {
gameUniverse.incrementTime(); gameUniverse.incrementTime();
//Dispatch tick event
GameEvent event = new TickEvent(gameUniverse.getTime());
eventDispatcher.dispatch(event); //Ignore cancellation
//Process user code //Process user code
ArrayList<User> users_ = gameUniverse.getUsers(); ArrayList<User> users_ = gameUniverse.getUsers();
for (User user : users_) { for (User user : users_) {
if (user.getCpu() != null) { if (user.getCpu() != null) {
try { try {
int timeout = Math.min(user.getControlledUnit().getEnergy(), maxExecutionTime);
user.getCpu().reset(); user.getCpu().reset();
user.getCpu().execute(); int cost = user.getCpu().execute(timeout);
user.getControlledUnit().spendEnergy(cost);
} catch (Exception e) { } catch (Exception e) {
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code"); LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
e.printStackTrace(); e.printStackTrace();
@@ -122,8 +147,12 @@ public class GameServer implements Runnable {
//Process each worlds //Process each worlds
//Avoid concurrent modification //Avoid concurrent modification
ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds()); ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds());
int updatedWorlds = 0;
for (World world : worlds) { for (World world : worlds) {
if (world.shouldUpdate()) {
world.update(); world.update();
updatedWorlds++;
}
} }
//Save //Save
@@ -131,16 +160,36 @@ public class GameServer implements Runnable {
save(new File("save.json")); 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(); 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 * Save game universe to file in JSON format
*
* @param file JSON file to save * @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 { try {
FileWriter fileWriter = new FileWriter(file); FileWriter fileWriter = new FileWriter(file);
@@ -176,4 +225,8 @@ public class GameServer implements Runnable {
public void setSocketServer(SocketServer socketServer) { public void setSocketServer(SocketServer socketServer) {
this.socketServer = socketServer; this.socketServer = socketServer;
} }
public DayNightCycle getDayNightCycle() {
return dayNightCycle;
}
} }

View File

@@ -17,11 +17,13 @@ public class Main {
//Load //Load
GameServer.INSTANCE.getGameUniverse().load(new File("save.json")); GameServer.INSTANCE.getGameUniverse().load(new File("save.json"));
SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"), SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"),
config.getInt("webSocket_port")), config); config.getInt("webSocket_port")), config);
GameServer.INSTANCE.setSocketServer(socketServer); GameServer.INSTANCE.setSocketServer(socketServer);
(new Thread(socketServer)).start(); (new Thread(socketServer)).start();
(new Thread(GameServer.INSTANCE)).start(); (new Thread(GameServer.INSTANCE)).start();
} }

View File

@@ -253,6 +253,8 @@ public class Assembler {
} else if (tokens[0].toUpperCase().equals(".DATA")) { } else if (tokens[0].toUpperCase().equals(".DATA")) {
LogManager.LOGGER.fine("DEBUG: .data @" + currentLine);
result.defineSegment(Segment.DATA, currentLine, currentOffset); result.defineSegment(Segment.DATA, currentLine, currentOffset);
throw new PseudoInstructionException(currentLine); throw new PseudoInstructionException(currentLine);
} }

View File

@@ -3,7 +3,10 @@ package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.AssemblyException; import net.simon987.server.assembly.exception.AssemblyException;
import net.simon987.server.assembly.exception.DuplicateSegmentException; 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.ArrayList;
import java.util.HashMap; import java.util.HashMap;
@@ -77,6 +80,10 @@ public class AssemblyResult {
if (!codeSegmentSet) { if (!codeSegmentSet) {
codeSegmentOffset = origin + currentOffset; codeSegmentOffset = origin + currentOffset;
codeSegmentLine = currentLine; codeSegmentLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .text offset @" + codeSegmentOffset);
codeSegmentSet = true; codeSegmentSet = true;
} else { } else {
throw new DuplicateSegmentException(currentLine); throw new DuplicateSegmentException(currentLine);
@@ -87,6 +94,9 @@ public class AssemblyResult {
if (!dataSegmentSet) { if (!dataSegmentSet) {
dataSegmentOffset = origin + currentOffset; dataSegmentOffset = origin + currentOffset;
dataSegmentLine = currentLine; dataSegmentLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .data offset @" + dataSegmentOffset);
dataSegmentSet = true; dataSegmentSet = true;
} else { } else {
throw new DuplicateSegmentException(currentLine); 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

@@ -60,10 +60,11 @@ public class CPU implements JSONSerialisable{
private ServerConfiguration config; private ServerConfiguration config;
private long timeout;
private int registerSetSize; private int registerSetSize;
private static final char EXECUTION_COST_ADDR = 0x0050;
private static final char EXECUTED_INS_ADDR = 0x0051;
/** /**
* Creates a new CPU * Creates a new CPU
*/ */
@@ -74,8 +75,6 @@ public class CPU implements JSONSerialisable{
attachedHardware = new HashMap<>(); attachedHardware = new HashMap<>();
codeSegmentOffset = config.getInt("org_offset"); codeSegmentOffset = config.getInt("org_offset");
timeout = config.getInt("user_timeout");
instructionSet.add(new JmpInstruction(this)); instructionSet.add(new JmpInstruction(this));
instructionSet.add(new JnzInstruction(this)); instructionSet.add(new JnzInstruction(this));
instructionSet.add(new JzInstruction(this)); instructionSet.add(new JzInstruction(this));
@@ -116,7 +115,7 @@ public class CPU implements JSONSerialisable{
ip = codeSegmentOffset; ip = codeSegmentOffset;
} }
public void execute() { public int execute(int timeout) {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
int counter = 0; int counter = 0;
@@ -128,10 +127,16 @@ public class CPU implements JSONSerialisable{
while (!status.isBreakFlag()) { while (!status.isBreakFlag()) {
counter++; counter++;
if(counter % 1000 == 0){ if (counter % 10000 == 0) {
if (System.currentTimeMillis() >= (startTime + timeout)) { if (System.currentTimeMillis() > (startTime + timeout)) {
LogManager.LOGGER.fine("CPU Timeout " + this + " after " + counter + "instructions (" + timeout + "ms): " + (double) counter / ((double) timeout / 1000) / 1000000 + "MHz"); 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); executeInstruction(instruction, source, destination);
// LogManager.LOGGER.info(instruction.getMnemonic()); // 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"); 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) { public void executeInstruction(Instruction instruction, int source, int destination) {
@@ -268,7 +282,7 @@ public class CPU implements JSONSerialisable{
if (destination == 0) { if (destination == 0) {
//Single operand //Single operand
ip++; ip++;
instruction.execute(memory, registerSet.get(source), status); instruction.execute(memory, registerSet.get(source - registerSetSize), status);
} else if (destination == Operand.IMMEDIATE_VALUE) { } else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value //Destination is an immediate value
//this shouldn't happen //this shouldn't happen
@@ -281,11 +295,11 @@ public class CPU implements JSONSerialisable{
} else if (destination <= registerSetSize) { } else if (destination <= registerSetSize) {
//Destination is a register //Destination is a register
ip++; 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) { } else if (destination <= registerSetSize * 2) {
//Destination is [reg] //Destination is [reg]
ip++; 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 { } else {
//Assuming that destination is [reg + x] //Assuming that destination is [reg + x]
ip += 2; ip += 2;
@@ -313,7 +327,7 @@ public class CPU implements JSONSerialisable{
ip += 2; ip += 2;
instruction.execute(memory, memory.get(ip - 1), memory, instruction.execute(memory, memory.get(ip - 1), memory,
registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status); registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
} else if (destination < registerSetSize) { } else if (destination <= registerSetSize) {
//Destination is a register //Destination is a register
ip++; ip++;
instruction.execute(registerSet, destination, memory, instruction.execute(registerSet, destination, memory,

View File

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

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