166 Commits
v1.0a ... v1.4a

Author SHA1 Message Date
simon
a7d1a00ae8 Fixes #27 2018-02-25 08:51:03 -05:00
simon
8d961ce572 Added JA and JNA Instructions 2018-01-20 14:18:44 -05:00
simon
c772abe0bf Fixed opcode clash for PUSHF instruction 2018-01-20 12:33:01 -05:00
simon
210e579995 Number of assembly errors is also sent on code upload 2018-01-17 19:02:36 -05:00
simon
33955d9639 Merge remote-tracking branch 'origin/master' 2018-01-14 11:01:23 -05:00
simon
6b91251b4e Should fix #125 2018-01-14 11:01:13 -05:00
Simon Fortier
695341428a Merge pull request #126 from mlaga97/patch-2
Fix maven build error
2018-01-11 22:09:51 -05:00
Luc Lagarde
c610929809 Fix maven build error
Removes a reference to com.sun.istack.internal.Nullable and an associated annotation, which causes the maven build to fail.
2018-01-11 21:00:26 -06:00
simon
54b72e89b3 Fixes #121 + Saner thread safety 2018-01-09 22:10:55 -05:00
Simon Fortier
59fd620e4a Merge pull request #118 from sg495/master
Implemented selective loading/unloading of worlds.
2018-01-09 20:35:41 -05:00
simon
2fbc55d0dd Fixed potential NullPointerException on server loading 2018-01-09 20:09:46 -05:00
Simon Fortier
e1dfb08635 Merge pull request #123 from Jaggernaut555/feature/logging
Only severe are directed to stderr
2018-01-09 19:25:30 -05:00
Jaggernaut555
7cbfb822b8 Updated LogManager 2018-01-09 14:00:36 -08:00
simon
6fc583d6f0 Registers are cleared on code upload 2018-01-08 19:12:39 -05:00
sg495
d65660b5e9 Merge branch 'master' of https://github.com/simon987/Much-Assembly-Required
# Conflicts:
#	Server/src/main/java/net/simon987/server/GameServer.java
2018-01-08 18:28:37 +01:00
sg495
593be7624e Implemented selective loading/unloading of worlds. Summary of changes:
1. Database is now iteratively updated, rather than dropped and recreated every time the universe is saved.
2. A single connection to the database is opened at server creation time, and used throughout.
3. Worlds, users and server information are now stored with appropriate IDs, so that they can be suitably updated. The world ID can be computed from world coordinates alone.
4. After saving, a world is unloaded from memory if it doesn't contain any updatable objects, and if all of its neighbours are either:  (i) uncharted; (ii) not loaded in memory; (iii) without any updatable objects. This ensures that world unloading/reloading cannot be spammed by a single bot repeatedly transitioning in/out of an otherwise empty world.
5. The instance method GameUniverse.getWorld(int,int,boolean) first checks the world with given coordinates is in memory, then tries to load it from database, and only then creates a new one (if required by the boolean flag).
6. Worlds are now stored in a Hashtable indexed by world ID, for faster retrieval.
2018-01-08 18:23:10 +01:00
simon
a14853b12c Changed working directory for tests (temporary fix?) 2018-01-07 14:04:24 -05:00
simon
735a231767 Moved tests to appropriate directory 2018-01-07 13:55:42 -05:00
simon
1131e4d512 Fixes #112 (Part two) 2018-01-07 13:29:42 -05:00
simon
cfb02869bb Fixes #112 2018-01-07 13:02:49 -05:00
simon
cde03af8af Fixes #113 2018-01-07 12:57:06 -05:00
Simon Fortier
ff9370fed5 Merge pull request #117 from ChartreuseK/feature-26
Added Inc and Dec Instructions
2018-01-07 12:44:27 -05:00
Hayden Kroepfl
eaef30eb49 Added Inc and Dec instructions based off Add code 2018-01-06 18:53:35 -07:00
simon
f68027bb4d Fixes tabs problem with equ 2018-01-06 14:04:31 -05:00
simon
24d81d194e Fixes #107 2018-01-05 22:08:53 -05:00
simon
c7b9df0690 Fixes #91 2018-01-05 21:51:47 -05:00
simon
a8beb8c3e2 Fixes #115 2018-01-05 21:38:07 -05:00
simon
0bd25df977 Fixes #114 2018-01-05 21:35:35 -05:00
simon
8b0460f5f1 Fixed typos and code cleanup 2018-01-05 20:14:38 -05:00
simon
ce0584a49f Merge remote-tracking branch 'origin/master' 2018-01-05 19:46:01 -05:00
simon
0dc4ddca0f Fixes de-syncing problem with Factory and their NPCs 2018-01-05 19:45:51 -05:00
Simon Fortier
811a443a4e Merge pull request #106 from meet-mrmaker/master
Removed gather_slow. Fixes #10
2018-01-04 17:17:10 -05:00
Josh
17359161fd Update for issue #10
Removes slow and fast gather and retains gather for 1 tick.
2018-01-04 17:49:02 +11:00
Josh
afbbce215e Merge pull request #2 from simon987/master
Update
2018-01-04 12:14:03 +11:00
Simon Fortier
1a39cf8454 Create CONTRIBUTING.md 2018-01-03 20:07:48 -05:00
simon
9bc3cbf4ce Remove NPC reference to Factory on death 2018-01-03 19:22:45 -05:00
simon
9b908a5310 Biomass count on NPC death is loaded from config 2018-01-03 19:19:19 -05:00
Simon Fortier
8ceeca564a Merge pull request #66 from jtara1/master
HarvesterNPC should spawn a biomass in-place after they die. Fixes #33
2018-01-03 19:00:55 -05:00
Simon Fortier
d4fcf22550 Merge pull request #105 from sg495/master
Windows instructions added
2018-01-03 17:09:23 -05:00
Simon Fortier
d25d42534a Merge pull request #104 from meet-mrmaker/meet-mrmaker-patch-1
Update to address issue #101
2018-01-03 17:08:10 -05:00
sg495
58a378d77f Updated instructions for Windows installation and running. 2018-01-03 20:14:31 +01:00
sg495
cfaf46ad52 Added installation instructions for Windows (tested on Windows 10). 2018-01-03 17:59:46 +01:00
sg495
ba53212986 Merge pull request #1 from simon987/master
getting up to date
2018-01-03 13:04:59 +01:00
Josh
7bb5f68ff2 Edited for style conformance 2018-01-03 22:24:32 +11:00
Josh
65ec6a2102 Merge pull request #1 from meet-mrmaker/meet-mrmaker-patch-1
Update to address issue #101
2018-01-03 18:36:52 +11:00
Josh
5a994fe437 Update to address issue #101 2018-01-03 18:36:18 +11:00
Simon Fortier
415500faa9 Merge pull request #103 from simon987/mongo
Loading & Saving support for MongoDB
2018-01-02 20:36:29 -05:00
James T
3ded64cb16 Update #66: add newest Server/Server.iml file 2018-01-02 15:29:14 -08:00
simon
1a0291d517 New players are now scattered around the spawn point 2018-01-02 18:11:24 -05:00
simon
4e76d57ef9 Loading & Saving support for MongoDB 2018-01-02 17:45:58 -05:00
Simon Fortier
2a5d6b5a13 Fixes #99 2018-01-01 16:12:42 -05:00
simon
e2763faeee Fixes #97 2018-01-01 15:58:42 -05:00
simon
2a8658c598 Fixes #90 2018-01-01 15:28:12 -05:00
simon
85548ec3cb CHanged default energy value for biomass to 4000 + code styling 2018-01-01 15:21:39 -05:00
Simon Fortier
0f7b40f3ae Merge pull request #95 from djsheehy/master
Inventory hardware: clearing a biomass yields energy. Fixes #94
2018-01-01 15:19:50 -05:00
simon
ee60216784 Small adjustments for laser hw, Improved OffsetOverFlow handling, Increased maximum guest count 2018-01-01 15:17:24 -05:00
Simon Fortier
c3a0d1bd4d Merge pull request #93 from ChartreuseK/bug-80
Added handling of offset overflow and DUP factor overflow
2018-01-01 15:12:01 -05:00
Dylan Sheehy
cd8d883134 Charging energy from biomass now looks up value in config.properties 2018-01-01 13:39:57 -06:00
Simon Fortier
c7946a6356 Merge pull request #87 from ChartreuseK/bug-81
Added minimum length check to 'DW' parsing
2018-01-01 14:36:38 -05:00
Dylan Sheehy
7ee361b0bc Inventory hardware: Now clearing a biomass gains 4000 kJ. 2018-01-01 13:15:14 -06:00
simon
1e26c63358 Boolean result of ComPort actions are stored in B register 2018-01-01 12:03:36 -05:00
Simon Fortier
d832f65535 Merge pull request #84 from mlaga97/npc-combat
Allow ability to damage NPCs with Laser. Fixes #34
2018-01-01 11:07:04 -05:00
Hayden Kroepfl
e47e573b61 Added handling of offset overflow and DUP factor overflow, added new exception type. 2018-01-01 08:30:39 -07:00
Simon Fortier
93786d92cb Merge pull request #83 from Francessco121/feature/pushf-popf
Add PUSHF and POPF instructions
2018-01-01 10:20:27 -05:00
Hayden Kroepfl
34178016b1 Added minimum length check to 'DW' parseing, fixes indexoutofboundsexception 2018-01-01 05:17:37 -07:00
Luc Lagarde
b31c187ad5 Allow NPCs to be damaged and killed 2017-12-31 18:26:44 -06:00
Ethan Lafrenais
deb3859dff Add PUSHF and POPF instructions 2017-12-31 18:25:46 -05:00
Simon Fortier
b21e33601e Added links to VS code extensions 2017-12-31 11:44:09 -05:00
Simon Fortier
b2474494cc Merge pull request #75 from sgerrand/dockerize
Add a Docker image definition for the application and a Docker Compose configuration file
2017-12-31 09:56:07 -05:00
Simon Fortier
6b2e3c17ed Merge branch 'master' into dockerize 2017-12-31 09:54:41 -05:00
Simon Fortier
079a63e39c Merge branch 'master' into dockerize 2017-12-31 09:52:45 -05:00
Simon Fortier
347dc2bce0 Merge pull request #76 from arthurpaulino/renaming-action-labels
Aligning action labels with documented examples
2017-12-31 09:42:20 -05:00
Simon Fortier
90ad8e82eb Merge pull request #74 from mlaga97/patch-1
Add Linux build instructions to README.md
2017-12-31 09:38:39 -05:00
Arthur Paulino
04374e6e0a aligning action labels with documented examples 2017-12-31 09:34:43 -03:00
Sasha Gerrand
4a6ee4cce6 📖 Add installation and running documentation 2017-12-31 08:45:39 +00:00
Sasha Gerrand
37e40d0329 ✂️ Remove extraneous whitespace 2017-12-31 08:37:31 +00:00
Sasha Gerrand
99cefba245 🍴 Orchestrate server and dependencies using containers 2017-12-31 08:35:02 +00:00
Sasha Gerrand
7821d428e2 🐳 Add Dockerfile 2017-12-31 08:34:17 +00:00
Luc Lagarde
93bea49a3e Add Linux build instructions to README.md 2017-12-30 23:47:08 -06:00
Simon Fortier
cca68ba139 Merge pull request #69 from renpnal/patch-2
Fix typos
2017-12-30 20:00:25 -05:00
simon
83f05efff6 Support for color in hologram. Renamed classes: fixes #72 2017-12-30 19:58:47 -05:00
Jesse Nieminen
ea3b06c54c Fix typos
Fixed typos in comments.
2017-12-30 23:52:06 +02:00
simon
1ed9e9e4db Fixed bug that sent console buffer to random players for real this time 2017-12-30 16:41:14 -05:00
simon
08f1aa8686 Fixed bug that sent console buffer to random players. 2017-12-30 16:29:39 -05:00
simon
55d4c19fe1 Added Console output, Cubots can receive data from ComPort, Fixed BOM being added to string literals, Fixed legs changing direction for free when energy < 100, Changed some log levels. 2017-12-30 15:30:44 -05:00
James T
2398219fab Update #66: rm npc plugin dependency from plant.event plugin 2017-12-30 11:08:43 -08:00
James T
81767ed5cf Updates for #66: reorganize and relocate some methods and calls 2017-12-30 09:01:58 -08:00
simon
2ef6f492c4 Fixes #64 2017-12-30 11:14:45 -05:00
simon
70a55dce59 Added features to Hologram hardware - Fixes #63 and #67 2017-12-30 11:03:09 -05:00
simon
fe0be03ab8 Fixes #68 & Reformatted code 2017-12-30 10:35:56 -05:00
simon
fd73a47796 Fixes #65 2017-12-30 10:30:18 -05:00
James T
eea9420192 HarvesterNPC should spawn a biomass in-place after they die (#33) 2017-12-29 22:35:02 -08:00
simon
9e402fe8a1 Fixed Radio Tower range 2017-12-29 22:36:52 -05:00
simon
b3d88b2813 Fixed Radio Tower range 2017-12-29 22:32:39 -05:00
simon
ef7f573256 Added basic Radio Tower functionality #32
Keypress buffer is cleared on code upload
2017-12-29 21:49:42 -05:00
simon
5afa767b4a Fixed OF and CF flags being always set to false in the other function 2017-12-29 17:09:30 -05:00
simon
a9e580f2ce Fixed OF and CF flags being always set to false 2017-12-29 17:06:28 -05:00
simon
c4caf4ab0b Changed CLEAR action for the inventory to 0 for consistency 2017-12-29 16:16:28 -05:00
simon
0c06d0bf09 Fixes #62 2017-12-29 15:53:29 -05:00
simon
017b89f97f Characters can be escaped in string literals 2017-12-29 14:35:26 -05:00
Simon Fortier
bd276e0a93 Merge pull request #60 from ScarySpider/More-Maven-fixes
More maven fixes
2017-12-29 13:48:56 -05:00
simon
72d43fccf7 Fixes #58 2017-12-29 13:39:13 -05:00
simon
18aaf91991 Fixed RET instruction that wouldn't assemble without any parameter 2017-12-29 13:09:47 -05:00
Jacob Swehla
bbcadbf253 Merge branch 'master' into More-Maven-fixes 2017-12-29 11:26:12 -06:00
Jacob Swehla
3d60f9a67c Merge remote-tracking branch 'upstream/master' 2017-12-29 11:25:55 -06:00
Jacob Swehla
b43cf9ac33 Moved config file and fixed some warnings 2017-12-29 11:25:31 -06:00
simon
293795b215 Fixes #55 and commas & semicolon can be inserted in string literals 2017-12-29 11:06:48 -05:00
Jacob Swehla
fde79ed97e Merge branch 'master' into More-Maven-fixes 2017-12-29 10:06:44 -06:00
Jacob Swehla
fcd339c315 Merge remote-tracking branch 'upstream/master' 2017-12-29 10:06:20 -06:00
Jacob Swehla
59e3e9430e Maven and file access
- Server config file is now accessed through the class loader
- Maven outputs server.jar, moves dependencys to adjacent /libs, and plugins to adjacent /plugins
2017-12-29 10:00:19 -06:00
simon
45ec7191b4 Added string literals support for the assembler 2017-12-29 08:28:04 -05:00
simon
d9732557fc Removed unused files 2017-12-28 23:08:05 -05:00
simon
eced45a358 Merge remote-tracking branch 'origin/master' 2017-12-28 22:39:22 -05:00
simon
0fee35baec Fixes #53 2017-12-28 22:35:49 -05:00
Simon Fortier
729debb1a3 Fixes #56 2017-12-28 20:41:02 -05:00
simon
2fb7d2f73e Fixes #54 2017-12-28 20:33:57 -05:00
simon
dab5cab602 Updated incorrect documentation 2017-12-28 19:29:48 -05:00
Jacob Swehla
c23ee0dc86 stuff 2017-12-28 17:02:41 -06:00
Jacob Swehla
96cce8478e Merge remote-tracking branch 'upstream/master' 2017-12-28 16:44:03 -06:00
Jacob Swehla
9d184cb515 Merge remote-tracking branch 'upstream/master' 2017-12-28 16:41:05 -06:00
Jacob Swehla
09e00fd032 maven work 2017-12-28 16:40:53 -06:00
simon
e1d0833c3a Recovering accidentally deleted file 2017-12-28 17:40:05 -05:00
simon
8a980fec6a Very small modifications for keyboard hardware 2017-12-28 16:51:03 -05:00
simon
e96b7982c8 Fixed Biomass pickup problem 2017-12-28 15:33:28 -05:00
simon
21ec4ae704 Cubot are now passable + Bug fixes 2017-12-28 13:34:11 -05:00
Simon Fortier
690b7e8d31 Merge pull request #47 from ScarySpider/Basic-Maven-fixes
Basic maven fixes
2017-12-28 09:57:03 -05:00
simon
d28ca387d0 Fixes ConcurrentModificationException errors 2017-12-28 09:17:31 -05:00
simon
f2b6387cc9 Fixes #50 2017-12-28 09:15:19 -05:00
simon
f3b20b3a2d Fixes #51 2017-12-28 08:43:13 -05:00
Simon Fortier
f4fd3866eb Merge pull request #48 from cooprocks123e/bugfix
Modified "RET imm" to add imm + 1 to the SP instead of imm
2017-12-27 19:20:42 -05:00
Cooper Harasyn
965ca91cb6 Modified "RET imm" to add imm + 1 to the SP instead of imm 2017-12-27 19:18:10 -05:00
Jacob Swehla
556f443ec2 Now outputs .jar files to /target
-Server jar outputs to /target/
-All other jars output to /target/plugins
2017-12-27 17:52:40 -06:00
Jacob Swehla
3158dd75ea Fixed Maven
Maven now builds correctly, may need further refinement.
2017-12-27 15:36:08 -06:00
Simon Fortier
1b6927c575 Merge pull request #41 from cooprocks123e/bugfix
Fixed typo in SubInstruction
2017-12-27 15:55:30 -05:00
Cooper Harasyn
3bd34bfcba Fixed typo in SubInstruction 2017-12-27 15:52:00 -05:00
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
simon
8701007ad9 Bug fixes related to floppy drive 2017-11-14 20:58:07 -05:00
simon
cfb8050cee Added basic floppy drives #3. 2017-11-14 17:25:12 -05:00
simon
da7d050661 Universe warp around and maximum size #9 2017-11-13 22:45:19 -05:00
simon
3ee9b4be95 Added SAR Instructions #7. 2017-11-13 21:39:16 -05:00
simon
42421b7710 Added RCR/RCL Instructions #7. 2017-11-13 20:08:07 -05:00
simon
9979986c6a Added SAL Instruction #6. Added ROL/ROR Instructions #7. 2017-11-13 17:51:16 -05:00
simon
c5abe2efc5 Added ROL/ROR Instructions #7 as well as JC/JNC and JO/JNO instructions 2017-11-13 11:28:06 -05:00
Simon Fortier
fdfa568e07 Update README.md 2017-11-12 13:07:39 -05:00
simon
1bf1682cb3 Updated readme 2017-11-12 13:05:39 -05:00
simon
a3fa3c4c09 Added Battery Hardware. #2 2017-11-12 10:27:07 -05:00
Simon Fortier
f7ea14275c Create LICENSE 2017-11-12 09:32:08 -05:00
simon
04d51e1f1f Added XCHG Instruction #5. Placeholder class for LEA #1 2017-11-11 20:14:13 -05:00
simon
8c5dcd0fba Added Hologram Projector Hardware. Added GET_WORLD_POS in LiDAR. Fixed Drill. 2017-11-11 19:43:06 -05:00
simon
1a6f92a29d Added NOT Instruction 2017-11-11 15:27:06 -05:00
simon
3d9bfb2a42 Added Clock 2017-11-11 15:07:28 -05:00
simon
e2ed744479 Added Random number generator 2017-11-11 14:34:33 -05:00
227 changed files with 7834 additions and 2694 deletions

17
.gitignore vendored Normal file
View File

@@ -0,0 +1,17 @@
plugins/Plugin NPC.jar
plugins/Plugin Misc HW.jar
plugins/Plant.jar
plugins/Cubot.jar
.idea/*
mar.log
mar.log.lck
*.iml
*.class
*/target/*
plugins/*.jar
save.json
Server/Server.iml
target/*
Server/Server.iml
Server/src/main/java/META-INF/MANIFEST.MF

19
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,19 @@
## General guide
[Collaboration guide](https://github.com/simon987/Much-Assembly-Required/wiki/Collaboration-Guide)
## Before creating a pull request
Here small unordered list of guidelines to read before creating a pull request
- Use java <= 1.8 features
- Please follow [Google's Java style guide](https://google.github.io/styleguide/javaguide.html)
- Constants (e.g. the energy cost of an in-game action) should be loaded from config.properties
- The project is separated into multiple modules, the `Server` module and its plugins. Plugins should
not depend on another plugin to compile or to run.
(e.g. NPC plugin shouldn't import `net.simon987.biomassplugin` )
- Use `Logmanager.LOGGER` to log messages to the console. Use `.fine()` for debugging messages and `.info()` for
info for more important messages
that are not too frequently used.
- Do not submit a pull request for a new feature that has not been approved
by [simon987](https://github.com/simon987) in an Issue beforehand
- Please state what tests have been performed in the pull request

7
Dockerfile Normal file
View File

@@ -0,0 +1,7 @@
FROM alpine:3.7
RUN apk add --no-cache maven openjdk8
COPY /. /app/
WORKDIR /app
RUN mvn package \
&& cp Server/src/main/resources/config.properties /app/
CMD ["java", "-jar", "/app/target/server-1.2a.jar"]

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -0,0 +1,25 @@
<?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: org.apache.commons:commons-text:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:2.10.1" 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>

34
Plugin Cubot/pom.xml Normal file
View File

@@ -0,0 +1,34 @@
<?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>
<parent>
<groupId>net.simon987.server</groupId>
<artifactId>server_root</artifactId>
<version>1.2a</version>
</parent>
<groupId>net.simon987.plugincubot</groupId>
<artifactId>plugin-cubot</artifactId>
<version>1.2a</version>
<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

@@ -0,0 +1,308 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Memory;
import net.simon987.server.game.*;
import net.simon987.server.user.User;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class Cubot extends GameObject implements Updatable, ControllableUnit, Programmable {
private static final char MAP_INFO = 0x0080;
public static final int ID = 1;
public static int TYPE_ID = 2;
private int hologram = 0;
private String hologramString = "";
private HologramMode hologramMode = HologramMode.CLEARED;
private HologramMode lastHologramMode = HologramMode.CLEARED;
private int hologramColor = 0;
/**
* Hit points
*/
private int hp;
private int heldItem;
private Action currentAction = Action.IDLE;
private Action lastAction = Action.IDLE;
private ArrayList<Integer> keyboardBuffer = new ArrayList<>();
private ArrayList<char[]> consoleMessagesBuffer = new ArrayList<>(CONSOLE_BUFFER_MAX_SIZE);
private ArrayList<char[]> lastConsoleMessagesBuffer = new ArrayList<>(CONSOLE_BUFFER_MAX_SIZE);
private ConsoleMode consoleMode = ConsoleMode.NORMAL;
private ConsoleMode lastConsoleMode = ConsoleMode.NORMAL;
private User parent;
private int energy;
private int maxEnergy;
private static final float SOLAR_PANEL_MULTIPLIER = 1;
private static final int CONSOLE_BUFFER_MAX_SIZE = 40;
public Cubot() {
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
storeEnergy((int) (SOLAR_PANEL_MULTIPLIER * GameServer.INSTANCE.getDayNightCycle().getSunIntensity()));
if (currentAction == Action.WALKING) {
if (spendEnergy(100)) {
if (!incrementLocation()) {
//Couldn't walk
currentAction = Action.IDLE;
}
} else {
currentAction = Action.IDLE;
}
}
/*
* CurrentAction is set during the code execution and this function is called right after
* If no action as been set, the action sent to the client is the action in currentAction that
* was set last tick (IDLE)
*/
lastAction = currentAction;
currentAction = Action.IDLE;
//Same principle for hologram
lastHologramMode = hologramMode;
hologramMode = HologramMode.CLEARED;
//And the console
lastConsoleMode = consoleMode;
consoleMode = ConsoleMode.NORMAL;
lastConsoleMessagesBuffer = new ArrayList<>(consoleMessagesBuffer);
consoleMessagesBuffer.clear();
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("i", getObjectId());
json.put("t", ID);
json.put("x", getX());
json.put("y", getY());
json.put("direction", getDirection().ordinal());
json.put("heldItem", heldItem);
json.put("hp", hp);
json.put("action", lastAction.ordinal());
json.put("holo", hologram);
json.put("holoStr", hologramString);
json.put("holoMode", lastHologramMode.ordinal());
json.put("holoC", hologramColor);
json.put("energy", energy);
if (parent != null) {
json.put("parent", parent.getUsername()); //Only used client-side for now
}
return json;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("t", ID);
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("direction", getDirection().ordinal());
dbObject.put("heldItem", heldItem);
dbObject.put("hp", hp);
dbObject.put("action", lastAction.ordinal());
dbObject.put("holo", hologram);
dbObject.put("holoStr", hologramString);
dbObject.put("holoMode", lastHologramMode.ordinal());
dbObject.put("holoC", hologramColor);
dbObject.put("energy", energy);
if (parent != null) {
dbObject.put("parent", parent.getUsername()); //Only used client-side for now
}
return dbObject;
}
public static Cubot deserialize(DBObject obj) {
Cubot cubot = new Cubot();
cubot.setObjectId((long) obj.get("i"));
cubot.setX((int) obj.get("x"));
cubot.setY((int) obj.get("y"));
cubot.hp = (int) obj.get("hp");
cubot.setDirection(Direction.getDirection((int) obj.get("direction")));
cubot.heldItem = (int) obj.get("heldItem");
cubot.energy = (int) obj.get("energy");
cubot.maxEnergy = GameServer.INSTANCE.getConfig().getInt("battery_max_energy");
return cubot;
}
public void setHeldItem(int heldItem) {
this.heldItem = heldItem;
}
public int getHeldItem() {
return heldItem;
}
@Override
public void setKeyboardBuffer(ArrayList<Integer> kbBuffer) {
keyboardBuffer = kbBuffer;
}
@Override
public ArrayList<Integer> getKeyboardBuffer() {
return keyboardBuffer;
}
public void clearKeyboardBuffer() {
keyboardBuffer.clear();
}
public void setCurrentAction(Action currentAction) {
this.currentAction = currentAction;
}
public User getParent() {
return parent;
}
public void setParent(User parent) {
this.parent = parent;
}
public Action getAction() {
return lastAction;
}
public Action getCurrentAction() {
return currentAction;
}
public void setHologram(int hologram) {
this.hologram = hologram;
}
public void setHologramString(String hologramString) {
this.hologramString = hologramString;
}
public int getEnergy() {
return energy;
}
public void setEnergy(int energy) {
this.energy = energy;
}
public boolean spendEnergy(int spent) {
if (energy - spent < 0) {
return false;
} else {
energy -= spent;
return true;
}
}
public void storeEnergy(int qty) {
energy = Math.min(energy + qty, maxEnergy);
}
public void setMaxEnergy(int maxEnergy) {
this.maxEnergy = maxEnergy;
}
public int getMaxEnergy() {
return maxEnergy;
}
@Override
public Memory getFloppyData() {
CubotFloppyDrive drive = ((CubotFloppyDrive) getParent().getCpu().getHardware(CubotFloppyDrive.DEFAULT_ADDRESS));
if (drive.getFloppy() != null) {
return drive.getFloppy().getMemory();
} else {
return null;
}
}
@Override
public boolean isAt(int x, int y) {
return false;
}
public void setHologramMode(HologramMode hologramMode) {
this.hologramMode = hologramMode;
}
public enum HologramMode {
CLEARED,
HEX,
STRING,
DEC
}
public enum ConsoleMode {
CLEAR,
NORMAL
}
@Override
public void setAction(Action action) {
currentAction = action;
}
@Override
public boolean sendMessage(char[] message) {
if (consoleMessagesBuffer.size() < CONSOLE_BUFFER_MAX_SIZE) {
consoleMessagesBuffer.add(message);
return true;
} else {
return false;
}
}
public ArrayList<char[]> getConsoleMessagesBuffer() {
return lastConsoleMessagesBuffer;
}
public int getConsoleMode() {
return lastConsoleMode.ordinal();
}
public void setConsoleMode(ConsoleMode consoleMode) {
this.consoleMode = consoleMode;
}
public void setHologramColor(int hologramColor) {
this.hologramColor = hologramColor;
}
}

