402 Commits

Author SHA1 Message Date
18a6858edd UI fix for UHD monitors 2020-09-14 20:33:09 -04:00
9315111793 Add tsc notes 2020-09-14 20:32:49 -04:00
60c763167d More work on debugger 2020-08-09 21:18:30 -04:00
3ae119072c Fix dissassembly display error 2020-08-09 20:26:42 -04:00
2ace932b52 Fix tests 2020-08-01 21:22:13 -04:00
50b95d1a9c Trap flag / Debugger first draft #232 2020-08-01 20:27:39 -04:00
ad08a5ac4f Fix #229 2020-07-31 19:27:14 -04:00
84a9132f5e Division by zero triggers INT #231 2020-07-31 18:34:57 -04:00
2ff19f24eb INTO instruction #78 2020-07-31 18:11:00 -04:00
b1d7121b22 Interrupts WIP #230 2020-07-30 21:26:47 -04:00
51c0d4c3c7 SETA test to confirm I can close #184 2020-07-30 20:00:15 -04:00
421a983910 More tests, add octal with '0o' prefix, fixes #166 2020-07-30 19:27:41 -04:00
73dc9b1dca More operand/dw tests (#228) 2020-07-30 19:13:07 -04:00
fe299fe061 Test for DW directive with strings (#228) 2020-07-30 18:40:34 -04:00
319abad130 Test for ORG directive (#228) 2020-07-30 18:38:19 -04:00
ad0124508c More refactoring, easier assembly testing (#227) 2020-07-29 21:08:52 -04:00
ba78d2fd93 Merge mischw plugin with cubot package 2020-07-29 19:13:11 -04:00
cc5627902e Remove NpcPlugin class 2020-07-29 18:58:34 -04:00
21a391e077 Simplify project structure (wip), editor keymap, UI tweaks 2020-07-28 20:09:51 -04:00
3b7cff6ac7 Hide phaser banner 2020-07-28 20:03:47 -04:00
304c063887 Simplify project structure (wip), run tsc during compilation 2020-07-27 19:38:29 -04:00
cd9e555e86 Merge pull request #226 from kevinramharak/fix-client-size-console-buffer-update
fix faulty object property name
2020-07-27 13:06:32 -04:00
Kevin Ramharak
7c0187f514 fix faulty object property name 2020-07-27 17:25:05 +02:00
ac27250f98 Merge pull request #225 from simon987/dependabot/maven/Server/org.springframework.security-spring-security-core-5.1.11.RELEASE
Bump spring-security-core from 5.1.5.RELEASE to 5.1.11.RELEASE in /Server
2020-06-15 16:10:53 -04:00
dependabot[bot]
84f59a5fa2 Bump spring-security-core in /Server
Bumps [spring-security-core](https://github.com/spring-projects/spring-security) from 5.1.5.RELEASE to 5.1.11.RELEASE.
- [Release notes](https://github.com/spring-projects/spring-security/releases)
- [Commits](https://github.com/spring-projects/spring-security/compare/5.1.5.RELEASE...5.1.11.RELEASE)

Signed-off-by: dependabot[bot] <support@github.com>
2020-06-15 19:36:46 +00:00
a0193621a8 Remove jenkins folder 2020-05-29 18:34:14 -04:00
922162660f Update footer.vm 2020-02-19 22:38:36 -05:00
014dab49da Merge pull request #221 from OrdoFlammae/radioactivecloud
Added Radioactive Cloud object.
2019-11-28 13:11:57 -05:00
Ordo Flammae
4c81937edc Added Radioactive Cloud object. 2019-11-27 19:35:49 -06:00
2597b558e6 Update slack link in play page 2019-11-08 10:10:17 -05:00
ea1ec1b1b3 jenkins hotfix 2019-10-27 22:20:28 -04:00
8b55466e7c Update README.md 2019-10-27 16:39:50 -04:00
Adam
03ff2e5527 Refactoring & code style (#212) 2019-10-23 08:38:01 -04:00
Mauricio Rivera
634af8859f Code style 197 (#213) 2019-10-23 08:34:24 -04:00
yesji
39ca4d5143 Fixed "'module' is defined but never used." issue (#208)
* Fixed "'module' is defined but never used." issue
2019-10-13 09:13:27 -04:00
CaderHancock
5f3c34911c Overload methods are not grouped together (#210)
* Overload methods are not grouped together
2019-10-10 16:46:49 -04:00
yesji
638c5b3bb3 Fixed 3 "switch without 'default' clause." issues (#207)
Fixed 3 "switch without 'default' clause."
2019-10-06 08:51:32 -04:00
Simon Fortier
50e0baa6ec Merge pull request #206 from RichardJamesC/master
moved the overloaded parseDWInstruction() #197
2019-06-18 20:40:36 -04:00
Richard Cuthbert
3a35f3fdfc In Assembler.java, I moved the overloaded parseDWInstruction() method to be sequential to the earlier method of the same name. 2019-06-19 00:05:44 +01:00
Simon Fortier
2982fcbbc1 Merge pull request #204 from Xychen1994/code-refactor
simplified getRandomTileWithAdjacent with for loop instead of similar branches
2019-06-01 13:48:25 -04:00
Xinyuan Chen
fb97415ee7 simplified getRandomTileWithAdjacent 2019-05-30 22:57:19 -07:00
Simon Fortier
f37ae36262 Update dates 2019-05-22 18:34:59 -04:00
Simon Fortier
556b46badc Typo 2019-05-22 18:34:25 -04:00
Simon Fortier
d57f8d2970 Merge pull request #203 from MyGodItsFull0fStars/reduce_complexity_of_method
#197 simplified getAdjacentTileCount
2019-05-12 15:53:15 -04:00
Christian Bauer
629dac6ea3 getAdjacentTileCount Method now uses for-loop instead of many if statements 2019-05-12 21:40:52 +02:00
simon987
55fdd93d9d Update dependency 2019-04-23 17:14:24 -04:00
simon987
2f7d2cd85a Fix build fail and refactor config file in tests 2019-04-23 17:04:20 -04:00
Simon Fortier
6e4b2358af Merge pull request #201 from kevinramharak/fix-configuration-path-java-11-#200
fix tests and configuration
2019-04-23 16:39:35 -04:00
Kevin Ramharak
f9c7f02870 fix tests and configuration 2019-04-23 21:56:31 +02:00
Simon Fortier
86b331fc60 Merge pull request #199 from matias9477/master
Code style & refactor for two issues
2019-04-18 15:35:47 -04:00
Matias
35b6f06687 Code style & refactor for two issues 2019-04-18 14:54:37 -03:00
simon987
bcd96be625 Change mongo transaction warning message 2019-04-11 18:43:47 -04:00
Woosle Park
f99f327480 Issue 182: Leaderboard changes (#194)
Implement new stats
2019-04-11 18:35:41 -04:00
simon987
d71b3dc97c Add badges 2019-04-03 18:58:20 -04:00
simon987
e378016c56 Jenkins setup 2019-04-03 18:19:51 -04:00
Simon Fortier
c50cc8c364 Merge pull request #192 from kevinramharak/implement-SETcc-instructions#184
actually add the implemented instrutions to instruction set :)
2019-01-24 19:06:23 -05:00
Kevin Ramharak
bf9cdc7b29 actually add the implemented instrutions to instruction set :) 2019-01-24 19:17:01 +01:00
Simon Fortier
75410cc0db Merge pull request #191 from kevinramharak/implement-SETcc-instructions#184
Implement setcc instructions#184
2019-01-23 19:23:22 -05:00
simon987
e0ed1e0e6f reformat code 2019-01-23 19:19:57 -05:00
Kevin Ramharak
0fbd1d1a6b add setcc instruction to editor lexer 2019-01-23 17:21:52 +01:00
Kevin Ramharak
8018fb3e30 update syntax highlighting 2019-01-23 17:18:29 +01:00
Kevin Ramharak
fb8fdac9c3 add tests for all SETcc instructions 2019-01-23 14:25:58 +01:00
Kevin Ramharak
a3253e8e3a fix setg 2019-01-23 14:08:40 +01:00
Kevin Ramharak
9ee754e5be add forgoten alias 2019-01-23 13:47:42 +01:00
Kevin Ramharak
e72e8b45c5 implement setcc tests 2019-01-23 10:08:30 +01:00
Kevin Ramharak
311889bc93 fix operandValid check; remove unused import; 2019-01-23 10:08:15 +01:00
Kevin Ramharak
9cb2c29f0f remove logs; 1 log might cause a null ref; 2019-01-23 09:48:43 +01:00
Kevin Ramharak
f3ae97c060 fix typo 2019-01-23 09:43:33 +01:00
Kevin Ramharak
e8033f3291 add operand constructors for easier testing 2019-01-23 09:39:44 +01:00
Kevin Ramharak
b19eb0568d remove magic numbers 2019-01-23 09:31:49 +01:00
Kevin Ramharak
9aa876df62 implement all aliases as instructions 2019-01-23 09:16:56 +01:00
Kevin Ramharak
b1da29d7fb fix feedback 2019-01-23 09:16:44 +01:00
Kevin Ramharak
12f20d178a example implementation of setcc and first cc setz 2019-01-22 22:13:25 +01:00
Kevin Ramharak
a030e9fc5d slightly rework aliases to work with inheritance 2019-01-22 22:12:34 +01:00
Kevin Ramharak
439547102f remove package private attributes 2019-01-22 20:54:59 +01:00
Kevin Ramharak
d5ddb8e439 allow operand validation methods to be overriden 2019-01-22 20:54:26 +01:00
Kevin Ramharak
4f4cecf60c allow operand checks to be overriden 2019-01-22 20:17:26 +01:00
Kevin Ramharak
a1136f9056 make MachineCode publicly visible 2019-01-22 20:16:40 +01:00
Kevin Ramharak
d2e7084354 update encode throw signature 2019-01-22 19:20:07 +01:00
Kevin Ramharak
1157bd5df5 remove random newline 2019-01-22 19:19:42 +01:00
Kevin Ramharak
0ff671713c allow inherited classes to get its own opcode and mnemonic 2019-01-22 18:48:49 +01:00
Kevin Ramharak
2590e8ec64 Merge branch 'master' into implement-SETcc-instructions#184 2019-01-22 18:40:32 +01:00
Simon Fortier
a768cf0f4b Merge pull request #189 from KevinRamharak/possible-implementation-aliases
add implementation for instruction aliases
2019-01-21 19:55:17 -05:00
Kevin Ramharak
7b3839f046 change types to map interface, remove unused import 2019-01-20 19:17:43 +01:00
Kevin Ramharak
4958c3d9a0 add implementation for instruction aliases 2019-01-20 13:32:48 +01:00
Kevin Ramharak
f8eec652ae basic skeleton 2019-01-20 13:10:06 +01:00
simon987
762bad758b Fixes #188 #187 2019-01-15 21:02:25 -05:00
Kevin Ramharak
3e2422775e Merge branch 'master' into implement-SETcc-instructions#184 2019-01-15 19:32:19 +01:00
simon987
993838651f Fixes #185 2019-01-14 18:24:34 -05:00
simon987
ce8c5375ee Merge remote-tracking branch 'origin/master' 2019-01-14 18:16:45 -05:00
Simon Fortier
91ebb51389 Merge pull request #186 from KevinRamharak/master
This will allow for easier search / grep's to figure out what opcodes are used
2019-01-14 18:16:42 -05:00
simon987
d113f635a1 Merge remote-tracking branch 'origin/master' 2019-01-14 18:14:44 -05:00
Kevin Ramharak
78a9f78a54 fix merge conflict 2019-01-14 18:46:23 +01:00
Kevin Ramharak
4f8eb2725e fix typo 2019-01-14 18:37:42 +01:00
Kevin Ramharak
ff4f6c23eb adjust source code so all instructions use the same patterns 2019-01-14 18:32:53 +01:00
Kevin Ramharak
c5a34c7a3f adjust source code so all instructions use the same patterns 2019-01-14 18:32:27 +01:00
Kevin Ramharak
1d3d441996 allow instructions to override the encode method 2019-01-14 17:48:49 +01:00
simon987
7ba46ec36e Updated dependencies 2019-01-09 18:52:13 -05:00
simon987
63cdfb22ac Merge branch 'master' of https://github.com/simon987/Much-Assembly-Required 2019-01-09 18:47:01 -05:00
simon987
f9898f57f4 Updated dependencies 2019-01-09 18:46:37 -05:00
Data Archivist
2548242da8 Updated dependencies 2019-01-09 18:36:33 -05:00
simon
46d5c9b51e HackedNPC code section offset same as Cubot (for real this time) 2019-01-01 10:16:54 -05:00
simon
7fd1c35f7a Merge remote-tracking branch 'origin/master' 2018-12-23 12:47:38 -05:00
simon
0dbec1d258 HackedNPC code section offset same as Cubot 2018-12-23 12:47:32 -05:00
Simon Fortier
45d3b84dd0 Merge pull request #181 from simon987/blueprints
Oops I pushed to the wrong branch
2018-12-23 11:56:24 -05:00
simon
af4ddbdd89 Increased HackedNPC specs & reverted accidental change 2018-12-23 11:54:47 -05:00
simon
84ca3acb52 revert debug values 2018-12-22 18:17:53 -05:00
Simon Fortier
0973548b71 Merge pull request #179 from simon987/factory-rewrite
NPCPlugin refactor, Added HackedNPC
2018-12-22 17:55:12 -05:00
simon
5f95c17aed More refactoring, updated mongodb driver + transactions on supported clusters 2018-12-22 17:48:29 -05:00
simon
b361f87154 NPC Plugin refactoring 2018-12-22 15:29:58 -05:00
simon
e4a06e79d4 Hacked NPC minimum viable 2018-12-22 11:26:34 -05:00
simon
955d61ce99 Password moved from vault door to settlement 2018-12-21 14:04:42 -05:00
simon
201d83f8d8 Bump version 2018-12-21 14:00:47 -05:00
simon
94b8ef5395 NPC Plugin rewrite.
Plugin-level data can be stored in DB
2018-12-21 14:00:18 -05:00
simon
70eeb1442d Added Fluid Tile 2018-12-21 10:47:46 -05:00
simon
bbaa338469 Fix 500 internal error when autologin option is not specified in the config 2018-12-21 10:45:08 -05:00
Simon
5de909cd9c Fixed some debug commands. Added blueprint item deserialization, Added inventory SCAN and SEEK actions 2018-12-06 11:13:06 -05:00
Simon
71e88afdc9 Fixed typos & cleaned comments. Added autologin debug option. Added construction site base 2018-12-02 20:04:45 -05:00
Simon
ae41bd9cb9 Added construction plugin module 2018-11-30 21:51:34 -05:00
Simon
de45eb1827 Fixes #160 2018-11-30 16:35:58 -05:00
Simon
6c7a2f0a73 Fixes #169 2018-11-30 15:11:24 -05:00
Simon
3776070689 Fixes #170, #155 2018-11-27 16:02:21 -05:00
Simon
54ed05b86c Move hologram-related fields to proper class. Breaks existing database saves! 2018-11-27 14:38:33 -05:00
Simon
b361583252 Added memory location option for LiDAR GET_PATH. Fixes #140 2018-11-27 13:52:00 -05:00
Simon
04c837d692 Removed TEMPORARY guest policy. Fixes #25 2018-11-27 13:35:42 -05:00
Simon
aaeb18068d Removed useless argument 2018-11-27 13:26:20 -05:00
Simon
e848fd8b8a Updated Phaser to 2.11, Added magnetic tile sprite 2018-11-27 12:50:18 -05:00
Simon
1435d31d36 Implemented guest BLOCK and ALLOW options #25 2018-11-27 10:25:21 -05:00
Simon
950f6b6b4b Minor cleanup 2018-11-27 09:30:03 -05:00
Simon
6a9cfb3acb Cubot drill module now functional 2018-11-15 12:24:37 -05:00
Simon
4be1bf2e8a TileMap now uses Tile instances instead of ints. No changes in the way it is stored in the database 2018-11-15 12:08:44 -05:00
Simon Fortier
e50bcdeab7 Merge pull request #177 from Wiewiogr/148-secret-key
Add secret key generator #148
2018-10-28 13:17:17 -04:00
Wiewiogr
c8214236ab update properties on secret key change 2018-10-28 18:13:56 +01:00
Wiewiogr
37b7bbff98 Merge pull request #2 from Wiewiogr/master
merge
2018-10-28 18:12:37 +01:00
Wiewiogr
be7304aa0b Merge pull request #1 from simon987/master
merge
2018-10-28 17:50:01 +01:00
Simon
0845438297 Fixed potential error in ServerConfiguration and added ability to programmatically modify server configuration 2018-10-28 09:45:53 -04:00
Simon Fortier
564a692c2e Merge pull request #176 from Wiewiogr/138-add-items-container
Added Container object #138
2018-10-28 09:43:17 -04:00
Wiewiogr
a40a0712f0 changed fields names 2018-10-27 18:26:24 +02:00
Wiewiogr
f89c39c756 changed implementation to list 2018-10-27 18:13:43 +02:00
Wiewiogr
a6f0ce1dfb moved test to correct folder 2018-10-27 18:11:56 +02:00
Wiewiogr
2f80205b2a added secret_key property to config.properties 2018-10-27 17:23:07 +02:00
Wiewiogr
71f96f27d1 add secretKey field to GameServer 2018-10-27 17:22:20 +02:00
Wiewiogr
98402dd45b Added SecretKeyGenerator class 2018-10-27 17:21:12 +02:00
Wiewiogr
548d756e90 Added tests for ItemsContainer 2018-10-27 15:51:21 +02:00
Wiewiogr
1a2332bc32 Create ItemsContainer.java 2018-10-27 15:49:39 +02:00
Simon Fortier
9a73b7b7d1 Merge pull request #175 from senatormailman/readme
Added MacOS instructions
fixes #152
2018-10-12 18:49:43 -04:00
Liam Hogan
d860591cc8 Minor formatting fixes following simon987's suggestion. 2018-10-12 17:45:38 -04:00
Liam Hogan
268acda773 Minor formatting fix. 2018-10-12 15:35:30 -04:00
Liam Hogan
6d66e19dc5 Added installation instructions for macOS. Pulled some of the formatting from Anarcroth's Linux instructions. 2018-10-12 15:30:34 -04:00
Simon Fortier
40e7899cf6 Merge pull request #174 from Anarcroth/add-arch-install-instructions
Added Arch Linux installation instructions in README.md
2018-10-03 21:47:27 -04:00
Martin Nestorov
abb92bfc75 Added Arch Linux installation instructions 2018-10-03 20:06:49 +03:00
Simon Fortier
becf6e5feb Merge pull request #173 from bobbyjudd/issue-172
Fixes issue 172
2018-09-06 15:56:07 -04:00
Bobby Judd
8af652482d Fixed memory displacement when subtracting labels, and added corresponding test 2018-09-05 21:11:11 -07:00
Simon
205845d6af Changed the way port configuration is done 2018-09-03 17:04:29 -04:00
Simon
64193ecf7a Should fix user creation problem 2018-09-03 16:12:36 -04:00
Simon Fortier
a1cf279b6f Merge pull request #171 from Francessco121/bug/unicode-string-crash
Fix assembler crash when invalid Unicode string escape sequences are used
2018-08-30 17:24:32 -04:00
Ethan Lafrenais
6074238131 Catch string unescape exceptions when parsing DW string operands 2018-08-29 23:15:06 -04:00
Ethan Lafrenais
fa62c49fa8 Add the Visual Studio Code workspace directory to .gitignore 2018-08-29 23:13:08 -04:00
Simon
a0aaee7ee7 Added find cubot button 2018-08-13 15:59:46 -04:00
Simon
96fc3ed68c Should fix server crash problem when harvesting biomass 2018-08-13 15:43:41 -04:00
Simon
e69111ff3c Should fix user creation problem 2018-08-13 15:41:24 -04:00
Simon Fortier
e7e9a3e6fb Merge pull request #168 from Mozzi20/master
Added radioactive obstacle
2018-06-08 12:09:36 -04:00
Unknown
a73aa7c3a5 Moved radioactive obstacle. 2018-06-08 09:58:52 +02:00
Unknown
e8543082ce Fixed radioactive obstacle.
Added "radioactive obstacle curruption block size" in config.properties and removed its getter and setter.
2018-06-07 23:24:49 +02:00
Unknown
4b7ebd7ad6 Added radioactive obstacle. 2018-06-07 21:40:59 +02:00
Simon
c389bbc92e Refactored SocketServer.tick() method 2018-06-04 18:06:31 -04:00
Simon
78f98c8227 JSONSerialisable objects now have a debug function #156 2018-06-04 17:07:20 -04:00
Simon
92008e553a ServerPlugin no longer implements JSONSerialisable (this feature was unused) 2018-06-04 17:06:11 -04:00
Simon
45d34c37ad Commented out some debug messages & fix for #161 2018-06-04 16:44:32 -04:00
Simon
a9cc9662f4 Changed unreliable sequential integer object id to BSON ObjectId #162 2018-06-04 14:53:20 -04:00
Simon
df9c466827 Avoid thread safety issues with objectIds #162 2018-06-04 12:18:21 -04:00
Simon
b65c57ceba Fixed exception showing when tick-based broadcast happens exactly when a user is connected but not authenticated pt.2 2018-06-04 11:46:31 -04:00
Simon
2f74dd45fc Reformat + Should fix #159 2018-06-04 10:49:34 -04:00
Simon
07160138aa Fixed exception showing when tick-based broadcast happens exactly when a user is connected but not authenticated 2018-06-04 10:46:55 -04:00
Simon
b6a206f3c7 Added basic Cubot.toString() and fixed account page debug info 2018-05-31 22:33:56 -04:00
Simon
ed1c4cff0b Fixed bug that prevents RadioReceiverHardware from being correctly loaded from database 2018-05-31 22:28:35 -04:00
Simon
a005e2b163 Reverted accidental change caused by search and replace 2018-05-31 22:21:33 -04:00
Simon
a7bdbd2513 I broke everything pt. 1: Moved helditem into CubotInventory, added debug commands for CubotInventory, Added vault complete GameEvent, moved CPU to Cubot, renamed CpuHardware to HardwareModule, moved HardwareModule to Cubot & added HardwareHost interface, removed getParent() in ControllableUnit, moved items to the Item class, started moving tiles to Tile classes, renamed Programmable to MessageReceiver 2018-05-31 22:13:07 -04:00
simon
ee9eeeef55 Reverted value of factory_spawn_rate that was accidentally changed 2018-05-12 20:33:41 -04:00
simon
4b67798180 Added structure class #145 and moved many constants to config.properties 2018-05-12 20:32:10 -04:00
simon
be8dd14d36 Added method to find objects of particular type in a world 2018-05-12 19:09:00 -04:00
simon
80f45f1eb0 Added catch clause to prevent crash when socket is not opened 2018-05-12 19:07:55 -04:00
simon
3368268924 Cubot object id is no longer stored inside every CpuHardware in the database. Renamed some fields in the database to make them more readable 2018-05-12 16:16:24 -04:00
simon
4cd58c86a5 Refactor: changed the way game objects and cpu hardware are saved/loaded from the database #151 2018-05-12 15:32:42 -04:00
simon
8d029cf621 Added vagrant instructions in readme #152 2018-05-11 21:23:41 -04:00
simon
10f088cb66 Updated gitattributes (again) 2018-05-11 21:19:36 -04:00
simon
159c217d59 Updated gitattributes 2018-05-11 21:18:25 -04:00
Simon Fortier
c5cb5df335 Merge pull request #153 from simon987/spark
Moved frontend to main server application
2018-05-11 21:13:01 -04:00
simon
854863ede9 Updated mongodb driver to 3.7.0 2018-05-11 21:06:18 -04:00
simon
e98575b23f Added vagrant support 2018-05-11 21:04:00 -04:00
simon
1a5d12a19f updated Docker support 2018-05-11 16:42:03 -04:00
simon
1678be25c5 Added UserStats and updated leaderboard page 2018-05-11 13:16:34 -04:00
simon
9c41c16079 Added debug command to save the game 2018-05-11 10:25:40 -04:00
simon
e97ecbe380 Added javadocs 2018-05-01 15:41:51 -04:00
simon
083af31b84 Fixed websocket problem by upgrading spark version. Also fixed z-index problem with console 2018-04-29 17:00:42 -04:00
simon
2c856aae80 Editor upload & reload buttons are now working. Floppy upload & download working. 2018-04-29 14:00:50 -04:00
simon
315e33055e Reorganised css files, some work on the home page design, console screen is now in a resizable panel 2018-04-29 11:17:54 -04:00
simon
e025b6d2da SSL now working and reorganised web server 2018-04-28 12:06:55 -04:00
simon
e3a650a4fc Reorganised debug info in account page and extracted user loading to UserManager 2018-04-27 21:59:07 -04:00
simon
113aa50d87 Websocket auth up and running 2018-04-27 21:28:46 -04:00
simon
dc034d1437 Users can change their password 2018-04-27 20:39:14 -04:00
simon
3492e133e1 login/register working and Websocket partially implemented 2018-04-27 19:42:53 -04:00
simon
bd5f8573e8 Added web server and partly integrated frontend 2018-04-27 16:58:50 -04:00
simon
3c5bfdb30b Fixed build errors 2018-04-24 08:09:42 -04:00
simon987
9349ae108b Removed some unnecessary unit tests 2018-04-02 10:58:24 -04:00
simon987
292adb5483 Updated maven version numbers. Removed .iml files 2018-04-02 10:52:36 -04:00
simon987
e479d89375 Added Radioactive cloud plugin 2018-04-02 10:41:37 -04:00
simon987
41d674d74a Removed unused constant 2018-04-02 10:06:44 -04:00
Simon Fortier
227f7ce5aa Merge pull request #144 from mlaga97/ram-corruption
Implement RAM corruption effect
2018-04-01 22:18:15 -04:00
Luc Lagarde
a091071d55 Implement RAM corruption effect 2018-03-31 17:50:51 -05:00
Simon Fortier
f1b8f3dc6d Merge pull request #143 from mlaga97/lidar-vault-fix
Make LiDAR work in Vaults (fixes #140)
2018-03-29 20:10:44 -04:00
Luc Lagarde
e62a51ee2e Modify LIDAR_GET_MAP to write to a given memory address 2018-03-28 23:37:05 -05:00
Luc Lagarde
217c997788 Add action to get world size from LiDAR 2018-03-28 23:34:23 -05:00
simon
ff61433c4b Fixed typo 2018-03-11 16:09:28 -04:00
simon
cbde2450fa Bug fixes: maxShield is now set on user creation and vault objectId is set on world generation 2018-03-11 16:06:15 -04:00
simon
1d780f7d9b Minor refactor 2018-03-11 13:34:10 -04:00
simon
cbb07891fc Cubot respawns on death. ElectricBox damages near objects 2018-03-10 15:22:11 -05:00
simon
2565d3338c Implemented shield hardware. Added heal, damage and charge shield debug commands. 2018-03-10 13:54:43 -05:00
simon
e4269b83c4 Fixed hardware deserialization issues 2018-03-10 11:51:31 -05:00
simon
9cac665101 Debug commands are easier to add. Added comPortMsg command 2018-03-10 11:24:29 -05:00
simon
dc19176dc8 Merge branch 'master' into vaults
# Conflicts:
#	Server/src/main/java/net/simon987/server/game/GameObject.java
#	Server/src/main/java/net/simon987/server/game/World.java
#	Server/src/main/java/net/simon987/server/webserver/TerrainRequestHandler.java
2018-03-10 09:53:55 -05:00
simon
8ed192f8d0 Cubot implements Attackable (untested) 2018-03-10 09:49:34 -05:00
Simon Fortier
d1a3cf9307 Merge pull request #110 from djsheehy/shield-hardware
Added Shield hardware
2018-03-05 22:18:44 -05:00
simon
f8c5dac969 Added logging of vault clears for display in the leaderboard 2018-03-05 21:47:28 -05:00
simon
0a75cb557d Added objective vault world & its exit portal 2018-03-04 15:51:30 -05:00
simon
f35e6c5a9a Objects can enter & leave vaults 2018-03-04 14:56:02 -05:00
simon
0ada6c29d4 More work on vaults 2018-03-01 10:42:24 -05:00
simon
156deb8f4e NPCs decrement World.updatable on death. Fixes problem making Worlds stay loaded forever in RAM 2018-02-27 16:51:18 -05:00
simon
039088ac00 Added electric boxes, debug command to teleport objects across Worlds. 2018-02-27 16:49:32 -05:00
simon
f530dafdee Basic world generation for entire Vault dimension 2018-02-26 17:17:40 -05:00
simon
817dbcc6c4 Basic world generation for single Vault world 2018-02-26 13:29:08 -05:00
simon
62f1403cb3 Started working on Vault worlds generation 2018-02-26 10:04:06 -05:00
simon
8c6e580ea9 Added support for multiple dimensions 2018-02-25 14:15:03 -05:00
simon
6a1519d97d Added many debug commands 2018-02-25 11:55:53 -05:00
simon
a7d1a00ae8 Fixes #27 2018-02-25 08:51:03 -05:00
simon
95a14ad1ab Added basic functionality for debug commands 2018-02-17 10:05:53 -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
187a828c79 Fixed opcode clash for PUSHF instruction 2018-01-20 09:40:23 -05:00
simon
ffca185fe5 Vault Door generation 2018-01-17 22:01:59 -05:00
simon
815f3de234 Changed the walking function to enable interaction with Enterable objects 2018-01-17 21:11:16 -05:00
simon
3505a466bb Fixed compilation errors 2018-01-17 20:31:35 -05:00
simon
3d10e4306b Merge branch 'master' into vaults
# Conflicts:
#	Server/src/main/java/net/simon987/server/GameServer.java
#	Server/src/main/java/net/simon987/server/game/World.java
2018-01-17 20:29:37 -05:00
simon
210e579995 Number of assembly errors is also sent on code upload 2018-01-17 19:02:36 -05:00
simon
a285b3104e Moved Vault Door code to NPC Plugin. Fixed code styling. Fixed compilation errors 2018-01-14 13:33:40 -05:00
simon
947deea784 Merge remote-tracking branch 'origin/vaults' into vaults 2018-01-14 12:04:04 -05:00
simon
4293fc0315 Support for variable World size 2018-01-14 12:02:32 -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
Simon Fortier
f1c1f8f807 Merge pull request #120 from sg495/vaults
New additional code for Vault doors
2018-01-09 19:22:42 -05:00
Jaggernaut555
7cbfb822b8 Updated LogManager 2018-01-09 14:00:36 -08:00
sg495
a04207b5e0 Added some cyphers for use in vault doors.
1. Created net.simon987.server.crypto package and moved RandomStringGenerator there.
2. Created CryptoProvider class, added a global instance to GameServer for use by game entities.
3. Created interface for cyphers, abstract class for shift substitution cyphers, classes for no cypher, Caesar cypher, Vigenere cypher and autokey cypher.
4. Created some Crypto exceptions.
5. Removed static encryption/decryption methods from VaultDoor, and moved getRandomPassword() to the global CryptoProvider instance.
2018-01-09 17:14:31 +01:00
simon
6fc583d6f0 Registers are cleared on code upload 2018-01-08 19:12:39 -05:00
sg495
46483b2bf8 Added a RandomString class from stackoverflow, to generate random alphanumeric strings (to be used as passwords).
Added some code to VaultDoor, including random password generation and code to encrypt/decrypt under a Vernam-like cypher.
Modified door opening policy to include the possibility of keeping the door open.
2018-01-08 20:40:50 +01: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
9bb0dc9034 Boilerplate code for Vault Door 2018-01-05 20:42:24 -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
Dylan Sheehy
1da894959e fixed serialization code for CubotShield 2018-01-05 11:20:52 -06:00
Dylan Sheehy
7e773699b6 Created Shield hardware 2018-01-05 11:04:05 -06:00
Dylan Sheehy
bc29c36204 Merge remote-tracking branch 'upstream/master' 2018-01-05 09:14:18 -06: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
Dylan Sheehy
eb3deba544 Merge branch 'master' of https://github.com/simon987/Much-Assembly-Required 2018-01-03 07:03:56 -06: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
Dylan Sheehy
c7da764505 Added entries to .gitignore to ignore files that vscode's java extension generates 2018-01-02 07:04:14 -06: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
524 changed files with 165155 additions and 6131 deletions

5
.gitattributes vendored Normal file
View File

@@ -0,0 +1,5 @@
src/main/resources/static/css/bootstrap4-neon-glow.min linguist-vendored
src/main/resources/static/css/bootstrap-grid.min linguist-vendored
src/main/resources/static/css/bootstrap-reboot.min linguist-vendored
src/main/resources/static/js/* linguist-vendored
src/main/resources/static/js/ace/* linguist-vendored

18
.gitignore vendored Normal file
View File

@@ -0,0 +1,18 @@
.idea/*
mar.log
mar.log.lck
*.iml
*.class
*/target/*
plugins/*.jar
save.json
Server/Server.iml
target/*
src/main/java/META-INF/MANIFEST.MF
src/main/resources/static/js/mar.js
.settings
.project
.classpath
# VSCode Workspace
.vscode/

14
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,14 @@
## 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
- 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.
- Please state what tests have been performed in the pull request

6
Dockerfile Normal file
View File

@@ -0,0 +1,6 @@
FROM maven:3.5-jdk-8
COPY /. /app/
WORKDIR /app
RUN mvn package
WORKDIR /app/target
CMD ["java", "-jar", "/app/target/server-1.6a.jar"]

View File

@@ -1,3 +0,0 @@
classpath=net.simon987.cubotplugin.CubotPlugin
name=Cubot Plugin
version=1.0

View File

@@ -1,192 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Memory;
import net.simon987.server.game.ControllableUnit;
import net.simon987.server.game.Direction;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.Updatable;
import net.simon987.server.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 char hologram = 0;
private char lastHologram = 0;
/**
* 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 FloppyDisk floppyDisk;
private User parent;
private int energy;
private int maxEnergy;
public Cubot() {
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
if (currentAction == CubotAction.WALKING) {
if (spendEnergy(100)) {
if (!incrementLocation()) {
//Couldn't walk
currentAction = CubotAction.IDLE;
}
} else {
currentAction = CubotAction.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 = CubotAction.IDLE;
//Same principle for hologram
lastHologram = hologram;
hologram = 0;
}
@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());
json.put("holo", (int) lastHologram);
json.put("energy", (int) lastHologram);
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");
cubot.energy = (int) (long) json.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(CubotAction currentAction) {
this.currentAction = currentAction;
}
public User getParent() {
return parent;
}
public void setParent(User parent) {
this.parent = parent;
}
public CubotAction getAction() {
return lastAction;
}
public void setHologram(char hologram) {
this.hologram = hologram;
}
public char getHologram() {
return lastHologram;
}
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 setMaxEnergy(int maxEnergy) {
this.maxEnergy = maxEnergy;
}
public int getMaxEnergy() {
return maxEnergy;
}
@Override
public Memory getFloppyData() {
return ((CubotFloppyDrive) getParent().getCpu().getHardware(CubotFloppyDrive.DEFAULT_ADDRESS)).getFloppy().getMemory();
}
}

View File

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

View File

@@ -1,59 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
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 POLL = 1;
private static final int 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 == POLL) {
getCpu().getRegisterSet().getRegister("B").setValue(cubot.getEnergy());
} else if (a == 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 JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotBattery deserialize(JSONObject hwJSON) {
return new CubotBattery((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

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.spendEnergy(1400)) {
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);
}
}
}
}
}
@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,49 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
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;
public CubotHologram(Cubot cubot) {
this.cubot = cubot;
}
@Override
public void handleInterrupt(Status status) {
char a = getCpu().getRegisterSet().getRegister("A").getValue();
cubot.setHologram(a);
}
@Override
public char getId() {
return HWID;
}
public static CubotHologram deserialize(JSONObject hwJSON) {
return new CubotHologram((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
}

View File

@@ -1,61 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class CubotInventory extends CpuHardware {
/**
* Hardware ID (Should be unique)
*/
static final char HWID = 0x0006;
public static final int DEFAULT_ADDRESS = 6;
private Cubot cubot;
private static final int POLL = 1;
private static final int CLEAR = 2;
public CubotInventory(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(cubot.getHeldItem());
} else if (a == CLEAR) {
if (cubot.spendEnergy(100)) {
cubot.setHeldItem(0);
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static CubotInventory deserialize(JSONObject hwJSON){
return new CubotInventory((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
}
}

View File

@@ -1,86 +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;
private static final int DEPOSIT = 2;
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) {
Point frontTile = cubot.getFrontTile();
ArrayList<GameObject> objects = cubot.getWorld().getGameObjectsAt(frontTile.x, frontTile.y);
if (cubot.getAction() != CubotAction.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(CubotAction.WITHDRAWING);
}
}
}
}
} else if (a == DEPOSIT) {
}
}
@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,85 +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){
if (cubot.spendEnergy(20)) {
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,152 +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 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 GET_POS:
getCpu().getRegisterSet().getRegister("X").setValue(cubot.getX());
getCpu().getRegisterSet().getRegister("Y").setValue(cubot.getY());
break;
case 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
byte[] mem = getCpu().getMemory().getBytes();
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[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:
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 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;
}
public static CubotLidar deserialize(JSONObject hwJSON) {
return new CubotLidar((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int) (long) hwJSON.get("cubot")));
}
}

View File

@@ -1,64 +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);
case CubotHologram.HWID:
return CubotHologram.deserialize(hwJson);
case CubotBattery.HWID:
return CubotBattery.deserialize(hwJson);
case CubotFloppyDrive.HWID:
return CubotFloppyDrive.deserialize(hwJson);
}
return null;
}
}

View File

@@ -1,67 +0,0 @@
package net.simon987.cubotplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
public class Keyboard extends CpuHardware {
public static final int DEFAULT_ADDRESS = 4;
private static final int CLEAR_BUFFER = 0;
private static final int FETCH_KEY = 1;
/**
* Hardware ID (Should be unique)
*/
public static final char HWID = 0x0004;
private Cubot cubot;
public Keyboard(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 == CLEAR_BUFFER){
cubot.clearKeyboardBuffer();
} else if (a == FETCH_KEY){
//pop
int key = 0;
if(cubot.getKeyboardBuffer().size() > 0){
key = cubot.getKeyboardBuffer().get(0);
cubot.getKeyboardBuffer().remove(0);
}
getCpu().getRegisterSet().getRegister("B").setValue(key);
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
json.put("cubot", cubot.getObjectId());
return json;
}
public static Keyboard deserialize(JSONObject hwJSON){
return new Keyboard((Cubot) GameServer.INSTANCE.getGameUniverse().getObject((int)(long)hwJSON.get("cubot")));
}
}

View File

@@ -1,54 +0,0 @@
package net.simon987.cubotplugin.event;
import net.simon987.cubotplugin.*;
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.logging.LogManager;
import net.simon987.server.user.User;
public class CpuInitialisationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return CpuInitialisationEvent.class;
}
@Override
public void handle(GameEvent event) {
LogManager.LOGGER.fine("(Plugin) Handled CPU Initialisation event (Cubot Plugin)");
CPU cpu = (CPU)event.getSource();
User user = ((CpuInitialisationEvent)event).getUser();
CubotLeg legHw = new CubotLeg((Cubot) user.getControlledUnit());
legHw.setCpu(cpu);
CubotLaser laserHw = new CubotLaser((Cubot) user.getControlledUnit());
laserHw.setCpu(cpu);
CubotLidar radarHw = new CubotLidar((Cubot) user.getControlledUnit());
radarHw.setCpu(cpu);
Keyboard keyboard = new Keyboard((Cubot) user.getControlledUnit());
keyboard.setCpu(cpu);
CubotDrill drillHw = new CubotDrill((Cubot) user.getControlledUnit());
drillHw.setCpu(cpu);
CubotInventory invHw = new CubotInventory((Cubot) user.getControlledUnit());
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);
cpu.attachHardware(legHw, CubotLeg.DEFAULT_ADDRESS);
cpu.attachHardware(laserHw, CubotLaser.DEFAULT_ADDRESS);
cpu.attachHardware(radarHw, CubotLidar.DEFAULT_ADDRESS);
cpu.attachHardware(keyboard, Keyboard.DEFAULT_ADDRESS);
cpu.attachHardware(drillHw, CubotDrill.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);
}
}

View File

@@ -1,50 +0,0 @@
package net.simon987.cubotplugin.event;
import net.simon987.cubotplugin.Cubot;
import net.simon987.server.GameServer;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.event.UserCreationEvent;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User;
import java.awt.*;
public class UserCreationListener implements GameEventListener {
@Override
public Class getListenedEventType() {
return UserCreationEvent.class;
}
@Override
public void handle(GameEvent event) {
User user = (User)event.getSource();
LogManager.LOGGER.fine("(Plugin) Handled User creation event (Cubot Plugin)");
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.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);
Point point = cubot.getWorld().getRandomPassableTile();
cubot.setX(point.x);
cubot.setY(point.y);
user.setControlledUnit(cubot);
}
}

View File

@@ -1,19 +0,0 @@
package net.simon987.cubotplugin;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CubotTest {
@Test
public void test(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(1,2);
}
}

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

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

View File

@@ -1,42 +0,0 @@
package net.simon987.mischwplugin;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Util;
import org.json.simple.JSONObject;
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(JSONObject hwJSON) {
return new Clock();
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
return json;
}
}

View File

@@ -1,33 +0,0 @@
package net.simon987.mischwplugin;
import net.simon987.mischwplugin.event.CpuInitialisationListener;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.logging.LogManager;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public class MiscHWPlugin extends ServerPlugin implements CpuHardwareDeserializer {
@Override
public void init() {
listeners.add(new CpuInitialisationListener());
LogManager.LOGGER.info("Initialised Misc Hardware Plugin");
}
@Override
public CpuHardware deserializeHardware(JSONObject hwJson) {
int hwid = (int) (long) hwJson.get("hwid");
switch (hwid) {
case RandomNumberGenerator.HWID:
return RandomNumberGenerator.deserialize(hwJson);
case Clock.HWID:
return Clock.deserialize(hwJson);
}
return null;
}
}

View File

@@ -1,44 +0,0 @@
package net.simon987.mischwplugin;
import net.simon987.server.assembly.CpuHardware;
import net.simon987.server.assembly.Status;
import org.json.simple.JSONObject;
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 JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("hwid", (int) HWID);
return json;
}
public static RandomNumberGenerator deserialize(JSONObject hwJSON) {
return new RandomNumberGenerator();
}
}

View File

@@ -1,30 +0,0 @@
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

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

View File

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

View File

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

View File

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

163
README.md
View File