View File

@@ -0,0 +1,63 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
public class CubotBattery extends CpuHardware {
public static final int DEFAULT_ADDRESS = 0x000A;
/**
* Hardware ID (Should be unique)
*/
public static final char HWID = 0x000A;
private Cubot cubot;
private static final int BATTERY_POLL = 1;
private static final int BATTERY_GET_MAX_CAPACITY = 2;
public CubotBattery(Cubot cubot) {
this.cubot = cubot;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == BATTERY_POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getEnergy());
} else if (a == BATTERY_GET_MAX_CAPACITY) {
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getMaxEnergy());
} else if (a == 0xFFFF) {
cubot.setEnergy(cubot.getMaxEnergy());
}
}
@Override
public char getId() {
return HWID;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotBattery deserialize(DBObject obj) {
return new CubotBattery((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,144 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Programmable;
import java.awt.*;
import java.util.ArrayList;
public class CubotComPort extends CpuHardware {
public static final char HWID = 0xD;
public static final int DEFAULT_ADDRESS = 0xD;
private Cubot cubot;
private static final int COMPORT_BUFFER_CLEAR = 0;
private static final int COMPORT_POLL = 1;
private static final int COMPORT_FRONT_PORT_OUT = 2;
private static final int COMPORT_SELF_OUT = 3;
private static final int COMPORT_CONSOLE_CLEAR = 4;
public CubotComPort(Cubot cubot) {
this.cubot = cubot;
}
private static final int MESSAGE_LENGTH = 8;
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == COMPORT_BUFFER_CLEAR) {
cubot.getConsoleMessagesBuffer().clear();
} else if (a == COMPORT_CONSOLE_CLEAR) {
cubot.setConsoleMode(Cubot.ConsoleMode.CLEAR);
} else if (a == COMPORT_POLL) {
if (cubot.spendEnergy(4)) {
int x = getCpu().getRegisterSet().getRegister("X").getValue();
//Read all messages in the console buffer to memory at X
for (char[] message : cubot.getConsoleMessagesBuffer()) {
if (x + MESSAGE_LENGTH >= getCpu().getMemory().getWords().length) {
//todo set interrupt ?
getCpu().getStatus().setErrorFlag(true);
} else {
System.arraycopy(message, 0, getCpu().getMemory().getWords(), x, MESSAGE_LENGTH);
}
}
//Set B = number of messages
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getConsoleMessagesBuffer().size());
}
} else if (a == COMPORT_FRONT_PORT_OUT) {
if (cubot.spendEnergy(20)) {
//Get object directly in front of the Cubot
Point frontTile = cubot.getFrontTile();
//Todo will have to add getGameObjectsBlockingAt to enable Factory
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y);
if (objects.size() > 0 && objects.get(0) instanceof Programmable) {
int x = getCpu().getRegisterSet().getRegister("X").getValue();
if (x + MESSAGE_LENGTH >= getCpu().getMemory().getWords().length) {
//todo set interrupt ?
getCpu().getStatus().setErrorFlag(true);
} else {
//Get MESSAGE_LENGTH-word message pointed by X
char[] message = new char[MESSAGE_LENGTH];
System.arraycopy(getCpu().getMemory().getWords(), x, message, 0, MESSAGE_LENGTH);
//Send it to the Programmable object
getCpu().getRegisterSet().getRegister("B").setValue(
((Programmable) objects.get(0)).sendMessage(message) ? 1 : 0);
return;
}
}
}
getCpu().getRegisterSet().getRegister("B").setValue(0); //Failed
} else if (a == COMPORT_SELF_OUT) {
if (cubot.spendEnergy(1)) {
int x = getCpu().getRegisterSet().getRegister("X").getValue();
//Write a single message to console buffer
if (x + MESSAGE_LENGTH >= getCpu().getMemory().getWords().length) {
//todo set interrupt ?
getCpu().getStatus().setErrorFlag(true);
} else {
//Get MESSAGE_LENGTH-word message pointed by X
char[] message = new char[MESSAGE_LENGTH];
System.arraycopy(getCpu().getMemory().getWords(), x, message, 0, MESSAGE_LENGTH);
getCpu().getRegisterSet().getRegister("B").setValue(cubot.sendMessage(message) ? 1 : 0);
return;
}
}
getCpu().getRegisterSet().getRegister("B").setValue(0); //Failed
}
}
@Override
public char getId() {
return HWID;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotComPort deserialize(DBObject obj) {
return new CubotComPort((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,78 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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;
public class CubotDrill extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0005;
public static final int DEFAULT_ADDRESS = 5;
private static final int DRILL_POLL = 1;
private static final int DRILL_GATHER = 2; // simplified gather
private Cubot cubot;
public CubotDrill(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == DRILL_POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(0);
} else if (a == DRILL_GATHER) {
if (cubot.spendEnergy(1400)) {
if (cubot.getCurrentAction() == Action.IDLE) {
int tile = cubot.getWorld().getTileMap().getTileAt(cubot.getX(), cubot.getY());
if (tile == TileMap.IRON_TILE) {
cubot.setHeldItem(TileMap.ITEM_IRON);
cubot.setCurrentAction(Action.DIGGING);
} else if (tile == TileMap.COPPER_TILE) {
cubot.setHeldItem(TileMap.ITEM_COPPER);
cubot.setCurrentAction(Action.DIGGING);
}
}
}
}
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotDrill deserialize(DBObject obj) {
return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,110 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
public class CubotFloppyDrive extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x000B;
public static final int DEFAULT_ADDRESS = 0x000B;
private static final int FLOPPY_POLL = 1;
private static final int FLOPPY_READ_SECTOR = 2;
private static final int FLOPPY_WRITE_SECTOR = 3;
private Cubot cubot;
private FloppyDisk floppyDisk;
public CubotFloppyDrive(Cubot cubot) {
this.cubot = cubot;
floppyDisk = new FloppyDisk();
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == FLOPPY_POLL) {
if (floppyDisk != null) {
getCpu().getRegisterSet().getRegister("B").setValue(0);
} else {
getCpu().getRegisterSet().getRegister("B").setValue(1);
}
} else if (a == FLOPPY_READ_SECTOR) {
if (floppyDisk == null) {
getCpu().getRegisterSet().getRegister("B").setValue(0);
} else {
if (cubot.spendEnergy(1)) {
getCpu().getRegisterSet().getRegister("B").setValue(1);
int x = getCpu().getRegisterSet().getRegister("X").getValue();
int y = getCpu().getRegisterSet().getRegister("Y").getValue();
floppyDisk.readSector(x, cubot.getParent().getCpu().getMemory(), y);
}
}
} else if (a == FLOPPY_WRITE_SECTOR) {
if (floppyDisk == null) {
getCpu().getRegisterSet().getRegister("B").setValue(0);
} else {
if (cubot.spendEnergy(1)) {
getCpu().getRegisterSet().getRegister("B").setValue(1);
int x = getCpu().getRegisterSet().getRegister("X").getValue();
int y = getCpu().getRegisterSet().getRegister("Y").getValue();
floppyDisk.writeSector(x, cubot.getParent().getCpu().getMemory(), y);
}
}
}
}
@Override
public char getId() {
return HWID;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
if (floppyDisk != null) {
dbObject.put("floppy", floppyDisk.mongoSerialise());
}
return dbObject;
}
public static CubotFloppyDrive deserialize(DBObject obj) {
CubotFloppyDrive drive = new CubotFloppyDrive((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
if (obj.containsField("floppy")) {
drive.floppyDisk = FloppyDisk.deserialise((DBObject) obj.get("floppy"));
}
return drive;
}
public FloppyDisk getFloppy() {
return floppyDisk;
}
}

View File

@@ -0,0 +1,101 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
public class CubotHologram extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0009;
public static final int DEFAULT_ADDRESS = 9;
private Cubot cubot;
private static final int HOLO_CLEAR = 0;
private static final int HOLO_DISPLAY_HEX = 1;
private static final int HOLO_DISPLAY_STRING = 2;
private static final int HOLO_DISPLAY_DEC = 3;
private static final int HOLO_DISPLAY_COLOR = 4;
private static final int STR_MAX_LEN = 8;
public CubotHologram(Cubot cubot) {
this.cubot = cubot;
}
@Override
public void handleInterrupt(Status status) {
char a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == HOLO_CLEAR) {
cubot.setHologramMode(Cubot.HologramMode.CLEARED);
} else if (a == HOLO_DISPLAY_HEX) {
char b = getCpu().getRegisterSet().getRegister("B").getValue();
cubot.setHologram(b);
cubot.setHologramMode(Cubot.HologramMode.HEX);
} else if (a == HOLO_DISPLAY_STRING) {
char x = getCpu().getRegisterSet().getRegister("X").getValue();
//Display zero-terminated string starting at X (max 8 chars)
StringBuilder holoString = new StringBuilder();
for (int i = 0; i < STR_MAX_LEN; i++) {
char nextChar = (char) getCpu().getMemory().get(x + i);
if (nextChar != 0) {
holoString.append((char) getCpu().getMemory().get(x + i));
} else {
break;
}
}
cubot.setHologramString(holoString.toString());
cubot.setHologramMode(Cubot.HologramMode.STRING);
} else if (a == HOLO_DISPLAY_DEC) {
//Display decimal number
char b = getCpu().getRegisterSet().getRegister("B").getValue();
cubot.setHologram(b);
cubot.setHologramMode(Cubot.HologramMode.DEC);
} else if (a == HOLO_DISPLAY_COLOR) {
if (cubot.spendEnergy(4)) {
int b = getCpu().getRegisterSet().getRegister("B").getValue();
int c = getCpu().getRegisterSet().getRegister("C").getValue();
cubot.setHologramColor((c | (b << 16))); //B:C
}
}
}
@Override
public char getId() {
return HWID;
}
public static CubotHologram deserialize(DBObject obj) {
return new CubotHologram((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
}

View File

@@ -1,9 +1,10 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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 org.json.simple.JSONObject;
public class CubotInventory extends CpuHardware { public class CubotInventory extends CpuHardware {
@@ -16,8 +17,8 @@ public class CubotInventory extends CpuHardware {
private Cubot cubot; private Cubot cubot;
private static final int POLL = 1; private static final int INV_CLEAR = 0;
private static final int CLEAR = 2; private static final int INV_POLL = 1;
public CubotInventory(Cubot cubot) { public CubotInventory(Cubot cubot) {
this.cubot = cubot; this.cubot = cubot;
@@ -33,27 +34,35 @@ public class CubotInventory extends CpuHardware {
int a = getCpu().getRegisterSet().getRegister("A").getValue(); int a = getCpu().getRegisterSet().getRegister("A").getValue();
if(a == POLL) { if (a == INV_POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getHeldItem()); getCpu().getRegisterSet().getRegister("B").setValue(cubot.getHeldItem());
} else if (a == CLEAR) { } else if (a == INV_CLEAR) {
cubot.setHeldItem(0); if (cubot.getHeldItem() == 0x0001) {
int energy = GameServer.INSTANCE.getConfig().getInt("biomassEnergyValue");
cubot.storeEnergy(energy);
cubot.setHeldItem(0);
} else if (cubot.spendEnergy(100)) {
cubot.setHeldItem(0);
}
} }
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static CubotInventory deserialize(JSONObject hwJSON){ public static CubotInventory deserialize(DBObject obj) {
return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot"))); return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@@ -1,20 +1,18 @@
package net.simon987.cubotplugin; package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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 org.json.simple.JSONObject;
public class Keyboard extends CpuHardware { public class CubotKeyboard extends CpuHardware {
public static final int DEFAULT_ADDRESS = 4; public static final int DEFAULT_ADDRESS = 4;
public static final String NAME = "Wireless Keyboard"; private static final int KEYBOARD_CLEAR_BUFFER = 0;
private static final int KEYBOARD_FETCH_KEY = 1;
private static final int CLEAR_BUFFER = 0;
private static final int FETCH_KEY = 1;
/** /**
* Hardware ID (Should be unique) * Hardware ID (Should be unique)
*/ */
@@ -22,7 +20,7 @@ public class Keyboard extends CpuHardware {
private Cubot cubot; private Cubot cubot;
public Keyboard(Cubot cubot) { public CubotKeyboard(Cubot cubot) {
this.cubot = cubot; this.cubot = cubot;
} }
@@ -36,14 +34,14 @@ public class Keyboard extends CpuHardware {
int a = getCpu().getRegisterSet().getRegister("A").getValue(); int a = getCpu().getRegisterSet().getRegister("A").getValue();
if(a == CLEAR_BUFFER){ if (a == KEYBOARD_CLEAR_BUFFER) {
cubot.clearKeyboardBuffer(); cubot.clearKeyboardBuffer();
} else if (a == FETCH_KEY){ } else if (a == KEYBOARD_FETCH_KEY) {
//pop //pop
int key = 0; int key = 0;
if(cubot.getKeyboardBuffer().size() > 0){ if (cubot.getKeyboardBuffer().size() > 0) {
key = cubot.getKeyboardBuffer().get(0); key = cubot.getKeyboardBuffer().get(0);
cubot.getKeyboardBuffer().remove(0); cubot.getKeyboardBuffer().remove(0);
} }
@@ -55,16 +53,17 @@ public class Keyboard extends CpuHardware {
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONObject json = new JSONObject(); BasicDBObject dbObject = new BasicDBObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json; dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
} }
public static Keyboard deserialize(JSONObject hwJSON){ public static CubotKeyboard deserialize(DBObject obj) {
return new Keyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot"))); return new CubotKeyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
} }
} }

View File

@@ -0,0 +1,105 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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.Attackable;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.InventoryHolder;
import java.awt.*;
import java.util.ArrayList;
public class CubotLaser extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0002;
public static final int DEFAULT_ADDRESS = 2;
private Cubot cubot;
private static final int LASER_WITHDRAW = 1;
private static final int LASER_DEPOSIT = 2;
private static final int LASER_ATTACK = 3;
private static final int LASER_DAMAGE = 25;
public CubotLaser(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if (a == LASER_WITHDRAW) {
Point frontTile = cubot.getFrontTile();
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsBlockingAt(frontTile.x, frontTile.y);
if (cubot.getCurrentAction() == 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)) {
if (cubot.spendEnergy(30)) {
//Take the item
((InventoryHolder) objects.get(0)).takeItem(b);
cubot.setHeldItem(b);
cubot.setCurrentAction(Action.WITHDRAWING);
}
}
}
}
} else if (a == LASER_DEPOSIT) {
// TODO
} else if (a == LASER_ATTACK) {
if (cubot.spendEnergy(70)) {
//Get object directly in front of the Cubot
Point frontTile = cubot.getFrontTile();
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y);
if (objects.size() > 0 && objects.get(0) instanceof Attackable) {
((Attackable) objects.get(0)).damage(LASER_DAMAGE);
}
}
}
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotLaser deserialize(DBObject obj) {
return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,104 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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;
public class CubotLeg extends CpuHardware implements JSONSerialisable {
public static final int DEFAULT_ADDRESS = 1;
public static final String NAME = "Cubot Leg";
private static final int LEGS_SET_DIR = 1;
private static final int LEGS_SET_DIR_AND_WALK = 2;
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0001;
private Cubot cubot;
public CubotLeg(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
if (cubot.getCurrentAction() == Action.IDLE) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if (a == LEGS_SET_DIR) {
Direction dir = Direction.getDirection(b);
if (dir != null) {
if (cubot.spendEnergy(20)) {
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
}
} else {
status.setErrorFlag(true);
}
} else if (a == LEGS_SET_DIR_AND_WALK) {
if (cubot.getMaxEnergy() >= 100) {
Direction dir = Direction.getDirection(b);
if (dir != null) {
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
} else {
status.setErrorFlag(true);
}
cubot.setCurrentAction(Action.WALKING);
}
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotLeg deserialize(DBObject obj) {
return new CubotLeg((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,160 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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;
import net.simon987.server.game.pathfinding.Pathfinder;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class CubotLidar extends CpuHardware implements JSONSerialisable {
/**
* Hardware ID (Should be unique)
*/
public static final char HWID = 0x0003;
public static final int DEFAULT_ADDRESS = 3;
private Cubot cubot;
private static final int LIDAR_GET_POS = 1;
private static final int LIDAR_GET_PATH = 2;
private static final int LIDAR_GET_MAP = 3;
private static final int LIDAR_GET_WORLD_POS = 4;
private static final int MEMORY_MAP_START = 0x0100;
private static final int MEMORY_PATH_START = 0x0000;
public CubotLidar(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
switch (a) {
case LIDAR_GET_POS:
getCpu().getRegisterSet().getRegister("X").setValue(cubot.getX());
getCpu().getRegisterSet().getRegister("Y").setValue(cubot.getY());
break;
case LIDAR_GET_PATH:
if (cubot.spendEnergy(50)) {
int b = getCpu().getRegisterSet().getRegister("B").getValue();
int destX = getCpu().getRegisterSet().getRegister("X").getValue();
int destY = getCpu().getRegisterSet().getRegister("Y").getValue();
//Get path
ArrayList<Node> nodes = Pathfinder.findPath(cubot.getWorld(), cubot.getX(), cubot.getY(),
destX, destY, b);
//Write to memory
Memory mem = getCpu().getMemory();
int counter = MEMORY_PATH_START;
if (nodes != null) {
Node lastNode = null;
for (Node n : nodes) {
//Store the path as a sequence of directions
if (lastNode == null) {
lastNode = n;
continue;
}
if (n.x < lastNode.x) {
//West
mem.set(counter++, 3);
} else if (n.x > lastNode.x) {
//East
mem.set(counter++, 1);
} else if (n.y < lastNode.y) {
//North
mem.set(counter++, 0);
} else if (n.y > lastNode.y) {
//South
mem.set(counter++, 2);
}
lastNode = n;
}
//Indicate end of path with 0xAAAA
mem.set(counter, 0xAAAA);
} else {
//Indicate invalid path 0xFFFF
mem.set(counter, 0xFFFF);
}
LogManager.LOGGER.fine("DEBUG: path to" + destX + "," + destY);
}
break;
case LIDAR_GET_MAP:
if (cubot.spendEnergy(10)) {
char[][] mapInfo = cubot.getWorld().getMapInfo();
int i = MEMORY_MAP_START;
for (int y = 0; y < World.WORLD_SIZE; y++) {
for (int x = 0; x < World.WORLD_SIZE; x++) {
getCpu().getMemory().set(i++, mapInfo[x][y]);
}
}
}
break;
case LIDAR_GET_WORLD_POS:
getCpu().getRegisterSet().getRegister("X").setValue(cubot.getWorld().getX());
getCpu().getRegisterSet().getRegister("Y").setValue(cubot.getWorld().getY());
break;
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static CubotLidar deserialize(DBObject obj) {
return new CubotLidar((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,67 @@
package net.simon987.cubotplugin;
import com.mongodb.DBObject;
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;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
public class CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer {
@Override
public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener());
listeners.add(new UserCreationListener());
LogManager.LOGGER.info("Initialised Cubot plugin");
}
@Override
public GameObject deserializeObject(DBObject object) {
int objType = (int) object.get("t");
if (objType == Cubot.ID) {
return Cubot.deserialize(object);
}
return null;
}
@Override
public CpuHardware deserializeHardware(DBObject obj) {
int hwid = (int) obj.get("hwid");
switch (hwid) {
case CubotLeg.HWID:
return CubotLeg.deserialize(obj);
case CubotLaser.HWID:
return CubotLaser.deserialize(obj);
case CubotLidar.HWID:
return CubotLidar.deserialize(obj);
case CubotDrill.HWID:
return CubotDrill.deserialize(obj);
case CubotInventory.HWID:
return CubotInventory.deserialize(obj);
case CubotKeyboard.HWID:
return CubotKeyboard.deserialize(obj);
case CubotHologram.HWID:
return CubotHologram.deserialize(obj);
case CubotBattery.HWID:
return CubotBattery.deserialize(obj);
case CubotFloppyDrive.HWID:
return CubotFloppyDrive.deserialize(obj);
case CubotComPort.HWID:
return CubotComPort.deserialize(obj);
}
return null;
}
}

View File

@@ -0,0 +1,109 @@
package net.simon987.cubotplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.assembly.Memory;
import net.simon987.server.io.MongoSerialisable;
/**
* Represents a floppy disk that is inside a floppy drive.
* Floppies contains 80 tracks with 18 sectors per track.
* That's 1440 sectors of 512 words. (total 1,474,560 bytes / 737,280 words / 1.44Mb)
*/
public class FloppyDisk implements MongoSerialisable {
/**
* Contents of the disk
*/
private Memory memory;
/**
* Current location of the read/write head.
* Used to calculate seek time
*/
private int rwHeadTrack = 0;
public FloppyDisk() {
this.memory = new Memory(512 * 1440);
}
/**
* Read 512 words from the specified sector to cpu memory at specified address
*
* @param sector sector to read (0-1440)
* @param cpuMemory Cpu memory to write to
* @param ramAddress address of the data to write in CPU memory
* @return Whether or not the read operation was in the same track as the last r/w
*/
public boolean readSector(int sector, Memory cpuMemory, int ramAddress) {
if (sector <= 1440) {
cpuMemory.write(ramAddress, memory.getWords(), sector * 512, 512);
//Calculate seek time
int deltaTrack = (sector / 80) - rwHeadTrack;
if (deltaTrack != 0) {
rwHeadTrack = (sector / 80);
return false;
} else {
return true;
}
}
return false;
}
/**
* Write 512 words to the specified sector from cpu memory at the specified address
*
* @param sector sector to write (0-1440)
* @param cpuMemory Cpu memory to read from
* @param ramAddress address of the data to read in CPU memory
* @return Whether or not the read operation was in the same track as the last r/w
*/
public boolean writeSector(int sector, Memory cpuMemory, int ramAddress) {
if (sector <= 1440) {
memory.write(sector * 512, cpuMemory.getWords(), ramAddress, 512);
//Calculate seek time
int deltaTrack = (sector / 80) - rwHeadTrack;
if (deltaTrack != 0) {
rwHeadTrack = (sector / 80);
return false;
} else {
return true;
}
} else {
return false;
}
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("rwHeadTrack", rwHeadTrack);
dbObject.put("memory", memory.mongoSerialise());
return dbObject;
}
public static FloppyDisk deserialise(DBObject obj) {
FloppyDisk floppyDisk = new FloppyDisk();
floppyDisk.rwHeadTrack = (int) obj.get("rwHeadTrack");
floppyDisk.memory = Memory.deserialize((DBObject) obj.get("memory"));
return floppyDisk;
}
public Memory getMemory() {
return memory;
}
}

View File

@@ -5,7 +5,6 @@ import net.simon987.server.assembly.CPU;
import net.simon987.server.event.CpuInitialisationEvent; import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener; import net.simon987.server.event.GameEventListener;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
public class CpuInitialisationListener implements GameEventListener { public class CpuInitialisationListener implements GameEventListener {
@@ -16,10 +15,10 @@ public class CpuInitialisationListener implements GameEventListener {
@Override @Override
public void handle(GameEvent event) { public void handle(GameEvent event) {
LogManager.LOGGER.fine("(Plugin) Handled CPU Initialisation event (Cubot Plugin)"); //LogManager.LOGGER.fine("(Plugin) Handled CPU Initialisation event (Cubot Plugin)");
CPU cpu = (CPU)event.getSource(); CPU cpu = (CPU) event.getSource();
User user = ((CpuInitialisationEvent)event).getUser(); User user = ((CpuInitialisationEvent) event).getUser();
CubotLeg legHw = new CubotLeg((Cubot) user.getControlledUnit()); CubotLeg legHw = new CubotLeg((Cubot) user.getControlledUnit());
legHw.setCpu(cpu); legHw.setCpu(cpu);
@@ -27,18 +26,31 @@ public class CpuInitialisationListener implements GameEventListener {
laserHw.setCpu(cpu); laserHw.setCpu(cpu);
CubotLidar radarHw = new CubotLidar((Cubot) user.getControlledUnit()); CubotLidar radarHw = new CubotLidar((Cubot) user.getControlledUnit());
radarHw.setCpu(cpu); radarHw.setCpu(cpu);
Keyboard keyboard = new Keyboard((Cubot) user.getControlledUnit()); CubotKeyboard keyboard = new CubotKeyboard((Cubot) user.getControlledUnit());
keyboard.setCpu(cpu); keyboard.setCpu(cpu);
CubotDrill drillHw = new CubotDrill((Cubot) user.getControlledUnit()); CubotDrill drillHw = new CubotDrill((Cubot) user.getControlledUnit());
drillHw.setCpu(cpu); drillHw.setCpu(cpu);
CubotInventory invHw = new CubotInventory((Cubot) user.getControlledUnit()); CubotInventory invHw = new CubotInventory((Cubot) user.getControlledUnit());
invHw.setCpu(cpu); invHw.setCpu(cpu);
CubotHologram emoteHw = new CubotHologram((Cubot) user.getControlledUnit());
emoteHw.setCpu(cpu);
CubotBattery batteryHw = new CubotBattery((Cubot) user.getControlledUnit());
batteryHw.setCpu(cpu);
CubotFloppyDrive floppyHw = new CubotFloppyDrive((Cubot) user.getControlledUnit());
floppyHw.setCpu(cpu);
CubotComPort comPortHw = new CubotComPort((Cubot) user.getControlledUnit());
comPortHw.setCpu(cpu);
cpu.attachHardware(legHw, CubotLeg.DEFAULT_ADDRESS); cpu.attachHardware(legHw, CubotLeg.DEFAULT_ADDRESS);
cpu.attachHardware(laserHw, CubotLaser.DEFAULT_ADDRESS); cpu.attachHardware(laserHw, CubotLaser.DEFAULT_ADDRESS);
cpu.attachHardware(radarHw, CubotLidar.DEFAULT_ADDRESS); cpu.attachHardware(radarHw, CubotLidar.DEFAULT_ADDRESS);
cpu.attachHardware(keyboard, Keyboard.DEFAULT_ADDRESS); cpu.attachHardware(keyboard, CubotKeyboard.DEFAULT_ADDRESS);
cpu.attachHardware(drillHw, CubotDrill.DEFAULT_ADDRESS); cpu.attachHardware(drillHw, CubotDrill.DEFAULT_ADDRESS);
cpu.attachHardware(invHw, CubotInventory.DEFAULT_ADDRESS); cpu.attachHardware(invHw, CubotInventory.DEFAULT_ADDRESS);
cpu.attachHardware(invHw, CubotInventory.DEFAULT_ADDRESS);
cpu.attachHardware(emoteHw, CubotHologram.DEFAULT_ADDRESS);
cpu.attachHardware(batteryHw, CubotBattery.DEFAULT_ADDRESS);
cpu.attachHardware(floppyHw, CubotFloppyDrive.DEFAULT_ADDRESS);
cpu.attachHardware(comPortHw, CubotComPort.DEFAULT_ADDRESS);
} }
} }

View File

@@ -9,6 +9,7 @@ import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import java.awt.*; import java.awt.*;
import java.util.Random;
public class UserCreationListener implements GameEventListener { public class UserCreationListener implements GameEventListener {
@Override @Override
@@ -19,29 +20,35 @@ public class UserCreationListener implements GameEventListener {
@Override @Override
public void handle(GameEvent event) { public void handle(GameEvent event) {
User user = (User)event.getSource(); Random random = new Random();
LogManager.LOGGER.fine("(Plugin) Handled User creation event (Cubot Plugin)");
User user = (User) event.getSource();
Cubot cubot = new Cubot(); Cubot cubot = new Cubot();
cubot.setWorld(GameServer.INSTANCE.getGameUniverse().getWorld(
GameServer.INSTANCE.getConfig().getInt("new_user_worldX"),
GameServer.INSTANCE.getConfig().getInt("new_user_worldY")));
cubot.getWorld().getGameObjects().add(cubot);
cubot.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId()); cubot.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
cubot.setHeldItem(GameServer.INSTANCE.getConfig().getInt("new_user_item")); Point point = null;
while (point == null || cubot.getWorld() == null) {
int spawnX = GameServer.INSTANCE.getConfig().getInt("new_user_worldX") + random.nextInt(5);
int spawnY = GameServer.INSTANCE.getConfig().getInt("new_user_worldY") + random.nextInt(5);
cubot.setWorld(GameServer.INSTANCE.getGameUniverse().getWorld(spawnX, spawnY, true));
cubot.setParent(user); point = cubot.getWorld().getRandomPassableTile();
}
Point point = cubot.getWorld().getRandomPassableTile();
cubot.setX(point.x); cubot.setX(point.x);
cubot.setY(point.y); cubot.setY(point.y);
cubot.getWorld().addObject(cubot);
cubot.getWorld().incUpdatable();
cubot.setHeldItem(GameServer.INSTANCE.getConfig().getInt("new_user_item"));
cubot.setEnergy(GameServer.INSTANCE.getConfig().getInt("battery_max_energy"));
cubot.setMaxEnergy(GameServer.INSTANCE.getConfig().getInt("battery_max_energy"));
cubot.setParent(user);
user.setControlledUnit(cubot); user.setControlledUnit(cubot);
LogManager.LOGGER.fine("(Plugin) Handled User creation event (Cubot Plugin)");
} }
} }

View File

@@ -1,131 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.game.*;
import net.simon987.server.user.User;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class Cubot extends GameObject implements Updatable, ControllableUnit {
private static final char MAP_INFO = 0x0080;
public static final int ID = 1;
private EffectType currentEmote = null;
/**
* Hit points
*/
private int hp;
private int heldItem;
private CubotAction currentAction = CubotAction.IDLE;
private CubotAction lastAction = CubotAction.IDLE;
private ArrayList<Integer> keyboardBuffer = new ArrayList<>();
private User parent;
public Cubot() {
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
if (currentAction == CubotAction.WALKING) {
if (!incrementLocation()) {
//Couldn't walk
currentAction = CubotAction.IDLE;
}
}
if (currentEmote != null) {
// getWorld().getQueuedGameEffects().add(new GameEffect(currentEmote, getX(), getY()));
currentEmote = null;
}
/*
* CurrentAction is set during the code execution and this function is called right after
* If no action as been set, the action sent to the client is the action in currentAction that
* was set last tick (IDLE)
*/
lastAction = currentAction;
currentAction = CubotAction.IDLE;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("id", getObjectId());
json.put("type", ID);
json.put("x", getX());
json.put("y", getY());
json.put("direction", getDirection().ordinal());
json.put("heldItem", heldItem);
json.put("hp", hp);
json.put("action", lastAction.ordinal());
if (parent != null) {
json.put("parent", parent.getUsername()); //Only used client-side for now
}
return json;
}
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");
return cubot;
}
public void setHeldItem(int heldItem) {
this.heldItem = heldItem;
}
public int getHeldItem() {
return heldItem;
}
@Override
public void setKeyboardBuffer(ArrayList<Integer> kbBuffer) {
keyboardBuffer = kbBuffer;
}
@Override
public ArrayList<Integer> getKeyboardBuffer() {
return keyboardBuffer;
}
public void clearKeyboardBuffer(){
keyboardBuffer.clear();
}
public void setCurrentAction(CubotAction currentAction) {
this.currentAction = currentAction;
}
public User getParent() {
return parent;
}
public void setParent(User parent) {
this.parent = parent;
}
public CubotAction getAction() {
return lastAction;
}
}

View File

@@ -1,10 +0,0 @@
package net.simon987.cubotplugin;
public enum CubotAction {
IDLE,
DIGGING,
WALKING,
WITHDRAWING,
DEPOSITING
}

View File

@@ -1,75 +0,0 @@
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.TileMap;
import org.json.simple.JSONObject;
public class CubotDrill extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0005;
public static final int DEFAULT_ADDRESS = 5;
private static final int POLL = 1;
private static final int GATHER_SLOW = 2;
private static final int GATHER_FAST = 3;
private Cubot cubot;
public CubotDrill(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(0);
} else if (a == GATHER_SLOW || a == GATHER_FAST) {
if (cubot.getAction() != CubotAction.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);
} else if (tile == TileMap.COPPER_TILE) {
cubot.setHeldItem(TileMap.ITEM_COPPER);
cubot.setCurrentAction(CubotAction.DIGGING);
} else {
//System.out.println("FAILED: dig");
}
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotDrill deserialize(JSONObject hwJSON){
return new CubotDrill((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
}
}

View File

@@ -1,89 +0,0 @@
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.GameObject;
import net.simon987.server.game.InventoryHolder;
import org.json.simple.JSONObject;
import java.awt.*;
import java.util.ArrayList;
public class CubotLaser extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0002;
public static final int DEFAULT_ADDRESS = 2;
private Cubot cubot;
private static final int WITHDRAW = 1;
public CubotLaser(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if(a == WITHDRAW) {
//System.out.println("withdraw");
Point frontTile = cubot.getFrontTile();
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y);
if (cubot.getAction() != CubotAction.IDLE && objects.size() > 0) {
if (objects.get(0) instanceof InventoryHolder) {
//Take the item
if (((InventoryHolder) objects.get(0)).takeItem(b)) {
cubot.setHeldItem(b);
//System.out.println("took " + b);
cubot.setCurrentAction(CubotAction.WITHDRAWING);
} else {
//The inventory holder can't provide this item
//todo Add emote here
// System.out.println("DEBUG: FAILED: take (The inventory holder can't provide this item)");
}
}
} else {
//Nothing in front
// System.out.println("DEBUG: FAILED: take (Nothing in front or Cubot is busy)");
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotLaser deserialize(JSONObject hwJSON){
return new CubotLaser((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
}
}

View File

@@ -1,82 +0,0 @@
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.Direction;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
public class CubotLeg extends CpuHardware implements JSONSerialisable {
public static final int DEFAULT_ADDRESS = 1;
public static final String NAME = "Cubot Leg";
private static final int SET_DIR = 1;
private static final int SET_DIR_AND_WALK = 2;
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0001;
private Cubot cubot;
public CubotLeg(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
int b = getCpu().getRegisterSet().getRegister("B").getValue();
if(a == SET_DIR){
Direction dir = Direction.getDirection(b);
if(dir != null){
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
} else {
status.setErrorFlag(true);
}
} else if(a == SET_DIR_AND_WALK){
Direction dir = Direction.getDirection(b);
if(dir != null){
cubot.setDirection(Direction.getDirection(b));
status.setErrorFlag(false);
} else {
status.setErrorFlag(true);
}
cubot.setCurrentAction(CubotAction.WALKING);
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotLeg deserialize(JSONObject hwJSON){
return new CubotLeg((Cubot)GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
}
}

View File

@@ -1,141 +0,0 @@
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.World;
import net.simon987.server.game.pathfinding.Node;
import net.simon987.server.game.pathfinding.Pathfinder;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class CubotLidar extends CpuHardware implements JSONSerialisable {
/**
* Hardware ID (Should be unique)
*/
public static final char HWID = 0x0003;
public static final int DEFAULT_ADDRESS = 3;
private Cubot cubot;
private static final int GET_POS = 1;
private static final int GET_PATH = 2;
private static final int GET_MAP = 3;
private static final int MEMORY_MAP_START = 0x0100;
private static final int MEMORY_PATH_START = 0x0000;
public CubotLidar(Cubot cubot) {
this.cubot = cubot;
}
@Override
public char getId() {
return HWID;
}
@Override
public void handleInterrupt(Status status) {
int a = getCpu().getRegisterSet().getRegister("A").getValue();
switch (a){
case GET_POS:
getCpu().getRegisterSet().getRegister("X").setValue(cubot.getX());
getCpu().getRegisterSet().getRegister("Y").setValue(cubot.getY());
break;
case GET_PATH:
int b = getCpu().getRegisterSet().getRegister("B").getValue();
int destX = getCpu().getRegisterSet().getRegister("X").getValue();
int destY = getCpu().getRegisterSet().getRegister("Y").getValue();
//Get path
ArrayList<Node> nodes = Pathfinder.findPath(cubot.getWorld(), cubot.getX(), cubot.getY(),
destX, destY, b);
// System.out.println(nodes.size() + " nodes");
//Write to memory
byte[] mem = getCpu().getMemory().getBytes();
int counter = 0; //todo get memory address from config/constant
if (nodes != null) {
Node lastNode = null;
for (Node n : nodes) {
//Store the path as a sequence of directions
if (lastNode == null) {
lastNode = n;
continue;
}
if (n.x < lastNode.x) {
//West
mem[counter++] = 0;
mem[counter++] = 3;
} else if (n.x > lastNode.x) {
//East
mem[counter++] = 0;
mem[counter++] = 1;
} else if (n.y < lastNode.y) {
//North
mem[counter++] = 0;
mem[counter++] = 0;
} else if (n.y > lastNode.y) {
//South
mem[counter++] = 0;
mem[counter++] = 2;
}
lastNode = n;
}
//Indicate end of path with 0xAAAA
mem[counter++] = -86;
mem[counter] = -86;
} else {
//Indicate invalid path 0xFFFF
mem[counter++] = -1;
mem[counter] = -1;
}
LogManager.LOGGER.fine("DEBUG: path to" + destX + "," + destY);
break;
case GET_MAP:
char[][] mapInfo = cubot.getWorld().getMapInfo();
int i = MEMORY_MAP_START;
for (int y = 0; y < World.WORLD_SIZE; y++) {
for (int x = 0; x < World.WORLD_SIZE; x++) {
getCpu().getMemory().set(i++, mapInfo[x][y]);
}
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotLidar deserialize(JSONObject hwJSON) {
return new CubotLidar((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -1,58 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.cubotplugin.event.CpuInitialisationListener;
import net.simon987.cubotplugin.event.UserCreationListener;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.CpuHardwareDeserializer;
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 CubotPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer{
@Override
public void init() {
listeners.add(new CpuInitialisationListener());
listeners.add(new UserCreationListener());
LogManager.LOGGER.info("Initialised Cubot plugin");
}
@Override
public GameObject deserializeObject(JSONObject object) {
int objType = (int)(long)object.get("type");
if(objType == Cubot.ID) {
return Cubot.deserialize(object);
}
return null;
}
@Override
public CpuHardware deserializeHardware(JSONObject hwJson) {
int hwid = (int)(long)hwJson.get("hwid");
switch (hwid){
case CubotLeg.HWID:
return CubotLeg.deserialize(hwJson);
case CubotLaser.HWID:
return CubotLaser.deserialize(hwJson);
case CubotLidar.HWID:
return CubotLidar.deserialize(hwJson);
case CubotDrill.HWID:
return CubotDrill.deserialize(hwJson);
case CubotInventory.HWID:
return CubotInventory.deserialize(hwJson);
case Keyboard.HWID:
return Keyboard.deserialize(hwJson);
}
return null;
}
}

View File

@@ -14,6 +14,6 @@ public class CubotTest {
} catch (InterruptedException e) { } catch (InterruptedException e) {
e.printStackTrace(); e.printStackTrace();
} }
assertEquals(1,2); assertEquals(1, 1);
} }
} }

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,24 @@
<?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: org.apache.commons:commons-text:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:2.10.1" 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>

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

@@ -0,0 +1,32 @@
<?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>
<parent>
<groupId>net.simon987.server</groupId>
<artifactId>server_root</artifactId>
<version>1.2a</version>
</parent>
<groupId>net.simon987.pluginmischw</groupId>
<artifactId>plugin-misc-hw</artifactId>
<version>1.2a</version>
<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

@@ -0,0 +1,45 @@
package net.simon987.mischwplugin;
import com.mongodb.BasicDBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Util;
public class Clock extends CpuHardware {
public static final char HWID = 0x0008;
public static final char DEFAULT_ADDRESS = 0x0008;
@Override
public void handleInterrupt(Status status) {
int time = (int) GameServer.INSTANCE.getGameUniverse().getTime();
//Will need to be changed to quadword in about 136 years
getCpu().getRegisterSet().getRegister("B").setValue(Util.getHigherWord(time));
getCpu().getRegisterSet().getRegister("C").setValue(Util.getLowerWord(time));
}
@Override
public char getId() {
return HWID;
}
public static Clock deserialize() {
return new Clock();
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
return dbObject;
}
}

View File

@@ -0,0 +1,34 @@
package net.simon987.mischwplugin;
import com.mongodb.DBObject;
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;
import net.simon987.server.plugin.ServerPlugin;
public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserializer {
@Override
public void init(ServerConfiguration config) {
listeners.add(new CpuInitialisationListener());
LogManager.LOGGER.info("Initialised Misc Hardware Plugin");
}
@Override
public CpuHardware deserializeHardware(DBObject hwJson) {
int hwid = (int) hwJson.get("hwid");
switch (hwid) {
case RandomNumberGenerator.HWID:
return RandomNumberGenerator.deserialize();
case Clock.HWID:
return Clock.deserialize();
}
return null;
}
}

View File

@@ -0,0 +1,46 @@
package net.simon987.mischwplugin;
import com.mongodb.BasicDBObject;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import java.util.Random;
public class RandomNumberGenerator extends CpuHardware {
public static final char HWID = 0x0007;
public static final char DEFAULT_ADDRESS = 0x0007;
private Random random;
public RandomNumberGenerator() {
random = new Random();
}
@Override
public void handleInterrupt(Status status) {
getCpu().getRegisterSet().getRegister("B").setValue(random.nextInt(0xFFFF));
}
@Override
public char getId() {
return HWID;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
return dbObject;
}
public static RandomNumberGenerator deserialize() {
return new RandomNumberGenerator();
}
}

View File

@@ -0,0 +1,30 @@
package net.simon987.mischwplugin.event;
import net.simon987.mischwplugin.Clock;
import net.simon987.mischwplugin.RandomNumberGenerator;
import net.simon987.server.assembly.CPU;
import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
public class CpuInitialisationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return CpuInitialisationEvent.class;
}
@Override
public void handle(GameEvent event) {
CPU cpu = (CPU) event.getSource();
RandomNumberGenerator rngHW = new RandomNumberGenerator();
rngHW.setCpu(cpu);
Clock clock = new Clock();
clock.setCpu(cpu);
cpu.attachHardware(rngHW, RandomNumberGenerator.DEFAULT_ADDRESS);
cpu.attachHardware(clock, Clock.DEFAULT_ADDRESS);
}
}

View File

@@ -0,0 +1,3 @@
classpath=net.simon987.mischwplugin.MiscHWPlugin
name=Misc HW Plugin
version=1.0

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

@@ -0,0 +1,24 @@
<?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" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-text:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:2.10.1" level="project" />
</component>
</module>

31
Plugin NPC/pom.xml Normal file
View File

@@ -0,0 +1,31 @@
<?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>
<parent>
<groupId>net.simon987.server</groupId>
<artifactId>server_root</artifactId>
<version>1.2a</version>
</parent>
<groupId>net.simon987.pluginnpc</groupId>
<artifactId>plugin-npc</artifactId>
<version>1.2a</version>
<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,210 @@
package net.simon987.npcplugin;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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);
if (npc != null) {
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().addObject(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;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("t", ID);
BasicDBList tmpNpcArray = new BasicDBList();
for (NonPlayerCharacter npc : npcs) {
tmpNpcArray.add(npc.getObjectId());
}
dbObject.put("n", tmpNpcArray);
return dbObject;
}
public static Factory deserialise(DBObject obj) {
Factory factory = new Factory();
factory.setObjectId((long) obj.get("i"));
factory.setX((int) obj.get("x"));
factory.setY((int) obj.get("y"));
factory.tmpNpcArray = ((BasicDBList) obj.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,100 @@
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
/* todo replace by some sort of .collect call with object
id (See https://github.com/simon987/Much-Assembly-Required/pull/66)*/
ArrayList<GameObject> biomass = npc.getWorld().findObjects(0x4000);
//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,105 @@
package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.event.ObjectDeathEvent;
import net.simon987.server.game.Direction;
import org.json.simple.JSONObject;
public class HarvesterNPC extends NonPlayerCharacter {
public static final int ID = 10;
public static final int MAX_HEALTH = GameServer.INSTANCE.getConfig().getInt("harvester_hp_max");
public static final int HEAL_RATE = GameServer.INSTANCE.getConfig().getInt("harvester_regen");
public HarvesterNPC() {
setTask(new HarvestTask());
setHp(MAX_HEALTH);
setMaxHp(MAX_HEALTH);
setHealRate(HEAL_RATE);
}
@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);
}
}
}
@Override
public void onDeadCallback() {
if (getFactory() != null && getFactory().getNpcs() != null) {
getFactory().getNpcs().remove(this);
}
GameServer.INSTANCE.getEventDispatcher().dispatch(
new ObjectDeathEvent(this, ID));
}
@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", getHp());
json.put("energy", energy);
json.put("action", getAction().ordinal());
json.put("t", ID);
return json;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("direction", getDirection().ordinal());
dbObject.put("hp", getHp());
// dbObject.put("energy", energy);
dbObject.put("action", getAction().ordinal());
dbObject.put("t", ID);
return dbObject;
}
public static HarvesterNPC deserialize(DBObject obj) {
HarvesterNPC npc = new HarvesterNPC();
npc.setObjectId((long) obj.get("i"));
npc.setX((int) obj.get("x"));
npc.setY((int) obj.get("y"));
npc.setHp((int) obj.get("hp"));
npc.setDirection(Direction.getDirection((int) obj.get("direction")));
// npc.energy = (int) obj.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,248 @@
package net.simon987.npcplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Util;
import net.simon987.server.game.*;
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, Attackable {
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");
// Set these just in case they aren't overridden in the subclass
public static final int HP_MAX_DEFAULT = 100;
public static final int HP_REGEN_RATE_DEFAULT = 0;
//Unused
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;
/**
* Current health of the npc
*/
private int hp = HP_MAX_DEFAULT;
/**
* Health regeneration rate of the npc
*/
private int hpRegenerationRate = HP_REGEN_RATE_DEFAULT;
/**
* Maximum health of the npc
*/
private int maxHp = HP_MAX_DEFAULT;
@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;
}
//Heal the NPC
heal(hpRegenerationRate);
}
/**
* 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;
}
}
@Override
public void setHealRate(int hp) {
hpRegenerationRate = hp;
}
@Override
public int getHp() {
return hp;
}
@Override
public void setHp(int hp) {
this.hp = hp;
}
@Override
public int getMaxHp() {
return maxHp;
}
@Override
public void setMaxHp(int hp) {
this.maxHp = hp;
this.hp = hp;
}
@Override
public void heal(int amount) {
hp += amount;
//Can't heal above max
if (hp > maxHp) {
hp = maxHp;
}
}
@Override
public void damage(int amount) {
hp -= amount;
//YOU ARE DEAD
if (hp <= 0) {
setDead(true);
}
}
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,65 @@
package net.simon987.npcplugin;
import com.mongodb.DBObject;
import net.simon987.npcplugin.event.CpuInitialisationListener;
import net.simon987.npcplugin.event.WorldCreationListener;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.game.GameObject;
import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import java.util.ArrayList;
public class NpcPlugin extends ServerPlugin implements GameObjectDeserializer, CpuHardwareDeserializer {
/**
* Radio tower cache
*/
private static ArrayList<RadioTower> radioTowers;
@Override
public void init(ServerConfiguration configuration) {
listeners.add(new WorldCreationListener());
listeners.add(new CpuInitialisationListener());
radioTowers = new ArrayList<>(32);
LogManager.LOGGER.info("Initialised NPC plugin");
}
@Override
public GameObject deserializeObject(DBObject obj) {
int objType = (int) obj.get("t");
if (objType == HarvesterNPC.ID) {
return HarvesterNPC.deserialize(obj);
} else if (objType == Factory.ID) {
return Factory.deserialise(obj);
} else if (objType == RadioTower.ID) {
return RadioTower.deserialize(obj);
}
return null;
}
@Override
public CpuHardware deserializeHardware(DBObject obj) {
int hwid = (int) obj.get("hwid");
switch (hwid) {
case RadioReceiverHardware.HWID:
return RadioReceiverHardware.deserialize(obj);
}
return null;
}
public static ArrayList<RadioTower> getRadioTowers() {
return radioTowers;
}
}

View File

@@ -0,0 +1,83 @@
package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Util;
import net.simon987.server.game.Action;
import net.simon987.server.game.ControllableUnit;
import java.util.ArrayList;
public class RadioReceiverHardware extends CpuHardware {
public static final char HWID = 0xC; //12
private static final int LISTEN = 1;
public static final int DEFAULT_ADDRESS = 0xC;
private ControllableUnit cubot;
public RadioReceiverHardware(ControllableUnit cubot) {
this.cubot = cubot;
}
@Override
public void handleInterrupt(Status status) {
int x = getCpu().getRegisterSet().getRegister("X").getValue();
int a = getCpu().getRegisterSet().getRegister("A").getValue();
if (a == LISTEN) {
//Find the nearest Radio Tower and query it
cubot.setAction(Action.LISTENING);
ArrayList<char[]> messages = new ArrayList<>(6);
ArrayList<RadioTower> towers = new ArrayList<>(NpcPlugin.getRadioTowers()); //Avoid ConcurrentModificationException
for (RadioTower tower : towers) {
if (Util.manhattanDist(tower.getWorld().getX(), tower.getWorld().getY(), cubot.getWorld().getX(),
cubot.getWorld().getY()) <= RadioTower.MAX_RANGE) {
//Tower is in range
messages.addAll(tower.getMessages());
}
}
//Write messages to memory
int offset = 0;
for (char[] message : messages) {
getCpu().getMemory().write(x + offset, message, 0, message.length);
offset += message.length;
}
//Write the amount of messages received to B
getCpu().getRegisterSet().getRegister("B").setValue(messages.size());
}
}
@Override
public char getId() {
return HWID;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("hwid", (int) HWID);
dbObject.put("cubot", cubot.getObjectId());
return dbObject;
}
public static RadioReceiverHardware deserialize(DBObject obj) {
return new RadioReceiverHardware((ControllableUnit) GameServer.INSTANCE.getGameUniverse().getObject((long) obj.get("cubot")));
}
}

View File

@@ -0,0 +1,120 @@
package net.simon987.npcplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Programmable;
import net.simon987.server.game.Updatable;
import org.json.simple.JSONObject;
import java.awt.*;
import java.util.ArrayList;
public class RadioTower extends GameObject implements Programmable, Updatable {
private static final int MAP_INFO = 0x1000;
public static final int ID = 4;
public static final int MAX_RANGE = 3; //todo load from config
private static final int MAX_MESSAGES = 16;
@Override
public char getMapInfo() {
return MAP_INFO;
}
/**
* Messages from the current tick
*/
private ArrayList<char[]> messages = new ArrayList<>(4);
/**
* Messages from the last tick
*/
private ArrayList<char[]> lastMessages = new ArrayList<>(4);
@Override
public void update() {
lastMessages = new ArrayList<>(messages);
messages.clear();
}
@Override
public boolean sendMessage(char[] message) {
if (message.length < MAX_MESSAGES) {
messages.add(message);
return true;
} else {
return false;
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("i", getObjectId());
json.put("x", getX());
json.put("y", getY());
json.put("t", ID);
return json;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("t", ID);
return dbObject;
}
public static RadioTower deserialize(DBObject obj) {
RadioTower tower = new RadioTower();
tower.setObjectId((long) obj.get("i"));
tower.setX((int) obj.get("x"));
tower.setY((int) obj.get("y"));
NpcPlugin.getRadioTowers().add(tower);
return tower;
}
public ArrayList<char[]> getMessages() {
return lastMessages;
}
/**
* Get the first directly adjacent tile (starting east, going clockwise)
*/
public Point getAdjacentTile() {
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())) {
return new Point(getX() - 1, getY());
} else if (!getWorld().isTileBlocked(getX(), getY() - 1)) {
return new Point(getX(), getY() - 1);
} else {
return null;
}
}
}

View File

@@ -0,0 +1,27 @@
package net.simon987.npcplugin.event;
import net.simon987.npcplugin.RadioReceiverHardware;
import net.simon987.server.assembly.CPU;
import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.user.User;
public class CpuInitialisationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return CpuInitialisationEvent.class;
}
@Override
public void handle(GameEvent event) {
CPU cpu = (CPU) event.getSource();
User user = ((CpuInitialisationEvent) event).getUser();
RadioReceiverHardware radioHw = new RadioReceiverHardware(user.getControlledUnit());
radioHw.setCpu(cpu);
cpu.attachHardware(radioHw, RadioReceiverHardware.DEFAULT_ADDRESS);
}
}

View File

@@ -0,0 +1,98 @@
package net.simon987.npcplugin.event;
import net.simon987.npcplugin.Factory;
import net.simon987.npcplugin.NpcPlugin;
import net.simon987.npcplugin.RadioTower;
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.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();
outerLoopFactory:
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.addObject(factory);
world.incUpdatable();
LogManager.LOGGER.info("Spawned Factory at (" + world.getX() + ", " + world.getY() +
") (" + x + ", " + y + ")");
break outerLoopFactory;
}
}
}
//Also spawn a radio tower in the same World
Point p = world.getRandomPassableTile();
if (p != null) {
while (p.x == 0 || p.x == World.WORLD_SIZE - 1 || p.y == World.WORLD_SIZE - 1 || p.y == 0) {
p = world.getRandomPassableTile();
if (p == null) {
//World is full
return;
}
}
RadioTower radioTower = new RadioTower();
radioTower.setWorld(world);
radioTower.setObjectId(GameServer.INSTANCE.getGameUniverse().getNextObjectId());
radioTower.setX(p.x);
radioTower.setY(p.y);
if (radioTower.getAdjacentTile() != null) {
//Radio Tower has adjacent tiles
world.addObject(radioTower);
world.incUpdatable(); //In case the Factory couldn't be spawned.
NpcPlugin.getRadioTowers().add(radioTower);
LogManager.LOGGER.info("Spawned RadioTower at (" + world.getX() + ", " + world.getY() +
") (" + p.x + ", " + p.y + ")");
}
}
}
}
}

View File

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

View File

@@ -0,0 +1,24 @@
<?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" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-text:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:2.10.1" level="project" />
</component>
</module>

View File

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

32
Plugin Plant/pom.xml Normal file
View File

@@ -0,0 +1,32 @@
<?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>
<parent>
<groupId>net.simon987.server</groupId>
<artifactId>server_root</artifactId>
<version>1.2a</version>
</parent>
<groupId>net.simon987.pluginplant</groupId>
<artifactId>plugin-biomassBlob</artifactId>
<version>1.2a</version>
<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,126 @@
package net.simon987.biomassplugin;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
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;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
dbObject.put("t", ID);
dbObject.put("i", getObjectId());
dbObject.put("x", getX());
dbObject.put("y", getY());
dbObject.put("b", biomassCount);
return dbObject;
}
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(DBObject obj) {
BiomassBlob biomassBlob = new BiomassBlob();
biomassBlob.setObjectId((long) obj.get("i"));
biomassBlob.setX((int) obj.get("x"));
biomassBlob.setY((int) obj.get("y"));
// biomassBlob.style = (int) json.get("style");
biomassBlob.biomassCount = (int) obj.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,37 @@
package net.simon987.biomassplugin;
import com.mongodb.DBObject;
import net.simon987.biomassplugin.event.ObjectDeathListener;
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;
public class BiomassPlugin extends ServerPlugin implements GameObjectDeserializer {
@Override
public void init(ServerConfiguration config) {
listeners.add(new WorldCreationListener());
listeners.add(new WorldUpdateListener(config));
listeners.add(new ObjectDeathListener(config));
LogManager.LOGGER.info("Initialised Biomass plugin");
}
@Override
public GameObject deserializeObject(DBObject object) {
int objType = (int) 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<>(blobCount);
//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.getGameObjectsAt(p.x, p.y).size() != 0) {
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,71 @@
package net.simon987.biomassplugin.event;
import net.simon987.biomassplugin.BiomassBlob;
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.ObjectDeathEvent;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
/**
* Handles ObjectDeathEvent events
*/
public class ObjectDeathListener implements GameEventListener {
private int biomassDropCount;
public ObjectDeathListener(ServerConfiguration config) {
biomassDropCount = config.getInt("harvester_biomass_drop_count");
}
@Override
public Class getListenedEventType() {
return ObjectDeathEvent.class;
}
@Override
public void handle(GameEvent event) {
// TODO: setup enum with all GameObject type IDs
if (((ObjectDeathEvent) event).getSourceObjectId() == 10) {
//An HarvesterNPC ObjectDeathEvent is received
GameObject dyingHarvesterNPC = (GameObject)event.getSource();
//Don't spawn biomass on World border
if (dyingHarvesterNPC.getX() != 0 && dyingHarvesterNPC.getX() != World.WORLD_SIZE - 1 &&
dyingHarvesterNPC.getY() != 0 && dyingHarvesterNPC.getY() != World.WORLD_SIZE - 1) {
//Create a new biomass
BiomassBlob newBiomassBlob = createBiomassBlobAt(
dyingHarvesterNPC.getX(), dyingHarvesterNPC.getY(), dyingHarvesterNPC.getWorld());
//Add it to the world game objects
dyingHarvesterNPC.getWorld().addObject(newBiomassBlob);
LogManager.LOGGER.fine("Spawned biomass at (" + newBiomassBlob.getX() +
", " + newBiomassBlob.getY() + ")");
}
}
}
/**
* Create and return a biomass at the given x, y coordinates and in the world
* @param x x coord of biomass location
* @param y y coord of biomass location
* @param world world in which the biomass will be created in
* @return the new BiomassBlob created
*/
private BiomassBlob createBiomassBlobAt(int x, int y, World world) {
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(biomassDropCount);
biomassBlob.setX(x);
biomassBlob.setY(y);
biomassBlob.setWorld(world);
return biomassBlob;
}
}

View File

@@ -0,0 +1,33 @@
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);
for (BiomassBlob blob : biomassBlobs) {
((WorldGenerationEvent) event).getWorld().addObject(blob);
}
}
}

View File

@@ -0,0 +1,74 @@
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 static int minBlobCount;
private static int maxBlobCount;
private static int blobYield;
private static int waitTime;
private static 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.findObjects(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);
for (BiomassBlob blob : newBlobs) {
world.addObject(blob);
}
//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,162 +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;
}
/**
* 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_*)
* @return true if the requested item is ITEM_BIOMASS and if the plant is grown
*/
@Override
public boolean takeItem(int item) {
if (item == ITM_BIOMASS) {
if (grown && biomassCount > 1) {
biomassCount--;
return true;
} else if (grown) {
//Delete plant
setDead(true);
return true;
} else {
return false;
}
} else {
return false;
}
}
}

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;
}
}

View File

@@ -1,3 +1,86 @@
# Much-Assembly-Required # [Live demo](https://muchassemblyrequired.com)
Program the 8086-like microprocessor of a robot in a grid-based multiplayer world. The game is web based so no installation is required.
In its current state, players can walk around the game universe and collect Biomass blobs & Iron/copper ore using the online code editor.
https://muchassemblyrequired.com ![screenshot from 2017-11-12 13-01-43](https://user-images.githubusercontent.com/7120851/32701793-e5d07e98-c7a9-11e7-9931-f8db7b287994.png)
Wiki: [GitHub](https://github.com/simon987/Much-Assembly-Required/wiki)
Chat: [Slack](https://join.slack.com/t/muchassemblyrequired/shared_invite/enQtMjY3Mjc1OTUwNjEwLTkyOTIwOTA5OGY4MDVlMGI4NzM5YzlhMWJiMGY1OWE2NjUxODQ1NWQ1YTcxMTA1NGZkYzNjYzMyM2E1ODdmNzg)
## VS Code Extensions
- [Much Assembly Required (Upload on Save)](https://marketplace.visualstudio.com/items?itemName=tomhodder.much-assembly-required-upload-on-save) by tomhodder
- [Much Assembly Required Language Support](https://marketplace.visualstudio.com/items?itemName=PJB3005.much-assembly-required-language-support) by PJB3005
# Deploying the server
Note: You can find the frontend [here](https://github.com/simon987/Much-Assembly-Required-Frontend)
## Linux (Ubuntu 16.04)
```bash
# Install tools
sudo apt install git maven openjdk-8-jdk
# Obtain source files
git clone https://github.com/simon987/Much-Assembly-Required.git
# Build
cd Much-Assembly-Required
mvn package
# Run
cd target
java -jar server-1.2a.jar
```
## Windows (tested on Windows 10)
Installation instructions:
1. Download the JDK from [here](http://www.oracle.com/technetwork/java/javase/downloads/index.html).
Install the JDK and update your PATH and JAVA_HOME enviroment variables.
2. Download Maven from [here](https://maven.apache.org/).
Install Maven (following the README) and update your PATH enviroment variable.
3. Download Mongo DB Community from [here](https://www.mongodb.com/download-center#community).
Install Mongo DB following the instructions [here](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/).
Update your PATH enviroment variable.
Building instructions:
```batch
:: Builds the server
cd Much-Assembly-Required
mvn package
```
Running instructions:
1. In one Command Prompt window, run Mongo DB:
```batch
:: Runs Mongo DB
mongod
```
2. In a second Command Prompt window, run the MAR server:
```batch
:: Runs the MAR server
cd Much-Assembly-Required\target
java -jar server-1.2a.jar
```
3. Run the frontend, following the instructions that you can find [here](https://github.com/simon987/Much-Assembly-Required-Frontend).
## Docker
### Requirements
1. [Docker Compose](https://docs.docker.com/compose/install/#install-compose) (and dependencies)
### Installation
Once Docker and Docker Compose are installed, you can build and start
this application by running the following command inside this
application's directory:
`docker-compose up`
This will start MySQL and then build and run this application. It will
be available via http://localhost.
Note that there is currently no frontend web application serving the
WebSocket feed served by the `Server` application!

23
Server/Server.iml Normal file
View File

@@ -0,0 +1,23 @@
<?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: 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" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-text:1.2" level="project" />
<orderEntry type="library" name="Maven: org.apache.commons:commons-lang3:3.7" level="project" />
<orderEntry type="library" name="Maven: org.mongodb:mongo-java-driver:2.10.1" level="project" />
</component>
</module>

134
Server/pom.xml Normal file
View File

@@ -0,0 +1,134 @@
<?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>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<id>default-resources</id>
<!-- here the phase you need -->
<phase>prepare-package</phase>
<goals>
<goal>resources</goal>
</goals>
<configuration>
<outputDirectory>../target/</outputDirectory>
<resources>
<resource>
<directory>../Server/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>config.properties</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<version>3.6.2</version>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>../target/libs</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<outputDirectory>../target</outputDirectory>
<archive>
<manifest>
<mainClass>net.simon987.server.Main</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>libs/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.2</version>
<configuration>
<workingDirectory>./src/main/resources</workingDirectory>
</configuration>
</plugin>
</plugins>
</build>
<groupId>net.simon987.server</groupId>
<artifactId>server</artifactId>
<version>1.2a</version>
<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>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
<properties>
<!-- explicitly set build encoding so not altered by build platform defaults -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -0,0 +1,277 @@
package net.simon987.server;
import com.mongodb.*;
import net.simon987.server.assembly.exception.CancelledException;
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.logging.LogManager;
import net.simon987.server.plugin.PluginManager;
import net.simon987.server.user.User;
import net.simon987.server.webserver.SocketServer;
import java.io.File;
import java.net.UnknownHostException;
public class GameServer implements Runnable {
public final static GameServer INSTANCE = new GameServer();
private GameUniverse gameUniverse;
private GameEventDispatcher eventDispatcher;
private PluginManager pluginManager;
private ServerConfiguration config;
private SocketServer socketServer;
private int maxExecutionTime;
private DayNightCycle dayNightCycle;
private MongoClient mongo = null;
public GameServer() {
this.config = new ServerConfiguration("config.properties");
try{
mongo = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
gameUniverse = new GameUniverse(config);
gameUniverse.setMongo(mongo);
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 (pluginFile.getName().endsWith(".jar")) {
pluginManager.load(pluginFile, config);
}
}
} else {
if (!pluginDir.mkdir()) {
LogManager.LOGGER.severe("Couldn't create plugin directory");
}
}
eventDispatcher = new GameEventDispatcher(pluginManager);
eventDispatcher.getListeners().add(dayNightCycle);
}
public GameUniverse getGameUniverse() {
return gameUniverse;
}
public GameEventDispatcher getEventDispatcher() {
return eventDispatcher;
}
@Override
public void run() {
LogManager.LOGGER.info("(G) Started game loop");
long startTime; //Start time of the loop
long uTime; //update time
long waitTime; //time to wait
boolean running = true;
while (running) {
startTime = System.currentTimeMillis();
tick();
uTime = System.currentTimeMillis() - startTime;
waitTime = config.getInt("tick_length") - uTime;
LogManager.LOGGER.info("Wait time : " + waitTime + "ms | Update time: " + uTime + "ms | " + (int) (((double) uTime / waitTime) * 100) + "% load");
try {
if (waitTime >= 0) {
Thread.sleep(waitTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void tick() {
gameUniverse.incrementTime();
//Dispatch tick event
GameEvent event = new TickEvent(gameUniverse.getTime());
eventDispatcher.dispatch(event); //Ignore cancellation
//Process user code
for (User user : gameUniverse.getUsers()) {
if (user.getCpu() != null) {
try {
int timeout = Math.min(user.getControlledUnit().getEnergy(), maxExecutionTime);
user.getCpu().reset();
int cost = user.getCpu().execute(timeout);
user.getControlledUnit().spendEnergy(cost);
} catch (Exception e) {
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
e.printStackTrace();
}
}
}
//Process each worlds
int updatedWorlds = 0;
for (World world : gameUniverse.getWorlds()) {
if (world.shouldUpdate()) {
world.update();
updatedWorlds++;
}
}
//Save
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
save();
}
socketServer.tick();
LogManager.LOGGER.info("Processed " + gameUniverse.getWorldCount() + " worlds (" + updatedWorlds +
") updated");
}
void load() {
LogManager.LOGGER.info("Loading all data from MongoDB");
DB db = mongo.getDB("mar");
DBCollection worlds = db.getCollection("world");
DBCollection users = db.getCollection("user");
DBCollection server = db.getCollection("server");
BasicDBObject whereQuery = new BasicDBObject();
whereQuery.put("shouldUpdate", true);
DBCursor cursor = worlds.find(whereQuery);
GameUniverse universe = GameServer.INSTANCE.getGameUniverse();
while (cursor.hasNext()) {
World w = World.deserialize(cursor.next());
universe.addWorld(w);
}
//Load users
cursor = users.find();
while (cursor.hasNext()) {
try {
universe.addUser(User.deserialize(cursor.next()));
} catch (CancelledException e) {
e.printStackTrace();
}
}
//Load misc server info
cursor = server.find();
if (cursor.hasNext()) {
DBObject serverObj = cursor.next();
gameUniverse.setTime((long) serverObj.get("time"));
gameUniverse.setNextObjectId((long) serverObj.get("nextObjectId"));
}
LogManager.LOGGER.info("Done loading! W:" + GameServer.INSTANCE.getGameUniverse().getWorldCount() +
" | U:" + GameServer.INSTANCE.getGameUniverse().getUserCount());
}
private void save() {
LogManager.LOGGER.info("Saving to MongoDB | W:" + gameUniverse.getWorldCount() + " | U:" + gameUniverse.getUserCount());
try{
DB db = mongo.getDB("mar");
int unloaded_worlds = 0;
DBCollection worlds = db.getCollection("world");
DBCollection users = db.getCollection("user");
DBCollection server = db.getCollection("server");
int insertedWorlds = 0;
GameUniverse universe = GameServer.INSTANCE.getGameUniverse();
for (World w : universe.getWorlds()) {
// LogManager.LOGGER.fine("Saving world "+w.getId()+" to mongodb");
insertedWorlds++;
worlds.save(w.mongoSerialise());
// If the world should unload, it is removed from the Universe after having been saved.
if (w.shouldUnload()){
unloaded_worlds++;
// LogManager.LOGGER.fine("Unloading world "+w.getId()+" from universe");
universe.removeWorld(w);
}
}
for (User u : GameServer.INSTANCE.getGameUniverse().getUsers()) {
if (!u.isGuest()) {
users.save(u.mongoSerialise());
}
}
BasicDBObject serverObj = new BasicDBObject();
serverObj.put("_id","serverinfo"); // a constant id ensures only one entry is kept and updated, instead of a new entry created every save.
serverObj.put("time", gameUniverse.getTime());
serverObj.put("nextObjectId", gameUniverse.getNextObjectId());
server.save(serverObj);
LogManager.LOGGER.info(""+insertedWorlds+" worlds saved, "+unloaded_worlds+" unloaded");
LogManager.LOGGER.info("Done!");
} catch (Exception e) {
LogManager.LOGGER.severe("Problem happened during save function");
e.printStackTrace();
}
}
public ServerConfiguration getConfig() {
return config;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public void setSocketServer(SocketServer socketServer) {
this.socketServer = socketServer;
}
public DayNightCycle getDayNightCycle() {
return dayNightCycle;
}
}

View File

@@ -0,0 +1,26 @@
package net.simon987.server;
import net.simon987.server.logging.LogManager;
import net.simon987.server.webserver.SocketServer;
import java.net.InetSocketAddress;
public class Main {
public static void main(String[] args) {
ServerConfiguration config = new ServerConfiguration("config.properties");
LogManager.initialize(config);
//Load
GameServer.INSTANCE.load();
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

@@ -6,6 +6,7 @@ import net.simon987.server.logging.LogManager;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.Properties; import java.util.Properties;
/** /**
@@ -18,11 +19,11 @@ public class ServerConfiguration {
*/ */
private Properties properties; private Properties properties;
public ServerConfiguration(File file) { public ServerConfiguration(String file) {
try { try {
properties = new Properties(); properties = new Properties();
InputStream is = new FileInputStream("config.properties");
properties.load(new FileInputStream(file)); properties.load(is);
} catch (IOException e) { } catch (IOException e) {
LogManager.LOGGER.severe("Problem loading server configuration: " + e.getMessage()); LogManager.LOGGER.severe("Problem loading server configuration: " + e.getMessage());

View File

@@ -3,11 +3,15 @@ package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.*; import net.simon987.server.assembly.exception.*;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import org.apache.commons.text.StringEscapeUtils;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream; import java.io.DataOutputStream;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** /**
* Top-level class for assembly operations. * Top-level class for assembly operations.
@@ -20,6 +24,8 @@ public class Assembler {
private RegisterSet registerSet; private RegisterSet registerSet;
private static final int MEM_SIZE = 0x10000; // Size in words todo load from config
public Assembler(InstructionSet instructionSet, RegisterSet registerSet, ServerConfiguration config) { public Assembler(InstructionSet instructionSet, RegisterSet registerSet, ServerConfiguration config) {
this.instructionSet = instructionSet; this.instructionSet = instructionSet;
this.registerSet = registerSet; this.registerSet = registerSet;
@@ -47,11 +53,9 @@ public class Assembler {
* @return The line without its label part * @return The line without its label part
*/ */
private static String removeLabel(String line) { private static String removeLabel(String line) {
if (line.indexOf(':') != -1) {
return line.substring(line.indexOf(':') + 1); return line.replaceAll("^\\s*\\b\\w*\\b:", "");
} else {
return line;
}
} }
/** /**
@@ -93,10 +97,11 @@ public class Assembler {
line = removeComment(line); line = removeComment(line);
//Check for labels //Check for labels
if (line.indexOf(':') != -1) { Pattern pattern = Pattern.compile("^\\s*\\b\\w*\\b:");
Matcher matcher = pattern.matcher(line);
line = line.substring(0, line.indexOf(':')); if (matcher.find()) {
String label = line.trim(); String label = matcher.group(0).substring(0, matcher.group(0).length() - 1).trim();
LogManager.LOGGER.fine("DEBUG: Label " + label + " @ " + (result.origin + currentOffset)); LogManager.LOGGER.fine("DEBUG: Label " + label + " @ " + (result.origin + currentOffset));
result.labels.put(label, (char) (result.origin + currentOffset)); result.labels.put(label, (char) (result.origin + currentOffset));
@@ -129,11 +134,12 @@ public class Assembler {
//System.out.println(line); //System.out.println(line);
if (line.substring(0, 2).toUpperCase().equals("DW")) { if (line.length() >= 2 && line.substring(0, 2).toUpperCase().equals("DW")) {
try { try {
String[] values = line.substring(2, line.length()).split(","); //Special thanks to https://stackoverflow.com/questions/1757065/
String[] values = line.substring(2, line.length()).split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);
for (String value : values) { for (String value : values) {
@@ -144,6 +150,14 @@ public class Assembler {
//Handle DUP operator //Handle DUP operator
if (valueTokens.length == 2 && valueTokens[1].toUpperCase().contains("DUP(")) { if (valueTokens.length == 2 && valueTokens[1].toUpperCase().contains("DUP(")) {
out.write(parseDUPOperator16(valueTokens, labels, currentLine)); out.write(parseDUPOperator16(valueTokens, labels, currentLine));
} else if (value.startsWith("\"") && value.endsWith("\"")) {
//Handle string
//Unescape the string
String string = value.substring(1, value.length() - 1);
string = StringEscapeUtils.unescapeJava(string);
out.write(string.getBytes(StandardCharsets.UTF_16BE));
} else if (labels != null && labels.containsKey(value)) { } else if (labels != null && labels.containsKey(value)) {
//Handle label //Handle label
out.writeChar(labels.get(value)); out.writeChar(labels.get(value));
@@ -161,7 +175,18 @@ public class Assembler {
out.writeChar(0); out.writeChar(0);
} else { } else {
throw new InvalidOperandException("Invalid operand \"" + value + '"', currentLine);
//Integer.decode failed, try binary
if (value.startsWith("0b")) {
try {
out.writeChar(Integer.parseInt(value.substring(2), 2));
} catch (NumberFormatException e2) {
throw new InvalidOperandException("Invalid operand \"" + value + '"', currentLine);
}
} else {
throw new InvalidOperandException("Invalid operand \"" + value + '"', currentLine);
}
} }
} }
} }
@@ -194,6 +219,11 @@ public class Assembler {
try { try {
int factor = Integer.decode(valueTokens[0]); int factor = Integer.decode(valueTokens[0]);
if (factor > MEM_SIZE) {
throw new InvalidOperandException("Factor '"+factor+"' exceeds total memory size", currentLine);
}
String value = valueTokens[1].substring(4, valueTokens[1].lastIndexOf(')')); String value = valueTokens[1].substring(4, valueTokens[1].lastIndexOf(')'));
//Handle label //Handle label
@@ -208,7 +238,7 @@ public class Assembler {
} else { } else {
//Handle integer value //Handle integer value
char s = (char)(int)Integer.decode(value); char s = (char) (int) Integer.decode(value);
for (int i = 0; i < factor; i++) { for (int i = 0; i < factor; i++) {
out.write(Util.getHigherByte(s)); out.write(Util.getHigherByte(s));
@@ -237,23 +267,25 @@ public class Assembler {
} }
/** /**
* Check for and handle segment declarations (.text & .data) * Check for and handle section declarations (.text & .data)
* *
* @param line Current line * @param line Current line
*/ */
private static void checkForSegmentDeclaration(String line, AssemblyResult result, private static void checkForSectionDeclaration(String line, AssemblyResult result,
int currentLine, int currentOffset) throws AssemblyException { int currentLine, int currentOffset) throws AssemblyException {
String[] tokens = line.split("\\s+"); String[] tokens = line.split("\\s+");
if (tokens[0].toUpperCase().equals(".TEXT")) { if (tokens[0].toUpperCase().equals(".TEXT")) {
result.defineSegment(Segment.TEXT, currentLine, currentOffset); result.defineSecton(Section.TEXT, currentLine, currentOffset);
throw new PseudoInstructionException(currentLine); throw new PseudoInstructionException(currentLine);
} else if (tokens[0].toUpperCase().equals(".DATA")) { } else if (tokens[0].toUpperCase().equals(".DATA")) {
result.defineSegment(Segment.DATA, currentLine, currentOffset); LogManager.LOGGER.fine("DEBUG: .data @" + currentLine);
result.defineSecton(Section.DATA, currentLine, currentOffset);
throw new PseudoInstructionException(currentLine); throw new PseudoInstructionException(currentLine);
} }
} }
@@ -271,15 +303,15 @@ public class Assembler {
* usage: constant_name EQU <immediate_value> * usage: constant_name EQU <immediate_value>
* A constant treated the same way as a label. * A constant treated the same way as a label.
*/ */
line = line.trim();
String[] tokens = line.split("\\s+"); String[] tokens = line.split("\\s+");
if (line.toUpperCase().contains(" EQU ")) { if (line.toUpperCase().matches(".*\\bEQU\\b.*")) {
if (tokens[1].toUpperCase().equals("EQU") && tokens.length == 3) { if (tokens[1].toUpperCase().equals("EQU") && tokens.length == 3) {
try { try {
//Save value as a label //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) { } catch (NumberFormatException e) {
throw new InvalidOperandException("Usage: constant_name EQU immediate_value", currentLine); throw new InvalidOperandException("Usage: constant_name EQU immediate_value", currentLine);
} }
@@ -327,17 +359,23 @@ public class Assembler {
} }
//Pass 2: Save label names and location //Pass 2: Save label names and location
char currentOffset = 0; int currentOffset = 0;
for (currentLine = 0; currentLine < lines.length; currentLine++) { for (currentLine = 0; currentLine < lines.length; currentLine++) {
try { try {
checkForLabel(lines[currentLine], result, currentOffset); checkForLabel(lines[currentLine], result, (char)currentOffset);
//Increment offset //Increment offset
currentOffset += parseInstruction(lines[currentLine], currentLine, instructionSet).length / 2; currentOffset += parseInstruction(lines[currentLine], currentLine, instructionSet).length / 2;
} catch (AssemblyException e) { if (currentOffset >= MEM_SIZE) {
throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine);
}
} catch (FatalAssemblyException e) {
//Don't bother parsing the rest of the code, since it will not be assembled anyway
break;
} catch (AssemblyException e1) {
//Ignore error on pass 2 //Ignore error on pass 2
//System.out.println(e);
} }
} }
@@ -358,17 +396,26 @@ public class Assembler {
} }
//Check for pseudo instructions //Check for pseudo instructions
checkForSegmentDeclaration(line, result, currentLine, currentOffset); checkForSectionDeclaration(line, result, currentLine, currentOffset);
checkForEQUInstruction(line, result.labels, currentLine); checkForEQUInstruction(line, result.labels, currentLine);
checkForORGInstruction(line, result, currentLine); checkForORGInstruction(line, result, currentLine);
//Encode instruction //Encode instruction
byte[] bytes = parseInstruction(line, currentLine, result.labels, instructionSet); byte[] bytes = parseInstruction(line, currentLine, result.labels, instructionSet);
currentOffset += bytes.length / 2; currentOffset += bytes.length / 2;
if (currentOffset >= MEM_SIZE) {
throw new OffsetOverflowException(currentOffset, MEM_SIZE, currentLine);
}
out.write(bytes); out.write(bytes);
} catch (EmptyLineException | PseudoInstructionException e) { } catch (EmptyLineException | PseudoInstructionException e) {
//Ignore empty lines and pseudo-instructions //Ignore empty lines and pseudo-instructions
} catch (FatalAssemblyException asmE) {
// Save error, but abort assembly at this line
result.exceptions.add(asmE);
break;
} catch (AssemblyException asmE) { } catch (AssemblyException asmE) {
//Save errors on pass3 //Save errors on pass3
result.exceptions.add(asmE); result.exceptions.add(asmE);
@@ -377,7 +424,26 @@ public class Assembler {
} }
} }
result.bytes = out.toByteArray(); //If the code contains OffsetOverFlowException(s), don't bother writing the assembled bytes to memory
boolean writeToMemory = true;
for (Exception e : result.exceptions) {
if (e instanceof OffsetOverflowException) {
writeToMemory = false;
}
}
if (writeToMemory) {
result.bytes = out.toByteArray();
} else {
result.bytes = new byte[0];
LogManager.LOGGER.fine("Skipping writing assembled bytes to memory. (OffsetOverflowException)");
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
LogManager.LOGGER.info("Assembled " + result.bytes.length + " bytes (" + result.exceptions.size() + " errors)"); LogManager.LOGGER.info("Assembled " + result.bytes.length + " bytes (" + result.exceptions.size() + " errors)");
for (AssemblyException e : result.exceptions) { for (AssemblyException e : result.exceptions) {

View File

@@ -0,0 +1,124 @@
package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.AssemblyException;
import net.simon987.server.assembly.exception.DuplicateSectionException;
import net.simon987.server.logging.LogManager;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Result of an assembly attempt
*/
public class AssemblyResult {
/**
* The origin of the program, default is 0x200
*/
public int origin;
/**
* A list of labels
*/
HashMap<String, Character> labels = new HashMap<>(20);
/**
* List of exceptions encountered during the assembly attempt,
* they will be displayed in the editor
*/
public ArrayList<AssemblyException> exceptions = new ArrayList<>(50);
/**
* Offset of the code segment
*/
private int codeSectionOffset;
/**
* Line of the code segment definition
*/
private int codeSectionLine;
/**
* The encoded user code (will be incomplete or invalid if the
* assembler encountered an error during assembly)
*/
public byte[] bytes;
/**
* Offset of the data segment
*/
private int dataSectionOffset;
/**
* Line of the data segment definition
*/
private int dataSectionLine;
/**
* Whether or not the code segment is set
*/
private boolean codeSectionSet = false;
/**
* Whether or not the data segment is set
*/
private boolean dataSectionSet = false;
AssemblyResult(ServerConfiguration config) {
origin = config.getInt("org_offset");
}
/**
* Define a section.
*
* @param section Section to define
* @param currentOffset Current offset, in bytes of the section
* @param currentLine Line number of the section declaration
* @throws DuplicateSectionException when a section is defined twice
*/
void defineSecton(Section section, int currentLine, int currentOffset) throws DuplicateSectionException {
if (section == Section.TEXT) {
//Code section
if (!codeSectionSet) {
codeSectionOffset = origin + currentOffset;
codeSectionLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .text offset @" + codeSectionOffset);
codeSectionSet = true;
} else {
throw new DuplicateSectionException(currentLine);
}
} else {
//Data section
if (!dataSectionSet) {
dataSectionOffset = origin + currentOffset;
dataSectionLine = currentLine;
LogManager.LOGGER.fine("DEBUG: .data offset @" + dataSectionOffset);
dataSectionSet = true;
} else {
throw new DuplicateSectionException(currentLine);
}
}
}
public char[] getWords() {
char[] assembledCode = new char[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(assembledCode);
return assembledCode;
}
public int getCodeSectionOffset() {
if (codeSectionSet) {
return codeSectionOffset;
} else {
return origin;
}
}
}

View File

@@ -1,18 +1,18 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration; import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.CancelledException; import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.assembly.instruction.*; import net.simon987.server.assembly.instruction.*;
import net.simon987.server.event.CpuInitialisationEvent; import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent; import net.simon987.server.event.GameEvent;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User; import net.simon987.server.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
/** /**
@@ -20,7 +20,7 @@ import java.util.HashMap;
* a Memory object and execute them. A CPU object holds registers objects & * a Memory object and execute them. A CPU object holds registers objects &
* a Memory object. * a Memory object.
*/ */
public class CPU implements JSONSerialisable{ public class CPU implements MongoSerialisable {
/** /**
* *
@@ -43,10 +43,10 @@ public class CPU implements JSONSerialisable{
private RegisterSet registerSet; private RegisterSet registerSet;
/** /**
* Offset of the code segment. The code starts to get * Offset of the code section. The code starts to get
* executed at this address each tick. Defaults to 0x4000 * executed at this address each tick. Defaults to org_offset@config.properties
*/ */
private int codeSegmentOffset; private int codeSectionOffset;
/** /**
* Instruction pointer, always points to the next instruction * Instruction pointer, always points to the next instruction
@@ -60,21 +60,20 @@ 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
*/ */
public CPU(ServerConfiguration config, User user) throws CancelledException{ public CPU(ServerConfiguration config, User user) throws CancelledException {
this.config = config; this.config = config;
instructionSet = new DefaultInstructionSet(); instructionSet = new DefaultInstructionSet();
registerSet = new DefaultRegisterSet(); registerSet = new DefaultRegisterSet();
attachedHardware = new HashMap<>(); attachedHardware = new HashMap<>();
codeSegmentOffset = config.getInt("org_offset"); codeSectionOffset = 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));
@@ -93,25 +92,32 @@ public class CPU implements JSONSerialisable{
instructionSet.add(new JsInstruction(this)); instructionSet.add(new JsInstruction(this));
instructionSet.add(new HwiInstruction(this)); instructionSet.add(new HwiInstruction(this));
instructionSet.add(new HwqInstruction(this)); instructionSet.add(new HwqInstruction(this));
instructionSet.add(new XchgInstruction(this));
instructionSet.add(new JcInstruction(this));
instructionSet.add(new JncInstruction(this));
instructionSet.add(new JnoInstruction(this));
instructionSet.add(new JoInstruction(this));
instructionSet.add(new PushfInstruction(this));
instructionSet.add(new PopfInstruction(this));
instructionSet.add(new JnaInstruction(this));
instructionSet.add(new JaInstruction(this));
status = new Status(); status = new Status();
memory = new Memory(config.getInt("memory_size")); memory = new Memory(config.getInt("memory_size"));
GameEvent event = new CpuInitialisationEvent(this, user); GameEvent event = new CpuInitialisationEvent(this, user);
GameServer.INSTANCE.getEventDispatcher().dispatch(event); GameServer.INSTANCE.getEventDispatcher().dispatch(event);
if(event.isCancelled()){ if (event.isCancelled()) {
throw new CancelledException(); throw new CancelledException();
} }
} }
public void reset() { public void reset() {
status.clear(); status.clear();
registerSet.getRegister("SP").setValue(config.getInt("stack_bottom")); ip = codeSectionOffset;
registerSet.getRegister("BP").setValue(config.getInt("stack_bottom"));
ip = codeSegmentOffset;
} }
public void execute() { public int execute(int timeout) {
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
int counter = 0; int counter = 0;
@@ -123,10 +129,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;
} }
} }
@@ -146,8 +158,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("----------\n" + 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) {
@@ -200,8 +221,7 @@ public class CPU implements JSONSerialisable{
if (destination == 0) { if (destination == 0) {
//Single operand //Single operand
ip++; ip++;
instruction.execute(sourceValue, status); instruction.execute(memory, memory.get(ip - 1), status);
instruction.execute(memory, memory.get(ip - 1), status); //For POP instruction
} else if (destination == Operand.IMMEDIATE_VALUE) { } else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value //Destination is an immediate value
@@ -219,7 +239,7 @@ public class CPU implements JSONSerialisable{
} 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, sourceValue, status); instruction.execute(memory, registerSet.get(destination - registerSetSize), sourceValue, status);
} else { } else {
//Assuming that destination is [reg + x] //Assuming that destination is [reg + x]
ip += 2; ip += 2;
@@ -263,7 +283,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
@@ -276,11 +296,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;
@@ -308,7 +328,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,
@@ -328,47 +348,47 @@ public class CPU implements JSONSerialisable{
} }
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
JSONObject json = new JSONObject(); dbObject.put("memory", memory.mongoSerialise());
json.put("memory", memory.serialise()); dbObject.put("registerSet", registerSet.mongoSerialise());
dbObject.put("codeSegmentOffset", codeSectionOffset);
json.put("registerSet", registerSet.serialise()); BasicDBList hardwareList = new BasicDBList();
json.put("codeSegmentOffset", codeSegmentOffset);
JSONArray hardwareList = new JSONArray(); for (Integer address : attachedHardware.keySet()) {
for(Integer address : attachedHardware.keySet()){
CpuHardware hardware = attachedHardware.get(address); CpuHardware hardware = attachedHardware.get(address);
JSONObject serialisedHw = hardware.serialise(); BasicDBObject serialisedHw = hardware.mongoSerialise();
serialisedHw.put("address", address); serialisedHw.put("address", address);
hardwareList.add(serialisedHw); hardwareList.add(serialisedHw);
} }
json.put("hardware", hardwareList); dbObject.put("hardware", hardwareList);
return dbObject;
return json;
} }
public static CPU deserialize(JSONObject json, User user) throws CancelledException { public static CPU deserialize(DBObject obj, User user) throws CancelledException {
CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user); CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user);
cpu.codeSegmentOffset = (int)(long)json.get("codeSegmentOffset"); cpu.codeSectionOffset = (int) obj.get("codeSegmentOffset");
JSONArray hardwareList = (JSONArray)json.get("hardware"); BasicDBList hardwareList = (BasicDBList) obj.get("hardware");
for(JSONObject serialisedHw : (ArrayList<JSONObject>)hardwareList){ for (Object serialisedHw : hardwareList) {
CpuHardware hw = CpuHardware.deserialize(serialisedHw); CpuHardware hardware = CpuHardware.deserialize((DBObject) serialisedHw);
hw.setCpu(cpu); hardware.setCpu(cpu);
cpu.attachHardware(hw, (int)(long)serialisedHw.get("address")); cpu.attachHardware(hardware, (int) ((BasicDBObject) serialisedHw).get("address"));
} }
cpu.memory = Memory.deserialize((JSONObject)json.get("memory")); cpu.memory = Memory.deserialize((DBObject) obj.get("memory"));
cpu.registerSet = RegisterSet.deserialize((JSONObject) json.get("registerSet")); cpu.registerSet = RegisterSet.deserialize((DBObject) obj.get("registerSet"));
return cpu; return cpu;
@@ -398,22 +418,22 @@ public class CPU implements JSONSerialisable{
this.ip = ip; this.ip = ip;
} }
public void setCodeSegmentOffset(int codeSegmentOffset) { public void setCodeSectionOffset(int codeSectionOffset) {
this.codeSegmentOffset = codeSegmentOffset; this.codeSectionOffset = codeSectionOffset;
} }
public void attachHardware(CpuHardware hardware, int address){ public void attachHardware(CpuHardware hardware, int address) {
attachedHardware.put(address, hardware); attachedHardware.put(address, hardware);
} }
public void detachHardware(int address){ public void detachHardware(int address) {
attachedHardware.remove(address); attachedHardware.remove(address);
} }
public boolean hardwareInterrupt(int address){ public boolean hardwareInterrupt(int address) {
CpuHardware hardware = attachedHardware.get(address); CpuHardware hardware = attachedHardware.get(address);
if(hardware != null){ if (hardware != null) {
hardware.handleInterrupt(status); hardware.handleInterrupt(status);
return true; return true;
} else { } else {
@@ -443,5 +463,11 @@ public class CPU implements JSONSerialisable{
return str; return str;
} }
public CpuHardware getHardware(int address) {
return attachedHardware.get(address);
}
} }

View File

@@ -1,13 +1,13 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import com.mongodb.DBObject;
import net.simon987.server.GameServer; import net.simon987.server.GameServer;
import net.simon987.server.io.CpuHardwareDeserializer; import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.JSONSerialisable; import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.plugin.ServerPlugin; import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public abstract class CpuHardware implements JSONSerialisable { public abstract class CpuHardware implements MongoSerialisable {
CPU cpu; CPU cpu;
@@ -26,14 +26,14 @@ public abstract class CpuHardware implements JSONSerialisable {
public abstract char getId(); public abstract char getId();
public static CpuHardware deserialize(JSONObject hwJson){ public static CpuHardware deserialize(DBObject obj) {
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); CpuHardware hw = ((CpuHardwareDeserializer) plugin).deserializeHardware(obj);
if(hw != null){ if (hw != null) {
return hw; return hw;
} }
} }

View File

@@ -1,6 +1,7 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import net.simon987.server.assembly.instruction.*; import net.simon987.server.assembly.instruction.*;
import net.simon987.server.logging.LogManager;
import java.util.HashMap; import java.util.HashMap;
@@ -31,11 +32,20 @@ public class DefaultInstructionSet implements InstructionSet {
add(new AndInstruction()); add(new AndInstruction());
add(new OrInstruction()); add(new OrInstruction());
add(new ShlInstruction()); add(new ShlInstruction());
add(new SalInstruction()); //Alias is added
add(new ShrInstruction()); add(new ShrInstruction());
add(new XorInstruction()); add(new XorInstruction());
add(new TestInstruction()); add(new TestInstruction());
add(new CmpInstruction()); add(new CmpInstruction());
add(new NegInstruction()); add(new NegInstruction());
add(new NotInstruction());
add(new RorInstruction());
add(new RolInstruction());
add(new RclInstruction());
add(new RcrInstruction());
add(new SarInstruction());
add(new IncInstruction());
add(new DecInstruction());
} }
/** /**
@@ -48,10 +58,10 @@ public class DefaultInstructionSet implements InstructionSet {
public Instruction get(int opcode) { public Instruction get(int opcode) {
Instruction instruction = instructionMap.get(opcode); Instruction instruction = instructionMap.get(opcode);
if(instruction != null){ if (instruction != null) {
return instruction; return instruction;
} else { } else {
// System.out.println("Invalid instruction " + opcode); // System.out.println("Invalid instruction " + opcode);
//Todo: Notify user? Set error flag? //Todo: Notify user? Set error flag?
return defaultInstruction; return defaultInstruction;
} }
@@ -82,6 +92,12 @@ public class DefaultInstructionSet implements InstructionSet {
@Override @Override
public void add(Instruction instruction) { public void add(Instruction instruction) {
instructionMap.put(instruction.getOpCode(), instruction); if (instructionMap.containsKey(instruction.getOpCode())) {
LogManager.LOGGER.fine(instruction.getMnemonic() + " instruction is an alias for " +
instructionMap.get(instruction.getOpCode()).getMnemonic());
} else {
instructionMap.put(instruction.getOpCode(), instruction);
}
} }
} }

View File

@@ -120,8 +120,8 @@ public abstract class Instruction {
* Whether or not the instruction is valid without any * Whether or not the instruction is valid without any
* operands * operands
*/ */
private static boolean noOperandsValid() { public boolean noOperandsValid() {
return true; return false;
} }
String getMnemonic() { String getMnemonic() {

View File

@@ -67,7 +67,6 @@ class MachineCode {
LogManager.LOGGER.severe("Couldn't write the dst operand for instruction :" + dst); LogManager.LOGGER.severe("Couldn't write the dst operand for instruction :" + dst);
} else { } else {
//Src is the 5 most significant bits
value &= 0xF83F; //1111 1000 0011 1111 value &= 0xF83F; //1111 1000 0011 1111
dst <<= 6; //0000 0XXX XX00 0000 dst <<= 6; //0000 0XXX XX00 0000
value |= dst; value |= dst;

View File

@@ -0,0 +1,167 @@
package net.simon987.server.assembly;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.GameServer;
import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager;
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;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
/**
* Represents the available memory for a CPU in the game universe
*/
public class Memory implements Target, MongoSerialisable {
/**
* Contents of the memory
*/
private char[] words;
/**
* Create an empty Memory object
*
* @param size Size of the memory, in words
*/
public Memory(int size) {
words = new char[size];
}
/**
* Get the value at an address
*
* @param address Address of the value
* @return 16-bit value at the specified address
*/
@Override
public int get(int address) {
address = (char) address;
if (address >= words.length) {
LogManager.LOGGER.info("DEBUG: Trying to get memory out of bounds " + address);
return 0;
}
return words[address];
}
/**
* Write x words from an array at an offset
*/
public boolean write(int offset, char[] src, int srcOffset, int count) {
if (offset + count > this.words.length || srcOffset >= src.length || count < 0 || offset < 0) {
return false;
}
System.arraycopy(src, srcOffset, this.words, offset, count);
return true;
}
/**
* Set the value at an address
*
* @param address address of the value to change
* @param value 16-bit value to set
*/
@Override
public void set(int address, int value) {
address = (char) address;
if (address >= words.length) {
LogManager.LOGGER.info("DEBUG: Trying to set memory out of bounds: " + address);
return;
}
words[address] = (char) value;
}
/**
* Fill the memory with 0s
*/
public void clear() {
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;
}
@Override
public BasicDBObject mongoSerialise() {
BasicDBObject dbObject = new BasicDBObject();
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
deflaterOutputStream.write(getBytes());
deflaterOutputStream.close();
byte[] compressedBytes = stream.toByteArray();
dbObject.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes)));
} catch (IOException e) {
e.printStackTrace();
}
return dbObject;
}
public static Memory deserialize(DBObject obj) {
Memory memory = new Memory(0);
String zipBytesStr = (String) obj.get("zipBytes");
if (zipBytesStr != null) {
byte[] compressedBytes = Base64.getDecoder().decode((String) obj.get("zipBytes"));
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.words = new char[bytes.length / 2];
ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(this.words);
}
public char[] getWords() {
return words;
}
}

View File

@@ -113,6 +113,18 @@ public class Operand {
value = IMMEDIATE_VALUE; value = IMMEDIATE_VALUE;
return true; return true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
//Try Binary number (format 0bXXXX)
if (text.startsWith("0b")) {
try {
data = Integer.parseInt(text.substring(2), 2);
value = IMMEDIATE_VALUE;
return true;
} catch (NumberFormatException e2) {
return false;
}
}
return false; return false;
} }
} }
@@ -212,11 +224,30 @@ public class Operand {
} }
//label is invalid //label is invalid
data = Integer.decode(expr); data = Integer.decode(expr);
value += registerSet.size() * 2; //refers to memory with disp value += registerSet.size() * 2; //refers to memory with disp
return true; return true;
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
//Integer.decode failed, try binary
if (expr.startsWith("+0b")) {
try {
data = Integer.parseInt(expr.substring(3), 2);
value += registerSet.size() * 2; //refers to memory with disp
return true;
} catch (NumberFormatException e2) {
return false;
}
} else if (expr.startsWith("-0b")) {
try {
data = -Integer.parseInt(expr.substring(3), 2);
value += registerSet.size() * 2; //refers to memory with disp
return true;
} catch (NumberFormatException e2) {
return false;
}
}
return false; return false;
} }
} }

View File

@@ -1,7 +1,10 @@
package net.simon987.server.assembly; package net.simon987.server.assembly;
import net.simon987.server.io.JSONSerialisable; import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import net.simon987.server.io.MongoSerialisable;
import net.simon987.server.logging.LogManager; import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray; import org.json.simple.JSONArray;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
@@ -12,7 +15,7 @@ import java.util.HashMap;
/** /**
* A set of registers for a CPU * A set of registers for a CPU
*/ */
public class RegisterSet implements Target, JSONSerialisable { public class RegisterSet implements Target, MongoSerialisable {
/** /**
* List of registers * List of registers
@@ -87,7 +90,7 @@ public class RegisterSet implements Target, JSONSerialisable {
Register register = registers.get(address); Register register = registers.get(address);
if(register != null){ if (register != null) {
return register.getValue(); return register.getValue();
} else { } else {
return 0; return 0;
@@ -106,7 +109,7 @@ public class RegisterSet implements Target, JSONSerialisable {
Register register = registers.get(address); Register register = registers.get(address);
if(register != null){ if (register != null) {
register.setValue(value); register.setValue(value);
} else { } else {
LogManager.LOGGER.info("DEBUG: trying to set unknown reg index : " + address); LogManager.LOGGER.info("DEBUG: trying to set unknown reg index : " + address);
@@ -142,9 +145,9 @@ public class RegisterSet implements Target, JSONSerialisable {
@Override @Override
public JSONObject serialise() { public BasicDBObject mongoSerialise() {
JSONArray registers = new JSONArray(); BasicDBList registers = new BasicDBList();
for(Integer index : this.registers.keySet()){ for (Integer index : this.registers.keySet()) {
JSONObject register = new JSONObject(); JSONObject register = new JSONObject();
register.put("index", index); register.put("index", index);
@@ -154,24 +157,42 @@ public class RegisterSet implements Target, JSONSerialisable {
registers.add(register); registers.add(register);
} }
JSONObject json = new JSONObject(); BasicDBObject obj = new BasicDBObject();
json.put("registers", registers); obj.put("registers", registers);
return json; return obj;
}
public static RegisterSet deserialize(DBObject obj) {
RegisterSet registerSet = new RegisterSet();
BasicDBList registers = (BasicDBList) obj.get("registers");
for (Object sRegister : registers) {
Register register = new Register((String) ((DBObject) sRegister).get("name"));
register.setValue((int) ((DBObject) sRegister).get("value"));
registerSet.registers.put((int) ((DBObject) sRegister).get("index"), register);
}
return registerSet;
} }
public static RegisterSet deserialize(JSONObject json) { public static RegisterSet deserialize(JSONObject json) {
RegisterSet registerSet = new RegisterSet(); 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 register = new Register((String) jsonRegister.get("name"));
register.setValue((int)(long)jsonRegister.get("value")); 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 +203,7 @@ public class RegisterSet implements Target, JSONSerialisable {
public String toString() { public String toString() {
String str = ""; 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"; str += index + " " + registers.get(index).getName() + "=" + Util.toHex(registers.get(index).getValue()) + "\n";
} }

View File

@@ -3,10 +3,9 @@ package net.simon987.server.assembly;
/** /**
* Section of a user-created program. * Section of a user-created program.
* The execution will start at the beginning of the code * The execution will start at the beginning of the code
* segment and a warning message will be displayed when execution * segment.
* reached the data segment during debugging
*/ */
public enum Segment { public enum Section {
/** /**
* Code section of the program. Contains executable code * Code section of the program. Contains executable code

View File

@@ -132,4 +132,20 @@ public class Status {
public void setErrorFlag(boolean errorFlag) { public void setErrorFlag(boolean errorFlag) {
this.errorFlag = errorFlag; this.errorFlag = errorFlag;
} }
public char toByte() {
char stat = 0;
stat = (char) (stat | ((signFlag ? 1 : 0) << 3));
stat = (char) (stat | ((zeroFlag ? 1 : 0) << 2));
stat = (char) (stat | ((carryFlag ? 1 : 0) << 1));
stat = (char) (stat | (overflowFlag ? 1 : 0));
return stat;
}
public void fromByte(char stat) {
setSignFlag((stat & (1 << 3)) != 0);
setZeroFlag((stat & (1 << 2)) != 0);
setCarryFlag((stat & (1 << 1)) != 0);
setOverflowFlag((stat & 1) != 0);
}
} }

View File

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

View File

@@ -3,17 +3,17 @@ package net.simon987.server.assembly.exception;
/** /**
* Threw when a user attempts to define the same section twice * Threw when a user attempts to define the same section twice
*/ */
public class DuplicateSegmentException extends AssemblyException { public class DuplicateSectionException extends AssemblyException {
/** /**
* Message of the exception * Message of the exception
*/ */
private static final String message = "Segments can only be defined once"; private static final String message = "Sections can only be defined once";
/** /**
* Create a new Duplicate Segment Exception * Create a new Duplicate Section Exception
*/ */
public DuplicateSegmentException(int line) { public DuplicateSectionException(int line) {
super(message, line); super(message, line);
} }
} }

View File

@@ -0,0 +1,20 @@
package net.simon987.server.assembly.exception;
/**
* Class of exceptions that should stop assembly immediatly
*/
public class FatalAssemblyException extends AssemblyException {
/**
* Message of the exception
*/
private static final String message = "A fatal assembly error has occurred";
/**
* Create a new Duplicate Section Exception
*/
public FatalAssemblyException(String msg, int line) {
super(msg, line);
}
}

View File

@@ -0,0 +1,19 @@
package net.simon987.server.assembly.exception;
/**
* Threw when offset for stored instruction/data overflows the size of memory
*/
public class OffsetOverflowException extends FatalAssemblyException {
/**
* Message of the exception
*/
private static final String message = "Program data exceeds memory size ";
/**
* Create a new Offset Overflow Exception
*/
public OffsetOverflowException(int offset, int memsiz, int line) {
super(message + offset + " > " + memsiz, line);
}
}

View File

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

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