@@ -1,11 +1,166 @@
# [Live demo](https://muchassemblyrequired.com)
### [Official website](https://muchassemblyrequired.com)
[![CodeFactor](https://www.codefactor.io/repository/github/simon987/much-assembly-required/badge)](https://www.codefactor.io/repository/github/simon987/much-assembly-required)
[![Build Status](https://ci.simon987.net/buildStatus/icon?job=Much-Assembly-Required)](https://ci.simon987.net/job/Much-Assembly-Required/)
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.
![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)
Wiki: [GitHub](https://github.com/simon987/Much-Assembly-Required/wiki)
Chat: [Slack](https://join.slack.com/t/muchassemblyrequired/shared_invite/enQtMjY3Mjc1OTUwNjEwLWRjMjRkZTg2N2EyNWRjN2YyMDc0YzIyMTUyYzFiNTBmMTU3OGQ1ZjA0MWY0M2IyYjUxZTA4NjRkMWVkNDk2NzY)
# Deploying the server
## Linux
**Installing tools**
On Ubuntu 16.04:
```bash
sudo apt install git maven openjdk-8-jdk mongodb
sudo npm install -g typescript
```
On Arch:
``` bash
sudo pacman -S git maven mongodb jdk8-opendjk
sudo npm install -g typescript
# Don't forget to start mongodb
sudo systemctl start mongodb.service
```
*If needed, visit [troubleshooting mongodb](https://wiki.archlinux.org/index.php/MongoDB#Troubleshooting).*
**Deploying server**
``` bash
# 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 muchassemblyrequired-*.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 muchassemblyrequired-*.jar
```
## macOS (tested on Sierra 10.12.6)
**Installation**
1. Install [Maven3](https://maven.apache.org/)
-Add Maven bin to your path
```bash
export PATH=/path/to/maven/bin.:$PATH
```
2. Install [MongoDB](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/?_ga=2.201359831.774868398.1539369140-197602459.1539369140).
-Via Brew:
```bash
#Update brew
brew update
#Install mongodb
brew install mongodb
#Install latest development release
brew install mongodb --devel
```
-Via .tar.gz
```bash
#Extract files:
tar -zxvf mongodb-osx-ssl-x86_64-4.0.3.tgz
#Ensure binaries are in your path
export PATH=<mongodb-install-directory>/bin:$PATH
```
If you do not wish to use the default data directory (/data/db), follow the steps for running MongoDB in the install doc.
**Deploying Server**
1. Begin MongoDB service
```bash
#If brew:
#Launch on login
brew services start mongodb
#Or, if you don't want/need a background service you can just run:
mongod --config /usr/local/etc/mongod.conf
#If binary:
mongod
#Optional, set data directory path:
mongod --dbpath <path to data directory>
```
2. Deploy server:
```bash
# 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 muchassemblyrequired-*.jar
```
## 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`
Make sure to change `mongo_address` in `config.properties` to `mongodb`.
_Building instructions coming soon_
# Running
Once the server is running, you should be able to connect to `http://localhost:4567` with your browser
## 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

View File

@@ -1,179 +0,0 @@
package net.simon987.server;
import net.simon987.server.event.GameEventDispatcher;
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.plugin.ServerPlugin;
import net.simon987.server.user.User;
import net.simon987.server.webserver.SocketServer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
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;
public GameServer() {
this.config = new ServerConfiguration(new File("config.properties"));
gameUniverse = new GameUniverse(config);
pluginManager = new PluginManager();
//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);
}
}
} else {
if(!pluginDir.mkdir()) {
LogManager.LOGGER.severe("Couldn't create plugin directory");
}
}
eventDispatcher = new GameEventDispatcher(pluginManager);
}
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();
//Process user code
ArrayList<User> users_ = gameUniverse.getUsers();
for (User user : users_) {
if(user.getCpu() != null){
try {
user.getCpu().reset();
user.getCpu().execute();
} catch (Exception e) {
LogManager.LOGGER.severe("Error executing " + user.getUsername() + "'s code");
e.printStackTrace();
}
}
}
//Process each worlds
//Avoid concurrent modification
ArrayList<World> worlds = new ArrayList<>(gameUniverse.getWorlds());
for (World world : worlds) {
world.update();
}
//Save
if (gameUniverse.getTime() % config.getInt("save_interval") == 0) {
save(new File("save.json"));
}
socketServer.tick();
LogManager.LOGGER.info("Processed " + gameUniverse.getWorlds().size() + " worlds");
}
/**
* Save game universe to file in JSON format
* @param file JSON file to save
*/
public void save(File file){
try {
FileWriter fileWriter = new FileWriter(file);
JSONObject universe = gameUniverse.serialise();
JSONArray plugins = new JSONArray();
for(ServerPlugin plugin : pluginManager.getPlugins()){
plugins.add(plugin.serialise());
}
universe.put("plugins", plugins);
fileWriter.write(universe.toJSONString());
fileWriter.close();
LogManager.LOGGER.info("Saved to file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
public ServerConfiguration getConfig() {
return config;
}
public PluginManager getPluginManager() {
return pluginManager;
}
public void setSocketServer(SocketServer socketServer) {
this.socketServer = socketServer;
}
}

View File

@@ -1,28 +0,0 @@
package net.simon987.server;
import net.simon987.server.logging.LogManager;
import net.simon987.server.webserver.SocketServer;
import java.io.File;
import java.net.InetSocketAddress;
public class Main {
public static void main(String[] args){
LogManager.initialize();
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
//Load
GameServer.INSTANCE.getGameUniverse().load(new File("save.json"));
SocketServer socketServer = new SocketServer(new InetSocketAddress(config.getString("webSocket_host"),
config.getInt("webSocket_port")), config);
GameServer.INSTANCE.setSocketServer(socketServer);
(new Thread(socketServer)).start();
(new Thread(GameServer.INSTANCE)).start();
}
}

View File

@@ -1,42 +0,0 @@
package net.simon987.server;
import net.simon987.server.logging.LogManager;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
/**
* Wrapper for Java Property
*/
public class ServerConfiguration {
/**
* Properties
*/
private Properties properties;
public ServerConfiguration(File file) {
try {
properties = new Properties();
properties.load(new FileInputStream(file));
} catch (IOException e) {
LogManager.LOGGER.severe("Problem loading server configuration: " + e.getMessage());
}
}
public int getInt(String key) {
return Integer.valueOf((String) properties.get(key));
}
public String getString(String key) {
return (String) properties.get(key);
}
}

View File

@@ -1,99 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.AssemblyException;
import net.simon987.server.assembly.exception.DuplicateSegmentException;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Result of an assembly attempt
*/
public class AssemblyResult {
/**
* The origin of the program, default is 0x400
*/
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
*/
ArrayList<AssemblyException> exceptions = new ArrayList<>(50);
/**
* Offset of the code segment
*/
private int codeSegmentOffset;
/**
* Line of the code segment definition (for editor icons)
*/
private int codeSegmentLine;
/**
* 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, default is 0x4000
*/
private int dataSegmentOffset;
/**
* Line of the data segment definition (for editor icons)
*/
private int dataSegmentLine;
/**
* Whether or not the code segment is set
*/
private boolean codeSegmentSet = false;
/**
* Whether or not the data segment is set
*/
private boolean dataSegmentSet = false;
AssemblyResult(ServerConfiguration config) {
origin = config.getInt("org_offset");
}
/**
* Define a segment.
*
* @param segment Segment to define
* @param currentOffset Current offset, in bytes of the segment
* @param currentLine Line number of the segment declaration
* @throws DuplicateSegmentException when a segment is defined twice
*/
void defineSegment(Segment segment, int currentLine, int currentOffset) throws DuplicateSegmentException {
if (segment == Segment.TEXT) {
//Code segment
if (!codeSegmentSet) {
codeSegmentOffset = origin + currentOffset;
codeSegmentLine = currentLine;
codeSegmentSet = true;
} else {
throw new DuplicateSegmentException(currentLine);
}
} else {
//Data segment
if (!dataSegmentSet) {
dataSegmentOffset = origin + currentOffset;
dataSegmentLine = currentLine;
dataSegmentSet = true;
} else {
throw new DuplicateSegmentException(currentLine);
}
}
}
}

View File

@@ -1,458 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.assembly.instruction.*;
import net.simon987.server.event.CpuInitialisationEvent;
import net.simon987.server.event.GameEvent;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* CPU: Central Processing Unit. A CPU is capable of reading bytes from
* a Memory object and execute them. A CPU object holds registers objects &
* a Memory object.
*/
public class CPU implements JSONSerialisable{
/**
*
*/
private Status status;
/**
* Memory associated with the CPU, 64kb max
*/
private Memory memory;
/**
* set of instructions of this CPU
*/
private InstructionSet instructionSet;
/**
* set of registers of this CPU
*/
private RegisterSet registerSet;
/**
* Offset of the code segment. The code starts to get
* executed at this address each tick. Defaults to 0x4000
*/
private int codeSegmentOffset;
/**
* Instruction pointer, always points to the next instruction
*/
private int ip;
/**
* List of attached hardware, 'modules'
*/
private HashMap<Integer, CpuHardware> attachedHardware;
private ServerConfiguration config;
private long timeout;
private int registerSetSize;
/**
* Creates a new CPU
*/
public CPU(ServerConfiguration config, User user) throws CancelledException{
this.config = config;
instructionSet = new DefaultInstructionSet();
registerSet = new DefaultRegisterSet();
attachedHardware = new HashMap<>();
codeSegmentOffset = config.getInt("org_offset");
timeout = config.getInt("user_timeout");
instructionSet.add(new JmpInstruction(this));
instructionSet.add(new JnzInstruction(this));
instructionSet.add(new JzInstruction(this));
instructionSet.add(new JgInstruction(this));
instructionSet.add(new JgeInstruction(this));
instructionSet.add(new JleInstruction(this));
instructionSet.add(new JlInstruction(this));
instructionSet.add(new PushInstruction(this));
instructionSet.add(new PopInstruction(this));
instructionSet.add(new CallInstruction(this));
instructionSet.add(new RetInstruction(this));
instructionSet.add(new MulInstruction(this));
instructionSet.add(new DivInstruction(this));
instructionSet.add(new JnsInstruction(this));
instructionSet.add(new JsInstruction(this));
instructionSet.add(new HwiInstruction(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));
status = new Status();
memory = new Memory(config.getInt("memory_size"));
GameEvent event = new CpuInitialisationEvent(this, user);
GameServer.INSTANCE.getEventDispatcher().dispatch(event);
if(event.isCancelled()){
throw new CancelledException();
}
}
public void reset() {
status.clear();
registerSet.getRegister("SP").setValue(config.getInt("stack_bottom"));
registerSet.getRegister("BP").setValue(config.getInt("stack_bottom"));
ip = codeSegmentOffset;
}
public void execute() {
long startTime = System.currentTimeMillis();
int counter = 0;
status.clear();
registerSetSize = registerSet.size();
// status.breakFlag = true;
while (!status.isBreakFlag()) {
counter++;
if(counter % 1000 == 0){
if (System.currentTimeMillis() >= (startTime + timeout)) {
LogManager.LOGGER.fine("CPU Timeout " + this + " after " + counter + "instructions (" + timeout + "ms): " + (double) counter / ((double) timeout / 1000) / 1000000 + "MHz");
return;
}
}
//fetch instruction
int machineCode = memory.get(ip);
/*
* Contents of machineCode should look like this:
* SSSS SDDD DDOO OOOO
* Where S is source, D is destination and O is the opCode
*/
Instruction instruction = instructionSet.get(machineCode & 0x03F); // 0000 0000 00XX XXXX
int source = (machineCode >> 11) & 0x001F; // XXXX X000 0000 0000
int destination = (machineCode >> 6) & 0x001F; // 0000 0XXX XX00 0000
executeInstruction(instruction, source, destination);
// LogManager.LOGGER.info(instruction.getMnemonic());
}
double elapsed = (System.currentTimeMillis() - startTime);
LogManager.LOGGER.fine(counter + " instruction in " + elapsed + "ms : " + (double) counter / (elapsed / 1000) / 1000000 + "MHz");
}
public void executeInstruction(Instruction instruction, int source, int destination) {
//Execute the instruction
if (source == 0) {
//No operand (assuming that destination is also null)
ip++;
instruction.execute(status);
} else if (source == Operand.IMMEDIATE_VALUE) {
ip++;
int sourceValue = memory.get(ip);
if (destination == 0) {
//Single operand
ip++;
instruction.execute(sourceValue, status);
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value too
//this shouldn't happen
LogManager.LOGGER.severe("Trying to execute an instruction with 2" +
"immediate values as operands"); //todo remove debug info
} else if (destination == Operand.IMMEDIATE_VALUE_MEM) {
//Destination is memory immediate
ip += 2;
instruction.execute(memory, memory.get(ip - 1), sourceValue, status);
} else if (destination <= registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, sourceValue, status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), sourceValue, status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
instruction.execute(memory, registerSet.get(destination - registerSetSize - registerSetSize) + memory.get(ip - 1),
sourceValue, status);
}
} else if (source == Operand.IMMEDIATE_VALUE_MEM) {
//Source is [x]
ip++;
int sourceValue = memory.get(memory.get(ip));
if (destination == 0) {
//Single operand
ip++;
instruction.execute(sourceValue, status);
instruction.execute(memory, memory.get(ip - 1), status); //For POP instruction
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value
//this shouldn't happen
LogManager.LOGGER.severe("Trying to execute an instruction with an" +
"immediate values as dst operand"); //todo remove debug info
} else if (destination == Operand.IMMEDIATE_VALUE_MEM) {
//Destination is memory immediate too
ip += 2;
instruction.execute(memory, memory.get(ip - 1), sourceValue, status);
} else if (destination <= registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, sourceValue, status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), memory, sourceValue, status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
instruction.execute(memory, registerSet.get(destination - registerSetSize - registerSetSize) + memory.get(ip - 1), sourceValue, status);
}
} else if (source <= registerSetSize) {
//Source is a register
if (destination == 0) {
//Single operand
ip++;
instruction.execute(registerSet, source, status);
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value
//this shouldn't happen
LogManager.LOGGER.severe("Trying to execute an instruction with an" +
"immediate values as dst operand"); //todo remove debug info
} else if (destination == Operand.IMMEDIATE_VALUE_MEM) {
//Destination is memory immediate
ip += 2;
instruction.execute(memory, memory.get(ip - 1), registerSet, source, status);
} else if (destination <= registerSetSize) {
//Destination is a register too
ip++;
instruction.execute(registerSet, destination, registerSet, source, status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), registerSet, source, status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
instruction.execute(memory, registerSet.get(destination - registerSetSize - registerSetSize) + memory.get(ip - 1),
registerSet, source, status);
}
} else if (source <= registerSetSize * 2) {
//Source is [reg]
if (destination == 0) {
//Single operand
ip++;
instruction.execute(memory, registerSet.get(source), status);
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value
//this shouldn't happen
LogManager.LOGGER.severe("Trying to execute an instruction with an" +
"immediate values as dst operand"); //todo remove debug info
} else if (destination == Operand.IMMEDIATE_VALUE_MEM) {
//Destination is an memory immediate
ip++;
instruction.execute(memory, memory.get(ip++), memory, registerSet.get(source - registerSetSize), status);
} else if (destination <= registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, memory, registerSet.get(source), status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), memory, registerSet.get(source), status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
instruction.execute(memory, registerSet.get(destination - registerSetSize - registerSetSize) + memory.get(ip - 1),
memory, registerSet.get(source - registerSetSize), status);
}
} else {
//Assuming that source is [reg + X]
ip++;
int sourceDisp = memory.get(ip);
if (destination == 0) {
//Single operand
ip += 1;
instruction.execute(memory, registerSet.get(source - registerSetSize - registerSetSize) + memory.get(ip - 1), status);
} else if (destination == Operand.IMMEDIATE_VALUE) {
//Destination is an immediate value
//this shouldn't happen
LogManager.LOGGER.severe("Trying to execute an instruction with an" +
"immediate values as dst operand"); //todo remove debug info
} else if (destination == Operand.IMMEDIATE_VALUE_MEM) {
//Destination is memory immediate
ip += 2;
instruction.execute(memory, memory.get(ip - 1), memory,
registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
} else if (destination < registerSetSize) {
//Destination is a register
ip++;
instruction.execute(registerSet, destination, memory,
registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
} else if (destination <= registerSetSize * 2) {
//Destination is [reg]
ip++;
instruction.execute(memory, registerSet.get(destination - registerSetSize), memory,
registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
} else {
//Assuming that destination is [reg + x]
ip += 2;
instruction.execute(memory, registerSet.get(destination - registerSetSize - registerSetSize) + memory.get(ip - 1),
memory, registerSet.get(source - registerSetSize - registerSetSize) + sourceDisp, status);
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("memory", memory.serialise());
json.put("registerSet", registerSet.serialise());
json.put("codeSegmentOffset", codeSegmentOffset);
JSONArray hardwareList = new JSONArray();
for(Integer address : attachedHardware.keySet()){
CpuHardware hardware = attachedHardware.get(address);
JSONObject serialisedHw = hardware.serialise();
serialisedHw.put("address", address);
hardwareList.add(serialisedHw);
}
json.put("hardware", hardwareList);
return json;
}
public static CPU deserialize(JSONObject json, User user) throws CancelledException {
CPU cpu = new CPU(GameServer.INSTANCE.getConfig(), user);
cpu.codeSegmentOffset = (int)(long)json.get("codeSegmentOffset");
JSONArray hardwareList = (JSONArray)json.get("hardware");
for(JSONObject serialisedHw : (ArrayList<JSONObject>)hardwareList){
CpuHardware hw = CpuHardware.deserialize(serialisedHw);
hw.setCpu(cpu);
cpu.attachHardware(hw, (int)(long)serialisedHw.get("address"));
}
cpu.memory = Memory.deserialize((JSONObject)json.get("memory"));
cpu.registerSet = RegisterSet.deserialize((JSONObject) json.get("registerSet"));
return cpu;
}
public InstructionSet getInstructionSet() {
return instructionSet;
}
public RegisterSet getRegisterSet() {
return registerSet;
}
public Memory getMemory() {
return memory;
}
public Status getStatus() {
return status;
}
public int getIp() {
return ip;
}
public void setIp(char ip) {
this.ip = ip;
}
public void setCodeSegmentOffset(int codeSegmentOffset) {
this.codeSegmentOffset = codeSegmentOffset;
}
public void attachHardware(CpuHardware hardware, int address){
attachedHardware.put(address, hardware);
}
public void detachHardware(int address){
attachedHardware.remove(address);
}
public boolean hardwareInterrupt(int address){
CpuHardware hardware = attachedHardware.get(address);
if(hardware != null){
hardware.handleInterrupt(status);
return true;
} else {
return false;
}
}
public void hardwareQuery(int address) {
CpuHardware hardware = attachedHardware.get(address);
if (hardware != null) {
registerSet.getRegister("B").setValue(hardware.getId());
} else {
registerSet.getRegister("B").setValue(0);
}
}
@Override
public String toString() {
String str = "------------------------\n";
str += registerSet.toString();
str += status.toString();
str += "------------------------\n";
return str;
}
public CpuHardware getHardware(int address) {
return attachedHardware.get(address);
}
}

View File

@@ -1,45 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.GameServer;
import net.simon987.server.io.CpuHardwareDeserializer;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
public abstract class CpuHardware implements JSONSerialisable {
CPU cpu;
/**
* Handle an HWI instruction
*/
public abstract void handleInterrupt(Status status);
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public abstract char getId();
public static CpuHardware deserialize(JSONObject hwJson){
for(ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()){
if(plugin instanceof CpuHardwareDeserializer){
CpuHardware hw = ((CpuHardwareDeserializer) plugin).deserializeHardware(hwJson);
if(hw != null){
return hw;
}
}
}
return null;
}
}

View File

@@ -1,22 +0,0 @@
package net.simon987.server.assembly;
/**
* RegisterSet with default values
*/
class DefaultRegisterSet extends RegisterSet {
DefaultRegisterSet() {
super();
addRegister(1, new Register("A"));
addRegister(2, new Register("B"));
addRegister(3, new Register("C"));
addRegister(4, new Register("D"));
addRegister(5, new Register("X"));
addRegister(6, new Register("Y"));
addRegister(7, new Register("SP"));
addRegister(8, new Register("BP"));
}
}

View File

@@ -1,152 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.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, JSONSerialisable {
/**
* Contents of the memory
*/
private byte[] bytes;
/**
* Create an empty Memory object
*
* @param size Size of the memory, in words
*/
public Memory(int size) {
bytes = new byte[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 * 2; //Because our Memory is only divisible by 16bits
if (address < 0 || address + 2 > bytes.length) {
LogManager.LOGGER.info("DEBUG: Trying to get memory out of bounds " + address);
return 0;
}
return (((bytes[address] & 0xFF) << 8) | (bytes[address + 1] & 0xFF));
}
/**
* Write x words from an array at an offset
*/
public boolean write(int offset, byte[] bytes, int srcOffset, int count) {
offset = (char)offset * 2;
if (offset + count > this.bytes.length || count < 0 || offset < 0 || srcOffset >= bytes.length) {
return false;
}
System.arraycopy(bytes, srcOffset, this.bytes, 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 * 2;
if (address < 0 || address + 2 > bytes.length) {
LogManager.LOGGER.info("DEBUG: Trying to set memory out of bounds: " + address);
return;
}
bytes[address] = (byte) ((value >> 8) & 0xFF);
bytes[address + 1] = (byte) (value & 0xFF);
}
/**
* Fill the memory with 0s
*/
public void clear() {
Arrays.fill(bytes, (byte) 0);
}
/**
* Get byte array of the Memory object
*/
public byte[] getBytes() {
return bytes;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
deflaterOutputStream.write(bytes);
deflaterOutputStream.close();
byte[] compressedBytes = stream.toByteArray();
json.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes)));
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
public static Memory deserialize(JSONObject json){
Memory memory = new Memory(0);
byte[] compressedBytes = Base64.getDecoder().decode((String)json.get("zipBytes"));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
memory.bytes = baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return memory;
}
public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
}

View File

@@ -1,191 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A set of registers for a CPU
*/
public class RegisterSet implements Target, JSONSerialisable {
/**
* List of registers
*/
private HashMap<Integer, Register> registers = new HashMap<>(8);
/**
* Create an empty Register set
*/
public RegisterSet() {
}
/**
* Get the index of a Register by its name
* This method assumes that the
*
* @param name Name of the register
* @return index of the register, -1 if not found
*/
int getIndex(String name) {
name = name.toUpperCase();
for (Integer i : registers.keySet()) {
if (registers.get(i).getName().equals(name)) {
return i;
}
}
return -1;
}
/**
* Get a register by its index
*
* @param index index of the register
*/
public Register getRegister(int index) {
return registers.get(index);
}
/**
* Get a register by its name (e.g. "AX")
*
* @param name Name of the register, case insensitive
*/
public Register getRegister(String name) {
name = name.toUpperCase();
for (Register r : registers.values()) {
if (r.getName().equals(name)) {
return r;
}
}
return null;
}
/**
* Get the value of a register
*
* @param address Address of the value. Can refer to a memory address or the index
* of a register
* @return 16-bit value of a register
*/
@Override
public int get(int address) {
Register register = registers.get(address);
if(register != null){
return register.getValue();
} else {
return 0;
}
}
/**
* Set the value of a register
*
* @param address index of the value to change
* @param value value to set
*/
@Override
public void set(int address, int value) {
Register register = registers.get(address);
if(register != null){
register.setValue(value);
} else {
LogManager.LOGGER.info("DEBUG: trying to set unknown reg index : " + address);
}
}
public void put(int index, Register register) {
registers.put(index, register);
}
public void clear() {
for (Register register : registers.values()) {
register.setValue(0);
}
}
/**
* Add a register to the register set
* <p>
* the register set will break if the indexes of the registers
* are not consecutive, starting at address 1.
*
* @param index Index of the register
* @param reg Register to add
*/
void addRegister(int index, Register reg) {
registers.put(index, reg);
}
int size() {
return registers.size();
}
@Override
public JSONObject serialise() {
JSONArray registers = new JSONArray();
for(Integer index : this.registers.keySet()){
JSONObject register = new JSONObject();
register.put("index", index);
register.put("name", getRegister(index).getName());
register.put("value", (int) getRegister(index).getValue());
registers.add(register);
}
JSONObject json = new JSONObject();
json.put("registers", registers);
return json;
}
public static RegisterSet deserialize(JSONObject json) {
RegisterSet registerSet = new RegisterSet();
JSONArray registers = (JSONArray)json.get("registers");
for(JSONObject jsonRegister : (ArrayList<JSONObject>)registers){
Register register = new Register((String)jsonRegister.get("name"));
register.setValue((int)(long)jsonRegister.get("value"));
registerSet.registers.put((int)(long)jsonRegister.get("index"), register);
}
return registerSet;
}
@Override
public String toString() {
String str = "";
for(Integer index: registers.keySet()){
str += index + " " + registers.get(index).getName() + "=" + Util.toHex(registers.get(index).getValue()) + "\n";
}
return str;
}
}

View File

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

View File

@@ -1,66 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.Instruction;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Target;
/**
* Divide instruction.
* <p>
* DIV C
* A = Y:A / C
* Y = Y:A % C
* </p>
*/
public class DivInstruction extends Instruction {
public static final int OPCODE = 24;
private CPU cpu;
public DivInstruction(CPU cpu) {
super("div", OPCODE);
this.cpu = cpu;
}
@Override
public Status execute(Target src, int srcIndex, Status status) {
//Source = Y:A
int source = ((((char)cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char)cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
if (src.get(srcIndex) == 0) {
//Division by 0
status.setBreakFlag(true);
status.setErrorFlag(true);
} else {
cpu.getRegisterSet().getRegister("A").setValue((char)(source / (char)src.get(srcIndex)));
cpu.getRegisterSet().getRegister("Y").setValue((char)(source % (char)src.get(srcIndex)));
}
return status;
}
@Override
public Status execute(int src, Status status) {
//Source = Y:A
int source = ((((char)cpu.getRegisterSet().getRegister("Y").getValue() & 0xFFFF) << 16)) |
((char)cpu.getRegisterSet().getRegister("A").getValue() & 0xFFFF);
if (src == 0) {
//Division by 0
status.setBreakFlag(true);
status.setErrorFlag(true);
} else {
cpu.getRegisterSet().getRegister("A").setValue((char)(source / (char)src));
cpu.getRegisterSet().getRegister("Y").setValue((char)(source % (char)src));
}
return status;
}
}

View File

@@ -1,40 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.Instruction;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Target;
/**
* Send hardware interupt
* Used to interact with the World using hardware
* </p>
*/
public class HwiInstruction extends Instruction {
public static final int OPCODE = 9;
private CPU cpu;
public HwiInstruction(CPU cpu) {
super("hwi", OPCODE);
this.cpu = cpu;
}
@Override
public Status execute(Target src, int srcIndex, Status status) {
status.setErrorFlag(cpu.hardwareInterrupt(src.get(srcIndex)));
return status;
}
@Override
public Status execute(int src, Status status) {
status.setErrorFlag(cpu.hardwareInterrupt(src));
return status;
}
}

View File

@@ -1,21 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.assembly.Instruction;
import net.simon987.server.assembly.Status;
import net.simon987.server.assembly.Target;
public class NegInstruction extends Instruction {
public static final int OPCODE = 25;
public NegInstruction() {
super("neg", OPCODE);
}
@Override
public Status execute(Target dst, int dstIndex, Status status) {
dst.set(dstIndex, -dst.get(dstIndex));
return status;
}
}

View File

@@ -1,14 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.assembly.Instruction;
/**
* NOP (No operation instruction).
* Does nothing
*/
public class NopInstruction extends Instruction {
public NopInstruction() {
super("nop", 63);
}
}

View File

@@ -1,13 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.assembly.Instruction;
/**
* Alias of SHL instruction
*/
public class SalInstruction extends Instruction {
public SalInstruction() {
super("sal", ShlInstruction.OPCODE);
}
}

View File

@@ -1,18 +0,0 @@
package net.simon987.server.event;
import net.simon987.server.assembly.CPU;
import net.simon987.server.user.User;
public class CpuInitialisationEvent extends GameEvent{
private User user;
public CpuInitialisationEvent(CPU cpu, User user) {
setSource(cpu);
this.user = user;
}
public User getUser() {
return user;
}
}

View File

@@ -1,26 +0,0 @@
package net.simon987.server.event;
import net.simon987.server.plugin.PluginManager;
import net.simon987.server.plugin.ServerPlugin;
public class GameEventDispatcher {
private PluginManager pluginManager;
public GameEventDispatcher(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
public void dispatch(GameEvent event){
for(ServerPlugin plugin: pluginManager.getPlugins()){
for(GameEventListener listener : plugin.getListeners()){
if(event.getClass().equals(listener.getListenedEventType())){
listener.handle(event);
}
}
}
}
}

View File

@@ -1,15 +0,0 @@
package net.simon987.server.event;
import net.simon987.server.game.World;
public class WorldGenerationEvent extends GameEvent {
public WorldGenerationEvent(World world) {
setSource(world);
}
public World getWorld(){
return (World)getSource();
}
}

View File

@@ -1,20 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.assembly.Memory;
import net.simon987.server.user.User;
import java.util.ArrayList;
public interface ControllableUnit {
int getObjectId();
void setKeyboardBuffer(ArrayList<Integer> kbBuffer);
void setParent(User user);
ArrayList<Integer> getKeyboardBuffer();
Memory getFloppyData();
}

View File

@@ -1,39 +0,0 @@
package net.simon987.server.game;
/**
* Direction of a game object in a 4-direction grid-based
* area
*/
public enum Direction {
/**
* North, up
*/
NORTH,
/**
* East, right
*/
EAST,
/**
* South, bottom
*/
SOUTH,
/**
* West, left
*/
WEST;
public static Direction getDirection(int x) {
switch (x) {
case 0:
return NORTH;
case 1:
return EAST;
case 2:
return SOUTH;
case 3:
return WEST;
default:
return null;
}
}
}

View File

@@ -1,26 +0,0 @@
package net.simon987.server.game;
/**
* Types of GameEffects
*/
public enum EffectType {
/**
* Warning icon
*/
WARNING,
/**
* Error icon
*/
ERROR,
/**
* Dig particle effect
*/
DIG,
/**
* 'A' Icon
*/
A_EMOTE
}

View File

@@ -1,64 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
/**
* Represents a game effect in a World (e.g. Particles made when digging, Error animation, Attack effects etc..)
* <br>
* These effects are purely visual and could be changed or ignored by the client
*/
public class GameEffect implements JSONSerialisable{
/**
* Type of the effect
*/
private EffectType type;
private int x;
private int y;
public GameEffect(EffectType type, int x, int y) {
this.type = type;
this.x = x;
this.y = y;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("x", x);
json.put("y", y);
json.put("type", type);
return json;
}
public EffectType getType() {
return type;
}
public void setType(EffectType type) {
this.type = type;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}

View File

@@ -1,246 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.GameServer;
import net.simon987.server.io.GameObjectDeserializer;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.plugin.ServerPlugin;
import org.json.simple.JSONObject;
import java.awt.*;
/**
* An INSTANCE of an object (e.g. a Tree, a character ...) inside the
* game universe
*/
public abstract class GameObject implements JSONSerialisable {
private boolean dead;
/**
* Object's unique identifier
*/
private int objectId;
/**
* X coordinate of the object in its World
*/
private int x;
/**
* Y coordinate of the object in its World
*/
private int y;
/**
* Direction of the object
*/
private Direction direction = Direction.NORTH;
/**
* Current World of the object
*/
private World world;
//--------
/**
* Increment the location of the game object by 1 tile
* Collision checks happen here
*/
public boolean incrementLocation() {
int newX = 0, newY = 0;
if (direction == Direction.NORTH) {
newX = x;
newY = (y - 1);
} else if (direction == Direction.EAST) {
newX = (x + 1);
newY = y;
} else if (direction == Direction.SOUTH) {
newX = x;
newY = (y + 1);
} else if (direction == Direction.WEST) {
newX = (x - 1);
newY = y;
}
//Check if out of World bounds / collision
if(newX < 0) {
//Move object to adjacent World (left)
World leftWorld;
if (world.getX() == 0) {
//Warp around
leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld(
GameServer.INSTANCE.getGameUniverse().getMaxWidth(), world.getY());
} else {
leftWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() - 1, world.getY());
}
if(leftWorld != null){
world.getGameObjects().remove(this);
leftWorld.getGameObjects().add(this);
setWorld(leftWorld);
x = World.WORLD_SIZE - 1;
}
} else if(newX >= World.WORLD_SIZE) {
//Move object to adjacent World (right)
World rightWorld;
if (world.getX() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) {
//Warp around
rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(0, world.getY());
} else {
rightWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX() + 1, world.getY());
}
if(rightWorld != null){
world.getGameObjects().remove(this);
rightWorld.getGameObjects().add(this);
setWorld(rightWorld);
x = 0;
}
} else if (newY < 0) {
//Move object to adjacent World (up)
World upWorld;
if (world.getY() == 0) {
//Warp around
upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(),
GameServer.INSTANCE.getGameUniverse().getMaxWidth());
} else {
upWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() - 1);
}
if(upWorld != null){
world.getGameObjects().remove(this);
upWorld.getGameObjects().add(this);
setWorld(upWorld);
y = World.WORLD_SIZE - 1;
}
} else if (newY >= World.WORLD_SIZE) {
//Move object to adjacent World (down)
World downWorld;
if (world.getY() == GameServer.INSTANCE.getGameUniverse().getMaxWidth()) {
//Warp around
downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), 0);
} else {
downWorld = GameServer.INSTANCE.getGameUniverse().getWorld(world.getX(), world.getY() + 1);
}
if (downWorld != null) {
world.getGameObjects().remove(this);
downWorld.getGameObjects().add(this);
setWorld(downWorld);
y = 0;
}
}
//Check collision
else if (!world.isTileBlocked(newX, newY)) {
//Tile is passable
x = newX;
y = newY;
} else {
return false;
}
return true;
}
public abstract char getMapInfo();
public Point getFrontTile() {
if (direction == Direction.NORTH) {
return new Point(x, y - 1);
} else if (direction == Direction.EAST) {
return new Point(x + 1, y);
} else if (direction == Direction.SOUTH) {
return new Point(x, y + 1);
} else {
return new Point(x - 1, y);
}
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction direction) {
this.direction = direction;
}
public World getWorld() {
return world;
}
public void setWorld(World world) {
this.world = world;
}
@Override
public JSONObject serialise() {
return new JSONObject();
}
public static GameObject deserialize(JSONObject objJson) {
for(ServerPlugin plugin : GameServer.INSTANCE.getPluginManager().getPlugins()){
if(plugin instanceof GameObjectDeserializer){
GameObject object = ((GameObjectDeserializer) plugin).deserializeObject(objJson);
if(object != null){
return object;
}
}
}
return null;
}
public boolean isAt(int x, int y) {
return this.x == x && this.y == y;
}
public boolean isDead() {
return dead;
}
public void setDead(boolean dead) {
this.dead = dead;
}
}

View File

@@ -1,270 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.Assembler;
import net.simon987.server.assembly.AssemblyResult;
import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class GameUniverse implements JSONSerialisable{
private ArrayList<World> worlds;
private ArrayList<User> users;
private WorldGenerator worldGenerator;
private long time;
private int nextObjectId = 0;
private int maxWidth = 0xFFFF;
public GameUniverse(ServerConfiguration config) {
worlds = new ArrayList<>(32);
users = new ArrayList<>(16);
worldGenerator = new WorldGenerator(config);
}
public long getTime() {
return time;
}
public World getWorld(int x, int y) {
for (World world : worlds) {
if (world.getX() == x && world.getY() == y) {
return world;
}
}
if (x >= 0 && x <= maxWidth && y >= 0 && y <= maxWidth) {
//World does not exist
LogManager.LOGGER.severe("Trying to read a World that does not exist!");
World world = createWorld(x, y);
worlds.add(world);
return world;
} else {
return null;
}
}
public World createWorld(int x, int y) {
World world = null;
try {
world = worldGenerator.generateWorld(x, y);
} catch (CancelledException e) {
e.printStackTrace();
}
return world;
}
public User getUser(String username) {
for (User user : users) {
if (user.getUsername().equals(username)) {
return user;
}
}
return null;
}
public User getOrCreateUser(String username, boolean makeControlledUnit){
User user = getUser(username);
if(user != null) {
return user;
} else {
LogManager.LOGGER.info("Creating new User: " + username);
try {
if(makeControlledUnit) {
user = new User();
user.setCpu(new CPU(GameServer.INSTANCE.getConfig(), user));
user.setUserCode(GameServer.INSTANCE.getConfig().getString("new_user_code"));
//Compile user code
AssemblyResult ar = new Assembler(user.getCpu().getInstructionSet(), user.getCpu().getRegisterSet(),
GameServer.INSTANCE.getConfig()).parse(user.getUserCode());
user.getCpu().getMemory().clear();
//Write assembled code to mem
user.getCpu().getMemory().write((short) ar.origin, ar.bytes, 0, ar.bytes.length);
user.getCpu().setCodeSegmentOffset(ar.origin);
//Init
} else {
user = new User(null);
}
user.setUsername(username);
users.add(user);
return user;
} catch (CancelledException e) {
e.printStackTrace();
return null;
}
}
}
/**
* Get an object by id
* <br>
* ConcurrentModificationException risk when inside game loop
*
* @param id id of the game object
* @return GameObject, null if not found
*/
public GameObject getObject(int id) {
//
for (World world : worlds) {
for(GameObject object : world.getGameObjects()){
if(object.getObjectId() == id){
return object;
}
}
}
return null;
}
public void incrementTime(){
time++;
}
public ArrayList<World> getWorlds() {
return worlds;
}
public ArrayList<User> getUsers() {
return users;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
JSONArray worlds = new JSONArray();
ArrayList<World> worlds_ = new ArrayList<>(this.worlds);
for (World world : worlds_){
worlds.add(world.serialise());
}
JSONArray users = new JSONArray();
ArrayList<User> users_ = new ArrayList<User>(this.users);
for (User user : users_){
if (!user.isGuest()) {
users.add(user.serialise());
}
}
json.put("users", users);
json.put("worlds", worlds);
json.put("time", time);
json.put("nextObjectId", nextObjectId);
return json;
}
/**
* Load game universe from JSON save file
* @param file JSON save file
*/
public void load(File file){
JSONParser parser = new JSONParser();
if (file.isFile()) {
try {
FileReader reader = new FileReader(file);
JSONObject universeJson = (JSONObject) parser.parse(reader);
time = (long) universeJson.get("time");
nextObjectId = (int) (long) universeJson.get("nextObjectId");
for (JSONObject worldJson : (ArrayList<JSONObject>) universeJson.get("worlds")) {
worlds.add(World.deserialize(worldJson));
}
for (JSONObject userJson : (ArrayList<JSONObject>) universeJson.get("users")) {
users.add(User.deserialize(userJson));
}
LogManager.LOGGER.info("Loaded " + worlds.size() + " worlds from file");
reader.close();
} catch (IOException | ParseException | CancelledException e) {
e.printStackTrace();
}
} else {
LogManager.LOGGER.severe("Couldn't load save file save.json, creating empty game universe.");
}
}
public int getNextObjectId() {
return ++nextObjectId;
}
public String getGuestUsername() {
int i = 1;
while (i < 1000) { //todo get Max guest user cap from config
if(getUser("guest" + String.valueOf(i)) != null) {
i++;
continue;
}
return "guest" + String.valueOf(i);
}
return null;
}
public void removeUser(User user) {
users.remove(user);
}
public int getMaxWidth() {
return maxWidth;
}
}

View File

@@ -1,24 +0,0 @@
package net.simon987.server.game;
public interface InventoryHolder {
/**
* Place an item into the inventory
*
* @param item item id (see MarConstants.ITEM_*)
*/
boolean placeItem(int item);
/**
* Take an item from the inventory
* @param item Desired item id (see MarConstants.ITEM_*)
*/
void takeItem(int item);
/**
* @param item item to take
* @return true if the InventoryHolder can provide this item
*/
boolean canTakeItem(int item);
}

View File

@@ -1,185 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Random;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
/**
* A 2D map of Tile objects of size width*height
*/
public class TileMap implements JSONSerialisable {
public static final int PLAIN_TILE = 0;
public static final int WALL_TILE = 1;
public static final int IRON_TILE = 2;
public static final int COPPER_TILE = 3;
public static final int ITEM_IRON = 3;
public static final int ITEM_COPPER = 4;
/**
* The map of tile
*/
private int[][] tiles;
/**
* width, in tiles
*/
private int width;
/**
* Height, in tiles
*/
private int height;
/**
* Create a blank (All 0s) map
*/
public TileMap(int width, int height) {
this.width = width;
this.height = height;
tiles = new int[width][height];
}
/**
* Change the tile at a specified position
* Sets the modified flag
*
* @param tileId id of the new Tile
* @param x X coordinate of the tile to set
* @param y Y coordinate of the tile to set
*/
public void setTileAt(int tileId, int x, int y) {
try {
tiles[x][y] = tileId;
} catch (ArrayIndexOutOfBoundsException e) {
//Shouldn't happen
e.printStackTrace();
}
}
/**
* Get the tile at a specific position
*
* @param x X coordinate of the tile to get
* @param y Y coordinate of the tile to get
* @return the tile at the specified position, -1 if out of bounds
*/
public int getTileAt(int x, int y) {
try {
return tiles[x][y];
} catch (ArrayIndexOutOfBoundsException e) {
return -1;
}
}
public int[][] getTiles() {
return tiles;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
byte[] terrain = new byte[width*width];
for (int x = 0; x < World.WORLD_SIZE; x++) {
for (int y = 0; y < World.WORLD_SIZE; y++) {
terrain[x * width + y] = (byte)tiles[x][y];
}
}
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
deflaterOutputStream.write(terrain);
deflaterOutputStream.close();
byte[] compressedBytes = stream.toByteArray();
json.put("zipTerrain", new String(Base64.getEncoder().encode(compressedBytes)));
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
public static TileMap deserialize(JSONObject object) {
TileMap tileMap = new TileMap(World.WORLD_SIZE, World.WORLD_SIZE);
byte[] compressedBytes = Base64.getDecoder().decode((String)object.get("zipTerrain"));
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Inflater decompressor = new Inflater(true);
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(baos, decompressor);
inflaterOutputStream.write(compressedBytes);
inflaterOutputStream.close();
byte[] terrain = baos.toByteArray();
for (int x = 0; x < World.WORLD_SIZE; x++) {
for (int y = 0; y < World.WORLD_SIZE; y++) {
tileMap.tiles[x][y] = terrain[x * World.WORLD_SIZE + y];
}
}
return tileMap;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Point getRandomPlainTile() {
Random random = new Random();
int counter = 0;
while (true) {
counter++;
//Prevent infinite loop
if (counter >= 2500) {
return null;
}
int rx = random.nextInt(World.WORLD_SIZE);
int ry = random.nextInt(World.WORLD_SIZE);
if (tiles[rx][ry] == TileMap.PLAIN_TILE) {
return new Point(rx, ry);
}
}
}
}

View File

@@ -1,234 +0,0 @@
package net.simon987.server.game;
import net.simon987.server.game.pathfinding.Pathfinder;
import net.simon987.server.io.JSONSerialisable;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.awt.*;
import java.util.ArrayList;
import java.util.Random;
public class World implements JSONSerialisable{
/**
* Size of the side of a world
*/
public static final int WORLD_SIZE = 16;
private static final char INFO_BLOCKED = 0x8000;
private static final char INFO_IRON = 0x0200;
private static final char INFO_COPPER = 0x0100;
private int x;
private int y;
private TileMap tileMap;
private ArrayList<GameObject> gameObjects = new ArrayList<>(16);
public World(int x, int y, TileMap tileMap) {
this.x = x;
this.y = y;
this.tileMap = tileMap;
}
private World(){
}
public TileMap getTileMap() {
return tileMap;
}
/**
* Check if a tile is blocked, either by a game object or an impassable tile type
*/
public boolean isTileBlocked(int x, int y) {
return getGameObjectsAt(x, y).size() > 0 || tileMap.getTileAt(x, y) == TileMap.WALL_TILE;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public ArrayList<GameObject> getGameObjects() {
return gameObjects;
}
public void update(){
ArrayList<GameObject> gameObjects_ = new ArrayList<>(gameObjects);
for(GameObject object : gameObjects_){
if(object.isDead()){
gameObjects.remove(object);
LogManager.LOGGER.fine("Removed object " + object + " id: " + object.getObjectId());
}
if (object instanceof Updatable) {
((Updatable) object).update();
}
}
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
JSONArray objects = new JSONArray();
ArrayList<GameObject> gameObjects_ = new ArrayList<>(gameObjects);
for (GameObject obj : gameObjects_) {
objects.add(obj.serialise());
}
json.put("objects", objects);
json.put("terrain", tileMap.serialise());
json.put("x", x);
json.put("y", y);
return json;
}
@Override
public String toString() {
String str = "World (" + x + ", " + y + ")\n";
int[][] tileMap = this.tileMap.getTiles();
for (int x = 0; x < WORLD_SIZE; x++) {
for (int y = 0; y < WORLD_SIZE; y++) {
str += tileMap[x][y] + " ";
}
str += "\n";
}
return str;
}
public static World deserialize(JSONObject json) {
World world = new World();
world.x = (int)(long)json.get("x");
world.y = (int)(long)json.get("y");
world.tileMap = TileMap.deserialize((JSONObject)json.get("terrain"));
for(JSONObject objJson : (ArrayList<JSONObject>)json.get("objects")){
GameObject object = GameObject.deserialize(objJson);
object.setWorld(world);
world.gameObjects.add(object);
}
return world;
}
/**
* Get a binary representation of the map as an array of 16-bit bit fields, one word for each
* tile.
* <p>
* todo Performance cache this?
*/
public char[][] getMapInfo() {
char[][] mapInfo = new char[World.WORLD_SIZE][World.WORLD_SIZE];
int[][] tiles = tileMap.getTiles();
//Tile
for (int y = 0; y < World.WORLD_SIZE; y++) {
for (int x = 0; x < World.WORLD_SIZE; x++) {
if (tiles[x][y] == TileMap.PLAIN_TILE) {
mapInfo[x][y] = 0;
} else if (tiles[x][y] == TileMap.WALL_TILE) {
mapInfo[x][y] = INFO_BLOCKED;
} else if (tiles[x][y] == TileMap.COPPER_TILE) {
mapInfo[x][y] = INFO_COPPER;
} else if (tiles[x][y] == TileMap.IRON_TILE) {
mapInfo[x][y] = INFO_IRON;
}
}
}
//Objects
for (GameObject obj : this.gameObjects) {
mapInfo[obj.getX()][obj.getY()] |= obj.getMapInfo();
}
return mapInfo;
}
/**
* Get a random tile that is empty and passable
* The function ensures that a object spawned there will not be trapped
* and will be able to leave the World
* <br>
* Note: This function is quite expensive and shouldn't be used
* by some CpuHardware in its current state
*
* @return random non-blocked tile
*/
public Point getRandomPassableTile(){
Random random = new Random();
int counter = 0;
while (true) {
counter++;
//Prevent infinite loop
if (counter >= 2500) {
return null;
}
int rx = random.nextInt(World.WORLD_SIZE);
int ry = random.nextInt(World.WORLD_SIZE);
if(!isTileBlocked(rx, ry)){
Object path = Pathfinder.findPath(this, rx, ry, 0, 6, 0);
if(path != null) {
return new Point(rx, ry);
}
}
}
}
/**
* Get the list of game objects at a location
*
* @param x X coordinate on the World
* @param y Y coordinate on the World
* @return the list of game objects at a location
*/
public ArrayList<GameObject> getGameObjectsAt(int x, int y) {
ArrayList<GameObject> gameObjects = new ArrayList<>(2);
for (GameObject obj : this.gameObjects) {
if (obj.isAt(x, y)) {
gameObjects.add(obj);
}
}
return gameObjects;
}
}

View File

@@ -1,10 +0,0 @@
package net.simon987.server.io;
import net.simon987.server.assembly.CpuHardware;
import org.json.simple.JSONObject;
public interface CpuHardwareDeserializer {
CpuHardware deserializeHardware(JSONObject hwJson);
}

View File

@@ -1,45 +0,0 @@
package net.simon987.server.io;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.logging.LogManager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* Manages the database: this class manages the interactions with the database
*/
public abstract class DatabaseManager {
/**
* SQL connection url
*/
private String url;
/**
* SQL username
*/
private String username;
/**
* SQL password
*/
private String password;
public DatabaseManager(ServerConfiguration config) {
this.url = config.getString("mysql_url");
this.username = config.getString("mysql_user");
this.password = config.getString("mysql_pass");
}
protected Connection getConnection() {
try {
return DriverManager.getConnection(url, this.username, password);
} catch (SQLException e) {
LogManager.LOGGER.severe("Couldn't connect to MySQL server state:" + e.getSQLState() + " error:" + e.getErrorCode());
return null;
}
}
}

View File

@@ -1,10 +0,0 @@
package net.simon987.server.io;
import net.simon987.server.game.GameObject;
import org.json.simple.JSONObject;
public interface GameObjectDeserializer {
GameObject deserializeObject(JSONObject object);
}

View File

@@ -1,9 +0,0 @@
package net.simon987.server.io;
import org.json.simple.JSONObject;
public interface JSONSerialisable {
JSONObject serialise();
}

View File

@@ -1,41 +0,0 @@
package net.simon987.server.logging;
import java.io.IOException;
import java.util.logging.*;
/**
* Utility class to manage log entries
*/
public class LogManager {
/**
* Singleton Logger
*/
public final static Logger LOGGER = Logger.getLogger("mar");
/**
* Initialises the logger
*/
public static void initialize() {
LOGGER.setUseParentHandlers(false);
Handler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
handler.setFormatter(new GenericFormatter());
try {
Handler fileHandler = new FileHandler("mar.log");
fileHandler.setLevel(Level.ALL);
fileHandler.setFormatter(new GenericFormatter());
LOGGER.addHandler(handler);
LOGGER.addHandler(fileHandler);
LOGGER.setLevel(Level.ALL);
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@@ -1,71 +0,0 @@
package net.simon987.server.plugin;
import net.simon987.server.logging.LogManager;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class PluginManager {
private ArrayList<ServerPlugin> plugins;
public PluginManager() {
this.plugins = new ArrayList<>(10);
}
public void load(File pluginFile){
LogManager.LOGGER.info("Loading plugin file " + pluginFile.getName());
try{
//Get the plugin config file from the archive
ZipFile zipFile = new ZipFile(pluginFile);
ZipEntry configEntry = zipFile.getEntry("plugin.properties");
if(configEntry != null){
InputStream stream = zipFile.getInputStream(configEntry);
Properties config = new Properties();
config.load(stream);
//Load the plugin
ClassLoader loader = URLClassLoader.newInstance(new URL[] {pluginFile.toURI().toURL() });
Class<?> aClass = Class.forName(config.getProperty("classpath"), true, loader);
Class<? extends ServerPlugin> pluginClass = aClass.asSubclass(ServerPlugin.class);
Constructor<? extends ServerPlugin> constructor = pluginClass.getConstructor();
ServerPlugin plugin = constructor.newInstance();
plugin.setName(config.getProperty("name"));
plugin.setVersion(config.getProperty("version"));
LogManager.LOGGER.info("Loaded " + plugin.name + " V" + plugin.version);
//Add it to the list
plugins.add(plugin);
//Init the plugin
plugin.init();
} else {
LogManager.LOGGER.severe("Couldn't find plugin.properties in " + pluginFile.getName());
}
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<ServerPlugin> getPlugins() {
return plugins;
}
}

View File

@@ -1,61 +0,0 @@
package net.simon987.server.plugin;
import net.simon987.server.event.GameEventListener;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public abstract class ServerPlugin implements JSONSerialisable {
/**
* Name of the plugin
*/
protected String name;
/**
* Version of the plugin
*/
protected String version;
/**
* List of event listeners
*/
protected ArrayList<GameEventListener> listeners = new ArrayList<>(5);
/**
* Called when the plugin is loaded
*/
public abstract void init();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public ArrayList<GameEventListener> getListeners() {
return listeners;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("version", version);
return json;
}
}

View File

@@ -1,110 +0,0 @@
package net.simon987.server.user;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.CPU;
import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.event.GameEvent;
import net.simon987.server.event.UserCreationEvent;
import net.simon987.server.game.ControllableUnit;
import net.simon987.server.io.JSONSerialisable;
import org.json.simple.JSONObject;
/**
* Represents a User (or player) of the game
*/
public class User implements JSONSerialisable{
private String username;
private String userCode;
private CPU cpu;
private ControllableUnit controlledUnit;
private boolean guest;
public User() throws CancelledException {
GameEvent event = new UserCreationEvent(this);
GameServer.INSTANCE.getEventDispatcher().dispatch(event);
if(event.isCancelled()) {
throw new CancelledException();
}
}
public User(ControllableUnit unit) {
this.controlledUnit = unit;
}
@Override
public JSONObject serialise() {
JSONObject json = new JSONObject();
json.put("username", username);
json.put("code", userCode);
json.put("controlledUnit", controlledUnit.getObjectId());
json.put("cpu", cpu.serialise());
return json;
}
public static User deserialize(JSONObject userJson) throws CancelledException {
User user = new User((ControllableUnit)GameServer.INSTANCE.getGameUniverse().getObject((int)(long)userJson.get("controlledUnit")));
user.username = (String)userJson.get("username");
user.userCode = (String)userJson.get("code");
user.getControlledUnit().setParent(user);
user.cpu = CPU.deserialize((JSONObject)userJson.get("cpu"), user);
return user;
}
//----
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public String getUsername() {
return username;
}
public ControllableUnit getControlledUnit() {
return controlledUnit;
}
public void setControlledUnit(ControllableUnit controlledUnit) {
this.controlledUnit = controlledUnit;
}
public void setUsername(String username) {
this.username = username;
}
public boolean isGuest() {
return guest;
}
public void setGuest(boolean guest) {
this.guest = guest;
}
}

View File

@@ -1,37 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
public class CodeRequestHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject json) {
if(json.get("t").equals("codeRequest")){
LogManager.LOGGER.info("(WS) Code request from " + user.getUser().getUsername());
if(user.isGuest()) {
JSONObject response = new JSONObject();
response.put("t", "code");
response.put("code", "; Create a free account to control your own Cubot with assembly language!"); //todo load from config
user.getWebSocket().send(response.toJSONString());
} else {
JSONObject response = new JSONObject();
response.put("t", "code");
response.put("code", user.getUser().getUserCode());
user.getWebSocket().send(response.toJSONString());
}
}
}
}

View File

@@ -1,45 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.assembly.Assembler;
import net.simon987.server.assembly.AssemblyResult;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
public class CodeUploadHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject json) {
if(json.get("t").equals("uploadCode")){
LogManager.LOGGER.info("(WS) Code upload from " + user.getUser().getUsername());
if(user.isGuest()) {
//Ignore
} else {
//TODO Should we wait at the end of the tick to modify the CPU ?
user.getUser().setUserCode((String)json.get("code"));
AssemblyResult ar = new Assembler(user.getUser().getCpu().getInstructionSet(),
user.getUser().getCpu().getRegisterSet(),
GameServer.INSTANCE.getConfig()).parse(user.getUser().getUserCode());
user.getUser().getCpu().getMemory().clear();
//Write assembled code to mem
user.getUser().getCpu().getMemory().write((char) ar.origin, ar.bytes, 0, ar.bytes.length);
user.getUser().getCpu().setCodeSegmentOffset(ar.origin);
JSONObject response = new JSONObject();
response.put("t", "codeResponse");
response.put("bytes", ar.bytes.length);
user.getWebSocket().send(response.toJSONString());
}
}
}
}

View File

@@ -1,36 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
public class FloppyHandler implements MessageHandler {
SocketServerDatabase db = new SocketServerDatabase(GameServer.INSTANCE.getConfig());
@Override
public void handle(OnlineUser user, JSONObject json) {
if (json.get("t").equals("floppyDown")) {
LogManager.LOGGER.info("(WS) Floppy download request from " + user.getUser().getUsername());
//floppy
byte[] bytes = user.getUser().getControlledUnit().getFloppyData().getBytes();
user.getWebSocket().send(bytes);
} else if (json.get("t").equals("floppyUp")) {
LogManager.LOGGER.info("(WS) Floppy upload request from " + user.getUser().getUsername());
//Check newly uploaded file on the database
byte[] bytes = db.getFloppy(user.getUser().getUsername());
if (bytes != null) {
user.getUser().getControlledUnit().getFloppyData().setBytes(bytes);
}
}
}
}

View File

@@ -1,23 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
public class KeypressHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject json) {
if(!user.isGuest()) {
if(json.get("t").equals("k")){
LogManager.LOGGER.info("(WS) Received keypress");
int key = (int)(long)json.get("k");
user.getUser().getControlledUnit().getKeyboardBuffer().add(key);
}
}
}
}

View File

@@ -1,43 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.util.ArrayList;
public class MessageEventDispatcher {
private ArrayList<MessageHandler> handlers = new ArrayList<>(10);
public MessageEventDispatcher() {
}
public void addHandler(MessageHandler handler) {
handlers.add(handler);
}
public void dispatch(OnlineUser user, String message) {
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(message);
if (json.containsKey("t")) {
for (MessageHandler handler : handlers) {
handler.handle(user, json);
}
} else {
LogManager.LOGGER.info("Malformed JSON sent by " + user.getUser().getUsername());
}
} catch (ParseException e) {
LogManager.LOGGER.info("Malformed JSON sent by " + user.getUser().getUsername());
}
}
}

View File

@@ -1,9 +0,0 @@
package net.simon987.server.webserver;
import org.json.simple.JSONObject;
public interface MessageHandler {
void handle(OnlineUser user, JSONObject json);
}

View File

@@ -1,53 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.game.GameObject;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class ObjectsRequestHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject json) {
if (json.get("t").equals("object")) {
LogManager.LOGGER.info("(WS) Objects request from " + user.getUser().getUsername());
int x, y;
try {
x = Long.valueOf((long) json.get("x")).intValue();
y = Long.valueOf((long) json.get("y")).intValue();
} catch (Exception e) {
LogManager.LOGGER.info("(WS) Malformed Objects request from " + user.getUser().getUsername());
return;
}
World world = GameServer.INSTANCE.getGameUniverse().getWorld(x, y);
if (world != null) {
ArrayList<GameObject> gameObjects = world.getGameObjects();
JSONObject response = new JSONObject();
JSONArray objects = new JSONArray();
for (GameObject object : gameObjects) {
objects.add(object.serialise());
}
response.put("t", "object");
response.put("objects", objects);
if (user.getWebSocket().isOpen()) {
user.getWebSocket().send(response.toJSONString());
}
}
}
}
}

View File

@@ -1,49 +0,0 @@
package net.simon987.server.webserver;
import org.java_websocket.WebSocket;
import java.util.ArrayList;
public class OnlineUserManager {
/**
* List of online users.
*/
private ArrayList<OnlineUser> onlineUsers = new ArrayList<>(10);
public OnlineUser getUser(WebSocket socket) {
ArrayList<OnlineUser> _onlineUsers = new ArrayList<>(onlineUsers);
for (OnlineUser user : _onlineUsers) {
if (user.getWebSocket().equals(socket)) {
return user;
}
}
return null;
}
/**
* Add an user to the list
*
* @param user user to add
*/
public void add(OnlineUser user) {
onlineUsers.add(user);
}
/**
* Remove an user to the list
*
* @param user user to remove
*/
public void remove(OnlineUser user) {
onlineUsers.remove(user);
}
public ArrayList<OnlineUser> getOnlineUsers() {
return onlineUsers;
}
}

View File

@@ -1,287 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.logging.LogManager;
import net.simon987.server.user.User;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.DefaultSSLWebSocketServerFactory;
import org.java_websocket.server.WebSocketServer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
public class SocketServer extends WebSocketServer {
private OnlineUserManager userManager = new OnlineUserManager();
private SocketServerDatabase database;
private MessageEventDispatcher messageEventDispatcher = new MessageEventDispatcher();
public SocketServer(InetSocketAddress address, ServerConfiguration config) {
super(address);
if (config.getInt("use_secure_webSocket") != 0) {
SSLContext context = getContext(config.getString("cert_path"));
if (context != null) {
setWebSocketFactory(new DefaultSSLWebSocketServerFactory(context));
LogManager.LOGGER.info("(WS) Enabled secure webSocket");
} else {
LogManager.LOGGER.severe("(WS) Failed to create SSL context");
}
}
setConnectionLostTimeout(30);
database = new SocketServerDatabase(config);
messageEventDispatcher.addHandler(new UserInfoRequestHandler());
messageEventDispatcher.addHandler(new TerrainRequestHandler());
messageEventDispatcher.addHandler(new ObjectsRequestHandler());
messageEventDispatcher.addHandler(new CodeUploadHandler());
messageEventDispatcher.addHandler(new CodeRequestHandler());
messageEventDispatcher.addHandler(new KeypressHandler());
messageEventDispatcher.addHandler(new FloppyHandler());
}
@Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
LogManager.LOGGER.info("(WS) New Websocket connection " + conn.getRemoteSocketAddress());
userManager.add(new OnlineUser(conn));
}
@Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
LogManager.LOGGER.info("(WS) Closed " + conn.getRemoteSocketAddress() + " with exit code " + code + " additional info: " + reason);
userManager.remove(userManager.getUser(conn));
}
@Override
public void onMessage(WebSocket conn, String message) {
OnlineUser onlineUser = userManager.getUser(conn);
if (onlineUser != null) {
if (onlineUser.isAuthenticated()) {
messageEventDispatcher.dispatch(onlineUser, message);
} else {
LogManager.LOGGER.info("(WS) Received message from unauthenticated user " + conn.getRemoteSocketAddress());
//We expect a 128 characters long token
if(message.length() == 128) {
String username = database.validateAuthToken(message);
if (username != null) {
User user = GameServer.INSTANCE.getGameUniverse().getOrCreateUser(username, true);
LogManager.LOGGER.info("(WS) User was successfully authenticated: " + user.getUsername());
onlineUser.setUser(user);
onlineUser.setAuthenticated(true);
conn.send("{\"t\":\"auth\", \"m\":\"ok\"}");
} else {
User user = GameServer.INSTANCE.getGameUniverse().getOrCreateUser(GameServer.INSTANCE.getGameUniverse().getGuestUsername(), false);
onlineUser.setUser(user);
onlineUser.setAuthenticated(true);
onlineUser.setGuest(true);
LogManager.LOGGER.info("(WS) Created guest user " +
onlineUser.getUser().getUsername() + conn.getRemoteSocketAddress());
conn.send("{\"t\":\"auth\", \"m\":\"ok\"}");
}
}
}
} else {
LogManager.LOGGER.severe("(WS) FIXME: SocketServer:onMessage");
}
}
@Override
public void onMessage(WebSocket conn, ByteBuffer message) {
//System.out.println("received ByteBuffer from " + conn.getRemoteSocketAddress());
}
@Override
public void onError(WebSocket conn, Exception ex) {
LogManager.LOGGER.severe("an error occured on connection " + conn.getRemoteSocketAddress() + ':' + ex);
userManager.remove(userManager.getUser(conn));
conn.close();
ex.printStackTrace();
}
@Override
public void onStart() {
LogManager.LOGGER.info("(WS) Server started successfully");
}
/**
* Called every tick
*/
public void tick() {
JSONObject json = new JSONObject();
json.put("t", "tick");
LogManager.LOGGER.info("Notified " + userManager.getOnlineUsers().size() + " users");
for (OnlineUser user : userManager.getOnlineUsers()) {
if (user.getWebSocket().isOpen()) {
if(user.isGuest()) {
user.getWebSocket().send(json.toJSONString());
} else {
//Send keyboard updated buffer
try{
ArrayList<Integer> kbBuffer = user.getUser().getControlledUnit().getKeyboardBuffer();
JSONArray keys = new JSONArray();
keys.addAll(kbBuffer);
json.put("keys", keys);
//Send tick message
user.getWebSocket().send(json.toJSONString());
} catch (NullPointerException e){
//User is online but not completely initialised
}
}
}
}
}
public OnlineUserManager getUserManager() {
return userManager;
}
/**
* See https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/SSLServerLetsEncryptExample.java
*/
/*
* * Copyright (c) 2010-2017 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*/
private static SSLContext getContext(String pathTo) {
SSLContext context;
String password = "MAR";
try {
context = SSLContext.getInstance("TLS");
byte[] certBytes = parseDERFromPEM(getBytes(new File(pathTo + File.separator + "cert.pem")),
"-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----");
byte[] keyBytes = parseDERFromPEM(getBytes(new File(pathTo + File.separator + "privkey.pem")),
"-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----");
X509Certificate cert = generateCertificateFromDER(certBytes);
RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(null);
keystore.setCertificateEntry("cert-alias", cert);
keystore.setKeyEntry("key-alias", key, password.toCharArray(), new Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keystore, password.toCharArray());
KeyManager[] km = kmf.getKeyManagers();
context.init(km, null, null);
} catch (Exception e) {
context = null;
}
return context;
}
private static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {
String data = new String(pem);
String[] tokens = data.split(beginDelimiter);
tokens = tokens[1].split(endDelimiter);
return DatatypeConverter.parseBase64Binary(tokens[0]);
}
private static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) factory.generatePrivate(spec);
}
private static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException {
CertificateFactory factory = CertificateFactory.getInstance("X.509");
return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes));
}
private static byte[] getBytes(File file) {
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis;
try {
fis = new FileInputStream(file);
fis.read(bytesArray); //read file into bytes[]
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytesArray;
}
}

View File

@@ -1,83 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.io.DatabaseManager;
import net.simon987.server.logging.LogManager;
import java.sql.*;
class SocketServerDatabase extends DatabaseManager {
public SocketServerDatabase(ServerConfiguration config) {
super(config);
}
String validateAuthToken(String token) {
Connection connection = null;
try {
connection = getConnection();
PreparedStatement p = connection.prepareStatement("SELECT username FROM mar_user WHERE authToken=?");
p.setString(1, token);
ResultSet rs = p.executeQuery();
if (rs.next()) {
return rs.getString("username");
} else {
return null;
}
} catch (SQLException e) {
LogManager.LOGGER.severe("MySQL Error " + e.getErrorCode() + ": " + e.getMessage());
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
byte[] getFloppy(String username) {
Connection connection = null;
try {
connection = getConnection();
PreparedStatement p = connection.prepareStatement("SELECT floppyData FROM mar_user WHERE username=?");
p.setString(1, username);
ResultSet rs = p.executeQuery();
if (rs.next()) {
Blob blob = rs.getBlob("floppyData");
if (blob != null) {
return blob.getBytes(1, (int) blob.length() - 1);
}
}
} catch (SQLException e) {
LogManager.LOGGER.severe("MySQL Error " + e.getErrorCode() + ": " + e.getMessage());
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@@ -1,49 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.game.World;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class TerrainRequestHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject json) {
if (json.get("t").equals("terrain") && json.containsKey("x") && json.containsKey("y")) {
LogManager.LOGGER.info("Terrain request from " + user.getUser().getUsername());
World world;
try {
world = GameServer.INSTANCE.getGameUniverse().getWorld(
Long.valueOf((long) json.get("x")).intValue(),
Long.valueOf((long) json.get("y")).intValue());
} catch (NullPointerException e) {
LogManager.LOGGER.severe("FIXME: handle TerrainRequestHandler");
return;
}
//todo It might be a good idea to cache this
if (world != null) {
JSONObject response = new JSONObject();
JSONArray terrain = new JSONArray();
int[][] tiles = world.getTileMap().getTiles();
for (int x = 0; x < World.WORLD_SIZE; x++) {
for (int y = 0; y < World.WORLD_SIZE; y++) {
terrain.add(tiles[y][x]);
}
}
response.put("t", "terrain");
response.put("terrain", terrain);
user.getWebSocket().send(response.toJSONString());
} else {
LogManager.LOGGER.severe("FIXME handle:TerrainRequestHandler");
}
}
}
}

View File

@@ -1,37 +0,0 @@
package net.simon987.server.webserver;
import net.simon987.server.GameServer;
import net.simon987.server.game.GameObject;
import net.simon987.server.logging.LogManager;
import org.json.simple.JSONObject;
public class UserInfoRequestHandler implements MessageHandler {
@Override
public void handle(OnlineUser user, JSONObject message) {
if (message.get("t").equals("userInfo")) {
LogManager.LOGGER.info("(WS) User info request from " + user.getUser().getUsername());
JSONObject json = new JSONObject();
if(user.isGuest()) {
json.put("worldX", GameServer.INSTANCE.getConfig().getInt("new_user_worldX"));
json.put("worldY", GameServer.INSTANCE.getConfig().getInt("new_user_worldY"));
} else {
GameObject object = (GameObject)user.getUser().getControlledUnit();
json.put("worldX", object.getWorld().getX());
json.put("worldY", object.getWorld().getY());
}
json.put("t", "userInfo");
json.put("maxWidth", GameServer.INSTANCE.getGameUniverse().getMaxWidth());
user.getWebSocket().send(json.toJSONString());
}
}
}

View File

@@ -1,39 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.exception.CancelledException;
import net.simon987.server.user.User;
import org.junit.Test;
import java.io.File;
import java.util.Random;
public class CPUTest {
@Test
public void executeInstruction() throws CancelledException {
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
User user = new User();
CPU cpu = new CPU(config, user);
for(int i = 0 ; i < 3 ; i++){
//Execute every possible instruction with random values in memory
cpu.reset();
cpu.getMemory().clear();
Random random = new Random();
random.nextBytes(cpu.getMemory().getBytes());
for (int machineCode = Character.MIN_VALUE; machineCode < Character.MAX_VALUE; machineCode++) {
Instruction instruction = cpu.getInstructionSet().get(machineCode & 0x03F); // 0000 0000 00XX XXXX
int source = (machineCode >> 11) & 0x001F; // XXXX X000 0000 0000
int destination = (machineCode >> 6) & 0x001F; // 0000 0XXX XX00 0000
cpu.executeInstruction(instruction, source, destination);
}
}
}
}

View File

@@ -1,51 +0,0 @@
package net.simon987.server.assembly;
import net.simon987.server.ServerConfiguration;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
public class MemoryTest {
@Test
public void getSet() {
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
int memorySize = config.getInt("memory_size");
Memory memory = new Memory(memorySize);
memory.set(1, 1);
assertEquals(1, memory.get(1));
memory.set(memorySize / 2 - 1, 1);
assertEquals(1, memory.get(memorySize / 2 - 1));
memory.get(memorySize / 2);
memory.get(-1);
memory.set(memorySize / 2, 1);
memory.set(-1, 1);
}
@Test
public void write() {
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
int memorySize = config.getInt("memory_size");
Memory memory = new Memory(memorySize);
assertTrue(memory.write(0, new byte[memorySize], 0, memorySize));
assertFalse(memory.write(0, new byte[memorySize], 0, memorySize + 1));
assertFalse(memory.write(0, new byte[memorySize], 0, -1));
assertFalse(memory.write(-1, new byte[memorySize], 0, 10));
assertFalse(memory.write(memorySize / 2, new byte[15], 0, 1));
assertFalse(memory.write((memorySize / 2) - 5, new byte[11], 0, 11));
assertTrue(memory.write((memorySize / 2) - 5, new byte[11], 0, 10));
}
}

View File

@@ -1,47 +0,0 @@
package net.simon987.server.assembly.instruction;
import net.simon987.server.ServerConfiguration;
import net.simon987.server.assembly.*;
import net.simon987.server.user.User;
import org.junit.Test;
import java.io.File;
public class CallInstructionTest {
@Test
public void execute() throws Exception {
ServerConfiguration config = new ServerConfiguration(new File("config.properties"));
int memorySize = config.getInt("memory_size");
//Memory
Memory memory = new Memory(memorySize);
memory.clear();
//RegisterSet
RegisterSet registerSet = new RegisterSet();
registerSet.put(1, new Register("T1"));
registerSet.put(2, new Register("T2"));
registerSet.clear();
//Status
Status status = new Status();
status.clear();
CPU cpu = new CPU(config, new User());
CallInstruction callInstruction = new CallInstruction(cpu);
//We have to check if IP is 'pushed' correctly (try to pop it), the
}
@Test
public void execute1() throws Exception {
}
}

View File

@@ -1,63 +0,0 @@
# MySQL username
mysql_user=mar
# MySQL password/
mysql_pass=mar
# MySQL address
mysql_url=jdbc:mysql://localhost:3306/mar?useSSL=false
save_interval=10
# Web server port
webSocket_port=8887
webSocket_host=0.0.0.0
use_secure_webSocket=0
cert_path=certificates
# ----------------------------------------------
# Length of a tick in ms
tick_length=1000
# Default offset of the origin (starting point of code execution) in words
org_offset=1024
# Address of the stack bottom
stack_bottom=32768
# Size of the memory in bytes
memory_size=65536
# Initial location of new user's controlled unit
new_user_worldX = 32767
new_user_worldY = 32767
# Default user code
new_user_code=; Welcome to Much Assembly required!\n\
; You will find useful information on the game here: https://github.com/simon987/Much-Assembly-Required/wiki\n\
.text\n\
\t; Write code here\n\
\tbrk
# Default held item
new_user_item=0
# ----------------------------------------------
# Biomass units yield for a plant
plant_yield=2
# Grow time in ticks for a plant to grow
plant_grow_time=32
# Minimum tree count for the WorldGenerator
minTreeCount=3
# Maximum tree count for the WorldGenerator
maxTreeCount=10
# Maximum energy of the battery hardware in kJ
battery_max_energy=60000
# ----------------------------------------------
# Minimum center point count for the WorldGenerator
wg_centerPointCountMin=5
# Maximum center point count for the WorldGenerator
wg_centerPointCountMax=15
# Wall/Plain tile ratio for the WorldGenerator
wg_wallPlainRatio=4
# Minimum iron tiles count for the WorldGenerator
wg_minIronCount=0
# Minimum iron tile count for the WorldGenerator
wg_maxIronCount=2
# Minimum copper tile count for the WorldGenerator
wg_minCopperCount=0
# Maximum copper tile count for the WorldGenerator
wg_maxCopperCount=2
# ----------------------------------------------
# Maximum execution time of user code in ms
user_timeout=40

27
docker-compose.yml Normal file
View File

@@ -0,0 +1,27 @@
version: "2.1"
services:
server:
build:
context: .
command: sh -c "/usr/bin/java -jar /app/target/server-1.4a.jar"
depends_on:
mongodb:
condition: service_healthy
ports:
- 4567:4567
mongodb:
image: mongo:latest
container_name: "mongodb"
environment:
- MONGO_DATA_DIR=/data/db
- MONGO_LOG_DIR=/dev/null
volumes:
- ./data/db:/data/db
ports:
- 27017:27017
command: mongod --smallfiles --logpath=/dev/null --port 27017
healthcheck:
test: echo 'db.stats().ok' | mongo localhost:27017/mar --quiet
interval: 2s
timeout: 2s
retries: 2

Binary file not shown.

Binary file not shown.

Binary file not shown.

155
pom.xml Normal file
View File

@@ -0,0 +1,155 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.simon987.mar</groupId>
<artifactId>muchassemblyrequired</artifactId>
<version>1.6a</version>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>tsc</executable>
<workingDirectory>./src/main/typescript/</workingDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>3.6.2</version>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<id>default-resources</id>
<phase>prepare-package</phase>
<goals>
<goal>resources</goal>
</goals>
<configuration>
<outputDirectory>./target/</outputDirectory>
<resources>
<resource>
<directory>./src/main/resources</directory>
</resource>
</resources>
</configuration>
</execution>
</executions>
</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.mar.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>
<forkMode>never</forkMode>
<workingDirectory>./src/main/resources</workingDirectory>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</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.6</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>3.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.1.11.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-template-velocity</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

View File

@@ -0,0 +1,94 @@
package net.simon987.mar.biomass;
import net.simon987.mar.server.game.item.Item;
import net.simon987.mar.server.game.objects.GameObject;
import net.simon987.mar.server.game.objects.InventoryHolder;
import org.bson.Document;
import org.json.simple.JSONObject;
public class BiomassBlob extends GameObject implements InventoryHolder {
private static final char MAP_INFO = 0x0101;
/**
* Yield of the blob, in biomass units
*/
private int biomassCount;
public BiomassBlob() {
}
public BiomassBlob(Document document) {
super(document);
biomassCount = document.getInteger("biomassCount");
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public JSONObject jsonSerialise() {
JSONObject json = super.jsonSerialise();
json.put("b", biomassCount);
return json;
}
@Override
public Document mongoSerialise() {
Document dbObject = super.mongoSerialise();
dbObject.put("biomassCount", biomassCount);
return dbObject;
}
public int getBiomassCount() {
return biomassCount;
}
public void setBiomassCount(int biomassCount) {
this.biomassCount = biomassCount;
}
/**
* Called when an object attempts to place an item in this BiomassBlob
*
* @return Always returns false
*/
@Override
public boolean placeItem(Item item) {
//Why would you want to place an item in a blob?
return false;
}
@Override
public boolean canTakeItem(int itemId) {
return itemId == ItemBiomass.ID && 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
*/
@Override
public void takeItem(int itemId) {
if (itemId == ItemBiomass.ID) {
if (biomassCount > 1) {
biomassCount--;
} else {
//Delete plant
setDead(true);
}
}
}
}

View File

@@ -0,0 +1,36 @@
package net.simon987.mar.biomass;
import net.simon987.mar.server.GameServer;
import net.simon987.mar.server.game.item.Item;
import net.simon987.mar.server.game.objects.ControllableUnit;
import org.bson.Document;
public class ItemBiomass extends Item {
public static final int ID = 0x0001;
private static final int energy = GameServer.INSTANCE.getConfig().getInt("biomassEnergyValue");
@Override
public int getId() {
return ID;
}
public ItemBiomass() {
super(null);
}
public ItemBiomass(Document document) {
super(document);
}
@Override
public void clear(ControllableUnit unit) {
unit.storeEnergy(energy);
}
@Override
public char poll() {
return ID;
}
}

View File

@@ -0,0 +1,78 @@
package net.simon987.mar.biomass;
import net.simon987.mar.server.game.world.TileMap;
import net.simon987.mar.server.game.world.TilePlain;
import net.simon987.mar.server.game.world.World;
import org.bson.types.ObjectId;
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
TileMap m = world.getTileMap();
int plainCount = 0;
for (int y = 0; y < world.getWorldSize(); y++) {
for (int x = 0; x < world.getWorldSize(); x++) {
if (m.getTileIdAt(x, y) == TilePlain.ID) {
plainCount++;
}
}
}
if (blobCount > plainCount) {
blobCount = plainCount;
}
outerLoop:
for (int i = 0; i < blobCount; i++) {
Point p = m.getRandomTile(TilePlain.ID);
if (p != null) {
//Don't block worlds
int counter = 0;
while (p.x == 0 || p.y == 0 || p.x == world.getWorldSize() - 1 || p.y == world.getWorldSize() - 1 ||
world.getGameObjectsAt(p.x, p.y).size() != 0) {
p = m.getRandomTile(TilePlain.ID);
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(new ObjectId());
biomassBlob.setBiomassCount(yield);
biomassBlob.setX(p.x);
biomassBlob.setY(p.y);
biomassBlob.setWorld(world);
biomassBlobs.add(biomassBlob);
}
}
return biomassBlobs;
}
}

View File

@@ -0,0 +1,65 @@
package net.simon987.mar.biomass.event;
import net.simon987.mar.biomass.BiomassBlob;
import net.simon987.mar.server.IServerConfiguration;
import net.simon987.mar.server.event.GameEvent;
import net.simon987.mar.server.event.GameEventListener;
import net.simon987.mar.server.event.ObjectDeathEvent;
import net.simon987.mar.server.game.objects.GameObject;
import net.simon987.mar.server.game.world.World;
import org.bson.types.ObjectId;
/**
* Handles ObjectDeathEvent events
*/
public class ObjectDeathListener implements GameEventListener {
private final int biomassDropCount;
public ObjectDeathListener(IServerConfiguration config) {
biomassDropCount = config.getInt("harvester_biomass_drop_count");
}
@Override
public Class getListenedEventType() {
return ObjectDeathEvent.class;
}
@Override
public void handle(GameEvent event) {
if (event.getSource().getClass().getCanonicalName().equals("net.simon987.mar.npc.HarvesterNPC")) {
//An HarvesterNPC ObjectDeathEvent is received
GameObject dyingHarvesterNPC = (GameObject) event.getSource();
//Don't spawn biomass on World border
if (dyingHarvesterNPC.getX() != 0 && dyingHarvesterNPC.getX() != dyingHarvesterNPC.getWorld().getWorldSize() - 1 &&
dyingHarvesterNPC.getY() != 0 && dyingHarvesterNPC.getY() != dyingHarvesterNPC.getWorld().getWorldSize() - 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);
}
}
}
/**
* 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(new ObjectId());
biomassBlob.setBiomassCount(biomassDropCount);
biomassBlob.setX(x);
biomassBlob.setY(y);
biomassBlob.setWorld(world);
return biomassBlob;
}
}

View File

@@ -0,0 +1,33 @@
package net.simon987.mar.biomass.event;
import net.simon987.mar.biomass.BiomassBlob;
import net.simon987.mar.biomass.WorldUtils;
import net.simon987.mar.server.GameServer;
import net.simon987.mar.server.event.GameEvent;
import net.simon987.mar.server.event.GameEventListener;
import net.simon987.mar.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,75 @@
package net.simon987.mar.biomass.event;
import net.simon987.mar.biomass.BiomassBlob;
import net.simon987.mar.biomass.WorldUtils;
import net.simon987.mar.server.GameServer;
import net.simon987.mar.server.IServerConfiguration;
import net.simon987.mar.server.event.GameEvent;
import net.simon987.mar.server.event.GameEventListener;
import net.simon987.mar.server.event.WorldUpdateEvent;
import net.simon987.mar.server.game.world.World;
import java.util.ArrayList;
import java.util.HashMap;
public class WorldUpdateListener implements GameEventListener {
private final 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(IServerConfiguration 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 (world.getDimension().startsWith("w")) {
//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.getUniverse().getTime() + waitTime);
} else {
long waitUntil = worldWaitMap.get(world);
if (GameServer.INSTANCE.getUniverse().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);
world.incUpdatable();
}
//Set the 'waitUntil' time to 0 to indicate that we are not waiting
worldWaitMap.replace(world, 0L);
}
}
}
}
}
}

View File

@@ -0,0 +1,111 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.game.item.Item;
import net.simon987.mar.server.game.objects.GameObject;
import net.simon987.mar.server.game.objects.InventoryHolder;
import net.simon987.mar.server.io.JSONSerializable;
import net.simon987.mar.server.io.MongoSerializable;
import org.bson.Document;
import org.json.simple.JSONObject;
import java.util.HashMap;
import java.util.Map;
public abstract class BluePrint implements InventoryHolder, JSONSerializable, MongoSerializable {
/**
* Map of items id and required amount
* <br>The amount is decremented as the items are added
*/
protected Map<Integer, Integer> requiredItems;
/**
* This object will be instantiated when completed
*/
protected Class<? extends GameObject> targetObject;
/**
* Set to true when all the requirements are met
*/
private boolean completed;
public BluePrint() {
requiredItems = new HashMap<>();
}
public BluePrint(Document document) {
requiredItems = (Map<Integer, Integer>) document.get("required_items");
completed = document.getBoolean("completed");
try {
targetObject = Class.forName(document.getString("target")).asSubclass(GameObject.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private void checkCompleted() {
for (Integer remaining : requiredItems.values()) {
if (remaining > 0) {
return;
}
}
completed = true;
}
@Override
public boolean placeItem(Item item) {
if (requiredItems.containsKey(item.getId()) && requiredItems.get(item.getId()) > 0) {
requiredItems.put(item.getId(), requiredItems.get(item.getId()) - 1);
checkCompleted();
return true;
}
return false;
}
@Override
public void takeItem(int itemId) {
}
@Override
public boolean canTakeItem(int itemId) {
return false;
}
public boolean isCompleted() {
return completed;
}
public Class<? extends GameObject> getTargetObject() {
return targetObject;
}
@Override
public JSONObject debugJsonSerialise() {
return jsonSerialise();
}
@Override
public JSONObject jsonSerialise() {
JSONObject json = new JSONObject();
json.put("target", targetObject);
json.put("required_items", requiredItems);
return json;
}
@Override
public Document mongoSerialise() {
Document document = new Document();
document.put("completed", completed);
document.put("target", targetObject);
document.put("required_items", requiredItems);
return document;
}
}

View File

@@ -0,0 +1,61 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.logging.LogManager;
import org.bson.Document;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class BluePrintRegistry {
public static final BluePrintRegistry INSTANCE = new BluePrintRegistry();
private final Map<String, Class<? extends BluePrint>> blueprints;
private final Map<String, String> digitizedBlueprints;
private BluePrintRegistry() {
blueprints = new HashMap<>();
digitizedBlueprints = new HashMap<>();
}
public void registerBluePrint(Class<? extends BluePrint> clazz) {
blueprints.put(clazz.getCanonicalName(), clazz);
String bpData = new String(BluePrintUtil.bluePrintData(clazz));
digitizedBlueprints.put(bpData, clazz.getCanonicalName());
}
public BluePrint deserializeBlueprint(Document document) {
String type = document.getString("type");
if (blueprints.containsKey(type)) {
try {
return blueprints.get(type).getConstructor(Document.class).newInstance(document);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException e) {
e.printStackTrace();
return null;
} catch (InvocationTargetException e) {
LogManager.LOGGER.severe("(Construction Plugin) Error while trying to deserialize object of type " + type + ": " + e.getTargetException().getMessage());
LogManager.LOGGER.severe(document.toJson());
e.getTargetException().printStackTrace();
return null;
}
} else {
LogManager.LOGGER.severe("(Construction Plugin) Trying to deserialize unknown BluePrint type: " + type);
return null;
}
}
public BluePrint deserializeBluePrint(char[] chars) {
String bpData = new String(chars);
if (digitizedBlueprints.containsKey(bpData)) {
return deserializeBlueprint(new Document("type", digitizedBlueprints.get(bpData)));
}
return null;
}
}

View File

@@ -0,0 +1,66 @@
package net.simon987.mar.construction;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
class BluePrintUtil {
private static byte[] secretKey;
private static final String SHA512 = "SHA-512";
//We need 1024 chars = 2048 bytes = 32 values
private static final char[] ARBITRARY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456".toCharArray();
static void setSecretKey(String secretKey) {
BluePrintUtil.secretKey = secretKey.getBytes(StandardCharsets.UTF_8);
}
/**
* Hash a message using SHA512 with the server secret key as the sal
*
* @return 128-bit char array
*/
private static char[] hashMessage(String message) {
try {
MessageDigest md = MessageDigest.getInstance(SHA512);
md.update(secretKey);
md.update(message.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
char[] chars = new char[digest.length / 2];
ByteBuffer.wrap(digest).order(ByteOrder.BIG_ENDIAN).asCharBuffer().get(chars);
return chars;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* Returns a char array representation of a blueprint. It is obtained by hashing the blueprint
* properties with the server secret key. Some arbitrary values are added to make a 1024-char
* array. The same blueprint and secret key always gives the same result.
*/
static char[] bluePrintData(Class<? extends BluePrint> blueprint) {
char[] result = new char[ARBITRARY_STRING.length * 32];
for (int i = ARBITRARY_STRING.length - 1; i > 0; --i) {
char[] hashedBlueprint = hashMessage(ARBITRARY_STRING[i] + blueprint.getName());
if (hashedBlueprint != null) {
System.arraycopy(hashedBlueprint, 0, result,
i * hashedBlueprint.length, hashedBlueprint.length);
}
}
return result;
}
}

View File

@@ -0,0 +1,12 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.GameServer;
public class ConstructionPlugin {
public void init(GameServer gameServer) {
// TODO
BluePrintUtil.setSecretKey(gameServer.getSecretKey());
BluePrintRegistry.INSTANCE.registerBluePrint(ObstacleBlueprint.class);
}
}

View File

@@ -0,0 +1,82 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.GameServer;
import net.simon987.mar.server.game.item.Item;
import net.simon987.mar.server.game.objects.InventoryHolder;
import net.simon987.mar.server.game.objects.Structure;
import net.simon987.mar.server.game.objects.Updatable;
import org.bson.Document;
import org.json.simple.JSONObject;
public class ConstructionSite extends Structure implements Updatable, InventoryHolder {
public static final int MAP_INFO = 0xFFFF; //TODO: determine
public static final int LIFETIME = GameServer.INSTANCE.getConfig().getInt("construction_site_ttl");
private int age;
private final BluePrint bluePrint;
public ConstructionSite(BluePrint bluePrint) {
super(1, 1);
this.bluePrint = bluePrint;
this.age = 0;
}
public ConstructionSite(Document document) {
super(document, 1, 1);
age = document.getInteger("age");
bluePrint = BluePrintRegistry.INSTANCE.deserializeBlueprint((Document) document.get("blueprint"));
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public void update() {
age += 1;
if (age > LIFETIME) {
setDead(true);
}
}
@Override
public boolean placeItem(Item item) {
return bluePrint.placeItem(item);
}
@Override
public void takeItem(int itemId) {
//NOOP
}
@Override
public boolean canTakeItem(int itemId) {
return false;
}
@Override
public JSONObject jsonSerialise() {
JSONObject json = super.jsonSerialise();
json.put("blueprint", bluePrint.jsonSerialise());
json.put("age", age);
return json;
}
@Override
public Document mongoSerialise() {
Document document = super.mongoSerialise();
document.put("blueprint", bluePrint.mongoSerialise());
document.put("age", age);
return document;
}
}

View File

@@ -0,0 +1,58 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.assembly.Memory;
import net.simon987.mar.server.game.item.Item;
import org.bson.Document;
import org.json.simple.JSONObject;
public class ItemBluePrint extends Item {
public static final int ID = 0x0005;
private Class<? extends BluePrint> bluePrint;
public ItemBluePrint() {
super(null);
}
public ItemBluePrint(Document document) {
super(document);
try {
bluePrint = Class.forName(document.getString("blueprint")).asSubclass(BluePrint.class);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void digitize(Memory memory, int offset) {
char[] data = BluePrintUtil.bluePrintData(bluePrint);
memory.write(offset, data, 0, data.length);
System.out.println("DEBUG: blueprint digitize " + data.length);
}
@Override
public char poll() {
return ID;
}
@Override
public int getId() {
return ID;
}
@Override
public JSONObject debugJsonSerialise() {
JSONObject json = super.debugJsonSerialise();
json.put("blueprint", bluePrint.getCanonicalName());
return json;
}
@Override
public Document mongoSerialise() {
Document document = super.mongoSerialise();
document.put("blueprint", bluePrint.getCanonicalName());
return document;
}
}

View File

@@ -0,0 +1,104 @@
package net.simon987.mar.construction;
import net.simon987.mar.server.GameServer;
import net.simon987.mar.server.game.objects.Attackable;
import net.simon987.mar.server.game.objects.Structure;
import net.simon987.mar.server.game.objects.Updatable;
import org.bson.Document;
import org.json.simple.JSONObject;
public class Obstacle extends Structure implements Attackable, Updatable {
public static final int MAP_INFO = 0x0601;
private static final int HEAL_RATE = GameServer.INSTANCE.getConfig().getInt("obstacle_regen");
private static final int MAX_HP = GameServer.INSTANCE.getConfig().getInt("obstacle_hp");
private int hp;
private int color;
public Obstacle() {
super(1, 1);
}
public Obstacle(Document document) {
super(document, 1, 1);
hp = document.getInteger(hp);
color = document.getInteger(color);
}
@Override
public void update() {
heal(HEAL_RATE);
}
@Override
public void setHealRate(int hp) {
}
@Override
public int getHp() {
return hp;
}
@Override
public void setHp(int hp) {
this.hp = hp;
}
@Override
public int getMaxHp() {
return MAX_HP;
}
@Override
public void setMaxHp(int hp) {
}
@Override
public void heal(int amount) {
hp = Math.min(getMaxHp(), hp + amount);
}
@Override
public void damage(int amount) {
hp -= amount;
if (hp < 0) {
setDead(true);
}
}
@Override
public char getMapInfo() {
return MAP_INFO;
}
@Override
public Document mongoSerialise() {
Document document = super.mongoSerialise();
document.put("hp", hp);
document.put("color", hp);
return document;
}
@Override
public JSONObject debugJsonSerialise() {
return jsonSerialise();
}
@Override
public JSONObject jsonSerialise() {
JSONObject json = super.jsonSerialise();
json.put("hp", hp);
json.put("color", hp);
return json;
}
}

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