From e0628ca6e22450b5653736c43deeee2575117735 Mon Sep 17 00:00:00 2001 From: Litorom Date: Sat, 30 Dec 2023 11:15:36 -0500 Subject: [PATCH] Converted to LF line separator --- .editorconfig | 2 +- .github/ISSUE_TEMPLATE/bug_report.md | 6 +- .github/workflows/autobuild.yml | 46 +- .github/workflows/codeql-analysis.yml | 54 +- .github/workflows/publish.yml | 2 +- ChangeLog.md | 7 +- Credits.md | 6 + README.md | 49 +- build.gradle | 6 +- settings.gradle | 2 +- src/client/java/minicraft/core/Action.java | 4 +- .../java/minicraft/core/CrashHandler.java | 101 +++- src/client/java/minicraft/core/Game.java | 25 +- .../java/minicraft/core/Initializer.java | 55 +- src/client/java/minicraft/core/Renderer.java | 10 +- src/client/java/minicraft/core/Updater.java | 42 +- src/client/java/minicraft/core/World.java | 58 +- .../minicraft/core/io/ClipboardHandler.java | 38 +- .../java/minicraft/core/io/FileHandler.java | 16 +- .../java/minicraft/core/io/InputHandler.java | 132 +++-- .../java/minicraft/core/io/Localization.java | 26 +- .../java/minicraft/core/io/Settings.java | 22 +- src/client/java/minicraft/core/io/Sound.java | 28 +- src/client/java/minicraft/entity/Arrow.java | 16 +- .../java/minicraft/entity/ClientTickable.java | 4 +- .../java/minicraft/entity/Direction.java | 19 +- src/client/java/minicraft/entity/Entity.java | 139 +++-- .../java/minicraft/entity/FireSpark.java | 13 +- .../java/minicraft/entity/ItemEntity.java | 31 +- .../java/minicraft/entity/ItemHolder.java | 4 +- src/client/java/minicraft/entity/Spark.java | 15 +- .../java/minicraft/entity/Tickable.java | 4 +- .../java/minicraft/entity/furniture/Bed.java | 22 +- .../minicraft/entity/furniture/Chest.java | 14 +- .../minicraft/entity/furniture/Crafter.java | 18 +- .../entity/furniture/DeathChest.java | 25 +- .../entity/furniture/DungeonChest.java | 12 +- .../minicraft/entity/furniture/Furniture.java | 46 +- .../entity/furniture/KnightStatue.java | 9 +- .../minicraft/entity/furniture/Lantern.java | 7 +- .../minicraft/entity/furniture/Spawner.java | 49 +- .../java/minicraft/entity/furniture/Tnt.java | 34 +- .../java/minicraft/entity/mob/AirWizard.java | 33 +- src/client/java/minicraft/entity/mob/Cow.java | 15 +- .../java/minicraft/entity/mob/Creeper.java | 15 +- .../java/minicraft/entity/mob/EnemyMob.java | 47 +- .../java/minicraft/entity/mob/Knight.java | 5 +- src/client/java/minicraft/entity/mob/Mob.java | 85 ++- .../java/minicraft/entity/mob/MobAi.java | 48 +- .../minicraft/entity/mob/ObsidianKnight.java | 23 +- .../java/minicraft/entity/mob/PassiveMob.java | 13 +- src/client/java/minicraft/entity/mob/Pig.java | 15 +- .../java/minicraft/entity/mob/Player.java | 205 ++++--- .../java/minicraft/entity/mob/Sheep.java | 15 +- .../java/minicraft/entity/mob/Skeleton.java | 3 +- .../java/minicraft/entity/mob/Slime.java | 14 +- .../java/minicraft/entity/mob/Snake.java | 4 +- .../java/minicraft/entity/mob/Zombie.java | 7 +- .../minicraft/entity/particle/Particle.java | 18 +- .../entity/particle/SandParticle.java | 1 + .../entity/particle/TextParticle.java | 25 +- src/client/java/minicraft/gfx/Color.java | 51 +- src/client/java/minicraft/gfx/Dimension.java | 15 +- src/client/java/minicraft/gfx/Ellipsis.java | 153 ++++-- src/client/java/minicraft/gfx/Font.java | 67 ++- src/client/java/minicraft/gfx/FontStyle.java | 75 ++- src/client/java/minicraft/gfx/Insets.java | 35 +- .../java/minicraft/gfx/MinicraftImage.java | 15 +- src/client/java/minicraft/gfx/Point.java | 25 +- src/client/java/minicraft/gfx/Rectangle.java | 114 ++-- src/client/java/minicraft/gfx/Screen.java | 126 +++-- src/client/java/minicraft/gfx/Sprite.java | 26 +- .../java/minicraft/gfx/SpriteAnimation.java | 45 +- .../java/minicraft/gfx/SpriteLinker.java | 174 ++++-- src/client/java/minicraft/item/ArmorItem.java | 9 +- src/client/java/minicraft/item/BookItem.java | 9 +- .../java/minicraft/item/BucketItem.java | 31 +- .../java/minicraft/item/ClothingItem.java | 23 +- .../java/minicraft/item/FishingData.java | 28 +- .../java/minicraft/item/FishingRodItem.java | 143 ++--- src/client/java/minicraft/item/FoodItem.java | 13 +- .../java/minicraft/item/FurnitureItem.java | 14 +- src/client/java/minicraft/item/HeartItem.java | 16 +- src/client/java/minicraft/item/Inventory.java | 84 ++- src/client/java/minicraft/item/Item.java | 45 +- src/client/java/minicraft/item/Items.java | 31 +- .../java/minicraft/item/PotionItem.java | 20 +- .../java/minicraft/item/PotionType.java | 26 +- src/client/java/minicraft/item/Recipe.java | 24 +- src/client/java/minicraft/item/Recipes.java | 280 +++++----- .../java/minicraft/item/StackableItem.java | 11 +- .../java/minicraft/item/SummonItem.java | 20 +- src/client/java/minicraft/item/TileItem.java | 25 +- src/client/java/minicraft/item/ToolItem.java | 27 +- src/client/java/minicraft/item/ToolType.java | 24 +- src/client/java/minicraft/item/TorchItem.java | 11 +- .../java/minicraft/item/WateringCanItem.java | 20 +- src/client/java/minicraft/level/Level.java | 186 ++++--- src/client/java/minicraft/level/LevelGen.java | 22 +- .../java/minicraft/level/Structure.java | 142 ++--- .../java/minicraft/level/tile/CactusTile.java | 2 +- .../minicraft/level/tile/ConnectTile.java | 22 +- .../java/minicraft/level/tile/DecorTile.java | 11 +- .../java/minicraft/level/tile/DirtTile.java | 23 +- .../java/minicraft/level/tile/DoorTile.java | 5 +- .../java/minicraft/level/tile/FloorTile.java | 27 +- .../java/minicraft/level/tile/FlowerTile.java | 4 +- .../java/minicraft/level/tile/GrassTile.java | 4 - .../minicraft/level/tile/HardRockTile.java | 2 +- .../level/tile/InfiniteFallTile.java | 9 +- .../minicraft/level/tile/LavaBrickTile.java | 8 +- .../minicraft/level/tile/MaterialTile.java | 21 +- .../java/minicraft/level/tile/OreTile.java | 24 +- .../java/minicraft/level/tile/PathTile.java | 40 +- .../java/minicraft/level/tile/RockTile.java | 2 +- .../java/minicraft/level/tile/SandTile.java | 12 +- .../java/minicraft/level/tile/Tile.java | 99 ++-- .../java/minicraft/level/tile/Tiles.java | 165 +++--- .../java/minicraft/level/tile/TorchTile.java | 12 +- .../java/minicraft/level/tile/TreeTile.java | 11 +- .../java/minicraft/level/tile/WallTile.java | 17 +- .../level/tile/farming/CarrotTile.java | 2 +- .../level/tile/farming/CropTile.java | 18 +- .../level/tile/farming/FarmTile.java | 31 +- .../tile/farming/HeavenlyBerriesTile.java | 2 +- .../tile/farming/HellishBerriesTile.java | 2 +- .../level/tile/farming/PotatoTile.java | 18 +- .../level/tile/farming/TomatoTile.java | 2 +- .../level/tile/farming/WheatTile.java | 2 +- .../java/minicraft/network/Analytics.java | 11 +- .../minicraft/network/MinicraftProtocol.java | 6 +- .../java/minicraft/network/Network.java | 15 +- .../java/minicraft/saveload/LegacyLoad.java | 120 +++-- src/client/java/minicraft/saveload/Load.java | 195 ++++--- src/client/java/minicraft/saveload/Save.java | 39 +- .../java/minicraft/saveload/Version.java | 28 +- .../minicraft/screen/AchievementsDisplay.java | 380 ++++++------- .../java/minicraft/screen/BookDisplay.java | 34 +- .../minicraft/screen/ContainerDisplay.java | 19 +- .../minicraft/screen/ControlsDisplay.java | 6 +- .../minicraft/screen/CraftingDisplay.java | 25 +- src/client/java/minicraft/screen/Display.java | 45 +- .../java/minicraft/screen/EndGameDisplay.java | 10 +- .../java/minicraft/screen/InfoDisplay.java | 8 +- .../java/minicraft/screen/InventoryMenu.java | 12 +- .../java/minicraft/screen/ItemListMenu.java | 5 +- .../minicraft/screen/KeyInputDisplay.java | 8 +- .../screen/LanguageSettingsDisplay.java | 8 +- .../screen/LevelTransitionDisplay.java | 12 +- .../java/minicraft/screen/LoadingDisplay.java | 10 +- src/client/java/minicraft/screen/Menu.java | 253 +++++---- .../minicraft/screen/MultiplayerDisplay.java | 84 +-- .../screen/OnScreenKeyboardMenu.java | 99 ++-- .../screen/OptionsMainMenuDisplay.java | 16 +- .../minicraft/screen/OptionsWorldDisplay.java | 5 +- .../java/minicraft/screen/PauseDisplay.java | 10 +- .../java/minicraft/screen/PlayDisplay.java | 28 +- .../minicraft/screen/PlayerDeathDisplay.java | 2 +- .../minicraft/screen/PlayerInvDisplay.java | 31 +- .../java/minicraft/screen/PopupDisplay.java | 38 +- .../java/minicraft/screen/QuestsDisplay.java | 62 ++- .../java/minicraft/screen/RecipeMenu.java | 6 +- src/client/java/minicraft/screen/RelPos.java | 23 +- .../minicraft/screen/ResourcePackDisplay.java | 132 +++-- .../java/minicraft/screen/SkinDisplay.java | 9 +- .../java/minicraft/screen/TempDisplay.java | 20 +- .../java/minicraft/screen/TitleDisplay.java | 59 +- .../screen/TutorialDisplayHandler.java | 22 +- .../minicraft/screen/WorldGenDisplay.java | 59 +- .../minicraft/screen/WorldSelectDisplay.java | 17 +- .../minicraft/screen/entry/ArrayEntry.java | 44 +- .../minicraft/screen/entry/BlankEntry.java | 10 +- .../minicraft/screen/entry/BooleanEntry.java | 2 +- .../minicraft/screen/entry/InputEntry.java | 6 +- .../minicraft/screen/entry/ItemEntry.java | 11 +- .../minicraft/screen/entry/ItemListing.java | 12 +- .../minicraft/screen/entry/KeyInputEntry.java | 2 +- .../minicraft/screen/entry/LinkEntry.java | 25 +- .../minicraft/screen/entry/ListEntry.java | 35 +- .../minicraft/screen/entry/RangeEntry.java | 22 +- .../minicraft/screen/entry/RecipeEntry.java | 3 +- .../minicraft/screen/entry/SelectEntry.java | 25 +- .../minicraft/screen/entry/StringEntry.java | 31 +- .../minicraft/util/AdvancementElement.java | 129 +++-- src/client/java/minicraft/util/Logging.java | 8 +- src/client/java/minicraft/util/MyUtils.java | 10 +- src/client/java/minicraft/util/Quest.java | 9 +- .../util/TinylogLoggingConfiguration.java | 55 +- .../util/TinylogLoggingProvider.java | 24 +- .../java/minicraft/util/TutorialElement.java | 4 +- src/client/java/minicraft/util/Vector2.java | 6 +- src/client/resources/resources/recipes.json | 503 ++++++++++++++---- src/client/resources/tinylog.properties | 42 +- 193 files changed, 4753 insertions(+), 2847 deletions(-) diff --git a/.editorconfig b/.editorconfig index 6effc03c5..642cf1e89 100644 --- a/.editorconfig +++ b/.editorconfig @@ -9,7 +9,7 @@ charset = utf-8 indent_style = tab indent_size = tab tab_width = 4 -ij_java_imports_layout = *,|,javax.**,|,java.**,|,$* +ij_java_imports_layout = *, |, javax.**, |, java.**, |, $* ij_java_packages_to_use_import_on_demand = unset ij_java_class_count_to_use_import_on_demand = 99999999 ij_java_names_count_to_use_import_on_demand = 99999999 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 50ae616dc..9a69af588 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -12,6 +12,7 @@ A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: + 1. Go to '...' 2. Click on '....' 3. See error @@ -23,8 +24,9 @@ A clear and concise description of what you expected to happen. If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - - OS: [e.g. Windows] - - Game version [e.g. 2.0.7] + +- OS: [e.g. Windows] +- Game version [e.g. 2.0.7] **Additional context** Add any other context about the problem here. diff --git a/.github/workflows/autobuild.yml b/.github/workflows/autobuild.yml index 2c260ae31..9bff81a7e 100644 --- a/.github/workflows/autobuild.yml +++ b/.github/workflows/autobuild.yml @@ -1,33 +1,33 @@ name: Nightly build on: schedule: - - cron: '0 0 * * *' + - cron: '0 0 * * *' workflow_dispatch: - + jobs: gradle: strategy: matrix: - os: [ubuntu-latest] + os: [ ubuntu-latest ] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v3 - - uses: actions/setup-java@v3 - with: - distribution: temurin - java-version: 8 - - - name: Setup Gradle - uses: gradle/gradle-build-action@v2.4.2 - - - name: Execute Gradle build - run: ./gradlew build - - - uses: actions/upload-artifact@v3.1.2 - with: - name: "Nightly release" - path: | - LICENSE - ChangeLog.md - build/libs/**.jar - if-no-files-found: error + - uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + distribution: temurin + java-version: 8 + + - name: Setup Gradle + uses: gradle/gradle-build-action@v2.4.2 + + - name: Execute Gradle build + run: ./gradlew build + + - uses: actions/upload-artifact@v3.1.2 + with: + name: "Nightly release" + path: | + LICENSE + ChangeLog.md + build/libs/**.jar + if-no-files-found: error diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index c1d66f49d..a0fefaba5 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -37,36 +37,36 @@ jobs: # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support steps: - - name: Checkout repository - uses: actions/checkout@v3 + - name: Checkout repository + uses: actions/checkout@v3 - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - - # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs - # queries: security-extended,security-and-quality + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v2 + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality - # ℹī¸ Command-line programs to run using the OS shell. - # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - # If the Autobuild fails above, remove it and uncomment the following three lines. - # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 - # - run: | - # echo "Run, Build Application using script" - # ./location_of_script_within_repo/buildscript.sh + # ℹī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c003ebe5b..a51f90c97 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,5 +1,5 @@ name: publish -on: [workflow_dispatch] # Manual trigger +on: [ workflow_dispatch ] # Manual trigger jobs: build: strategy: diff --git a/ChangeLog.md b/ChangeLog.md index 68880e22c..bae0c1a36 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -16,7 +16,8 @@ but some sections are changed to compliant this project. * Added obsidian knight as the second boss * Added limitation to inventories * Added limitation to stackable items -* Added seven new debug arguments - `--debug-log-time`, `--debug-log-thread`, `--debug-log-trace`, `--debug-filelog-full`, `--debug-level`, `--debug-locale`, `--debug-unloc-tracing` +* Added seven new debug + arguments - `--debug-log-time`, `--debug-log-thread`, `--debug-log-trace`, `--debug-filelog-full`, `--debug-level`, `--debug-locale`, `--debug-unloc-tracing` * Added a new argument for disabling hardware acceleration - `--no-hardware-acceleration` * Added a toggle for HUD display * Added a toggle for simplified effect display @@ -412,7 +413,11 @@ but some sections are changed to compliant this project. > * Added an Iron Lantern at the entrance of the purple dungeon [2.2.0]: https://github.com/MinicraftPlus/minicraft-plus-revived/compare/v2.1.3...HEAD + [2.1.3]: https://github.com/MinicraftPlus/minicraft-plus-revived/compare/v2.1.2...v2.1.3 + [2.1.2]: https://github.com/MinicraftPlus/minicraft-plus-revived/compare/v2.1.1...v2.1.2 + [2.1.1]: https://github.com/MinicraftPlus/minicraft-plus-revived/compare/v2.1.0...v2.1.1 + [2.1.0]: https://github.com/MinicraftPlus/minicraft-plus-revived/compare/v2.0.7...v2.1.0 diff --git a/Credits.md b/Credits.md index 2d13f6ee4..87c04ecf3 100644 --- a/Credits.md +++ b/Credits.md @@ -1,16 +1,20 @@ ## Credits + Original game by Markus "Notch" Persson. ### Former maintainers + * David.b * Dillyg10 * Chris J * afyber ### Current maintainer + * Makkkkus ### Code contributions from + * A.L.I.C.E * BenCheung0422 * Christoffer Holmesland @@ -21,11 +25,13 @@ Original game by Markus "Notch" Persson. * rocketedsocks ### Art contributions from + * TheBigEye * JamesTDG * Geek_Joystick ### Localisation contributions from + * A.L.I.C.E * Christoffer Holmesland * GladfanIsHere diff --git a/README.md b/README.md index c16169dbf..8404efba3 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,27 @@ [![CodeQL](https://github.com/MinicraftPlus/minicraft-plus-revived/actions/workflows/codeql-analysis.yml/badge.svg?branch=main)](https://github.com/MinicraftPlus/minicraft-plus-revived/actions/workflows/codeql-analysis.yml) # Minicraft+ + ![Minicraft+](https://user-images.githubusercontent.com/37084190/138313821-75ac3112-7044-45c1-bdbb-d89f2333c2c0.png) -Minicraft+ is an overhaul mod of Minicraft, a game made by Markus "Notch" Persson in the Ludum Dare 22 contest. To learn more about Minicraft take a look at [playminicraft.com](https://www.playminicraft.com), talk to the community at our [Discord](https://discord.me/minicraft), or check out our [Fandom Wiki](https://minicraft.fandom.com/wiki/Minicraft_Wiki). +Minicraft+ is an overhaul mod of Minicraft, a game made by Markus "Notch" Persson in the Ludum Dare 22 contest. To learn +more about Minicraft take a look at [playminicraft.com](https://www.playminicraft.com), talk to the community at +our [Discord](https://discord.me/minicraft), or check out +our [Fandom Wiki](https://minicraft.fandom.com/wiki/Minicraft_Wiki). -Check the [releases](https://github.com/minicraftplus/minicraft-plus-revived/releases) page to download the latest version, or older versions. +Check the [releases](https://github.com/minicraftplus/minicraft-plus-revived/releases) page to download the latest +version, or older versions. ## Major features + * Four new gamemodes - * Creative - * Hardcore - * Score - * Survival + * Creative + * Hardcore + * Score + * Survival * Saving and loading -* Multiplayer mode and an account system (Now supported by [El-Virus](https://www.github.com/ElVir-Software/minicraft-plus-online)) +* Multiplayer mode and an account system (Now supported + by [El-Virus](https://www.github.com/ElVir-Software/minicraft-plus-online)) * More mobs * Personal crafting menu * Beds @@ -33,24 +40,36 @@ Check the [releases](https://github.com/minicraftplus/minicraft-plus-revived/rel * and many, many more! ## Current goals and ideas -Take a look at the [ideas](ideas/) folder or the [issues](https://github.com/minicraftplus/minicraft-plus-revived/issues) page. + +Take a look at the [ideas](ideas/) folder or +the [issues](https://github.com/minicraftplus/minicraft-plus-revived/issues) page. ## Getting the game and run the game -Head over [releases](https://github.com/minicraftplus/minicraft-plus-revived/releases) and find the latest version of Minicraft+. -There, you can find an file called `minicraft_plus.jar`. Click the file, and after you have downloaded the file, you must double-click the file in downloads folder to open it. -You must first confirm that you have [Java](https://www.java.com/en/download/) (at least version 8) installed on your computer. + +Head over [releases](https://github.com/minicraftplus/minicraft-plus-revived/releases) and find the latest version of +Minicraft+. +There, you can find an file called `minicraft_plus.jar`. Click the file, and after you have downloaded the file, you +must double-click the file in downloads folder to open it. +You must first confirm that you have [Java](https://www.java.com/en/download/) (at least version 8) installed on your +computer. ## Localization -This project is running with an external localization platform called POEditor. You can contribute localization by clicking the image below! + +This project is running with an external localization platform called POEditor. You can contribute localization by +clicking the image below! [![Minicraft+ POEditor Stats](https://minicraft-plus-poeditor-stats.vercel.app/api/card)](https://minicraft-plus-poeditor-stats.vercel.app) ## How to build/run in development + Because this project uses a build tool called gradle it is very easy to build or run the project from the source code. 1. Download the source code by clicking the green code button, and download it as a ZIP. 2. Extract the contents of the folder. 3. Open command prompt and enter `cd `, this will open the folder in the command prompt. -4. Type `gradlew run` or `gradlew build` to run or build the program. This might take some time. If on unix, add "./" to the front. - 1. If you built the project, the jar file is found in `build/libs` - 2. If you get an error screaming that you're missing java. You need to [set up](https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html) your JAVA_HOME environment variable, or download a JDK if you haven't already. +4. Type `gradlew run` or `gradlew build` to run or build the program. This might take some time. If on unix, add "./" to + the front. + 1. If you built the project, the jar file is found in `build/libs` + 2. If you get an error screaming that you're missing java. You need + to [set up](https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html) your + JAVA_HOME environment variable, or download a JDK if you haven't already. diff --git a/build.gradle b/build.gradle index 3c1e4c6ee..f8e2d2271 100644 --- a/build.gradle +++ b/build.gradle @@ -94,13 +94,13 @@ jar { from files(sourceSets.main.output.classesDirs) from files(sourceSets.main.output.resourcesDir) - from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }} + from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } } } // Don't override if we're building a tar package. -tasks.withType(Tar){ +tasks.withType(Tar) { duplicatesStrategy = DuplicatesStrategy.EXCLUDE } -tasks.withType(Zip){ +tasks.withType(Zip) { duplicatesStrategy = DuplicatesStrategy.INCLUDE } diff --git a/settings.gradle b/settings.gradle index ed6c13faa..0360f2e6a 100644 --- a/settings.gradle +++ b/settings.gradle @@ -4,6 +4,6 @@ include "common" include "client" include "server" -rootProject.children.each {project -> +rootProject.children.each { project -> project.projectDir = new File(settingsDir, "src/${project.name}") } diff --git a/src/client/java/minicraft/core/Action.java b/src/client/java/minicraft/core/Action.java index 4b931e34b..520187682 100644 --- a/src/client/java/minicraft/core/Action.java +++ b/src/client/java/minicraft/core/Action.java @@ -2,7 +2,7 @@ @FunctionalInterface public interface Action { - + void act(); - + } diff --git a/src/client/java/minicraft/core/CrashHandler.java b/src/client/java/minicraft/core/CrashHandler.java index 15157c31e..ddeb5b206 100644 --- a/src/client/java/minicraft/core/CrashHandler.java +++ b/src/client/java/minicraft/core/CrashHandler.java @@ -28,10 +28,18 @@ import java.util.concurrent.Future; public class CrashHandler { - public static void crashHandle(Thread thread, Throwable throwable) { crashHandle(throwable); } - public static void crashHandle(Throwable throwable) { crashHandle(throwable, new ErrorInfo(true)); } - /** This handles application crashing errors by giving notification to the user clearly.
- * The user can only exit the program. */ + public static void crashHandle(Thread thread, Throwable throwable) { + crashHandle(throwable); + } + + public static void crashHandle(Throwable throwable) { + crashHandle(throwable, new ErrorInfo(true)); + } + + /** + * This handles application crashing errors by giving notification to the user clearly.
+ * The user can only exit the program. + */ public static void crashHandle(Throwable throwable, ErrorInfo info) { Logging.CRASHHANDLER.error(throwable); @@ -45,7 +53,8 @@ public static void crashHandle(Throwable throwable, ErrorInfo info) { if (GraphicsEnvironment.isHeadless() && ping != null) { try { ping.get(); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return; } @@ -100,11 +109,20 @@ public static void crashHandle(Throwable throwable, ErrorInfo info) { System.exit(info.type.exitCode); } - public static void errorHandle(Throwable throwable) { errorHandle(throwable, new ErrorInfo()); } - public static void errorHandle(Throwable throwable, ErrorInfo info) { errorHandle(throwable, info, null); } - /** This handles application crashing errors by giving notification to the user clearly.
+ public static void errorHandle(Throwable throwable) { + errorHandle(throwable, new ErrorInfo()); + } + + public static void errorHandle(Throwable throwable, ErrorInfo info) { + errorHandle(throwable, info, null); + } + + /** + * This handles application crashing errors by giving notification to the user clearly.
* The user can ignore the error, continue handling the error or exit the program (only in serious errors or error reports). - * @param handling The handling function of the error. */ + * + * @param handling The handling function of the error. + */ public static void errorHandle(Throwable throwable, ErrorInfo info, @Nullable Action handling) { throwable.printStackTrace(); @@ -118,7 +136,8 @@ public static void errorHandle(Throwable throwable, ErrorInfo info, @Nullable Ac if (GraphicsEnvironment.isHeadless() && ping != null) { try { ping.get(); - } catch (Exception ignored) {} + } catch (Exception ignored) { + } return; } @@ -161,13 +180,18 @@ public static void errorHandle(Throwable throwable, ErrorInfo info, @Nullable Ac dialog.setVisible(true); // Shows the dialog. } - /** Getting the stack trace display component. */ + /** + * Getting the stack trace display component. + */ private static JScrollPane getErrorScrollPane(String stackTrace) { JTextArea errorDisplay = new JTextArea(stackTrace); errorDisplay.setEditable(false); return new JScrollPane(errorDisplay); } - /** Getting the panel for crashing handling dialog. */ + + /** + * Getting the panel for crashing handling dialog. + */ private static JPanel getCrashPanel(ErrorInfo info, JScrollPane errorPane, JDialog dialog, String stackTrace) { JPanel panel = new JPanel(new BorderLayout()); panel.add(errorPane); @@ -190,6 +214,7 @@ private static JPanel getCrashPanel(ErrorInfo info, JScrollPane errorPane, JDial panel.add(buttonPanel, BorderLayout.SOUTH); return panel; } + private static JPanel getErrorPanel(ErrorInfo info, JScrollPane errorPane, JDialog dialog, String stackTrace, Action callback, Future> ping) { JPanel panel = new JPanel(new BorderLayout()); panel.add(errorPane); @@ -249,13 +274,31 @@ public static class ErrorInfo { public final String message; public final boolean serious; - public ErrorInfo() { this(false); } - public ErrorInfo(boolean crashing) { this(crashing ? "General Application Crash" : "General Application Error", - crashing ? ErrorType.DEFAULT : ErrorType.REPORT); } - public ErrorInfo(String topic) { this(topic, ErrorType.DEFAULT); } - public ErrorInfo(String topic, ErrorType type) { this(topic, type, type.exitCode != 0); } - public ErrorInfo(String topic, ErrorType type, boolean serious) { this(topic, type, serious, null); } - public ErrorInfo(String topic, ErrorType type, String message) { this(topic, type, type.exitCode < 0, message); } + public ErrorInfo() { + this(false); + } + + public ErrorInfo(boolean crashing) { + this(crashing ? "General Application Crash" : "General Application Error", + crashing ? ErrorType.DEFAULT : ErrorType.REPORT); + } + + public ErrorInfo(String topic) { + this(topic, ErrorType.DEFAULT); + } + + public ErrorInfo(String topic, ErrorType type) { + this(topic, type, type.exitCode != 0); + } + + public ErrorInfo(String topic, ErrorType type, boolean serious) { + this(topic, type, serious, null); + } + + public ErrorInfo(String topic, ErrorType type, String message) { + this(topic, type, type.exitCode < 0, message); + } + public ErrorInfo(String topic, ErrorType type, boolean serious, String message) { this.title = topic; this.type = type; @@ -263,17 +306,21 @@ public ErrorInfo(String topic, ErrorType type, boolean serious, String message) this.serious = serious; } - /** The error types. Add more types when needed. */ + /** + * The error types. Add more types when needed. + */ public static enum ErrorType { - DEFAULT (-1, "Unhandled error"), - UNEXPECTED (-2, "Unexpected error"), - UNHANDLEABLE (-3, "Unhandleable error"), - SERIOUS (1, "Serious error"), - HANDLED (0, "Handled error"), - REPORT (0, "Error report"), + DEFAULT(-1, "Unhandled error"), + UNEXPECTED(-2, "Unexpected error"), + UNHANDLEABLE(-3, "Unhandleable error"), + SERIOUS(1, "Serious error"), + HANDLED(0, "Handled error"), + REPORT(0, "Error report"), ; - /** The exit codes are referring to https://www.techiedelight.com/exit-codes-java-system-exit-method/ */ + /** + * The exit codes are referring to https://www.techiedelight.com/exit-codes-java-system-exit-method/ + */ public final int exitCode; public final String name; diff --git a/src/client/java/minicraft/core/Game.java b/src/client/java/minicraft/core/Game.java index 544d6de12..226af77d5 100644 --- a/src/client/java/minicraft/core/Game.java +++ b/src/client/java/minicraft/core/Game.java @@ -4,7 +4,6 @@ import minicraft.core.io.Settings; import minicraft.core.io.Sound; import minicraft.entity.mob.Player; -import minicraft.gfx.Screen; import minicraft.level.Level; import minicraft.level.tile.Tiles; import minicraft.network.Analytics; @@ -21,7 +20,8 @@ import java.util.List; public class Game { - protected Game() {} // Can't instantiate the Game class. + protected Game() { + } // Can't instantiate the Game class. public static final String NAME = "Minicraft Plus"; // This is the name on the application window. @@ -37,13 +37,18 @@ protected Game() {} // Can't instantiate the Game class. // DISPLAY static Display currentDisplay = null; static final ArrayDeque displayQuery = new ArrayDeque<>(); + public static void setDisplay(@Nullable Display display) { if (display == null) displayQuery.clear(); else displayQuery.add(display); } - public static void exitDisplay() { exitDisplay(1); } + + public static void exitDisplay() { + exitDisplay(1); + } + public static void exitDisplay(int depth) { if (depth < 1) return; // There is nothing needed to exit. if (displayQuery.isEmpty()) { @@ -61,11 +66,16 @@ public static void exitDisplay(int depth) { displayQuery.add(parent); } } + @Nullable - public static Display getDisplay() { return displayQuery.isEmpty() ? null : displayQuery.peekLast(); } + public static Display getDisplay() { + return displayQuery.isEmpty() ? null : displayQuery.peekLast(); + } // GAMEMODE - public static boolean isMode(String mode) { return ((String)Settings.get("mode")).equalsIgnoreCase(mode); } + public static boolean isMode(String mode) { + return ((String) Settings.get("mode")).equalsIgnoreCase(mode); + } // LEVEL public static Level[] levels = new Level[6]; // This array stores the different levels. @@ -76,7 +86,10 @@ public static void exitDisplay(int depth) { static boolean gameOver = false; // If the player wins this is set to true. static boolean running = true; - public static void quit() { running = false; } + + public static void quit() { + running = false; + } public static void main(String[] args) { diff --git a/src/client/java/minicraft/core/Initializer.java b/src/client/java/minicraft/core/Initializer.java index 95872d3b2..fa0149844 100644 --- a/src/client/java/minicraft/core/Initializer.java +++ b/src/client/java/minicraft/core/Initializer.java @@ -21,7 +21,8 @@ import java.io.IOException; public class Initializer extends Game { - private Initializer() {} + private Initializer() { + } /** * Reference to actual frame, also it may be null. @@ -29,8 +30,13 @@ private Initializer() {} static JFrame frame; static int fra, tik; // These store the number of frames and ticks in the previous second; used for fps, at least. - public static JFrame getFrame() { return frame; } - public static int getCurFps() { return fra; } + public static JFrame getFrame() { + return frame; + } + + public static int getCurFps() { + return fra; + } static void parseArgs(String[] args) { // Parses command line arguments @@ -68,10 +74,11 @@ static void parseArgs(String[] args) { FileHandler.determineGameDir(saveDir); } - /** This is the main loop that runs the game. It: - * -keeps track of the amount of time that has passed - * -fires the ticks needed to run the game - * -fires the command to render out the screen. + /** + * This is the main loop that runs the game. It: + * -keeps track of the amount of time that has passed + * -fires the ticks needed to run the game + * -fires the command to render out the screen. */ static void run() { long lastTick = System.nanoTime(); @@ -109,7 +116,8 @@ static void run() { //noinspection BusyWait Thread.sleep((long) Math.floor(timeToWait / 1E6), (int) ((timeToWait - Math.floor(timeToWait)) % 1E6)); } - } catch (InterruptedException ignored) {} + } catch (InterruptedException ignored) { + } if (System.currentTimeMillis() - lastTimer1 > 1000) { //updates every 1 second long interval = System.currentTimeMillis() - lastTimer1; @@ -153,12 +161,25 @@ public void componentResized(ComponentEvent e) { }); frame.addWindowListener(new WindowListener() { - public void windowActivated(WindowEvent e) {} - public void windowDeactivated(WindowEvent e) {} - public void windowIconified(WindowEvent e) {} - public void windowDeiconified(WindowEvent e) {} - public void windowOpened(WindowEvent e) {} - public void windowClosed(WindowEvent e) { Logging.GAMEHANDLER.debug("Window closed"); } + public void windowActivated(WindowEvent e) { + } + + public void windowDeactivated(WindowEvent e) { + } + + public void windowIconified(WindowEvent e) { + } + + public void windowDeiconified(WindowEvent e) { + } + + public void windowOpened(WindowEvent e) { + } + + public void windowClosed(WindowEvent e) { + Logging.GAMEHANDLER.debug("Window closed"); + } + public void windowClosing(WindowEvent e) { Logging.GAMEHANDLER.info("Window closing"); quit(); @@ -166,7 +187,9 @@ public void windowClosing(WindowEvent e) { }); } - /** Launching the main window. */ + /** + * Launching the main window. + */ static void launchWindow() { frame.setVisible(true); frame.requestFocus(); @@ -178,7 +201,7 @@ static void launchWindow() { * that is extracted via PrintStream. * * @param throwable Throwable/Exception from which stack trace is to be - * extracted. + * extracted. * @return String with provided Throwable's stack trace. */ public static String getExceptionTrace(final Throwable throwable) { diff --git a/src/client/java/minicraft/core/Renderer.java b/src/client/java/minicraft/core/Renderer.java index 3d2fcce91..63a12cb55 100644 --- a/src/client/java/minicraft/core/Renderer.java +++ b/src/client/java/minicraft/core/Renderer.java @@ -330,7 +330,7 @@ private static void renderGui() { // Draws the text WateringCanItem tin = (WateringCanItem) player.activeItem; int dura = tin.content * 100 / tin.CAPACITY; - int green = (int)(dura * 2.55f); // Let duration show as normal. + int green = (int) (dura * 2.55f); // Let duration show as normal. Font.drawBackground(dura + "%", screen, 164, Screen.h - 16, Color.get(1, 255 - green, green, 0)); } @@ -445,7 +445,7 @@ public static void renderBossbar(int length, String title) { } } - screen.render(x - 5 , y , 0, ACTIVE_BOSSBAR, 0, hudSheet.getSheet()); // right corner + screen.render(x - 5, y, 0, ACTIVE_BOSSBAR, 0, hudSheet.getSheet()); // right corner for (int bx = 0; bx < bar_length; bx++) { for (int by = 0; by < 1; by++) { @@ -467,10 +467,10 @@ private static void renderQuestsDisplay() { for (Quest q : quests) { QuestSeries series = q.getSeries(); - questsShown.add(!expanding? - new StringEntry(Localization.getLocalized(q.key), Color.WHITE, false): + questsShown.add(!expanding ? + new StringEntry(Localization.getLocalized(q.key), Color.WHITE, false) : new StringEntry(q.shouldAllCriteriaBeCompleted() && q.getTotalNumCriteria() > 1 ? - String.format("%s (%d/%d)", Localization.getLocalized(series.key), q.getNumCriteriaCompleted(), q.getTotalNumCriteria()) : + String.format("%s (%d/%d)", Localization.getLocalized(series.key), q.getNumCriteriaCompleted(), q.getTotalNumCriteria()) : Localization.getLocalized(series.key), Color.WHITE, false) ); diff --git a/src/client/java/minicraft/core/Updater.java b/src/client/java/minicraft/core/Updater.java index 7e1178a62..70dacc202 100644 --- a/src/client/java/minicraft/core/Updater.java +++ b/src/client/java/minicraft/core/Updater.java @@ -20,7 +20,8 @@ import java.awt.GraphicsDevice; public class Updater extends Game { - private Updater() {} + private Updater() { + } // TIME AND TICKS @@ -31,8 +32,8 @@ private Updater() {} public static int tickCount = 0; // The number of ticks since the beginning of the game day. static int time = 0; // Facilites time of day / sunlight. public static final int dayLength = 64800; // This value determines how long one game day is. - public static final int sleepEndTime = dayLength/8; // This value determines when the player "wakes up" in the morning. - public static final int sleepStartTime = dayLength/2+dayLength/8; // This value determines when the player allowed to sleep. + public static final int sleepEndTime = dayLength / 8; // This value determines when the player "wakes up" in the morning. + public static final int sleepStartTime = dayLength / 2 + dayLength / 8; // This value determines when the player allowed to sleep. //public static int noon = 32400; // This value determines when the sky switches from getting lighter to getting darker. public static int gameTime = 0; // This stores the total time (number of ticks) you've been playing your @@ -56,10 +57,10 @@ private Updater() {} public static int screenshot = 0; // Counter for screenshot queries. public enum Time { - Morning (0), - Day (dayLength/4), - Evening (dayLength/2), - Night (dayLength/4*3); + Morning(0), + Day(dayLength / 4), + Evening(dayLength / 2), + Night(dayLength / 4 * 3); public int tickTime; @@ -92,10 +93,10 @@ static void updateFullscreen() { public static void tick() { // Quick Level change: move the player for -1, or 1 levels - if (isMode("minicraft.settings.mode.creative") && input.getMappedKey("SHIFT-S").isClicked() ) { + if (isMode("minicraft.settings.mode.creative") && input.getMappedKey("SHIFT-S").isClicked()) { Game.setDisplay(new LevelTransitionDisplay(-1)); - } else if (isMode("minicraft.settings.mode.creative") && input.getMappedKey("SHIFT-W").isClicked() ){ + } else if (isMode("minicraft.settings.mode.creative") && input.getMappedKey("SHIFT-W").isClicked()) { Game.setDisplay(new LevelTransitionDisplay(1)); } @@ -151,7 +152,7 @@ public static void tick() { } // Auto-save tick; marks when to do autosave. - if(!paused) + if (!paused) asTick++; if (asTick > astime) { if ((boolean) Settings.get("autosave") && !gameOver && player.health > 0) { @@ -163,7 +164,7 @@ public static void tick() { } // Increment tickCount if the game is not paused - if (!paused) setTime(tickCount+1); + if (!paused) setTime(tickCount + 1); // SCORE MODE ONLY @@ -239,7 +240,7 @@ public static void tick() { if (input.getMappedKey("F3-T-3").isClicked()) changeTimeOfDay(Time.Evening); if (input.getMappedKey("F3-T-4").isClicked()) changeTimeOfDay(Time.Night); - String prevMode = (String)Settings.get("mode"); + String prevMode = (String) Settings.get("mode"); if (input.getMappedKey("F3-F4-2").isClicked()) { Settings.set("mode", "minicraft.settings.mode.creative"); Logging.WORLDNAMED.trace("Game mode changed from {} into {}.", prevMode, "minicraft.settings.mode.creative"); @@ -264,12 +265,12 @@ public static void tick() { } if (input.getMappedKey("F3-S-equals").isClicked()) { if (gamespeed < 1) gamespeed *= 2; - else if (normSpeed*gamespeed < 2000) gamespeed++; + else if (normSpeed * gamespeed < 2000) gamespeed++; Logging.WORLDNAMED.trace("Tick speed increased from {} into {}.", prevSpeed, gamespeed); } if (input.getMappedKey("F3-S-minus").isClicked()) { if (gamespeed > 1) gamespeed--; - else if (normSpeed*gamespeed > 5) gamespeed /= 2; + else if (normSpeed * gamespeed > 5) gamespeed /= 2; Logging.WORLDNAMED.trace("Tick speed decreased from {} into {}.", prevSpeed, gamespeed); } @@ -278,13 +279,14 @@ public static void tick() { if (input.getMappedKey("F3-M-0").isClicked()) player.moveSpeed = 1; if (input.getMappedKey("F3-M-equals").isClicked()) player.moveSpeed++; - if (input.getMappedKey("F3-M-minus").isClicked() && player.moveSpeed > 1) player.moveSpeed--; // -= 0.5D; + if (input.getMappedKey("F3-M-minus").isClicked() && player.moveSpeed > 1) + player.moveSpeed--; // -= 0.5D; if (input.getMappedKey("F3-u").isClicked()) { - levels[currentLevel].setTile(player.x>>4, player.y>>4, Tiles.get("Stairs Up")); + levels[currentLevel].setTile(player.x >> 4, player.y >> 4, Tiles.get("Stairs Up")); } if (input.getMappedKey("F3-d").isClicked()) { - levels[currentLevel].setTile(player.x>>4, player.y>>4, Tiles.get("Stairs Down")); + levels[currentLevel].setTile(player.x >> 4, player.y >> 4, Tiles.get("Stairs Down")); } } // End debug only cond. } // End "menu-null" conditional @@ -311,6 +313,7 @@ public static void setTime(int ticks) { public static void changeTimeOfDay(Time t) { setTime(t.tickTime); } + // This one works too. public static void changeTimeOfDay(int t) { Time[] times = Time.values(); @@ -325,10 +328,13 @@ public static Time getTime() { return times[time]; } - /** This adds a notification to all player games. */ + /** + * This adds a notification to all player games. + */ public static void notifyAll(String msg) { notifyAll(msg, 0); } + public static void notifyAll(String msg, int notetick) { msg = Localization.getLocalized(msg); notifications.add(msg); diff --git a/src/client/java/minicraft/core/World.java b/src/client/java/minicraft/core/World.java index 4e5a2aa8d..6aeb52452 100644 --- a/src/client/java/minicraft/core/World.java +++ b/src/client/java/minicraft/core/World.java @@ -22,7 +22,8 @@ import java.util.Random; public class World extends Game { - private World() {} + private World() { + } public static final int[] idxToDepth = {-3, -2, -1, 0, 1, -4}; /// This is to map the level depths to each level's index in Game's levels array. This must ALWAYS be the same length as the levels array, of course. public static final int minLevelDepth, maxLevelDepth; @@ -44,7 +45,7 @@ private World() {} static { int min, max; min = max = idxToDepth[0]; - for (int depth: idxToDepth) { + for (int depth : idxToDepth) { if (depth < min) min = depth; if (depth > max) @@ -54,7 +55,9 @@ private World() {} maxLevelDepth = max; } - /** This is for a contained way to find the index in the levels array of a level, based on it's depth. This is also helpful because add a new level in the future could change this. */ + /** + * This is for a contained way to find the index in the levels array of a level, based on it's depth. This is also helpful because add a new level in the future could change this. + */ public static int lvlIdx(int depth) { if (depth > maxLevelDepth) return lvlIdx(minLevelDepth); if (depth < minLevelDepth) return lvlIdx(maxLevelDepth); @@ -65,8 +68,13 @@ public static int lvlIdx(int depth) { } - /** This method is used when respawning, and by initWorld to reset the vars. It does not generate any new terrain. */ - public static void resetGame() { resetGame(true); } + /** + * This method is used when respawning, and by initWorld to reset the vars. It does not generate any new terrain. + */ + public static void resetGame() { + resetGame(true); + } + public static void resetGame(boolean keepPlayer) { Logging.WORLD.debug("Resetting..."); playerDeadTime = 0; @@ -91,7 +99,8 @@ public static void resetGame(boolean keepPlayer) { } } - /** This method is used to create a brand new world, or to load an existing one from a file. + /** + * This method is used to create a brand new world, or to load an existing one from a file. * For the loading screen updates to work, it it assumed that *this* is called by a thread *other* than the one rendering the current *menu*. **/ public static void initWorld() { // This is a full reset; everything. @@ -135,7 +144,7 @@ public static void resetGame(boolean keepPlayer) { Logging.WORLD.trace("Generating level " + i + "..."); LoadingDisplay.setMessage(Level.getDepthString(i)); - levels[lvlIdx(i)] = new Level(worldSize, worldSize, random.nextLong(), i, levels[lvlIdx(i+1)], !WorldSelectDisplay.hasLoadedWorld()); + levels[lvlIdx(i)] = new Level(worldSize, worldSize, random.nextLong(), i, levels[lvlIdx(i + 1)], !WorldSelectDisplay.hasLoadedWorld()); LoadingDisplay.progress(loadingInc); } @@ -159,20 +168,32 @@ public static void resetGame(boolean keepPlayer) { Logging.WORLD.trace("World initialized."); } - public static long getWorldSeed() { return seed; } - public static void setWorldSeed(long seed) { World.seed = seed; } + public static long getWorldSeed() { + return seed; + } + + public static void setWorldSeed(long seed) { + World.seed = seed; + } + + /** + * This method is called when you interact with stairs, this will give you the transition effect. While changeLevel(int) just changes the level. + */ + public static void scheduleLevelChange(int dir) { + scheduleLevelChange(dir, null); + } - /** This method is called when you interact with stairs, this will give you the transition effect. While changeLevel(int) just changes the level. */ - public static void scheduleLevelChange(int dir) { scheduleLevelChange(dir, null); } public static void scheduleLevelChange(int dir, @Nullable Action changeAction) { onChangeAction = changeAction; pendingLevelChange = dir; } - /** This method changes the level that the player is currently on. + /** + * This method changes the level that the player is currently on. * It takes 1 integer variable, which is used to tell the game which direction to go. * For example, 'changeLevel(1)' will make you go up a level, - while 'changeLevel(-1)' will make you go down a level. */ + * while 'changeLevel(-1)' will make you go down a level. + */ public static void changeLevel(int dir) { if (onChangeAction != null) { onChangeAction.act(); @@ -182,7 +203,7 @@ public static void changeLevel(int dir) { levels[currentLevel].remove(player); // Removes the player from the current level. int nextLevel = currentLevel + dir; - if (nextLevel <= -1) nextLevel = levels.length-1; // Fix accidental level underflow + if (nextLevel <= -1) nextLevel = levels.length - 1; // Fix accidental level underflow if (nextLevel >= levels.length) nextLevel = 0; // Fix accidental level overflow Logging.WORLD.trace("Setting level from {} to {}", currentLevel, nextLevel); currentLevel = nextLevel; @@ -206,6 +227,11 @@ public static void onWorldExits() { lastWorldExitTime = System.currentTimeMillis(); } - public static long getLastWorldExitTime() { return lastWorldExitTime; } - public static long getLastWorldEnterTime() { return lastWorldEnterTime; } + public static long getLastWorldExitTime() { + return lastWorldExitTime; + } + + public static long getLastWorldEnterTime() { + return lastWorldEnterTime; + } } diff --git a/src/client/java/minicraft/core/io/ClipboardHandler.java b/src/client/java/minicraft/core/io/ClipboardHandler.java index 0fa75b5fc..1b3b537cf 100644 --- a/src/client/java/minicraft/core/io/ClipboardHandler.java +++ b/src/client/java/minicraft/core/io/ClipboardHandler.java @@ -13,36 +13,38 @@ public final class ClipboardHandler implements ClipboardOwner { - @Override - public void lostOwnership(Clipboard clipboard, Transferable contents) { } + @Override + public void lostOwnership(Clipboard clipboard, Transferable contents) { + } /** * Give the system clipboard data. */ - public void setClipboardContents(String string) { - StringSelection stringSelection = new StringSelection(string); - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - clipboard.setContents(stringSelection, this); - } + public void setClipboardContents(String string) { + StringSelection stringSelection = new StringSelection(string); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + clipboard.setContents(stringSelection, this); + } /** * Get the string from the system clipboard data. + * * @return A string with the contents. */ public String getClipboardContents() { - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - Transferable contents = clipboard.getContents(null); + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + Transferable contents = clipboard.getContents(null); - String result = ""; + String result = ""; - if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { - try { - result = (String) contents.getTransferData(DataFlavor.stringFlavor); - } catch (UnsupportedFlavorException | IOException ex) { + if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) { + try { + result = (String) contents.getTransferData(DataFlavor.stringFlavor); + } catch (UnsupportedFlavorException | IOException ex) { CrashHandler.errorHandle(ex); - } - } + } + } - return result; - } + return result; + } } diff --git a/src/client/java/minicraft/core/io/FileHandler.java b/src/client/java/minicraft/core/io/FileHandler.java index a831c3160..cdde3472c 100644 --- a/src/client/java/minicraft/core/io/FileHandler.java +++ b/src/client/java/minicraft/core/io/FileHandler.java @@ -26,7 +26,8 @@ import java.util.stream.Stream; public class FileHandler extends Game { - private FileHandler() {} + private FileHandler() { + } public static final int REPLACE_EXISTING = 0; public static final int RENAME_COPY = 1; @@ -99,11 +100,11 @@ public static void determineGameDir(@Nullable String saveDir) { } public static String getSystemGameDir() { - return systemGameDir; + return systemGameDir; } public static String getLocalGameDir() { - return localGameDir; + return localGameDir; } private static void deleteFolder(File top) { @@ -133,7 +134,7 @@ else if (ifExisting == RENAME_COPY) { newFilename = newFilename.substring(0, newFilename.lastIndexOf(".")); do { newFilename += "(Old)"; - } while(new File(newFilename).exists()); + } while (new File(newFilename).exists()); newFilename += Save.extension; } } @@ -146,12 +147,15 @@ else if (ifExisting == RENAME_COPY) { } return FileVisitResult.CONTINUE; } + public FileVisitResult preVisitDirectory(Path p, BasicFileAttributes bfa) { return FileVisitResult.CONTINUE; } + public FileVisitResult postVisitDirectory(Path p, IOException ex) { return FileVisitResult.CONTINUE; } + public FileVisitResult visitFileFailed(Path p, IOException ex) { return FileVisitResult.CONTINUE; } @@ -179,7 +183,7 @@ public static ArrayList listAssets() { ArrayList names = new ArrayList<>(); try (Stream paths = Files.walk(path)) { Path finalPath = path; - paths.forEach(p -> names.add(finalPath.getParent().relativize(p).toString().replace('\\', '/')+ + paths.forEach(p -> names.add(finalPath.getParent().relativize(p).toString().replace('\\', '/') + (p.toFile().isDirectory() ? "/" : ""))); return names; } catch (IOException e) { @@ -203,7 +207,7 @@ private static ArrayList listResourcesUsingIDE() { Path folderPath = Paths.get(fUrl.toURI()); Files.walk(folderPath) - .forEach(p -> { + .forEach(p -> { names.add(folderPath.relativize(p).toString().replace('\\', '/') + (p.toFile().isDirectory() ? "/" : "")); }); diff --git a/src/client/java/minicraft/core/io/InputHandler.java b/src/client/java/minicraft/core/io/InputHandler.java index d7037ced3..f45a7e180 100644 --- a/src/client/java/minicraft/core/io/InputHandler.java +++ b/src/client/java/minicraft/core/io/InputHandler.java @@ -24,30 +24,29 @@ public class InputHandler implements KeyListener { /** - This class handles key presses; this also implements MouseListener... but I have no idea why. - It's not used in any way. Ever. As far as I know. Anyway, here are a few tips about this class: - - -This class must instantiated to be used; and it's pretty much always called "input" in the code. - - -The keys are stored in two arrays, one for physical keyboard keys(called "keyboard"), and one for "keys" you make-up (called "keymap") to represent different actions ("virtual keys", you could say). - - -All the Keys in the keyboard array are generated automatically as you ask for them in the code (if they don't already exist), so there's no need to define anything in the keyboard array here. - --Note: this shouldn't matter, but keys that are not asked for or defined as values here in keymap will be ignored when it comes to key presses. - - -All the "virtual keys" in keymap "map" to a Key object in the keyboard array; that is to say, - keymap contains a HashMap of string keys, to string values. The keys are the names of the actions, - and the values are the names of the keyboard keys you physically press to do them. - - -To get whether a key is pressed or not, use input.getKey("key"), where "key" is the name of the key, either physical or virtual. If virtual, all it does is then fetch the corrosponding key from keyboard anyway; but it allows one to change the controls while still making the same key requests in the code. - - -If you want to have multiple possibilities at once when it comes to which key to press to do something, you can! just put a "|" between the mappings. For example, say you wanted both "wasd" and arrow key controls to work, at the same time. How you do this is in the construstor below, where it says "keymap.put(" UP, DOWN, LEFT, and RIGHT. - - -This class supports modifier keys as inputs. To specify a "compound" key (one using modifiders), write "MOD1-MOD2-KEY", that is, "SHIFT-ALT-D" or "ALT-F", with a "-" between the keys. ALWAYS put the actual trigger key last, after all modifiers (the modifiers are: shift, ctrl, and alt). - - --All the magic happens in the getKey() method: If the String keyname input has hyphens("-"), then it's a compound key, and it splits it up between the hyphens. Then, it compares which modifiers are currently being pressed, and which are being requested. Then, a Key object is created, which if the modifiers match, reflects the non-modifier key's "down" and "clicked" values; otherwise they're both false. - --If a key with no hyph is requested, it skips most of that and just gives you the Key, generating it if needed. - - */ + * This class handles key presses; this also implements MouseListener... but I have no idea why. + * It's not used in any way. Ever. As far as I know. Anyway, here are a few tips about this class: + *

+ * -This class must instantiated to be used; and it's pretty much always called "input" in the code. + *

+ * -The keys are stored in two arrays, one for physical keyboard keys(called "keyboard"), and one for "keys" you make-up (called "keymap") to represent different actions ("virtual keys", you could say). + *

+ * -All the Keys in the keyboard array are generated automatically as you ask for them in the code (if they don't already exist), so there's no need to define anything in the keyboard array here. + * --Note: this shouldn't matter, but keys that are not asked for or defined as values here in keymap will be ignored when it comes to key presses. + *

+ * -All the "virtual keys" in keymap "map" to a Key object in the keyboard array; that is to say, + * keymap contains a HashMap of string keys, to string values. The keys are the names of the actions, + * and the values are the names of the keyboard keys you physically press to do them. + *

+ * -To get whether a key is pressed or not, use input.getKey("key"), where "key" is the name of the key, either physical or virtual. If virtual, all it does is then fetch the corrosponding key from keyboard anyway; but it allows one to change the controls while still making the same key requests in the code. + *

+ * -If you want to have multiple possibilities at once when it comes to which key to press to do something, you can! just put a "|" between the mappings. For example, say you wanted both "wasd" and arrow key controls to work, at the same time. How you do this is in the construstor below, where it says "keymap.put(" UP, DOWN, LEFT, and RIGHT. + *

+ * -This class supports modifier keys as inputs. To specify a "compound" key (one using modifiders), write "MOD1-MOD2-KEY", that is, "SHIFT-ALT-D" or "ALT-F", with a "-" between the keys. ALWAYS put the actual trigger key last, after all modifiers (the modifiers are: shift, ctrl, and alt). + *

+ * --All the magic happens in the getKey() method: If the String keyname input has hyphens("-"), then it's a compound key, and it splits it up between the hyphens. Then, it compares which modifiers are currently being pressed, and which are being requested. Then, a Key object is created, which if the modifiers match, reflects the non-modifier key's "down" and "clicked" values; otherwise they're both false. + * --If a key with no hyph is requested, it skips most of that and just gives you the Key, generating it if needed. + */ public String keyToChange = null; // This is used when listening to change key bindings. private String keyChanged = null; // This is used when listening to change key bindings. private boolean overwrite = false; @@ -64,20 +63,22 @@ public String getChangedKey() { } private static HashMap keyNames = new HashMap<>(); + static { Field[] keyEventFields = KeyEvent.class.getFields(); ArrayList keyConstants = new ArrayList<>(); - for (Field field: keyEventFields) { + for (Field field : keyEventFields) { if (field.getName().contains("VK_") && (field.getType().getName().equals(int.class.getName()))) keyConstants.add(field); } - for (Field keyConst: keyConstants) { + for (Field keyConst : keyConstants) { String name = keyConst.getName(); name = name.substring(3); // Removes the "VK_" try { - keyNames.put(((Integer)keyConst.get(0)), name); - } catch(IllegalAccessException ignored) {} + keyNames.put(((Integer) keyConst.get(0)), name); + } catch (IllegalAccessException ignored) { + } } // For compatibility becuase I'm lazy. :P @@ -117,6 +118,7 @@ public InputHandler() { Logging.CONTROLLER.debug("No Controllers Detected, moving on."); } } + public InputHandler(Component inputSource) { this(); inputSource.addKeyListener(this); // Add key listener to game @@ -166,6 +168,7 @@ private void initKeyMap() { // The button mapping should not be modifiable. private final HashMap buttonMap = new HashMap<>(); + private void initButtonMap() { buttonMap.put("MOVE-UP", ControllerButton.DPAD_UP); buttonMap.put("MOVE-DOWN", ControllerButton.DPAD_DOWN); @@ -198,13 +201,15 @@ public void resetKeyBindings() { initKeyMap(); } - /** Processes each key one by one, in keyboard. */ + /** + * Processes each key one by one, in keyboard. + */ public void tick() { lastKeyTyped = keyTypedBuffer; keyTypedBuffer = ""; inputMask = null; synchronized ("lock") { - for (PhysicalKey key: keyboard.values()) + for (PhysicalKey key : keyboard.values()) key.tick(); // Call tick() for each key. } @@ -216,7 +221,8 @@ public void tick() { controllerButtonBooleanMapJust.put(btn, controllerIndex.isButtonJustPressed(btn)); } catch (ControllerUnpluggedException e) { controllerButtonBooleanMapJust.put(btn, false); - } try { + } + try { controllerButtonBooleanMap.put(btn, controllerIndex.isButtonPressed(btn)); } catch (ControllerUnpluggedException e) { controllerButtonBooleanMap.put(btn, false); @@ -250,7 +256,10 @@ private static class PhysicalKey extends Key { protected boolean stayDown; - public PhysicalKey() { this(false); } + public PhysicalKey() { + this(false); + } + public PhysicalKey(boolean stayDown) { this.stayDown = stayDown; } @@ -265,17 +274,21 @@ public boolean isClicked() { return clicked; } - /** toggles the key down or not down. */ + /** + * toggles the key down or not down. + */ public void toggle(boolean pressed) { down = pressed; // Set down to the passed in value; the if statement is probably unnecessary... if (pressed && !sticky) presses++; // Add to the number of total presses. } - /** Processes the key presses. */ + /** + * Processes the key presses. + */ public void tick() { if (absorbs < presses) { // If there are more key presses to process... absorbs++; // Process them! - if(presses - absorbs > 3) absorbs = presses - 3; + if (presses - absorbs > 3) absorbs = presses - 3; clicked = true; // Make clicked true, since key presses are still being processed. } else { // All key presses so far for this key have been processed. if (!sticky) sticky = presses > 3; @@ -357,9 +370,11 @@ public void maskInput(@Nullable Predicate filter) { inputMask = inputMask == null ? filter : inputMask.and(filter); } - /** This is used to stop all of the actions when the game is out of focus. */ + /** + * This is used to stop all of the actions when the game is out of focus. + */ public void releaseAll() { - for (PhysicalKey key: keyboard.values()) { + for (PhysicalKey key : keyboard.values()) { key.release(); } } @@ -370,7 +385,9 @@ public void setKey(String keymapKey, String keyboardKey) { keymap.put(keymapKey, keyboardKey); } - /** Simply returns the mapped value of key in keymap. */ + /** + * Simply returns the mapped value of key in keymap. + */ public String getMapping(String actionKey) { actionKey = actionKey.toUpperCase(); if (lastInputActivityListener.lastButtonActivityTimestamp > lastInputActivityListener.lastKeyActivityTimestamp) { @@ -386,7 +403,8 @@ public String getMapping(String actionKey) { /** * Returning the corresponding mapping depends on the device last acted. - * @param keyMap The keyboard mapping. + * + * @param keyMap The keyboard mapping. * @param buttonMap The controller mapping * @return The selected mapping. */ @@ -399,6 +417,7 @@ public String selectMapping(String keyMap, String buttonMap) { /** * Getting the last input device type. + * * @return The input device type: 0 for keyboard, 1 for controller. */ public int getLastInputType() { @@ -421,7 +440,7 @@ public Key getMappedKey(String keyText) { if (keyText.contains("|")) { /// Multiple key possibilities exist for this action; so, combine the results of each one! ArrayList keys = new ArrayList<>(); - for (String keyposs: keyText.split("\\|")) { // String.split() uses regex, and "|" is a special character, so it must be escaped; but the backslash must be passed in, so it needs escaping. + for (String keyposs : keyText.split("\\|")) { // String.split() uses regex, and "|" is a special character, so it must be escaped; but the backslash must be passed in, so it needs escaping. // It really does combine using "or": keys.add(getMappedKey(keyposs)); } @@ -440,6 +459,7 @@ public Key getMappedKey(String keyText) { //if(key.clicked && Game.debug) System.out.println("Processed key: " + keytext + " is clicked; tickNum=" + ticks); return new CompoundedKey(keys); // Return the Key object. } + // Physical keys only private Key getKey(String keytext) { // If the passed-in key is blank, or null, then return null. @@ -450,7 +470,7 @@ private Key getKey(String keytext) { if (keytext.contains("|")) { /// Multiple key possibilities exist for this action; so, combine the results of each one! ArrayList keys = new ArrayList<>(); - for (String keyposs: keytext.split("\\|")) { // String.split() uses regex, and "|" is a special character, so it must be escaped; but the backslash must be passed in, so it needs escaping. + for (String keyposs : keytext.split("\\|")) { // String.split() uses regex, and "|" is a special character, so it must be escaped; but the backslash must be passed in, so it needs escaping. // It really does combine using "or": keys.add(getKey(keyposs)); } @@ -532,8 +552,8 @@ private void toggle(int keycode, boolean pressed) { //System.out.println("Interpreted key press: " + keytext); //System.out.println("Toggling " + keytext + " key (keycode " + keycode + ") to "+pressed+"."); - if( pressed && keyToChange != null && !isMod(keytext) ) { - keymap.put(keyToChange, ( overwrite ? "" : keymap.get(keyToChange) + "|" ) + getCurModifiers() + keytext); + if (pressed && keyToChange != null && !isMod(keytext)) { + keymap.put(keyToChange, (overwrite ? "" : keymap.get(keyToChange) + "|") + getCurModifiers() + keytext); keyChanged = keyToChange; keyToChange = null; return; @@ -581,15 +601,17 @@ private static boolean isMod(String keyname) { private String getCurModifiers() { return (getKey("ctrl").isDown() ? "CTRL-" : "") + - (getKey("alt").isDown() ? "ALT-" : "") + - (getKey("shift").isDown() ? "SHIFT-" : ""); + (getKey("alt").isDown() ? "ALT-" : "") + + (getKey("shift").isDown() ? "SHIFT-" : ""); } - /** Used by Save.java, to save user key preferences. */ + /** + * Used by Save.java, to save user key preferences. + */ public String[] getKeyPrefs() { ArrayList keystore = new ArrayList<>(); // Make a list for keys - for (String keyname: keymap.keySet()) // Go though each mapping + for (String keyname : keymap.keySet()) // Go though each mapping keystore.add(keyname + ";" + keymap.get(keyname)); // Add the mapping values as one string, seperated by a semicolon. return keystore.toArray(new String[0]); // Return the array of encoded key preferences. @@ -607,19 +629,26 @@ public void addKeyBinding(String actionKey) { } /// Event methods, many to satisfy interface requirements... - public void keyPressed(KeyEvent ke) { toggle(ke.getExtendedKeyCode(), true); } - public void keyReleased(KeyEvent ke) { toggle(ke.getExtendedKeyCode(), false); } + public void keyPressed(KeyEvent ke) { + toggle(ke.getExtendedKeyCode(), true); + } + + public void keyReleased(KeyEvent ke) { + toggle(ke.getExtendedKeyCode(), false); + } + public void keyTyped(KeyEvent ke) { // Stores the last character typed keyTypedBuffer = String.valueOf(ke.getKeyChar()); } private static final String control = "\\p{Print}"; // Should match only printable characters. + public String addKeyTyped(String typing, @Nullable String pattern) { if (lastKeyTyped.length() > 0) { String letter = lastKeyTyped; lastKeyTyped = ""; - if ( letter.matches(control) && (pattern == null || letter.matches(pattern)) || letter.equals("\b") ) + if (letter.matches(control) && (pattern == null || letter.matches(pattern)) || letter.equals("\b")) typing += letter; } @@ -688,7 +717,7 @@ public boolean inputDown(String mapping) { * vibration (maybe the controller doesn't support left/right vibration, maybe it was unplugged in the * middle of trying, etc...) * - * @param leftMagnitude The speed for the left motor to vibrate (this should be between 0 and 1) + * @param leftMagnitude The speed for the left motor to vibrate (this should be between 0 and 1) * @param rightMagnitude The speed for the right motor to vibrate (this should be between 0 and 1) * @return Whether or not the controller was able to be vibrated (i.e. if haptics are supported) or controller not connected. */ @@ -714,6 +743,7 @@ public boolean leftTriggerPressed() { return false; } } + public boolean rightTriggerPressed() { try { if (rightTriggerCooldown == 0 && controllerIndex.getAxisState(ControllerAxis.TRIGGERRIGHT) > 0.5) { diff --git a/src/client/java/minicraft/core/io/Localization.java b/src/client/java/minicraft/core/io/Localization.java index 019aa243a..3d74cff79 100644 --- a/src/client/java/minicraft/core/io/Localization.java +++ b/src/client/java/minicraft/core/io/Localization.java @@ -27,7 +27,8 @@ public class Localization { /** * Get the provided key's localization for the currently selected language. - * @param key The key to localize. + * + * @param key The key to localize. * @param arguments The additional arguments to format the localized string. * @return A localized string. */ @@ -39,12 +40,14 @@ public static String getLocalized(String key, Object... arguments) { try { Double.parseDouble(key); return key; // This is a number; don't try to localize it - } catch(NumberFormatException ignored) {} + } catch (NumberFormatException ignored) { + } String localString = localization.get(key); if (localString == null) { - if (!knownUnlocalizedStrings.containsKey(selectedLocale)) knownUnlocalizedStrings.put(selectedLocale, new HashSet<>()); + if (!knownUnlocalizedStrings.containsKey(selectedLocale)) + knownUnlocalizedStrings.put(selectedLocale, new HashSet<>()); if (!knownUnlocalizedStrings.get(selectedLocale).contains(key)) { Logger.tag("LOC").trace(unlocalizedStringTracing ? new Throwable("Tracing") : null, "{}: '{}' is unlocalized.", selectedLocale.toLanguageTag(), key); knownUnlocalizedStrings.get(selectedLocale).add(key); @@ -60,12 +63,16 @@ public static String getLocalized(String key, Object... arguments) { /** * Gets the currently selected locale. + * * @return A locale object. */ - public static Locale getSelectedLocale() { return selectedLocale; } + public static Locale getSelectedLocale() { + return selectedLocale; + } /** * Get the currently selected locale, but as a full name without the country code. + * * @return A string with the name of the language. */ @NotNull @@ -75,20 +82,27 @@ public static LocaleInformation getSelectedLanguage() { /** * Gets a list of all the known locales. + * * @return A list of locales. */ @NotNull - public static LocaleInformation[] getLocales() { return localeInfo.values().toArray(new LocaleInformation[0]); } + public static LocaleInformation[] getLocales() { + return localeInfo.values().toArray(new LocaleInformation[0]); + } /** * Changes the selected language and loads it. * If the provided language doesn't exist, it loads the default locale. + * * @param newLanguage The language-country code of the language to load. */ public static void changeLanguage(@NotNull String newLanguage) { changeLanguage(Locale.forLanguageTag(newLanguage)); } - /** @see #changeLanguage(String) */ + + /** + * @see #changeLanguage(String) + */ public static void changeLanguage(@NotNull Locale newLanguage) { selectedLocale = newLanguage; loadLanguage(); diff --git a/src/client/java/minicraft/core/io/Settings.java b/src/client/java/minicraft/core/io/Settings.java index ce0c92622..792a5639e 100644 --- a/src/client/java/minicraft/core/io/Settings.java +++ b/src/client/java/minicraft/core/io/Settings.java @@ -43,29 +43,39 @@ public final class Settings { /** * Returns the value of the specified option. + * * @param option The setting to get. * @return The value of the setting */ - public static Object get(String option) { return options.get(option.toLowerCase()).getValue(); } + public static Object get(String option) { + return options.get(option.toLowerCase()).getValue(); + } /** * Returns the index of the value in the list of values for the specified option. + * * @param option The setting to get. * @return The index of the setting. */ - public static int getIdx(String option) { return options.get(option.toLowerCase()).getSelection(); } + public static int getIdx(String option) { + return options.get(option.toLowerCase()).getSelection(); + } /** * Return the ArrayEntry object associated with the given option name. + * * @param option The setting to get. * @return The ArrayEntry. */ - public static ArrayEntry getEntry(String option) { return options.get(option.toLowerCase()); } + public static ArrayEntry getEntry(String option) { + return options.get(option.toLowerCase()); + } /** * Sets the value of the given option name, to the given value, provided it is a valid value for that option. + * * @param option The setting to edit. - * @param value The value to change to. + * @param value The value to change to. */ public static void set(String option, Object value) { options.get(option.toLowerCase()).setValue(value); @@ -73,8 +83,9 @@ public static void set(String option, Object value) { /** * Sets the index of the value of the given option, provided it is a valid index. + * * @param option The setting to edit. - * @param idx Index to select. + * @param idx Index to select. */ public static void setIdx(String option, int idx) { options.get(option.toLowerCase()).setSelection(idx); @@ -83,6 +94,7 @@ public static void setIdx(String option, int idx) { /** * Gets the refresh rate of the default monitor. * Safely handles headless environments (if that were to happen for some reason). + * * @return The refresh rate if successful. 60 if not. */ private static int getDefaultRefreshRate() { diff --git a/src/client/java/minicraft/core/io/Sound.java b/src/client/java/minicraft/core/io/Sound.java index fd547a7a3..09d9cc032 100644 --- a/src/client/java/minicraft/core/io/Sound.java +++ b/src/client/java/minicraft/core/io/Sound.java @@ -36,7 +36,7 @@ public static void loadSound(String key, InputStream in, String pack) { DataLine.Info info = new DataLine.Info(Clip.class, AudioSystem.getAudioFileFormat(in).getFormat()); if (!AudioSystem.isLineSupported(info)) { - Logging.RESOURCEHANDLER_SOUND.error("ERROR: Audio format of file \"{}\" in pack \"\" is not supported: {}", key, pack, AudioSystem.getAudioFileFormat(in)); + Logging.RESOURCEHANDLER_SOUND.error("ERROR: Audio format of file \"{}\" in pack \"\" is not supported: {}", key, pack, AudioSystem.getAudioFileFormat(in)); Logging.RESOURCEHANDLER_SOUND.error("Supported audio formats:"); Logging.RESOURCEHANDLER_SOUND.error("-source:"); @@ -51,13 +51,11 @@ public static void loadSound(String key, InputStream in, String pack) { } } Logging.RESOURCEHANDLER_SOUND.error("-target:"); - for (int i = 0; i < tinfo.length; i++) - { - if (tinfo[i] instanceof DataLine.Info) - { + for (int i = 0; i < tinfo.length; i++) { + if (tinfo[i] instanceof DataLine.Info) { DataLine.Info dataLineInfo = (DataLine.Info) tinfo[i]; AudioFormat[] supportedFormats = dataLineInfo.getFormats(); - for (AudioFormat af: supportedFormats) + for (AudioFormat af : supportedFormats) Logging.RESOURCEHANDLER_SOUND.error(af); } } @@ -65,7 +63,7 @@ public static void loadSound(String key, InputStream in, String pack) { return; } - Clip clip = (Clip)AudioSystem.getLine(info); + Clip clip = (Clip) AudioSystem.getLine(info); clip.open(AudioSystem.getAudioInputStream(in)); clip.addLineListener(e -> { @@ -83,26 +81,32 @@ public static void loadSound(String key, InputStream in, String pack) { } } - /** Recommend {@link #play(String)} and {@link #loop(String, boolean)}. */ + /** + * Recommend {@link #play(String)} and {@link #loop(String, boolean)}. + */ @Nullable public static Sound getSound(String key) { return sounds.get(key); } - /** This method does safe check for {@link #play()}. */ + /** + * This method does safe check for {@link #play()}. + */ public static void play(String key) { Sound sound = sounds.get(key); if (sound != null) sound.play(); } - /** This method does safe check for {@link #loop(boolean)}. */ + /** + * This method does safe check for {@link #loop(boolean)}. + */ public static void loop(String key, boolean start) { Sound sound = sounds.get(key); if (sound != null) sound.loop(start); } public void play() { - if (!(boolean)Settings.get("sound") || clip == null) return; + if (!(boolean) Settings.get("sound") || clip == null) return; if (clip.isRunning() || clip.isActive()) clip.stop(); @@ -111,7 +115,7 @@ public void play() { } public void loop(boolean start) { - if (!(boolean)Settings.get("sound") || clip == null) return; + if (!(boolean) Settings.get("sound") || clip == null) return; if (start) clip.loop(Clip.LOOP_CONTINUOUSLY); diff --git a/src/client/java/minicraft/entity/Arrow.java b/src/client/java/minicraft/entity/Arrow.java index c5220d4a9..19cb2a13b 100644 --- a/src/client/java/minicraft/entity/Arrow.java +++ b/src/client/java/minicraft/entity/Arrow.java @@ -23,8 +23,9 @@ public class Arrow extends Entity implements ClientTickable { public Arrow(Mob owner, Direction dir, int dmg) { this(owner, owner.x, owner.y, dir, dmg); } + public Arrow(Mob owner, int x, int y, Direction dir, int dmg) { - super(Math.abs(dir.getX())+1, Math.abs(dir.getY())+1); + super(Math.abs(dir.getX()) + 1, Math.abs(dir.getY()) + 1); this.owner = owner; this.x = x; this.y = y; @@ -34,9 +35,9 @@ public Arrow(Mob owner, int x, int y, Direction dir, int dmg) { col = Color.get(-1, 111, 222, 430); int xt = 0; - if(dir == Direction.LEFT) xt = 1; - if(dir == Direction.UP) xt = 2; - if(dir == Direction.DOWN) xt = 3; + if (dir == Direction.LEFT) xt = 1; + if (dir == Direction.UP) xt = 2; + if (dir == Direction.DOWN) xt = 3; sprite.setSpritePos(xt, 0); if (damage > 3) speed = 8; @@ -46,10 +47,11 @@ public Arrow(Mob owner, int x, int y, Direction dir, int dmg) { /** * Generates information about the arrow. + * * @return string representation of owner, xdir, ydir and damage. */ public String getData() { - return owner.eid + ":" + dir.ordinal() + ":"+damage; + return owner.eid + ":" + dir.ordinal() + ":" + damage; } @Override @@ -75,8 +77,8 @@ public void tick() { } if (!level.getTile(x / 16, y / 16).mayPass(level, x / 16, y / 16, this) - && !level.getTile(x / 16, y / 16).connectsToFluid - && level.getTile(x / 16, y / 16).id != 16) { + && !level.getTile(x / 16, y / 16).connectsToFluid + && level.getTile(x / 16, y / 16).id != 16) { this.remove(); try { sprite.destroy(); diff --git a/src/client/java/minicraft/entity/ClientTickable.java b/src/client/java/minicraft/entity/ClientTickable.java index 81cc73998..55c4325d8 100644 --- a/src/client/java/minicraft/entity/ClientTickable.java +++ b/src/client/java/minicraft/entity/ClientTickable.java @@ -1,9 +1,9 @@ package minicraft.entity; public interface ClientTickable extends Tickable { - + default void clientTick() { tick(); } - + } diff --git a/src/client/java/minicraft/entity/Direction.java b/src/client/java/minicraft/entity/Direction.java index 68c93f079..291be85f9 100644 --- a/src/client/java/minicraft/entity/Direction.java +++ b/src/client/java/minicraft/entity/Direction.java @@ -13,11 +13,17 @@ public enum Direction { public static final Direction[] values = Direction.values(); - public int getX() { return x; } - public int getY() { return y; } + public int getX() { + return x; + } + + public int getY() { + return y; + } public static Direction getDirection(int xd, int yd) { - if (xd == 0 && yd == 0) return Direction.NONE; // The attack was from the same entity, probably; or at least the exact same space. + if (xd == 0 && yd == 0) + return Direction.NONE; // The attack was from the same entity, probably; or at least the exact same space. if (Math.abs(xd) > Math.abs(yd)) { // The x distance is more prominent than the y distance @@ -34,7 +40,10 @@ public static Direction getDirection(int xd, int yd) { } public static Direction getDirection(int dir) { - return values[dir+1]; + return values[dir + 1]; + } + + public int getDir() { + return ordinal() - 1; } - public int getDir() { return ordinal()-1; } } diff --git a/src/client/java/minicraft/entity/Entity.java b/src/client/java/minicraft/entity/Entity.java index 81d245aae..6dc8089da 100644 --- a/src/client/java/minicraft/entity/Entity.java +++ b/src/client/java/minicraft/entity/Entity.java @@ -49,6 +49,7 @@ public abstract class Entity implements Tickable { * Assings null/none values to the instace variables. * The exception is removed which is set to true, and * lastUpdate which is set to System.nanoTime(). + * * @param xr X radius of entity. * @param yr Y radius of entity. */ @@ -70,48 +71,84 @@ public Entity(int xr, int yr) { // Add color to this later, in color update /** * Returns true if the entity is removed from the level, otherwise false. + * * @return removed */ - public boolean isRemoved() { return removed/* || level == null*/; } + public boolean isRemoved() { + return removed/* || level == null*/; + } /** * Returns the level which this entity belongs in. + * * @return level */ - public Level getLevel() { return level; } + public Level getLevel() { + return level; + } - /** Returns a Rectangle instance using the defined bounds of the entity. */ - protected Rectangle getBounds() { return new Rectangle(x, y, xr * 2, yr * 2, Rectangle.CENTER_DIMS); } + /** + * Returns a Rectangle instance using the defined bounds of the entity. + */ + protected Rectangle getBounds() { + return new Rectangle(x, y, xr * 2, yr * 2, Rectangle.CENTER_DIMS); + } - /** Returns true if this entity is found in the rectangle specified by given two coordinates. */ - public boolean isTouching(Rectangle area) { return area.intersects(getBounds()); } + /** + * Returns true if this entity is found in the rectangle specified by given two coordinates. + */ + public boolean isTouching(Rectangle area) { + return area.intersects(getBounds()); + } - /** Returns if this entity stops other solid entities from moving. */ - public boolean isSolid() { return true; } // Most entities are solid + /** + * Returns if this entity stops other solid entities from moving. + */ + public boolean isSolid() { + return true; + } // Most entities are solid + + /** + * Determines if the given entity should prevent this entity from moving. + */ + public boolean blocks(Entity e) { + return isSolid() && e.isSolid(); + } + + public boolean canSwim() { + return false; + } // Determines if the entity can swim (extended in sub-classes) - /** Determines if the given entity should prevent this entity from moving. */ - public boolean blocks(Entity e) { return isSolid() && e.isSolid(); } + public boolean canWool() { + return false; + } // This, strangely enough, determines if the entity can walk on wool; among some other things..? - public boolean canSwim() { return false; } // Determines if the entity can swim (extended in sub-classes) - public boolean canWool() { return false; } // This, strangely enough, determines if the entity can walk on wool; among some other things..? public boolean canBurn() { return true; } // Determines if the entity can burn. + public boolean canBeAffectedByLava() { return true; } // Determines if the entity can burn in lava. + public int burningDuration = 0; - public int getLightRadius() { return 0; } // Used for lanterns... and player? that might be about it, though, so idk if I want to put it here. + public int getLightRadius() { + return 0; + } // Used for lanterns... and player? that might be about it, though, so idk if I want to put it here. - /** If this entity is touched by another entity (extended by sub-classes) */ - protected void touchedBy(Entity entity) {} + /** + * If this entity is touched by another entity (extended by sub-classes) + */ + protected void touchedBy(Entity entity) { + } /** * Interacts with the entity this method is called on - * @param player The player attacking - * @param item The item the player attacked with + * + * @param player The player attacking + * @param item The item the player attacked with * @param attackDir The direction to interact * @return If the interaction was successful */ @@ -119,7 +156,9 @@ public boolean interact(Player player, @Nullable Item item, Direction attackDir) return false; } - /** Moves an entity horizontally and vertically. Returns whether entity was unimpeded in it's movement. */ + /** + * Moves an entity horizontally and vertically. Returns whether entity was unimpeded in it's movement. + */ public boolean move(int xd, int yd) { if (Updater.saving || (xd == 0 && yd == 0)) return true; // Pretend that it kept moving @@ -134,6 +173,7 @@ public boolean move(int xd, int yd) { /** * Moves the entity a long only on X axis without "teleporting". * Will throw exception otherwise. + * * @param d Displacement relative to the axis. * @return true if the move was successful, false if not. */ @@ -167,6 +207,7 @@ protected boolean moveX(int d) { /** * Moves the entity a long only on X axis without "teleporting". * Will throw exception otherwise. + * * @param d Displacement relative to the axis. * @return true if the move was successful, false if not. */ @@ -199,16 +240,17 @@ protected boolean moveY(int d) { /** * Moves the entity by checking entity hit boxes being interacted with the given possible length of straight path. - * @param sgn One-dimensional direction of displacement - * @param hitBoxFront The front boundary of hit box - * @param maxFront Maximum position can be reached with front hit box (firstly checked by tile hot box) - * @param xMove The value of the willing x movement - * @param yMove The value of the willing y movement - * @param incrementMove The movement call when the movement is possible - * @param hitBoxLeft The left boundary of hit box - * @param hitBoxRight The right boundary of hit box - * @param bumpingHandler The consumer handling bumping into a new tile; - * the first parameter takes the front tile position and second one takes the horizontal position + * + * @param sgn One-dimensional direction of displacement + * @param hitBoxFront The front boundary of hit box + * @param maxFront Maximum position can be reached with front hit box (firstly checked by tile hot box) + * @param xMove The value of the willing x movement + * @param yMove The value of the willing y movement + * @param incrementMove The movement call when the movement is possible + * @param hitBoxLeft The left boundary of hit box + * @param hitBoxRight The right boundary of hit box + * @param bumpingHandler The consumer handling bumping into a new tile; + * the first parameter takes the front tile position and second one takes the horizontal position * @param steppingHandler The consumer handling stepping on a new tile; * the first parameter takes the front tile position and second one takes the horizontal position * @return {@code true} if the movement is successful, {@code false} otherwise. @@ -261,13 +303,22 @@ protected boolean moveByEntityHitBoxChecks(int sgn, int hitBoxFront, int maxFron return successful; } - /** Checks if the entity is able to naturally be despawned in general conditions. Handles (despawns) if true. */ - public void handleDespawn() {} + /** + * Checks if the entity is able to naturally be despawned in general conditions. Handles (despawns) if true. + */ + public void handleDespawn() { + } - /** This exists as a way to signify that the entity has been removed through player action and/or world action; basically, it's actually gone, not just removed from a level because it's out of range or something. Calls to this method are used to, say, drop items. */ - public void die() { remove(); } + /** + * This exists as a way to signify that the entity has been removed through player action and/or world action; basically, it's actually gone, not just removed from a level because it's out of range or something. Calls to this method are used to, say, drop items. + */ + public void die() { + remove(); + } - /** Removes the entity from the level. */ + /** + * Removes the entity from the level. + */ public void remove() { if (removed && !(this instanceof ItemEntity)) // Apparently this happens fairly often with item entities. Logging.ENTITY.debug("Note: remove() called on removed entity: " + this); @@ -280,7 +331,9 @@ public void remove() { level.remove(this); } - /** This should ONLY be called by the Level class. To properly remove an entity from a level, use level.remove(entity) */ + /** + * This should ONLY be called by the Level class. To properly remove an entity from a level, use level.remove(entity) + */ public void remove(Level level) { if (level != this.level) { Logging.ENTITY.debug("Tried to remove entity " + this + " from level it is not in: " + level + "; in level " + this.level); @@ -290,7 +343,9 @@ public void remove(Level level) { } } - /** This should ONLY be called by the Level class. To properly add an entity to a level, use level.add(entity) */ + /** + * This should ONLY be called by the Level class. To properly add an entity to a level, use level.add(entity) + */ public void setLevel(Level level, int x, int y) { if (level == null) { Logging.ENTITY.debug("Tried to set level of entity " + this + " to a null level; Should use remove(level)"); @@ -308,7 +363,8 @@ public void setLevel(Level level, int x, int y) { public boolean isWithin(int tileRadius, Entity other) { if (level == null || other.getLevel() == null) return false; - if (level.depth != other.getLevel().depth) return false; // Obviously, if they are on different levels, they can't be next to each other. + if (level.depth != other.getLevel().depth) + return false; // Obviously, if they are on different levels, they can't be next to each other. double distance = Math.abs(Math.hypot(x - other.x, y - other.y)); // Calculate the distance between the two entities, in entity coordinates. @@ -317,6 +373,7 @@ public boolean isWithin(int tileRadius, Entity other) { /** * Returns the closest player to this entity. + * * @return the closest player. */ protected Player getClosestPlayer() { @@ -326,6 +383,7 @@ protected Player getClosestPlayer() { /** * Returns the closes player to this entity. * If this is called on a player it can return itself. + * * @param returnSelf determines if the method can return itself. * @return The closest player to this entity. */ @@ -338,7 +396,10 @@ protected Player getClosestPlayer(boolean returnSelf) { return level.getClosestPlayer(x, y); } - public String toString() { return getClass().getSimpleName() + getDataPrints(); } + public String toString() { + return getClass().getSimpleName() + getDataPrints(); + } + protected List getDataPrints() { List prints = new ArrayList<>(); prints.add("eid=" + eid); @@ -351,5 +412,7 @@ public final boolean equals(Object other) { } @Override - public final int hashCode() { return eid; } + public final int hashCode() { + return eid; + } } diff --git a/src/client/java/minicraft/entity/FireSpark.java b/src/client/java/minicraft/entity/FireSpark.java index 06dd9daf3..9f07662d3 100644 --- a/src/client/java/minicraft/entity/FireSpark.java +++ b/src/client/java/minicraft/entity/FireSpark.java @@ -20,9 +20,10 @@ public class FireSpark extends Entity { /** * Creates a new spark. Owner is the Obsidian Knight which is spawning this spark. + * * @param owner The Obsidian Knight spawning the spark. - * @param xa X velocity. - * @param ya Y velocity. + * @param xa X velocity. + * @param ya Y velocity. */ public FireSpark(ObsidianKnight owner, double xa, double ya) { super(0, 0); @@ -59,7 +60,8 @@ public void tick() { yy += ya; boolean stopped = true; //noinspection RedundantIfStatement - if (moveX(((int) xx) - x0)) stopped = false; // This kind of difference is handled due to errors by flooring. + if (moveX(((int) xx) - x0)) + stopped = false; // This kind of difference is handled due to errors by flooring. if (moveY(((int) yy) - y0)) stopped = false; if (stopped) { this.stopped = true; @@ -74,7 +76,9 @@ public void tick() { } } - /** Can this entity block you? Nope. */ + /** + * Can this entity block you? Nope. + */ public boolean isSolid() { return false; } @@ -102,6 +106,7 @@ public void render(Screen screen) { /** * Returns the owners id as a string. + * * @return the owners id as a string. */ public String getData() { diff --git a/src/client/java/minicraft/entity/ItemEntity.java b/src/client/java/minicraft/entity/ItemEntity.java index 6c7e09083..be94bd7ef 100644 --- a/src/client/java/minicraft/entity/ItemEntity.java +++ b/src/client/java/minicraft/entity/ItemEntity.java @@ -20,9 +20,10 @@ public class ItemEntity extends Entity implements ClientTickable { /** * Creates an item entity of the item item at position (x,y) with size 2*2. + * * @param item Item to add as item entity - * @param x position on map - * @param y position on map + * @param x position on map + * @param y position on map */ public ItemEntity(Item item, int x, int y) { super(2, 2); @@ -45,15 +46,16 @@ public ItemEntity(Item item, int x, int y) { /** * Creates an item entity of the item item at position (x,y) with size 2*2. - * @param item Item to add as item entity. - * @param x position on map - * @param y position on map - * @param zz z position? + * + * @param item Item to add as item entity. + * @param x position on map + * @param y position on map + * @param zz z position? * @param lifetime lifetime (in ticks) of the entity. - * @param time starting time (in ticks) of the entity. - * @param xa x velocity - * @param ya y velocity - * @param za z velocity? + * @param time starting time (in ticks) of the entity. + * @param xa x velocity + * @param ya y velocity + * @param za z velocity? */ public ItemEntity(Item item, int x, int y, double zz, int lifetime, int time, double xa, double ya, double za) { this(item, x, y); @@ -67,10 +69,11 @@ public ItemEntity(Item item, int x, int y, double zz, int lifetime, int time, do /** * Returns a string representation of the itementity + * * @return string representation of this entity */ public String getData() { - return String.join(":", (new String[] {item.getData(), zz + "", lifeTime+"", time + "", xa + "", ya + "", za + ""})); + return String.join(":", (new String[]{item.getData(), zz + "", lifeTime + "", time + "", xa + "", ya + "", za + ""})); } @Override @@ -128,18 +131,18 @@ public void render(Screen screen) { if (time / 6 % 2 == 0) return; } - screen.render(x-4, y - 4, item.sprite.getSprite(), 0, false, Color.get(0, 31)); // Item shadow + screen.render(x - 4, y - 4, item.sprite.getSprite(), 0, false, Color.get(0, 31)); // Item shadow screen.render(x - 4, y - 4 - (int) zz, item.sprite); // Item } @Override protected void touchedBy(Entity entity) { - if(!(entity instanceof Player)) return; // For the time being, we only care when a player touches an item. + if (!(entity instanceof Player)) return; // For the time being, we only care when a player touches an item. if (time > 30) { // Conditional prevents this from being collected immediately. if (!pickedUp) {// Don't register if we are online and a player touches it; the client will register that. pickedUp = true; - ((Player)entity).pickupItem(this); + ((Player) entity).pickupItem(this); pickedUp = isRemoved(); } } diff --git a/src/client/java/minicraft/entity/ItemHolder.java b/src/client/java/minicraft/entity/ItemHolder.java index 6e374cfb7..6d6b3191d 100644 --- a/src/client/java/minicraft/entity/ItemHolder.java +++ b/src/client/java/minicraft/entity/ItemHolder.java @@ -3,7 +3,7 @@ import minicraft.item.Inventory; public interface ItemHolder { - + Inventory getInventory(); - + } diff --git a/src/client/java/minicraft/entity/Spark.java b/src/client/java/minicraft/entity/Spark.java index 4ce29a876..f937abe67 100644 --- a/src/client/java/minicraft/entity/Spark.java +++ b/src/client/java/minicraft/entity/Spark.java @@ -19,9 +19,10 @@ public class Spark extends Entity { /** * Creates a new spark. Owner is the AirWizard which is spawning this spark. + * * @param owner The AirWizard spawning the spark. - * @param xa X velocity. - * @param ya Y velocity. + * @param xa X velocity. + * @param ya Y velocity. */ public Spark(AirWizard owner, double xa, double ya) { super(0, 0); @@ -50,12 +51,14 @@ public void tick() { y = (int) yy; Player player = getClosestPlayer(); - if (player.isWithin(0,this)) { - player.hurt(owner,1); + if (player.isWithin(0, this)) { + player.hurt(owner, 1); } } - /** Can this entity block you? Nope. */ + /** + * Can this entity block you? Nope. + */ public boolean isSolid() { return false; } @@ -72,7 +75,6 @@ public void render(Screen screen) { } - randmirror = random.nextInt(4); } @@ -83,6 +85,7 @@ public void render(Screen screen) { /** * Returns the owners id as a string. + * * @return the owners id as a string. */ public String getData() { diff --git a/src/client/java/minicraft/entity/Tickable.java b/src/client/java/minicraft/entity/Tickable.java index c39c8f4d8..1ab3e4e42 100644 --- a/src/client/java/minicraft/entity/Tickable.java +++ b/src/client/java/minicraft/entity/Tickable.java @@ -2,7 +2,9 @@ public interface Tickable { - /** Called every frame before Render() is called. Most game functionality in the game is based on this method.*/ + /** + * Called every frame before Render() is called. Most game functionality in the game is based on this method. + */ void tick(); } diff --git a/src/client/java/minicraft/entity/furniture/Bed.java b/src/client/java/minicraft/entity/furniture/Bed.java index 41f57fd99..f9515c00a 100644 --- a/src/client/java/minicraft/entity/furniture/Bed.java +++ b/src/client/java/minicraft/entity/furniture/Bed.java @@ -22,7 +22,9 @@ public Bed() { super("Bed", new LinkedSprite(SpriteType.Entity, "bed"), new LinkedSprite(SpriteType.Item, "bed"), 3, 2); } - /** Called when the player attempts to get in bed. */ + /** + * Called when the player attempts to get in bed. + */ public boolean use(Player player) { if (checkCanSleep(player)) { // If it is late enough in the day to sleep... @@ -44,7 +46,7 @@ public static boolean checkCanSleep(Player player) { if (!(Updater.tickCount >= Updater.sleepStartTime || Updater.tickCount < Updater.sleepEndTime && Updater.pastDay1)) { // It is too early to sleep; display how much time is remaining. - int sec = (int)Math.ceil((Updater.sleepStartTime - Updater.tickCount)*1.0 / Updater.normSpeed); // gets the seconds until sleeping is allowed. // normSpeed is in tiks/sec. + int sec = (int) Math.ceil((Updater.sleepStartTime - Updater.tickCount) * 1.0 / Updater.normSpeed); // gets the seconds until sleeping is allowed. // normSpeed is in tiks/sec. String note = Localization.getLocalized("minicraft.notification.cannot_sleep", sec / 60, sec % 60); Game.notifications.add(note); // Add the notification displaying the time remaining in minutes and seconds. @@ -54,9 +56,14 @@ public static boolean checkCanSleep(Player player) { return true; } - public static boolean sleeping() { return playersAwake == 0; } + public static boolean sleeping() { + return playersAwake == 0; + } + + public static boolean inBed(Player player) { + return sleepingPlayers.containsKey(player); + } - public static boolean inBed(Player player) { return sleepingPlayers.containsKey(player); } public static Level getBedLevel(Player player) { Bed bed = sleepingPlayers.get(player); if (bed == null) @@ -69,7 +76,9 @@ public static void removePlayer(Player player) { sleepingPlayers.remove(player); } - public static void removePlayers() { sleepingPlayers.clear(); } + public static void removePlayers() { + sleepingPlayers.clear(); + } // Client should not call this. public static void restorePlayer(Player player) { @@ -83,9 +92,10 @@ public static void restorePlayer(Player player) { playersAwake = 1; } } + // Client should not call this. public static void restorePlayers() { - for (Player p: sleepingPlayers.keySet()) { + for (Player p : sleepingPlayers.keySet()) { Bed bed = sleepingPlayers.get(p); bed.getLevel().add(p); } diff --git a/src/client/java/minicraft/entity/furniture/Chest.java b/src/client/java/minicraft/entity/furniture/Chest.java index 71944b462..395d78dcf 100644 --- a/src/client/java/minicraft/entity/furniture/Chest.java +++ b/src/client/java/minicraft/entity/furniture/Chest.java @@ -20,11 +20,17 @@ public class Chest extends Furniture implements ItemHolder { private Inventory inventory; // Inventory of the chest - public Chest() { this("Chest"); } + public Chest() { + this("Chest"); + } + + public Chest(String name) { + this(name, new LinkedSprite(SpriteType.Item, "chest")); + } - public Chest(String name) { this(name, new LinkedSprite(SpriteType.Item, "chest")); } /** * Creates a chest with a custom name. + * * @param name Name of chest. */ public Chest(String name, LinkedSprite itemSprite) { @@ -33,7 +39,9 @@ public Chest(String name, LinkedSprite itemSprite) { inventory = new Inventory(); // Initialize the inventory. } - /** This is what occurs when the player uses the "Menu" command near this */ + /** + * This is what occurs when the player uses the "Menu" command near this + */ public boolean use(Player player) { Game.setDisplay(new ContainerDisplay(player, this)); return true; diff --git a/src/client/java/minicraft/entity/furniture/Crafter.java b/src/client/java/minicraft/entity/furniture/Crafter.java index 27f40ee23..49fab3dd5 100644 --- a/src/client/java/minicraft/entity/furniture/Crafter.java +++ b/src/client/java/minicraft/entity/furniture/Crafter.java @@ -14,12 +14,12 @@ public class Crafter extends Furniture { public enum Type { - Workbench (new LinkedSprite(SpriteType.Entity, "workbench"), new LinkedSprite(SpriteType.Item, "workbench"), 3, 2, Recipes.workbenchRecipes), - Oven (new LinkedSprite(SpriteType.Entity, "oven"), new LinkedSprite(SpriteType.Item, "oven"), 3, 2, Recipes.ovenRecipes), - Furnace (new LinkedSprite(SpriteType.Entity, "furnace"), new LinkedSprite(SpriteType.Item, "furnace"), 3, 2, Recipes.furnaceRecipes), - Anvil (new LinkedSprite(SpriteType.Entity, "anvil"), new LinkedSprite(SpriteType.Item, "anvil"), 3, 2, Recipes.anvilRecipes), - Enchanter (new LinkedSprite(SpriteType.Entity, "enchanter"), new LinkedSprite(SpriteType.Item, "enchanter"), 7, 2, Recipes.enchantRecipes), - Loom (new LinkedSprite(SpriteType.Entity, "loom"), new LinkedSprite(SpriteType.Item, "loom"), 7, 2, Recipes.loomRecipes); + Workbench(new LinkedSprite(SpriteType.Entity, "workbench"), new LinkedSprite(SpriteType.Item, "workbench"), 3, 2, Recipes.workbenchRecipes), + Oven(new LinkedSprite(SpriteType.Entity, "oven"), new LinkedSprite(SpriteType.Item, "oven"), 3, 2, Recipes.ovenRecipes), + Furnace(new LinkedSprite(SpriteType.Entity, "furnace"), new LinkedSprite(SpriteType.Item, "furnace"), 3, 2, Recipes.furnaceRecipes), + Anvil(new LinkedSprite(SpriteType.Entity, "anvil"), new LinkedSprite(SpriteType.Item, "anvil"), 3, 2, Recipes.anvilRecipes), + Enchanter(new LinkedSprite(SpriteType.Entity, "enchanter"), new LinkedSprite(SpriteType.Item, "enchanter"), 7, 2, Recipes.enchantRecipes), + Loom(new LinkedSprite(SpriteType.Entity, "loom"), new LinkedSprite(SpriteType.Item, "loom"), 7, 2, Recipes.loomRecipes); public ArrayList recipes; protected LinkedSprite sprite; @@ -35,12 +35,14 @@ public enum Type { Crafter.names.add(this.name()); } } + public static ArrayList names = new ArrayList<>(); public Crafter.Type type; /** * Creates a crafter of a given type. + * * @param type What type of crafter this is. */ public Crafter(Crafter.Type type) { @@ -59,5 +61,7 @@ public boolean use(Player player) { } @Override - public String toString() { return type.name()+getDataPrints(); } + public String toString() { + return type.name() + getDataPrints(); + } } diff --git a/src/client/java/minicraft/entity/furniture/DeathChest.java b/src/client/java/minicraft/entity/furniture/DeathChest.java index 3e7741dd4..d9528da25 100644 --- a/src/client/java/minicraft/entity/furniture/DeathChest.java +++ b/src/client/java/minicraft/entity/furniture/DeathChest.java @@ -22,7 +22,9 @@ public class DeathChest extends Chest { public int time; // Time passed (used for death chest despawn) private int redtick = 0; //This is used to determine the shade of red when the chest is about to expire. private boolean reverse; // What direction the red shade (redtick) is changing. - private Inventory inventory = new Inventory() {{ unlimited = true; }}; // Implement the inventory locally instead. + private Inventory inventory = new Inventory() {{ + unlimited = true; + }}; // Implement the inventory locally instead. /** * Creates a custom chest with the name Death Chest @@ -33,11 +35,11 @@ public DeathChest() { /// Set the expiration time based on the world difficulty. if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) { - time = 300*Updater.normSpeed; + time = 300 * Updater.normSpeed; } else if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) { - time = 120*Updater.normSpeed; + time = 120 * Updater.normSpeed; } else if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { - time = 30*Updater.normSpeed; + time = 30 * Updater.normSpeed; } } @@ -86,20 +88,23 @@ public void tick() { public void render(Screen screen) { super.render(screen); String timeString = (time / Updater.normSpeed) + "S"; - Font.draw(timeString, screen, x - Font.textWidth(timeString)/2, y - Font.textHeight() - getBounds().getHeight()/2, Color.WHITE); + Font.draw(timeString, screen, x - Font.textWidth(timeString) / 2, y - Font.textHeight() - getBounds().getHeight() / 2, Color.WHITE); } - public boolean use(Player player) { return false; } // can't open it, just walk into it. + public boolean use(Player player) { + return false; + } // can't open it, just walk into it. - public void take(Player player) {} // can't grab a death chest. + public void take(Player player) { + } // can't grab a death chest. @Override public void touchedBy(Entity other) { - if(other instanceof Player) { - Inventory playerInv = ((Player)other).getInventory(); + if (other instanceof Player) { + Inventory playerInv = ((Player) other).getInventory(); for (Item i : inventory.getItems()) { int total = 1; - if (i instanceof StackableItem) total = ((StackableItem)i).count; + if (i instanceof StackableItem) total = ((StackableItem) i).count; int returned = playerInv.add(i); if (returned < total) { diff --git a/src/client/java/minicraft/entity/furniture/DungeonChest.java b/src/client/java/minicraft/entity/furniture/DungeonChest.java index a7aaf9ddf..6647745c5 100644 --- a/src/client/java/minicraft/entity/furniture/DungeonChest.java +++ b/src/client/java/minicraft/entity/furniture/DungeonChest.java @@ -27,6 +27,7 @@ public class DungeonChest extends Chest { /** * Creates a custom chest with the name Dungeon Chest. + * * @param populateInv Populate the inventory of the DungeonChest using the loot table system. */ public DungeonChest(boolean populateInv) { @@ -52,9 +53,9 @@ public boolean use(Player player) { boolean activeKey = player.activeItem != null && player.activeItem.equals(Items.get("Key")); boolean invKey = player.getInventory().count(Items.get("key")) > 0; - if(activeKey || invKey) { // If the player has a key... + if (activeKey || invKey) { // If the player has a key... if (activeKey) { // Remove activeItem - StackableItem key = (StackableItem)player.activeItem; + StackableItem key = (StackableItem) player.activeItem; key.count--; } else { // Remove from inv player.getInventory().removeItem(Items.get("key")); @@ -76,8 +77,7 @@ public boolean use(Player player) { } return false; // the chest is locked, and the player has no key. - } - else return super.use(player); // the chest was already unlocked. + } else return super.use(player); // the chest was already unlocked. } /** @@ -108,13 +108,13 @@ public void setLocked(boolean locked) { */ @Override protected void touchedBy(Entity entity) { - if(!isLocked) // can only be pushed if unlocked. + if (!isLocked) // can only be pushed if unlocked. super.touchedBy(entity); } @Override public boolean interact(Player player, @Nullable Item item, Direction attackDir) { - if(!isLocked) + if (!isLocked) return super.interact(player, item, attackDir); return false; } diff --git a/src/client/java/minicraft/entity/furniture/Furniture.java b/src/client/java/minicraft/entity/furniture/Furniture.java index 148a8098a..0a339c345 100644 --- a/src/client/java/minicraft/entity/furniture/Furniture.java +++ b/src/client/java/minicraft/entity/furniture/Furniture.java @@ -12,7 +12,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -/** Many furniture classes are very similar; they might not even need to be there at all... */ +/** + * Many furniture classes are very similar; they might not even need to be there at all... + */ public class Furniture extends Entity { @@ -25,7 +27,8 @@ public class Furniture extends Entity { /** * Constructor for the furniture entity. * Size will be set to 3. - * @param name Name of the furniture. + * + * @param name Name of the furniture. * @param sprite Furniture sprite. */ public Furniture(String name, LinkedSprite sprite, LinkedSprite itemSprite) { @@ -35,10 +38,11 @@ public Furniture(String name, LinkedSprite sprite, LinkedSprite itemSprite) { /** * Constructor for the furniture entity. * Radius is only used for collision detection. - * @param name Name of the furniture. + * + * @param name Name of the furniture. * @param sprite Furniture sprite. - * @param xr Horizontal radius. - * @param yr Vertical radius. + * @param xr Horizontal radius. + * @param yr Vertical radius. */ public Furniture(String name, LinkedSprite sprite, LinkedSprite itemSprite, int xr, int yr) { // All of these are 2x2 on the spritesheet; radius is for collisions only. @@ -67,11 +71,19 @@ public void tick() { else multiPushTime = 0; } - /** Draws the furniture on the screen. */ - public void render(Screen screen) { screen.render(x-8, y-8, sprite); } + /** + * Draws the furniture on the screen. + */ + public void render(Screen screen) { + screen.render(x - 8, y - 8, sprite); + } - /** Called when the player presses the MENU key in front of this. */ - public boolean use(Player player) { return false; } + /** + * Called when the player presses the MENU key in front of this. + */ + public boolean use(Player player) { + return false; + } @Override public boolean blocks(Entity e) { @@ -86,23 +98,25 @@ protected void touchedBy(Entity entity) { /** * Used in PowerGloveItem.java to let the user pick up furniture. + * * @param player The player picking up the furniture. */ @Override public boolean interact(Player player, @Nullable Item item, Direction attackDir) { if (item instanceof PowerGloveItem) { Sound.play("monsterhurt"); - remove(); - if (player.activeItem != null && !(player.activeItem instanceof PowerGloveItem)) - player.getLevel().dropItem(player.x, player.y, player.activeItem); // Put whatever item the player is holding into their inventory - player.activeItem = new FurnitureItem(this); // Make this the player's current item. - return true; + remove(); + if (player.activeItem != null && !(player.activeItem instanceof PowerGloveItem)) + player.getLevel().dropItem(player.x, player.y, player.activeItem); // Put whatever item the player is holding into their inventory + player.activeItem = new FurnitureItem(this); // Make this the player's current item. + return true; } return false; } /** * Tries to let the player push this furniture. + * * @param player The player doing the pushing. */ public void tryPush(Player player) { @@ -113,5 +127,7 @@ public void tryPush(Player player) { } @Override - public boolean canWool() { return true; } + public boolean canWool() { + return true; + } } diff --git a/src/client/java/minicraft/entity/furniture/KnightStatue.java b/src/client/java/minicraft/entity/furniture/KnightStatue.java index 566b0ed13..e2a6f5219 100644 --- a/src/client/java/minicraft/entity/furniture/KnightStatue.java +++ b/src/client/java/minicraft/entity/furniture/KnightStatue.java @@ -43,13 +43,16 @@ public boolean interact(Player player, Item heldItem, Direction attackDir) { } @Override - public void tryPush(Player player) {} // Nothing happens. + public void tryPush(Player player) { + } // Nothing happens. @Override - public @NotNull Furniture copy(){ + public @NotNull Furniture copy() { return new KnightStatue(bossHealth); } - public int getBossHealth() { return bossHealth; } + public int getBossHealth() { + return bossHealth; + } } diff --git a/src/client/java/minicraft/entity/furniture/Lantern.java b/src/client/java/minicraft/entity/furniture/Lantern.java index 857108724..b63f0aa36 100644 --- a/src/client/java/minicraft/entity/furniture/Lantern.java +++ b/src/client/java/minicraft/entity/furniture/Lantern.java @@ -6,9 +6,9 @@ public class Lantern extends Furniture { public enum Type { - NORM ("Lantern", 9, 0), - IRON ("Iron Lantern", 12, 2), - GOLD ("Gold Lantern", 15, 4); + NORM("Lantern", 9, 0), + IRON("Iron Lantern", 12, 2), + GOLD("Gold Lantern", 15, 4); protected int light, offset; protected String title; @@ -24,6 +24,7 @@ public enum Type { /** * Creates a lantern of a given type. + * * @param type Type of lantern. */ public Lantern(Lantern.Type type) { diff --git a/src/client/java/minicraft/entity/furniture/Spawner.java b/src/client/java/minicraft/entity/furniture/Spawner.java index 6a9eb9059..f2f916901 100644 --- a/src/client/java/minicraft/entity/furniture/Spawner.java +++ b/src/client/java/minicraft/entity/furniture/Spawner.java @@ -38,7 +38,7 @@ public class Spawner extends Furniture { private final Random rnd = new Random(); - private static final int ACTIVE_RADIUS = 8*16; + private static final int ACTIVE_RADIUS = 8 * 16; private static final int minSpawnInterval = 200, maxSpawnInterval = 500; private static final int minMobSpawnChance = 10; // 1 in minMobSpawnChance chance of calling trySpawn every interval. @@ -48,6 +48,7 @@ public class Spawner extends Furniture { /** * Initializes the spawners variables to the corresponding values from the mob. + * * @param m The mob which this spawner will spawn. */ private void initMob(MobAi m) { @@ -55,7 +56,7 @@ private void initMob(MobAi m) { sprite.setColor(col = mob.col); if (m instanceof EnemyMob) { - lvl = ((EnemyMob)mob).lvl; + lvl = ((EnemyMob) mob).lvl; maxMobLevel = mob.getMaxLevel(); } else { lvl = 1; @@ -69,19 +70,20 @@ private void initMob(MobAi m) { /** * Creates a new spawner for the mob m. + * * @param m Mob which will be spawned. */ public Spawner(MobAi m) { - super(getClassName(m.getClass()) + " Spawner", new LinkedSprite(SpriteType.Entity, "spawner"), m instanceof Cow ? new LinkedSprite(SpriteType.Item, "cow_spawner"): - m instanceof Pig ? new LinkedSprite(SpriteType.Item, "pig_spawner"): - m instanceof Sheep ? new LinkedSprite(SpriteType.Item, "sheep_spawner"): - m instanceof Slime ? new LinkedSprite(SpriteType.Item, "slime_spawner"): - m instanceof Zombie ? new LinkedSprite(SpriteType.Item, "zombie_spawner"): - m instanceof Creeper ? new LinkedSprite(SpriteType.Item, "creeper_spawner"): - m instanceof Skeleton ? new LinkedSprite(SpriteType.Item, "skeleton_spawner"): - m instanceof Snake ? new LinkedSprite(SpriteType.Item, "snake_spawner"): - m instanceof Knight ? new LinkedSprite(SpriteType.Item, "knight_spawner"): - new LinkedSprite(SpriteType.Item, "air_wizard_spawner"), 7, 2); + super(getClassName(m.getClass()) + " Spawner", new LinkedSprite(SpriteType.Entity, "spawner"), m instanceof Cow ? new LinkedSprite(SpriteType.Item, "cow_spawner") : + m instanceof Pig ? new LinkedSprite(SpriteType.Item, "pig_spawner") : + m instanceof Sheep ? new LinkedSprite(SpriteType.Item, "sheep_spawner") : + m instanceof Slime ? new LinkedSprite(SpriteType.Item, "slime_spawner") : + m instanceof Zombie ? new LinkedSprite(SpriteType.Item, "zombie_spawner") : + m instanceof Creeper ? new LinkedSprite(SpriteType.Item, "creeper_spawner") : + m instanceof Skeleton ? new LinkedSprite(SpriteType.Item, "skeleton_spawner") : + m instanceof Snake ? new LinkedSprite(SpriteType.Item, "snake_spawner") : + m instanceof Knight ? new LinkedSprite(SpriteType.Item, "knight_spawner") : + new LinkedSprite(SpriteType.Item, "air_wizard_spawner"), 7, 2); health = 100; initMob(m); resetSpawnInterval(); @@ -89,12 +91,13 @@ public Spawner(MobAi m) { /** * Returns the classname of a class. + * * @param c The class. * @return String representation of the classname. */ private static String getClassName(Class c) { String fullName = c.getCanonicalName(); - return fullName.substring(fullName.lastIndexOf(".")+1); + return fullName.substring(fullName.lastIndexOf(".") + 1); } @Override @@ -152,11 +155,11 @@ private void trySpawn() { Point pos = new Point(x >> 4, y >> 4); Point[] areaPositions = level.getAreaTilePositions(pos.x, pos.y, 1); ArrayList validPositions = new ArrayList<>(); - for (Point p: areaPositions) - if (!( !level.getTile(p.x, p.y).mayPass(level, p.x, p.y, newmob) || mob instanceof EnemyMob && level.getTile(p.x, p.y).getLightRadius(level, p.x, p.y) > 0 )) + for (Point p : areaPositions) + if (!(!level.getTile(p.x, p.y).mayPass(level, p.x, p.y, newmob) || mob instanceof EnemyMob && level.getTile(p.x, p.y).getLightRadius(level, p.x, p.y) > 0)) validPositions.add(p); - if(validPositions.size() == 0) return; // Cannot spawn mob. + if (validPositions.size() == 0) return; // Cannot spawn mob. Point spawnPos = validPositions.get(random.nextInt(validPositions.size())); @@ -166,16 +169,16 @@ private void trySpawn() { level.add(newmob); Sound.play("monsterhurt"); for (int i = 0; i < 6; i++) { - int randX = rnd.nextInt(16); - int randY = rnd.nextInt(12); - level.add(new FireParticle(x - 8 + randX, y - 6 + randY)); + int randX = rnd.nextInt(16); + int randY = rnd.nextInt(12); + level.add(new FireParticle(x - 8 + randX, y - 6 + randY)); } } @Override public boolean interact(Player player, Item item, Direction attackDir) { if (item instanceof ToolItem) { - ToolItem tool = (ToolItem)item; + ToolItem tool = (ToolItem) item; Sound.play("monsterhurt"); @@ -222,7 +225,7 @@ public boolean use(Player player) { lvl++; if (lvl > maxMobLevel) lvl = 1; try { - EnemyMob newmob = (EnemyMob)mob.getClass().getConstructor(int.class).newInstance(lvl); + EnemyMob newmob = (EnemyMob) mob.getClass().getConstructor(int.class).newInstance(lvl); initMob(newmob); } catch (Exception ex) { ex.printStackTrace(); @@ -234,5 +237,7 @@ public boolean use(Player player) { } @Override - public @NotNull Furniture copy() { return new Spawner(mob); } + public @NotNull Furniture copy() { + return new Spawner(mob); + } } diff --git a/src/client/java/minicraft/entity/furniture/Tnt.java b/src/client/java/minicraft/entity/furniture/Tnt.java index 9b659d2c0..4bea171ca 100644 --- a/src/client/java/minicraft/entity/furniture/Tnt.java +++ b/src/client/java/minicraft/entity/furniture/Tnt.java @@ -32,7 +32,7 @@ public class Tnt extends Furniture implements ActionListener { private Timer explodeTimer; private Level levelSave; - private final String[] explosionBlacklist = new String[]{ "hard rock", "obsidian wall", "stairs up", "stairs down" }; + private final String[] explosionBlacklist = new String[]{"hard rock", "obsidian wall", "stairs up", "stairs down"}; /** * Creates a new tnt furniture. @@ -56,21 +56,21 @@ public void tick() { // Blow up List entitiesInRange = level.getEntitiesInRect(new Rectangle(x, y, BLAST_RADIUS * 2, BLAST_RADIUS * 2, Rectangle.CENTER_DIMS)); - for (Entity e: entitiesInRange) { - float dist = (float) Math.hypot(e.x - x, e.y - y); - int dmg = (int) (BLAST_DAMAGE * (1 - (dist / BLAST_RADIUS))) + 1; - if (e instanceof Mob && dmg > 0) - ((Mob)e).onExploded(this, dmg); - - // Ignite other bombs in range. - if (e instanceof Tnt) { - Tnt tnt = (Tnt) e; - if (!tnt.fuseLit) { - tnt.fuseLit = true; - Sound.play("fuse"); - tnt.ftik = FUSE_TIME * 2 / 3; - } - } + for (Entity e : entitiesInRange) { + float dist = (float) Math.hypot(e.x - x, e.y - y); + int dmg = (int) (BLAST_DAMAGE * (1 - (dist / BLAST_RADIUS))) + 1; + if (e instanceof Mob && dmg > 0) + ((Mob) e).onExploded(this, dmg); + + // Ignite other bombs in range. + if (e instanceof Tnt) { + Tnt tnt = (Tnt) e; + if (!tnt.fuseLit) { + tnt.fuseLit = true; + Sound.play("fuse"); + tnt.ftik = FUSE_TIME * 2 / 3; + } + } } int xt = x >> 4; @@ -100,7 +100,7 @@ public void tick() { @Override public void render(Screen screen) { if (fuseLit) { - int colFctr = 100 * ((ftik%15)/5) + 200; + int colFctr = 100 * ((ftik % 15) / 5) + 200; col = Color.get(-1, colFctr, colFctr + 100, 555); } super.render(screen); diff --git a/src/client/java/minicraft/entity/mob/AirWizard.java b/src/client/java/minicraft/entity/mob/AirWizard.java index 42920abe7..976f295a5 100644 --- a/src/client/java/minicraft/entity/mob/AirWizard.java +++ b/src/client/java/minicraft/entity/mob/AirWizard.java @@ -16,7 +16,7 @@ import minicraft.screen.AchievementsDisplay; public class AirWizard extends EnemyMob { - private static final LinkedSprite[][][] sprites = new LinkedSprite[][][] { + private static final LinkedSprite[][][] sprites = new LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "air_wizard"), Mob.compileMobSpriteAnimations(0, 2, "air_wizard") }; @@ -32,7 +32,9 @@ public class AirWizard extends EnemyMob { /** * This is used by the spawner to spawn air wizards. {@code lvl} is unused. */ - public AirWizard(int lvl) { this(); } + public AirWizard(int lvl) { + this(); + } /** * Constructor for the AirWizard. @@ -85,7 +87,7 @@ public void tick() { if (player != null && randomWalkTime == 0) { // If there is a player around, and the walking is not random int xd = player.x - x; // The horizontal distance between the player and the air wizard. int yd = player.y - y; // The vertical distance between the player and the air wizard. - if (xd * xd + yd * yd < 16*16 * 2*2) { + if (xd * xd + yd * yd < 16 * 16 * 2 * 2) { /// Move away from the player if less than 2 blocks away this.xmov = 0; // Accelerations @@ -96,12 +98,12 @@ public void tick() { if (xd > 0) this.xmov = -1; if (yd < 0) this.ymov = +1; if (yd > 0) this.ymov = -1; - } else if (xd * xd + yd * yd > 16*16 * 15*15) {// 15 squares away + } else if (xd * xd + yd * yd > 16 * 16 * 15 * 15) {// 15 squares away /// Drags the airwizard to the player, maintaining relative position. double hypot = Math.sqrt(xd * xd + yd * yd); - int newxd = (int)(xd * Math.sqrt(16*16 * 15*15) / hypot); - int newyd = (int)(yd * Math.sqrt(16*16 * 15*15) / hypot); + int newxd = (int) (xd * Math.sqrt(16 * 16 * 15 * 15) / hypot); + int newyd = (int) (yd * Math.sqrt(16 * 16 * 15 * 15) / hypot); x = player.x - newxd; y = player.y - newyd; } @@ -136,30 +138,31 @@ public void render(Screen screen) { if (percent < 16) { textcol = Color.get(1, 204, 0, 0); textcol2 = Color.get(1, 51, 0, 0); - } - else if (percent < 51) { + } else if (percent < 51) { textcol = Color.get(1, 204, 204, 9); textcol2 = Color.get(1, 51, 51, 0); } int textwidth = Font.textWidth(h); - Font.draw(h, screen, (x - textwidth/2) + 1, y - 17, textcol2); - Font.draw(h, screen, (x - textwidth/2), y - 18, textcol); + Font.draw(h, screen, (x - textwidth / 2) + 1, y - 17, textcol2); + Font.draw(h, screen, (x - textwidth / 2), y - 18, textcol); } @Override protected void touchedBy(Entity entity) { if (entity instanceof Player) { // If the entity is the Player, then deal them 1 damage points. - ((Player)entity).hurt(this, 1); + ((Player) entity).hurt(this, 1); } } - /** What happens when the air wizard dies */ + /** + * What happens when the air wizard dies + */ @Override public void die() { Player[] players = level.getPlayers(); if (players.length > 0) { // If the player is still here - for (Player p: players) { + for (Player p : players) { p.addScore(100000); // Give the player 100K points. dropItem(5, 10, Items.get("cloud ore")); // Drop cloud ore to guarantee respawn. } @@ -187,5 +190,7 @@ public void die() { } @Override - public int getMaxLevel() { return 2; } + public int getMaxLevel() { + return 2; + } } diff --git a/src/client/java/minicraft/entity/mob/Cow.java b/src/client/java/minicraft/entity/mob/Cow.java index a3baf9f4b..4275db4d7 100644 --- a/src/client/java/minicraft/entity/mob/Cow.java +++ b/src/client/java/minicraft/entity/mob/Cow.java @@ -19,9 +19,18 @@ public Cow() { public void die() { int min = 0, max = 0; - if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) {min = 1; max = 3;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) {min = 1; max = 2;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) {min = 0; max = 1;} + if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) { + min = 1; + max = 3; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) { + min = 1; + max = 2; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { + min = 0; + max = 1; + } dropItem(min, max, Items.get("leather"), Items.get("raw beef")); diff --git a/src/client/java/minicraft/entity/mob/Creeper.java b/src/client/java/minicraft/entity/mob/Creeper.java index acaa6810d..d1d132c15 100644 --- a/src/client/java/minicraft/entity/mob/Creeper.java +++ b/src/client/java/minicraft/entity/mob/Creeper.java @@ -16,11 +16,11 @@ import java.util.List; public class Creeper extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { - new LinkedSprite[][] {Mob.compileSpriteList(0, 0, 2, 2, 0, 2, "creeper")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 2, 2, 2, 0, 2, "creeper")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 4, 2, 2, 0, 2, "creeper")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 6, 2, 2, 0, 2, "creeper")} + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ + new LinkedSprite[][]{Mob.compileSpriteList(0, 0, 2, 2, 0, 2, "creeper")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 2, 2, 2, 0, 2, "creeper")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 4, 2, 2, 0, 2, "creeper")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 6, 2, 2, 0, 2, "creeper")} }; private static final int MAX_FUSE_TIME = 60; @@ -30,7 +30,7 @@ public class Creeper extends EnemyMob { private int fuseTime = 0; private boolean fuseLit = false; - private final String[] explosionBlacklist = new String[] { "hard rock", "obsidian wall", "raw obsidian"}; + private final String[] explosionBlacklist = new String[]{"hard rock", "obsidian wall", "raw obsidian"}; public Creeper(int lvl) { super(lvl, sprites, 10, 50); @@ -48,7 +48,8 @@ public boolean move(int xd, int yd) { public void tick() { super.tick(); - if (Game.isMode("minicraft.settings.mode.creative")) return; // Creeper should not explode if player is in creative mode + if (Game.isMode("minicraft.settings.mode.creative")) + return; // Creeper should not explode if player is in creative mode if (fuseTime > 0) { fuseTime--; // Fuse getting shorter... diff --git a/src/client/java/minicraft/entity/mob/EnemyMob.java b/src/client/java/minicraft/entity/mob/EnemyMob.java index 9a950b533..6d4a5fc19 100644 --- a/src/client/java/minicraft/entity/mob/EnemyMob.java +++ b/src/client/java/minicraft/entity/mob/EnemyMob.java @@ -22,25 +22,26 @@ public void handleDespawn() { if (level.depth == 0 && Updater.tickCount >= Updater.dayLength / 4 && Updater.tickCount <= Updater.dayLength / 2) if (isWithinLight()) // If it is now morning and on the surface, the mob despawns when it is within light. super.handleDespawn(); - else if (!isWithinLight()) // Otherwise, it despawns when it is not within light. - super.handleDespawn(); + else if (!isWithinLight()) // Otherwise, it despawns when it is not within light. + super.handleDespawn(); } /** * Constructor for a hostile (enemy) mob. The level determines what the mob does. sprites contains all the graphics and animations for the mob. * lvlcols is the different color the mob has depending on its level. isFactor determines if the mob's health should be affected by the level and * the difficulty. - * @param lvl The mob's level. + * + * @param lvl The mob's level. * @param lvlSprites The mob's sprites (ordered by level, then direction, then animation frame). - * @param health How much health the mob has. - * @param isFactor false if maxHealth=health, true if maxHealth=health*level*level*difficulty + * @param health How much health the mob has. + * @param isFactor false if maxHealth=health, true if maxHealth=health*level*level*difficulty * @param detectDist The distance where the mob will detect the player and start moving towards him/her. - * @param lifetime How many ticks this mob will live. - * @param rwTime How long the mob will walk in a random direction. (random walk duration) - * @param rwChance The chance of this mob will walk in a random direction (random walk chance) + * @param lifetime How many ticks this mob will live. + * @param rwTime How long the mob will walk in a random direction. (random walk duration) + * @param rwChance The chance of this mob will walk in a random direction (random walk chance) */ public EnemyMob(int lvl, LinkedSprite[][][] lvlSprites, int health, boolean isFactor, int detectDist, int lifetime, int rwTime, int rwChance) { - super(lvlSprites[0], isFactor ? (lvl == 0 ? 1 : lvl * lvl) * health * ((Double)(Math.pow(2, Settings.getIdx("diff")))).intValue() : health, lifetime, rwTime, rwChance); + super(lvlSprites[0], isFactor ? (lvl == 0 ? 1 : lvl * lvl) * health * ((Double) (Math.pow(2, Settings.getIdx("diff")))).intValue() : health, lifetime, rwTime, rwChance); this.lvl = lvl == 0 ? 1 : lvl; this.lvlSprites = java.util.Arrays.copyOf(lvlSprites, lvlSprites.length); this.detectDist = detectDist; @@ -49,13 +50,14 @@ public EnemyMob(int lvl, LinkedSprite[][][] lvlSprites, int health, boolean isFa /** * Constructor for a hostile (enemy) mob. * Lifetime will be set to 60 * Game.normSpeed. - * @param lvl The mob's level. + * + * @param lvl The mob's level. * @param lvlSprites The mob's sprites (ordered by level, then direction, then animation frame). - * @param health How much health the mob has. - * @param isFactor false if maxHealth=health, true if maxHealth=health*level*level*difficulty + * @param health How much health the mob has. + * @param isFactor false if maxHealth=health, true if maxHealth=health*level*level*difficulty * @param detectDist The distance where the mob will detect the player and start moving towards him/her. - * @param rwTime How long the mob will walk in a random direction. (random walk duration) - * @param rwChance The chance of this mob will walk in a random direction (random walk chance) + * @param rwTime How long the mob will walk in a random direction. (random walk duration) + * @param rwChance The chance of this mob will walk in a random direction (random walk chance) */ public EnemyMob(int lvl, LinkedSprite[][][] lvlSprites, int health, boolean isFactor, int detectDist, int rwTime, int rwChance) { this(lvl, lvlSprites, health, isFactor, detectDist, 60 * Updater.normSpeed, rwTime, rwChance); @@ -67,9 +69,9 @@ public EnemyMob(int lvl, LinkedSprite[][][] lvlSprites, int health, boolean isFa * rwTime=60, * rwChance=200. * - * @param lvl The mob's level. + * @param lvl The mob's level. * @param lvlSprites The mob's sprites (ordered by level, then direction, then animation frame). - * @param health How much health the mob has. + * @param health How much health the mob has. * @param detectDist The distance where the mob will detect the player and start moving towards him/her. */ public EnemyMob(int lvl, LinkedSprite[][][] lvlSprites, int health, int detectDist) { @@ -95,7 +97,7 @@ public void tick() { if (yd > sig0) this.ymov = +1; } else { // If the enemy was following the player, but has now lost it, it stops moving. - // *That would be nice, but I'll just make it move randomly instead. + // *That would be nice, but I'll just make it move randomly instead. randomizeWalkDir(false); } } @@ -111,8 +113,8 @@ public void render(Screen screen) { protected void touchedBy(Entity entity) { // If an entity (like the player) touches the enemy mob super.touchedBy(entity); // Hurts the player, damage is based on lvl. - if(entity instanceof Player) { - ((Player)entity).hurt(this, lvl * (Settings.get("diff").equals("minicraft.settings.difficulty.hard") ? 2 : 1)); + if (entity instanceof Player) { + ((Player) entity).hurt(this, lvl * (Settings.get("diff").equals("minicraft.settings.difficulty.hard") ? 2 : 1)); } } @@ -122,15 +124,16 @@ public void die() { /** * Determines if the mob can spawn at the giving position in the given map. + * * @param level The level which the mob wants to spawn in. - * @param x X map spawn coordinate. - * @param y Y map spawn coordinate. + * @param x X map spawn coordinate. + * @param y Y map spawn coordinate. * @return true if the mob can spawn here, false if not. */ public static boolean checkStartPos(Level level, int x, int y) { // Find a place to spawn the mob int r = (level.depth == -4 ? (Game.isMode("minicraft.settings.mode.score") ? 22 : 15) : 13); - if(!MobAi.checkStartPos(level, x, y, 60, r)) + if (!MobAi.checkStartPos(level, x, y, 60, r)) return false; x = x >> 4; diff --git a/src/client/java/minicraft/entity/mob/Knight.java b/src/client/java/minicraft/entity/mob/Knight.java index 91b74df0f..24183cb98 100644 --- a/src/client/java/minicraft/entity/mob/Knight.java +++ b/src/client/java/minicraft/entity/mob/Knight.java @@ -5,7 +5,7 @@ import minicraft.item.Items; public class Knight extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "knight"), Mob.compileMobSpriteAnimations(0, 2, "knight"), Mob.compileMobSpriteAnimations(0, 4, "knight"), @@ -14,6 +14,7 @@ public class Knight extends EnemyMob { /** * Creates a knight of a given level. + * * @param lvl The knights level. */ public Knight(int lvl) { @@ -27,7 +28,7 @@ public void die() { dropItem(0, 2, Items.get("shard") ); - if(random.nextInt(24/lvl/(Settings.getIdx("diff")+1)) == 0) + if (random.nextInt(24 / lvl / (Settings.getIdx("diff") + 1)) == 0) dropItem(1, 1, Items.get("key")); super.die(); diff --git a/src/client/java/minicraft/entity/mob/Mob.java b/src/client/java/minicraft/entity/mob/Mob.java index 5484c6c15..e96679663 100644 --- a/src/client/java/minicraft/entity/mob/Mob.java +++ b/src/client/java/minicraft/entity/mob/Mob.java @@ -32,8 +32,9 @@ public abstract class Mob extends Entity { /** * Default constructor for a mob. * Default x radius is 4, and y radius is 3. + * * @param sprites All of this mob's sprites. - * @param health The mob's max health. + * @param health The mob's max health. */ public Mob(LinkedSprite[][] sprites, int health) { super(4, 3); @@ -79,19 +80,22 @@ public void tick() { /// The code below checks the direction of the knockback, moves the Mob accordingly, and brings the knockback closer to 0. int xd = 0, yd = 0; if (xKnockback != 0) { - xd = (int)Math.ceil(xKnockback/2); - xKnockback -= xKnockback/Math.abs(xKnockback); + xd = (int) Math.ceil(xKnockback / 2); + xKnockback -= xKnockback / Math.abs(xKnockback); } if (yKnockback != 0) { - yd = (int)Math.ceil(yKnockback/2); - yKnockback -= yKnockback/Math.abs(yKnockback); + yd = (int) Math.ceil(yKnockback / 2); + yKnockback -= yKnockback / Math.abs(yKnockback); } move(xd, yd, false); } @Override - public boolean move(int xd, int yd) { return move(xd, yd, true); } // Move the mob, overrides from Entity + public boolean move(int xd, int yd) { + return move(xd, yd, true); + } // Move the mob, overrides from Entity + private boolean move(int xd, int yd, boolean changeDir) { // Knockback shouldn't change mob direction if (level == null) return false; // Stopped b/c there's no level to move in! @@ -117,9 +121,9 @@ private boolean move(int xd, int yd, boolean changeDir) { // Knockback shouldn't // This part makes it so you can't move in a direction that you are currently being knocked back from. if (xKnockback != 0) - xd = Math.copySign(xd, xKnockback)*-1 != xd ? xd : 0; // If xKnockback and xd have different signs, do nothing, otherwise, set xd to 0. + xd = Math.copySign(xd, xKnockback) * -1 != xd ? xd : 0; // If xKnockback and xd have different signs, do nothing, otherwise, set xd to 0. if (yKnockback != 0) - yd = Math.copySign(yd, yKnockback)*-1 != yd ? yd : 0; // Same as above. + yd = Math.copySign(yd, yKnockback) * -1 != yd ? yd : 0; // Same as above. moved = super.move(xd, yd); // Call the move method from Entity } @@ -127,22 +131,30 @@ private boolean move(int xd, int yd, boolean changeDir) { // Knockback shouldn't return moved; } - /** The mob immediately despawns if the distance of the closest player is greater than the return value of this. */ + /** + * The mob immediately despawns if the distance of the closest player is greater than the return value of this. + */ protected int getDespawnDistance() { return 1280; } - /** The mob randomly despawns if the distance of the closest player is greater than the return value of this. */ + /** + * The mob randomly despawns if the distance of the closest player is greater than the return value of this. + */ protected int getNoDespawnDistance() { return 640; } - /** @see #handleDespawn() */ + /** + * @see #handleDespawn() + */ protected boolean removeWhenFarAway(@SuppressWarnings("unused") double distance) { return true; } - /** This is an easy way to make a list of sprites that are all part of the same "Sprite", so they have similar parameters, but they're just at different locations on the spreadsheet. */ + /** + * This is an easy way to make a list of sprites that are all part of the same "Sprite", so they have similar parameters, but they're just at different locations on the spreadsheet. + */ public static LinkedSprite[] compileSpriteList(int sheetX, int sheetY, int width, int height, int mirror, int number, String key) { LinkedSprite[] sprites = new LinkedSprite[number]; for (int i = 0; i < sprites.length; i++) @@ -190,15 +202,17 @@ private boolean isWooling() { // supposed to walk at half speed on wool /** * Checks if this Mob is currently on a light tile; if so, the mob sprite is brightened. + * * @return true if the mob is on a light tile, false if not. */ public boolean isLight() { if (level == null) return false; - return level.isLight(x>>4, y>>4); + return level.isLight(x >> 4, y >> 4); } /** * Checks if the mob is swimming (standing on a liquid tile). + * * @return true if the mob is swimming, false if not. */ public boolean isSwimming() { @@ -209,37 +223,42 @@ public boolean isSwimming() { /** * Do damage to the mob this method is called on. - * @param tile The tile that hurt the player - * @param x The x position of the mob - * @param y The x position of the mob + * + * @param tile The tile that hurt the player + * @param x The x position of the mob + * @param y The x position of the mob * @param damage The amount of damage to hurt the mob with */ public void hurt(Tile tile, int x, int y, int damage) { // Hurt the mob, when the source of damage is a tile Direction attackDir = Direction.getDirection(dir.getDir() ^ 1); // Set attackDir to our own direction, inverted. XORing it with 1 flips the rightmost bit in the variable, this effectively adds one when even, and subtracts one when odd. - if (!(tile == Tiles.get("lava") && this instanceof Player && ((Player)this).potioneffects.containsKey(PotionType.Lava))) + if (!(tile == Tiles.get("lava") && this instanceof Player && ((Player) this).potioneffects.containsKey(PotionType.Lava))) doHurt(damage, tile.mayPass(level, x, y, this) ? Direction.NONE : attackDir); // Call the method that actually performs damage, and set it to no particular direction } /** * Do damage to the mob this method is called on. - * @param mob The mob that hurt this mob + * + * @param mob The mob that hurt this mob * @param damage The amount of damage to hurt the mob with */ - public void hurt(Mob mob, int damage) { hurt(mob, damage, getAttackDir(mob, this)); } + public void hurt(Mob mob, int damage) { + hurt(mob, damage, getAttackDir(mob, this)); + } /** * Do damage to the mob this method is called on. - * @param mob The mob that hurt this mob - * @param damage The amount of damage to hurt the mob with + * + * @param mob The mob that hurt this mob + * @param damage The amount of damage to hurt the mob with * @param attackDir The direction this mob was attacked from */ public void hurt(Mob mob, int damage, Direction attackDir) { // Hurt the mob, when the source is another mob - if (mob instanceof Player && Game.isMode("minicraft.settings.mode.creative") && mob != this) doHurt(health, attackDir); // Kill the mob instantly + if (mob instanceof Player && Game.isMode("minicraft.settings.mode.creative") && mob != this) + doHurt(health, attackDir); // Kill the mob instantly else doHurt(damage, attackDir); // Call the method that actually performs damage, and use our provided attackDir } /** - * * @param sec duration in seconds */ public void burn(int sec) { @@ -248,30 +267,36 @@ public void burn(int sec) { /** * Executed when a TNT bomb explodes near this mob. + * * @param tnt The TNT exploding. * @param dmg The amount of damage the explosion does. */ - public void onExploded(Tnt tnt, int dmg) { doHurt(dmg, getAttackDir(tnt, this)); } + public void onExploded(Tnt tnt, int dmg) { + doHurt(dmg, getAttackDir(tnt, this)); + } /** * Hurt the mob, based on only damage and a direction * This is overridden in Player.java - * @param damage The amount of damage to hurt the mob with + * + * @param damage The amount of damage to hurt the mob with * @param attackDir The direction this mob was attacked from */ protected void doHurt(int damage, Direction attackDir) { - if (isRemoved() || hurtTime > 0) return; // If the mob has been hurt recently and hasn't cooled down, don't continue + if (isRemoved() || hurtTime > 0) + return; // If the mob has been hurt recently and hasn't cooled down, don't continue health -= damage; // Actually change the health // Add the knockback in the correct direction - xKnockback = attackDir.getX()*6; - yKnockback = attackDir.getY()*6; + xKnockback = attackDir.getX() * 6; + yKnockback = attackDir.getY() * 6; hurtTime = 10; // Set a delay before we can be hurt again } /** * Restores health to this mob. + * * @param heal How much health is restored. */ public void heal(int heal) { // Restore health on the mob @@ -279,7 +304,8 @@ public void heal(int heal) { // Restore health on the mob level.add(new TextParticle("" + heal, x, y, Color.GREEN)); // Add a text particle in our level at our position, that is green and displays the amount healed health += heal; // Actually add the amount to heal to our current health - if (health > (Player.baseHealth + Player.extraHealth)) health = (Player.baseHealth + Player.extraHealth); // If our health has exceeded our maximum, lower it back down to said maximum + if (health > (Player.baseHealth + Player.extraHealth)) + health = (Player.baseHealth + Player.extraHealth); // If our health has exceeded our maximum, lower it back down to said maximum } protected static Direction getAttackDir(Entity attacker, Entity hurt) { @@ -288,6 +314,7 @@ protected static Direction getAttackDir(Entity attacker, Entity hurt) { /** * This checks how the {@code attacker} can damage this mob. + * * @param attacker The attacker entity. * @return The calculated damage. */ diff --git a/src/client/java/minicraft/entity/mob/MobAi.java b/src/client/java/minicraft/entity/mob/MobAi.java index 61df74259..2652fedf7 100644 --- a/src/client/java/minicraft/entity/mob/MobAi.java +++ b/src/client/java/minicraft/entity/mob/MobAi.java @@ -2,7 +2,6 @@ import minicraft.core.io.Sound; import minicraft.entity.Direction; -import minicraft.entity.Entity; import minicraft.entity.furniture.Lantern; import minicraft.entity.particle.TextParticle; import minicraft.gfx.Color; @@ -26,11 +25,12 @@ public abstract class MobAi extends Mob { /** * Constructor for a mob with an ai. - * @param sprites All of this mob's sprites. + * + * @param sprites All of this mob's sprites. * @param maxHealth Maximum health of the mob. - * @param lifetime How many ticks this mob can live before its removed. - * @param rwTime How long the mob will walk in a random direction. (random walk duration) - * @param rwChance The chance of this mob will walk in a random direction (random walk chance) + * @param lifetime How many ticks this mob can live before its removed. + * @param rwTime How long the mob will walk in a random direction. (random walk duration) + * @param rwChance The chance of this mob will walk in a random direction (random walk chance) */ protected MobAi(LinkedSprite[][] sprites, int maxHealth, int lifetime, int rwTime, int rwChance) { super(sprites, maxHealth); @@ -62,18 +62,20 @@ public void handleDespawn() { /** * Checking whether the mob is within any light. From tiles or from lanterns. + * * @return {@code true} if the mob is within any light. */ protected boolean isWithinLight() { return Arrays.stream(level.getEntityArray()).anyMatch(e -> e instanceof Lantern && isWithin(e.getLightRadius(), e)) || !level.getMatchingTiles((tile, x, y) -> { - int xx = Math.abs(this.x - x), yy = Math.abs(this.y - y), l = tile.getLightRadius(level, x, y); - return xx * xx + yy * yy <= l * l; + int xx = Math.abs(this.x - x), yy = Math.abs(this.y - y), l = tile.getLightRadius(level, x, y); + return xx * xx + yy * yy <= l * l; }).isEmpty(); } /** * Checks if the mob should sleep this tick. + * * @return true if mob should sleep, false if not. */ protected boolean skipTick() { @@ -98,7 +100,7 @@ public void tick() { if (getLevel() != null) { boolean foundPlayer = false; - for (Player p: level.getPlayers()) { + for (Player p : level.getPlayers()) { if (p.isWithin(8, this) && p.potioneffects.containsKey(PotionType.Time)) { foundPlayer = true; break; @@ -143,7 +145,8 @@ public boolean move(int xd, int yd) { @Override public void doHurt(int damage, Direction attackDir) { - if (isRemoved() || hurtTime > 0) return; // If the mob has been hurt recently and hasn't cooled down, don't continue + if (isRemoved() || hurtTime > 0) + return; // If the mob has been hurt recently and hasn't cooled down, don't continue Player player = getClosestPlayer(); if (player != null) { // If there is a player in the level @@ -167,8 +170,9 @@ public boolean canWool() { /** * Sets the mob to walk in a random direction for a given amount of time. + * * @param byChance true if the mob should always get a new direction to walk, false if - * there should be a chance that the mob moves. + * there should be a chance that the mob moves. */ public void randomizeWalkDir(boolean byChance) { // Boolean specifies if this method, from where it's called, is called every tick, or after a random chance. if (!byChance && random.nextInt(randomWalkChance) != 0) return; @@ -182,24 +186,26 @@ public void randomizeWalkDir(boolean byChance) { // Boolean specifies if this me /** * Adds some items to the level. + * * @param mincount Least amount of items to add. * @param maxcount Most amount of items to add. - * @param items Which items should be added. + * @param items Which items should be added. */ protected void dropItem(int mincount, int maxcount, Item... items) { - int count = random.nextInt(maxcount-mincount+1) + mincount; + int count = random.nextInt(maxcount - mincount + 1) + mincount; for (int i = 0; i < count; i++) - level.dropItem(x, y, items); + level.dropItem(x, y, items); } /** * Determines if a friendly mob can spawn here. - * @param level The level the mob is trying to spawn in. - * @param x X map coordinate of spawn. - * @param y Y map coordinate of spawn. + * + * @param level The level the mob is trying to spawn in. + * @param x X map coordinate of spawn. + * @param y Y map coordinate of spawn. * @param playerDist Max distance from the player the mob can be spawned in. * @param soloRadius How far out can there not already be any entities. - * This is multiplied by the monster density of the level + * This is multiplied by the monster density of the level * @return true if the mob can spawn, false if not. */ protected static boolean checkStartPos(Level level, int x, int y, int playerDist, int soloRadius) { @@ -221,13 +227,17 @@ protected static boolean checkStartPos(Level level, int x, int y, int playerDist /** * Returns the maximum level of this mob. + * * @return max level of the mob. */ public abstract int getMaxLevel(); - protected void die(int points) { die(points, 0); } + protected void die(int points) { + die(points, 0); + } + protected void die(int points, int multAdd) { - for (Player p: level.getPlayers()) { + for (Player p : level.getPlayers()) { p.addScore(points); // Add score for mob death if (multAdd != 0) p.addMultiplier(multAdd); diff --git a/src/client/java/minicraft/entity/mob/ObsidianKnight.java b/src/client/java/minicraft/entity/mob/ObsidianKnight.java index 8ee4bcf89..16c5b1338 100644 --- a/src/client/java/minicraft/entity/mob/ObsidianKnight.java +++ b/src/client/java/minicraft/entity/mob/ObsidianKnight.java @@ -19,13 +19,13 @@ import org.jetbrains.annotations.Range; public class ObsidianKnight extends EnemyMob { - private static final SpriteLinker.LinkedSprite[][][] armored = new SpriteLinker.LinkedSprite[][][] { + private static final SpriteLinker.LinkedSprite[][][] armored = new SpriteLinker.LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "obsidian_knight_armored"), Mob.compileMobSpriteAnimations(0, 2, "obsidian_knight_armored"), Mob.compileMobSpriteAnimations(0, 4, "obsidian_knight_armored"), Mob.compileMobSpriteAnimations(0, 6, "obsidian_knight_armored") }; - private static final SpriteLinker.LinkedSprite[][][] broken = new SpriteLinker.LinkedSprite[][][] { + private static final SpriteLinker.LinkedSprite[][][] broken = new SpriteLinker.LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "obsidian_knight_broken"), Mob.compileMobSpriteAnimations(0, 2, "obsidian_knight_broken"), Mob.compileMobSpriteAnimations(0, 4, "obsidian_knight_broken"), @@ -42,7 +42,9 @@ public class ObsidianKnight extends EnemyMob { private int attackPhaseCooldown = 0; // Cooldown between attacks private AttackPhase attackPhase = AttackPhase.Attacking; - private enum AttackPhase { Attacking, Dashing, Walking; } // Using fire sparks in attacking. + + private enum AttackPhase {Attacking, Dashing, Walking;} // Using fire sparks in attacking. + private static final AttackPhase[] ATTACK_PHASES = AttackPhase.values(); private int dashTime = 0; @@ -217,33 +219,34 @@ public void render(Screen screen) { if (percent < 16) { textcol = Color.get(1, 204, 0, 0); textcol2 = Color.get(1, 51, 0, 0); - } - else if (percent < 51) { + } else if (percent < 51) { textcol = Color.get(1, 204, 204, 9); textcol2 = Color.get(1, 51, 51, 0); } int textwidth = Font.textWidth(h); - Font.draw(h, screen, (x - textwidth/2) + 1, y - 17, textcol2); - Font.draw(h, screen, (x - textwidth/2), y - 18, textcol); + Font.draw(h, screen, (x - textwidth / 2) + 1, y - 17, textcol2); + Font.draw(h, screen, (x - textwidth / 2), y - 18, textcol); } @Override protected void touchedBy(Entity entity) { if (entity instanceof Player) { // If the entity is the Player, then deal them 2 damage points. - ((Player)entity).hurt(this, 2); + ((Player) entity).hurt(this, 2); if (attackPhase == AttackPhase.Dashing) { dashTime = Math.max(dashTime - 10, 0); } } } - /** What happens when the obsidian knight dies */ + /** + * What happens when the obsidian knight dies + */ @Override public void die() { Player[] players = level.getPlayers(); if (players.length > 0) { // If the player is still here - for (Player p: players) { + for (Player p : players) { p.addScore(300000); // Give the player 300K points. dropItem(15, 25, Items.get("shard")); dropItem(1, 1, Items.get("Obsidian Heart")); // Drop it's precious item. diff --git a/src/client/java/minicraft/entity/mob/PassiveMob.java b/src/client/java/minicraft/entity/mob/PassiveMob.java index 0a563787d..a53295a26 100644 --- a/src/client/java/minicraft/entity/mob/PassiveMob.java +++ b/src/client/java/minicraft/entity/mob/PassiveMob.java @@ -15,6 +15,7 @@ public class PassiveMob extends MobAi { /** * Constructor for a non-hostile (passive) mob. * healthFactor = 3. + * * @param sprites The mob's sprites. */ public PassiveMob(LinkedSprite[][] sprites) { @@ -23,12 +24,13 @@ public PassiveMob(LinkedSprite[][] sprites) { /** * Constructor for a non-hostile (passive) mob. - * @param sprites The mob's sprites. + * + * @param sprites The mob's sprites. * @param healthFactor Determines the mobs health. Will be multiplied by the difficulty - * and then added with 5. + * and then added with 5. */ public PassiveMob(LinkedSprite[][] sprites, int healthFactor) { - super(sprites, 5 + healthFactor * Settings.getIdx("diff"), 5*60*Updater.normSpeed, 45, 40); + super(sprites, 5 + healthFactor * Settings.getIdx("diff"), 5 * 60 * Updater.normSpeed, 45, 40); } @Override @@ -60,9 +62,10 @@ public void die() { /** * Checks a given position in a given level to see if the mob can spawn there. * Passive mobs can only spawn on grass or flower tiles. + * * @param level The level which the mob wants to spawn in. - * @param x X map spawn coordinate. - * @param y Y map spawn coordinate. + * @param x X map spawn coordinate. + * @param y Y map spawn coordinate. * @return true if the mob can spawn here, false if not. */ public static boolean checkStartPos(Level level, int x, int y) { diff --git a/src/client/java/minicraft/entity/mob/Pig.java b/src/client/java/minicraft/entity/mob/Pig.java index 1cc2ee567..8881d7391 100644 --- a/src/client/java/minicraft/entity/mob/Pig.java +++ b/src/client/java/minicraft/entity/mob/Pig.java @@ -16,9 +16,18 @@ public Pig() { public void die() { int min = 0, max = 0; - if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) {min = 1; max = 3;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) {min = 1; max = 2;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) {min = 0; max = 2;} + if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) { + min = 1; + max = 3; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) { + min = 1; + max = 2; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { + min = 0; + max = 2; + } dropItem(min, max, Items.get("raw pork")); diff --git a/src/client/java/minicraft/entity/mob/Player.java b/src/client/java/minicraft/entity/mob/Player.java index f5b168199..b9a74e976 100644 --- a/src/client/java/minicraft/entity/mob/Player.java +++ b/src/client/java/minicraft/entity/mob/Player.java @@ -103,7 +103,8 @@ public class Player extends Mob implements ItemHolder, ClientTickable { public int hunger, stamina, armor; // The current stats public int armorDamageBuffer; - @Nullable public ArmorItem curArmor; // The color/type of armor to be displayed. + @Nullable + public ArmorItem curArmor; // The color/type of armor to be displayed. private int staminaRecharge; // The ticks before charging a bolt of the player's stamina private static final int maxStaminaRecharge = 10; // Cutoff value for staminaRecharge @@ -214,7 +215,9 @@ public void updateInv(String items) { updateSprites(); } - public int getMultiplier() { return Game.isMode("minicraft.settings.mode.score") ? multiplier : 1; } + public int getMultiplier() { + return Game.isMode("minicraft.settings.mode.score") ? multiplier : 1; + } void resetMultiplier() { multiplier = 1; @@ -223,7 +226,7 @@ void resetMultiplier() { public void addMultiplier(int value) { if (!Game.isMode("minicraft.settings.mode.score")) return; - multiplier = Math.min(MAX_MULTIPLIER, multiplier+value); + multiplier = Math.min(MAX_MULTIPLIER, multiplier + value); multipliertime = Math.max(multipliertime, mtm - 5); } @@ -234,15 +237,22 @@ public void tickMultiplier() { } } - public int getScore() { return score; } - public void setScore(int score) { this.score = score; } + public int getScore() { + return score; + } + + public void setScore(int score) { + this.score = score; + } + public void addScore(int points) { score += points * getMultiplier(); } /** * Adds a new potion effect to the player. - * @param type Type of potion. + * + * @param type Type of potion. * @param duration How long the effect lasts. */ public void addPotionEffect(PotionType type, int duration) { @@ -251,6 +261,7 @@ public void addPotionEffect(PotionType type, int duration) { /** * Adds a potion effect to the player. + * * @param type Type of effect. */ public void addPotionEffect(PotionType type) { @@ -259,9 +270,12 @@ public void addPotionEffect(PotionType type) { /** * Returns all the potion effects currently affecting the player. + * * @return all potion effects on the player. */ - public HashMap getPotionEffects() { return potioneffects; } + public HashMap getPotionEffects() { + return potioneffects; + } @Override public void tick() { @@ -285,10 +299,11 @@ public void tick() { } if (potioneffects.size() > 0 && !Bed.inBed(this)) { - for (PotionType potionType: potioneffects.keySet().toArray(new PotionType[0])) { + for (PotionType potionType : potioneffects.keySet().toArray(new PotionType[0])) { if (potioneffects.get(potionType) <= 1) // If time is zero (going to be set to 0 in a moment)... PotionItem.applyPotion(this, potionType, false); // Automatically removes this potion effect. - else potioneffects.put(potionType, potioneffects.get(potionType) - 1); // Otherwise, replace it with one less. + else + potioneffects.put(potionType, potioneffects.get(potionType) - 1); // Otherwise, replace it with one less. } } @@ -333,7 +348,8 @@ public void tick() { } onStairDelay = 10; // Resets the delay, if on a stairs tile, but the delay is greater than 0. In other words, this prevents you from ever activating a level change on a stair tile, UNTIL you get off the tile for 10+ ticks. - } else if (onStairDelay > 0) onStairDelay--; // Decrements stairDelay if it's > 0, but not on stair tile... does the player get removed from the tile beforehand, or something? + } else if (onStairDelay > 0) + onStairDelay--; // Decrements stairDelay if it's > 0, but not on stair tile... does the player get removed from the tile beforehand, or something? if (onTile == Tiles.get("Infinite Fall") && !Game.isMode("minicraft.settings.mode.creative")) { if (onFallDelay <= 0) { @@ -360,7 +376,8 @@ public void tick() { if (staminaRechargeDelay == 0) { staminaRecharge++; // Ticks since last recharge, accounting for the time potion effect. - if (isSwimming() && !potioneffects.containsKey(PotionType.Swim)) staminaRecharge = 0; // Don't recharge stamina while swimming. + if (isSwimming() && !potioneffects.containsKey(PotionType.Swim)) + staminaRecharge = 0; // Don't recharge stamina while swimming. // Recharge a bolt for each multiple of maxStaminaRecharge. while (staminaRecharge > maxStaminaRecharge) { @@ -374,14 +391,14 @@ public void tick() { if (hunger < 0) hunger = 0; // Error correction if (stamina < maxStamina) { - stamHungerTicks-=diffIdx; // Affect hunger if not at full stamina; this is 2 levels away from a hunger "burger". - if( stamina == 0) stamHungerTicks-=diffIdx; // Double effect if no stamina at all. + stamHungerTicks -= diffIdx; // Affect hunger if not at full stamina; this is 2 levels away from a hunger "burger". + if (stamina == 0) stamHungerTicks -= diffIdx; // Double effect if no stamina at all. } // This if statement encapsulates the hunger system - if(!Bed.inBed(this)) { + if (!Bed.inBed(this)) { if (hungerChargeDelay > 0) { // If the hunger is recharging health... - stamHungerTicks -= 2+diffIdx; // Penalize the hunger + stamHungerTicks -= 2 + diffIdx; // Penalize the hunger if (hunger == 0) stamHungerTicks -= diffIdx; // Further penalty if at full hunger } @@ -404,14 +421,13 @@ public void tick() { } /// System that heals you depending on your hunger - if (health < (baseHealth + extraHealth) && hunger > maxHunger/2) { + if (health < (baseHealth + extraHealth) && hunger > maxHunger / 2) { hungerChargeDelay++; - if (hungerChargeDelay > 20*Math.pow(maxHunger-hunger+2, 2)) { + if (hungerChargeDelay > 20 * Math.pow(maxHunger - hunger + 2, 2)) { health++; hungerChargeDelay = 0; } - } - else hungerChargeDelay = 0; + } else hungerChargeDelay = 0; if (hungerStarveDelay == 0) { hungerStarveDelay = 120; @@ -479,10 +495,10 @@ public void tick() { if (activeItem != null && (input.inputPressed("drop-one") || input.inputPressed("drop-stack"))) { Item drop = activeItem.copy(); - if (input.inputPressed("drop-one") && drop instanceof StackableItem && ((StackableItem)drop).count > 1) { + if (input.inputPressed("drop-one") && drop instanceof StackableItem && ((StackableItem) drop).count > 1) { // Drop one from stack - ((StackableItem)activeItem).count--; - ((StackableItem)drop).count = 1; + ((StackableItem) activeItem).count--; + ((StackableItem) drop).count = 1; } else { activeItem = null; // Remove it from the "inventory" if (isFishing) { @@ -504,7 +520,7 @@ public void tick() { if (input.inputPressed("menu") && activeItem != null) { int returned = inventory.add(0, activeItem); if (activeItem instanceof StackableItem) { - StackableItem stackable = (StackableItem)activeItem; + StackableItem stackable = (StackableItem) activeItem; if (stackable.count > 0) { getLevel().dropItem(x, y, stackable.copy()); } @@ -557,7 +573,7 @@ public void tick() { if (attackTime > 0) { attackTime--; - if(attackTime == 0) attackItem = null; // null the attackItem once we are done attacking. + if (attackTime == 0) attackItem = null; // null the attackItem once we are done attacking. } } } @@ -571,7 +587,7 @@ public void resolveHeldItem() { if (prevItem != null) { // and you had a previous item that we should care about... int returned = inventory.add(0, prevItem); // Then add that previous item to your inventory so it isn't lost. if (prevItem instanceof StackableItem) { - if (((StackableItem)prevItem).count > 0) { + if (((StackableItem) prevItem).count > 0) { getLevel().dropItem(x, y, prevItem.copy()); } } else if (returned == 0) { @@ -632,7 +648,7 @@ protected void attack() { if (!Game.isMode("minicraft.settings.mode.creative")) tool.dur--; - AchievementsDisplay.setAchievement("minicraft.achievement.bow",true); + AchievementsDisplay.setAchievement("minicraft.achievement.bow", true); return; } @@ -663,7 +679,7 @@ protected void attack() { done = true; // Returns true if the target tile successfully interacts with the item. - } else if (tile.interact(level, t.x, t.y, this, activeItem, attackDir)){ + } else if (tile.interact(level, t.x, t.y, this, activeItem, attackDir)) { done = true; } } @@ -695,7 +711,7 @@ protected void attack() { } if (used && activeItem instanceof ToolItem) - ((ToolItem)activeItem).payDurability(); + ((ToolItem) activeItem).payDurability(); } } @@ -706,10 +722,10 @@ private Rectangle getInteractionBox(int range) { int paraClose = 4, paraFar = range; int perpClose = 0, perpFar = 8; - int xClose = x + dir.getX()*paraClose + dir.getY()*perpClose; - int yClose = y + dir.getY()*paraClose + dir.getX()*perpClose; - int xFar = x + dir.getX()*paraFar + dir.getY()*perpFar; - int yFar = y + dir.getY()*paraFar + dir.getX()*perpFar; + int xClose = x + dir.getX() * paraClose + dir.getY() * perpClose; + int yClose = y + dir.getY() * paraClose + dir.getX() * perpClose; + int xFar = x + dir.getX() * paraFar + dir.getY() * perpFar; + int yFar = y + dir.getY() * paraFar + dir.getX() * perpFar; return new Rectangle(Math.min(xClose, xFar), Math.min(yClose, yFar), Math.max(xClose, xFar), Math.max(yClose, yFar), Rectangle.CORNERS); } @@ -717,8 +733,8 @@ private Rectangle getInteractionBox(int range) { private Point getInteractionTile() { int x = this.x, y = this.y - 2; - x += dir.getX()*INTERACT_DIST; - y += dir.getY()*INTERACT_DIST; + x += dir.getX() * INTERACT_DIST; + y += dir.getY() * INTERACT_DIST; return new Point(x >> 4, y >> 4); } @@ -741,7 +757,7 @@ private void goFishing() { } if (data != null) { // If you've caught something - for (String line: data) { + for (String line : data) { // Check all the entries in the data // The number is a percent, if one fails, it moves down the list @@ -760,7 +776,7 @@ private void goFishing() { Game.notifications.add(itemData.substring(1)); } else { if (Items.get(itemData).equals(Items.get("Raw Fish"))) { - AchievementsDisplay.setAchievement("minicraft.achievement.fish",true); + AchievementsDisplay.setAchievement("minicraft.achievement.fish", true); } level.dropItem(x, y, Items.get(itemData)); caught = true; @@ -778,27 +794,37 @@ private void goFishing() { fishingTicks = maxFishingTicks; // If you didn't catch anything, try again in 120 ticks } - private boolean use() { return use(getInteractionBox(INTERACT_DIST)); } + private boolean use() { + return use(getInteractionBox(INTERACT_DIST)); + } - /** called by other use method; this serves as a buffer in case there is no entity in front of the player. */ + /** + * called by other use method; this serves as a buffer in case there is no entity in front of the player. + */ private boolean use(Rectangle area) { List entities = level.getEntitiesInRect(area); // Gets the entities within the 4 points for (Entity e : entities) { - if (e instanceof Furniture && ((Furniture) e).use(this)) return true; // If the entity is not the player, then call it's use method, and return the result. Only some furniture classes use this. + if (e instanceof Furniture && ((Furniture) e).use(this)) + return true; // If the entity is not the player, then call it's use method, and return the result. Only some furniture classes use this. } return false; } - /** same, but for interaction. */ + /** + * same, but for interaction. + */ private boolean interact(Rectangle area) { List entities = level.getEntitiesInRect(area); for (Entity e : entities) { - if (e != this && e.interact(this, activeItem, attackDir)) return true; // This is the ONLY place that the Entity.interact method is actually called. + if (e != this && e.interact(this, activeItem, attackDir)) + return true; // This is the ONLY place that the Entity.interact method is actually called. } return false; } - /** same, but for attacking. */ + /** + * same, but for attacking. + */ private boolean hurt(Rectangle area) { List entities = level.getEntitiesInRect(area); int maxDmg = 0; @@ -816,13 +842,14 @@ private boolean hurt(Rectangle area) { /** * Calculates how much damage the player will do. + * * @param e Entity being attacked. * @return How much damage the player does. */ private int getAttackDamage(Entity e) { int dmg = random.nextInt(2) + 1; if (activeItem != null && activeItem instanceof ToolItem) { - dmg += ((ToolItem)activeItem).getAttackDamageBonus(e); // Sword/Axe are more effective at dealing damage. + dmg += ((ToolItem) activeItem).getAttackDamageBonus(e); // Sword/Axe are more effective at dealing damage. } return dmg; } @@ -851,23 +878,23 @@ public void render(Screen screen) { if (level.getTile(x / 16, y / 16) == Tiles.get("water")) { // animation effect - if (tickTime / 8 % 2 == 0) { - screen.render(xo + 0, yo + 3, 5, 0, 0, hudSheet.getSheet()); // Render the water graphic - screen.render(xo + 8, yo + 3, 5, 0, 1, hudSheet.getSheet()); // Render the mirrored water graphic to the right. - } else { + if (tickTime / 8 % 2 == 0) { + screen.render(xo + 0, yo + 3, 5, 0, 0, hudSheet.getSheet()); // Render the water graphic + screen.render(xo + 8, yo + 3, 5, 0, 1, hudSheet.getSheet()); // Render the mirrored water graphic to the right. + } else { screen.render(xo + 0, yo + 3, 5, 1, 0, hudSheet.getSheet()); screen.render(xo + 8, yo + 3, 5, 1, 1, hudSheet.getSheet()); - } + } } else if (level.getTile(x / 16, y / 16) == Tiles.get("lava")) { - if (tickTime / 8 % 2 == 0) { + if (tickTime / 8 % 2 == 0) { screen.render(xo + 0, yo + 3, 6, 0, 1, hudSheet.getSheet()); // Render the lava graphic screen.render(xo + 8, yo + 3, 6, 0, 0, hudSheet.getSheet()); // Render the mirrored lava graphic to the right. - } else { + } else { screen.render(xo + 0, yo + 3, 6, 1, 1, hudSheet.getSheet()); screen.render(xo + 8, yo + 3, 6, 1, 0, hudSheet.getSheet()); - } + } } } @@ -966,20 +993,22 @@ public void render(Screen screen) { if (activeItem instanceof FurnitureItem) { Furniture furniture = ((FurnitureItem) activeItem).furniture; furniture.x = x; - furniture.y = yo-4; + furniture.y = yo - 4; furniture.render(screen); } } - /** What happens when the player interacts with a itemEntity */ + /** + * What happens when the player interacts with a itemEntity + */ public void pickupItem(ItemEntity itemEntity) { int picked = 0; int total = 1; - if (itemEntity.item instanceof StackableItem && ((StackableItem)itemEntity.item).stacksWith(activeItem)) { // Picked up item equals the one in your hand - ((StackableItem)activeItem).count += ((StackableItem)itemEntity.item).count; - picked = ((StackableItem)itemEntity.item).count; + if (itemEntity.item instanceof StackableItem && ((StackableItem) itemEntity.item).stacksWith(activeItem)) { // Picked up item equals the one in your hand + ((StackableItem) activeItem).count += ((StackableItem) itemEntity.item).count; + picked = ((StackableItem) itemEntity.item).count; } else { - if (itemEntity.item instanceof StackableItem) total = ((StackableItem)itemEntity.item).count; + if (itemEntity.item instanceof StackableItem) total = ((StackableItem) itemEntity.item).count; picked = inventory.add(itemEntity.item); // Add item to inventory } @@ -992,14 +1021,19 @@ public void pickupItem(ItemEntity itemEntity) { } // The player can swim. - public boolean canSwim() { return true; } + public boolean canSwim() { + return true; + } // Can walk on wool tiles..? quickly..? - public boolean canWool() { return true; } + public boolean canWool() { + return true; + } /** * Finds a starting position for the player. - * @param level Level which the player wants to start in. + * + * @param level Level which the player wants to start in. * @param spawnSeed Spawn seed. */ public void findStartPos(Level level, long spawnSeed) { @@ -1009,9 +1043,13 @@ public void findStartPos(Level level, long spawnSeed) { /** * Finds the starting position for the player in a level. + * * @param level The level. */ - public void findStartPos(Level level) { findStartPos(level, true); } + public void findStartPos(Level level) { + findStartPos(level, true); + } + public void findStartPos(Level level, boolean setSpawn) { Point spawnPos; @@ -1025,13 +1063,13 @@ public void findStartPos(Level level, boolean setSpawn) { // There are no tiles in the entire map which the player is allowed to stand on. Not likely. if (spawnTilePositions.size() == 0) { - spawnPos = new Point(random.nextInt(level.w/4)+level.w*3/8, random.nextInt(level.h/4)+level.h*3/8); + spawnPos = new Point(random.nextInt(level.w / 4) + level.w * 3 / 8, random.nextInt(level.h / 4) + level.h * 3 / 8); level.setTile(spawnPos.x, spawnPos.y, Tiles.get("grass")); } else { // Gets random valid spawn tile position. spawnPos = spawnTilePositions.get(random.nextInt(spawnTilePositions.size())); } - if(setSpawn) { + if (setSpawn) { // Used to save (tile) coordinates of spawn point outside this method. spawnx = spawnPos.x; spawny = spawnPos.y; @@ -1044,6 +1082,7 @@ public void findStartPos(Level level, boolean setSpawn) { /** * Finds a location where the player can respawn in a given level. + * * @param level The level. */ public void respawn(Level level) { @@ -1058,11 +1097,13 @@ public void respawn(Level level) { /** * Uses an amount of stamina to do an action. + * * @param cost How much stamina the action requires. * @return true if the player had enough stamina, false if not. */ public boolean payStamina(int cost) { - if (potioneffects.containsKey(PotionType.Energy)) return true; // If the player has the potion effect for infinite stamina, return true (without subtracting cost). + if (potioneffects.containsKey(PotionType.Energy)) + return true; // If the player has the potion effect for infinite stamina, return true (without subtracting cost). else if (stamina <= 0) return false; // If the player doesn't have enough stamina, then return false; failure. if (cost < 0) cost = 0; // Error correction @@ -1079,13 +1120,16 @@ public int getLightRadius() { if (activeItem != null && activeItem instanceof FurnitureItem) { // If player is holding furniture int rr = ((FurnitureItem) activeItem).furniture.getLightRadius(); // Gets furniture light radius - if (rr > r) r = rr; // Brings player light up to furniture light, if less, since the furnture is not yet part of the level and so doesn't emit light even if it should. + if (rr > r) + r = rr; // Brings player light up to furniture light, if less, since the furnture is not yet part of the level and so doesn't emit light even if it should. } return r; // Return light radius } - /** What happens when the player dies */ + /** + * What happens when the player dies + */ @Override public void die() { Analytics.SinglePlayerDeath.ping(); @@ -1113,15 +1157,20 @@ public void onExploded(Tnt tnt, int dmg) { payStamina(dmg * 2); } - /** Hurt the player. - * @param damage How much damage to do to player. + /** + * Hurt the player. + * + * @param damage How much damage to do to player. * @param attackDir What direction to attack. */ - public void hurt(int damage, Direction attackDir) { doHurt(damage, attackDir); } + public void hurt(int damage, Direction attackDir) { + doHurt(damage, attackDir); + } @Override protected void doHurt(int damage, Direction attackDir) { - if (Game.isMode("minicraft.settings.mode.creative") || hurtTime > 0 || Bed.inBed(this)) return; // Can't get hurt in creative, hurt cooldown, or while someone is in bed + if (Game.isMode("minicraft.settings.mode.creative") || hurtTime > 0 || Bed.inBed(this)) + return; // Can't get hurt in creative, hurt cooldown, or while someone is in bed int healthDam = 0, armorDam = 0; if (this == Game.player) { @@ -1131,8 +1180,8 @@ protected void doHurt(int damage, Direction attackDir) { armorDamageBuffer += damage; armorDam += damage; - while (armorDamageBuffer >= curArmor.level+1) { - armorDamageBuffer -= curArmor.level+1; + while (armorDamageBuffer >= curArmor.level + 1) { + armorDamageBuffer -= curArmor.level + 1; healthDam++; } } @@ -1161,11 +1210,13 @@ protected void doHurt(int damage, Direction attackDir) { /** * Hurt the player directly. Don't use the armor as a shield. - * @param damage Amount of damage to do to player + * + * @param damage Amount of damage to do to player * @param attackDir The direction of attack. */ private void directHurt(int damage, Direction attackDir) { - if (Game.isMode("minicraft.settings.mode.creative") || hurtTime > 0 || Bed.inBed(this)) return; // Can't get hurt in creative, hurt cooldown, or while someone is in bed + if (Game.isMode("minicraft.settings.mode.creative") || hurtTime > 0 || Bed.inBed(this)) + return; // Can't get hurt in creative, hurt cooldown, or while someone is in bed int healthDam = 0; if (this == Game.player) { @@ -1192,7 +1243,9 @@ public Inventory getInventory() { return inventory; } - public String getDebugHunger() { return hungerStamCnt + "_" + stamHungerTicks; } + public String getDebugHunger() { + return hungerStamCnt + "_" + stamHungerTicks; + } /** * Trying to add item(s) to the player inventory. @@ -1202,7 +1255,7 @@ public void tryAddToInvOrDrop(@Nullable Item item) { if (item != null) { int returned = inventory.add(0, item); if (item instanceof StackableItem) { - if (((StackableItem)item).count > 0) { + if (((StackableItem) item).count > 0) { getLevel().dropItem(x, y, item); } } else if (returned == 0) { diff --git a/src/client/java/minicraft/entity/mob/Sheep.java b/src/client/java/minicraft/entity/mob/Sheep.java index 5aefa8709..f8c1dc583 100644 --- a/src/client/java/minicraft/entity/mob/Sheep.java +++ b/src/client/java/minicraft/entity/mob/Sheep.java @@ -67,9 +67,18 @@ public boolean interact(Player player, @Nullable Item item, Direction attackDir) public void die() { int min = 0, max = 0; - if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) {min = 1; max = 3;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) {min = 1; max = 2;} - if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) {min = 0; max = 2;} + if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) { + min = 1; + max = 3; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.normal")) { + min = 1; + max = 2; + } + if (Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { + min = 0; + max = 2; + } if (!cut) dropItem(min, max, Items.get("wool")); dropItem(min, max, Items.get("Raw Beef")); diff --git a/src/client/java/minicraft/entity/mob/Skeleton.java b/src/client/java/minicraft/entity/mob/Skeleton.java index 09fc27c56..8714aca2c 100644 --- a/src/client/java/minicraft/entity/mob/Skeleton.java +++ b/src/client/java/minicraft/entity/mob/Skeleton.java @@ -7,7 +7,7 @@ import minicraft.item.Items; public class Skeleton extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "skeleton"), Mob.compileMobSpriteAnimations(0, 2, "skeleton"), Mob.compileMobSpriteAnimations(0, 4, "skeleton"), @@ -19,6 +19,7 @@ public class Skeleton extends EnemyMob { /** * Creates a skeleton of a given level. + * * @param lvl The skeleton's level. */ public Skeleton(int lvl) { diff --git a/src/client/java/minicraft/entity/mob/Slime.java b/src/client/java/minicraft/entity/mob/Slime.java index e6a416ba2..b1b1de77d 100644 --- a/src/client/java/minicraft/entity/mob/Slime.java +++ b/src/client/java/minicraft/entity/mob/Slime.java @@ -8,17 +8,18 @@ import minicraft.item.Items; public class Slime extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { - new LinkedSprite[][] {Mob.compileSpriteList(0, 0, 2, 2, 0, 2, "slime")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 2, 2, 2, 0, 2, "slime")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 4, 2, 2, 0, 2, "slime")}, - new LinkedSprite[][] {Mob.compileSpriteList(0, 6, 2, 2, 0, 2, "slime")} + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ + new LinkedSprite[][]{Mob.compileSpriteList(0, 0, 2, 2, 0, 2, "slime")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 2, 2, 2, 0, 2, "slime")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 4, 2, 2, 0, 2, "slime")}, + new LinkedSprite[][]{Mob.compileSpriteList(0, 6, 2, 2, 0, 2, "slime")} }; private int jumpTime = 0; // jumpTimer, also acts as a rest timer before the next jump /** * Creates a slime of the given level. + * * @param lvl Slime's level. */ public Slime(int lvl) { @@ -60,8 +61,7 @@ public void render(Screen screen) { if (jumpTime > 0) { walkDist = 8; // Set to jumping sprite. y -= 4; // Raise up a bit. - } - else walkDist = 0; // Set to ground sprite. + } else walkDist = 0; // Set to ground sprite. dir = Direction.DOWN; diff --git a/src/client/java/minicraft/entity/mob/Snake.java b/src/client/java/minicraft/entity/mob/Snake.java index fdcc43eaa..c22c62a70 100644 --- a/src/client/java/minicraft/entity/mob/Snake.java +++ b/src/client/java/minicraft/entity/mob/Snake.java @@ -6,7 +6,7 @@ import minicraft.item.Items; public class Snake extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "snake"), Mob.compileMobSpriteAnimations(0, 2, "snake"), Mob.compileMobSpriteAnimations(0, 4, "snake"), @@ -21,7 +21,7 @@ public Snake(int lvl) { protected void touchedBy(Entity entity) { if (entity instanceof Player) { int damage = lvl + Settings.getIdx("diff"); - ((Player)entity).hurt(this, damage); + ((Player) entity).hurt(this, damage); } } diff --git a/src/client/java/minicraft/entity/mob/Zombie.java b/src/client/java/minicraft/entity/mob/Zombie.java index 987b26072..02ba06ade 100644 --- a/src/client/java/minicraft/entity/mob/Zombie.java +++ b/src/client/java/minicraft/entity/mob/Zombie.java @@ -5,7 +5,7 @@ import minicraft.item.Items; public class Zombie extends EnemyMob { - private static LinkedSprite[][][] sprites = new LinkedSprite[][][] { + private static LinkedSprite[][][] sprites = new LinkedSprite[][][]{ Mob.compileMobSpriteAnimations(0, 0, "zombie"), Mob.compileMobSpriteAnimations(0, 2, "zombie"), Mob.compileMobSpriteAnimations(0, 4, "zombie"), @@ -14,6 +14,7 @@ public class Zombie extends EnemyMob { /** * Creates a zombie of the given level. + * * @param lvl Zombie's level. */ public Zombie(int lvl) { @@ -33,9 +34,9 @@ public void die() { int rand = random.nextInt(3); if (rand == 0) { level.dropItem(x, y, Items.get("green clothes")); - } else if(rand == 1) { + } else if (rand == 1) { level.dropItem(x, y, Items.get("red clothes")); - } else if(rand == 2) { + } else if (rand == 2) { level.dropItem(x, y, Items.get("blue clothes")); } } diff --git a/src/client/java/minicraft/entity/particle/Particle.java b/src/client/java/minicraft/entity/particle/Particle.java index 5480f4876..9088d4214 100644 --- a/src/client/java/minicraft/entity/particle/Particle.java +++ b/src/client/java/minicraft/entity/particle/Particle.java @@ -16,11 +16,12 @@ public class Particle extends Entity implements ClientTickable { /** * Creates an particle entity at the given position. The particle has a x and y radius = 1. - * @param x X map coordinate - * @param y Y map coorindate - * @param xr x radius of the particle + * + * @param x X map coordinate + * @param y Y map coorindate + * @param xr x radius of the particle * @param lifetime How many game ticks the particle lives before its removed - * @param sprite The particle's sprite + * @param sprite The particle's sprite */ public Particle(int x, int y, int xr, int lifetime, LinkedSprite sprite) { // Make a particle at the given coordinates @@ -31,6 +32,7 @@ public Particle(int x, int y, int xr, int lifetime, LinkedSprite sprite) { this.sprite = sprite; time = 0; } + public Particle(int x, int y, int lifetime, LinkedSprite sprite) { this(x, y, 1, lifetime, sprite); } @@ -49,8 +51,12 @@ public void tick() { } @Override - public void render(Screen screen) { screen.render(x, y, sprite); } + public void render(Screen screen) { + screen.render(x, y, sprite); + } @Override - public boolean isSolid() { return false; } + public boolean isSolid() { + return false; + } } diff --git a/src/client/java/minicraft/entity/particle/SandParticle.java b/src/client/java/minicraft/entity/particle/SandParticle.java index ea268e113..e2a8a7df8 100644 --- a/src/client/java/minicraft/entity/particle/SandParticle.java +++ b/src/client/java/minicraft/entity/particle/SandParticle.java @@ -8,6 +8,7 @@ public class SandParticle extends Particle { /** * Creating a sand particle. + * * @param x X map position * @param y Y map position */ diff --git a/src/client/java/minicraft/entity/particle/TextParticle.java b/src/client/java/minicraft/entity/particle/TextParticle.java index d4d9a8892..964d02588 100644 --- a/src/client/java/minicraft/entity/particle/TextParticle.java +++ b/src/client/java/minicraft/entity/particle/TextParticle.java @@ -8,26 +8,26 @@ public class TextParticle extends Particle { private String msg; // Message of the text particle private double xa, ya, za; // x, y, z acceleration private double xx, yy, zz; // x, y, z coordinates - + private FontStyle style; - + /** * Creates a text particle which shows a message on the screen. - * + * * @param msg Message to display - * @param x X map position - * @param y Y map position + * @param x X map position + * @param y Y map position * @param col Text color */ public TextParticle(String msg, int x, int y, int col) { super(x, y, msg.length(), 60, null); - + style = new FontStyle(col).setShadowType(Color.BLACK, false); this.msg = msg; xx = x; // Assigns x pos yy = y; // Assigns y pos zz = 2; // Assigns z pos to be 2 - + // Assigns x,y,z acceleration: xa = random.nextGaussian() * 0.3; ya = random.nextGaussian() * 0.2; @@ -37,13 +37,13 @@ public TextParticle(String msg, int x, int y, int col) { @Override public void tick() { super.tick(); - + // Move the particle according to the acceleration xx += xa; yy += ya; zz += za; if (zz < 0) { - + // If z pos if less than 0, alter accelerations... zz = 0; za *= -0.5; @@ -55,14 +55,15 @@ public void tick() { x = (int) xx; y = (int) yy; } - + @Override public void render(Screen screen) { - style.setXPos(x - msg.length() * 4).setYPos(y - (int)zz).draw(msg, screen); + style.setXPos(x - msg.length() * 4).setYPos(y - (int) zz).draw(msg, screen); } - + /** * Returns the message and color divied by the character :. + * * @return string representation of the particle */ public String getData() { diff --git a/src/client/java/minicraft/gfx/Color.java b/src/client/java/minicraft/gfx/Color.java index cdc1e757d..b71ed651a 100644 --- a/src/client/java/minicraft/gfx/Color.java +++ b/src/client/java/minicraft/gfx/Color.java @@ -51,22 +51,25 @@ public class Color { public static final String MAGENTA_CODE = Color.toStringCode(Color.MAGENTA); public static final String CYAN_CODE = Color.toStringCode(Color.CYAN); - /** This returns a minicraftrgb. - * a should be between 0-1, r,g,and b should be 0-255 */ + /** + * This returns a minicraftrgb. + * a should be between 0-1, r,g,and b should be 0-255 + */ public static int get(int a, int r, int g, int b) { return (a << 24) + (r << 16) + (g << 8) + (b); } + public static int get(int a, int copy) { return get(a, copy, copy, copy); } public static String toStringCode(int color) { - return new String(new char[] { - Color.COLOR_CHAR, - (char) ((color >> 24) & 0xFF), // Alpha - (char) ((color >> 16) & 0xFF), // Red - (char) ((color >> 8) & 0xFF), // Blue - (char) (color & 0xFF) // Green + return new String(new char[]{ + Color.COLOR_CHAR, + (char) ((color >> 24) & 0xFF), // Alpha + (char) ((color >> 16) & 0xFF), // Red + (char) ((color >> 8) & 0xFF), // Blue + (char) (color & 0xFF) // Green }); } @@ -91,7 +94,9 @@ public static int rgb(int red, int green, int blue) { // rgbInt array -> rgbRead return red / 50 * 100 + green / 50 * 10 + blue / 50; // This is: rgbReadable } - /** This method darkens or lightens a color by the specified amount. */ + /** + * This method darkens or lightens a color by the specified amount. + */ public static int tint(int color, int amount, boolean isSpriteCol) { if (isSpriteCol) { int[] rgbBytes = separateEncodedSprite(color); // This just separates the four 8-bit sprite colors; they are still in base-6 added form. @@ -103,19 +108,25 @@ public static int tint(int color, int amount, boolean isSpriteCol) { return tint(color, amount); // This is: rgbByte } } + private static int tint(int rgbByte, int amount) { if (rgbByte == 255) return 255; // See description of bit shifting above; it will hold the 255 value, not -1 int[] rgb = decodeRGB(rgbByte); // This returns the rgb values as 0-5 numbers. for (int i = 0; i < rgb.length; i++) - rgb[i] = limit(rgb[i]+amount, 0, 5); + rgb[i] = limit(rgb[i] + amount, 0, 5); return rgb[0] * 36 + rgb[1] * 6 + rgb[2]; // This is: rgbByte } - /** seperates a 4-part sprite color (rgb4Sprite) into it's original 4 component colors (which are each rgbBytes) */ + /** + * seperates a 4-part sprite color (rgb4Sprite) into it's original 4 component colors (which are each rgbBytes) + */ /// Reverse of Color.get(a, b, c, d). - public static int[] separateEncodedSprite(int rgb4Sprite) { return separateEncodedSprite(rgb4Sprite, false); } + public static int[] separateEncodedSprite(int rgb4Sprite) { + return separateEncodedSprite(rgb4Sprite, false); + } + public static int[] separateEncodedSprite(int rgb4Sprite, boolean convertToReadable) { // The numbers are stored, most to least shifted, as d, c, b, a. @@ -124,7 +135,7 @@ public static int[] separateEncodedSprite(int rgb4Sprite, boolean convertToReada int c = (rgb4Sprite & 0x00_00_FF_00) >> 8; int d = (rgb4Sprite & 0x00_00_00_FF); - if(convertToReadable) { + if (convertToReadable) { // They become rgbReadable a = unGet(a); b = unGet(b); @@ -132,20 +143,22 @@ public static int[] separateEncodedSprite(int rgb4Sprite, boolean convertToReada d = unGet(d); } // Else, they are rgbByte - return new int[] {a, b, c, d}; + return new int[]{a, b, c, d}; } - /** This turns a 216 scale rgb int into a 0-5 scale "concatenated" rgb int. (aka rgbByte -> r/g/b Readables) */ + /** + * This turns a 216 scale rgb int into a 0-5 scale "concatenated" rgb int. (aka rgbByte -> r/g/b Readables) + */ public static int[] decodeRGB(int rgbByte) { int r = (rgbByte / 36) % 6; int g = (rgbByte / 6) % 6; int b = rgbByte % 6; - return new int[] {r, g, b}; + return new int[]{r, g, b}; } public static int unGet(int rgbByte) { // rgbByte -> rgbReadable int[] cols = decodeRGB(rgbByte); - return cols[0]*100 + cols[1]*10 + cols[2]; + return cols[0] * 100 + cols[1] * 10 + cols[2]; } /// This turns a 25-bit minicraft color into a 24-bit rgb color. @@ -160,7 +173,7 @@ protected static int tintColor(int rgbInt, int amount) { int[] comps = decodeRGBColor(rgbInt); for (int i = 0; i < comps.length; i++) - comps[i] = limit(comps[i]+amount, 0, 255); + comps[i] = limit(comps[i] + amount, 0, 255); return comps[0] << 16 | comps[1] << 8 | comps[2]; } @@ -170,7 +183,7 @@ protected static int[] decodeRGBColor(int rgbInt) { int g = (rgbInt & 0x00_FF_00) >> 8; int b = (rgbInt & 0x00_00_FF); - return new int[] {r, g, b}; + return new int[]{r, g, b}; } /// This is for color testing. diff --git a/src/client/java/minicraft/gfx/Dimension.java b/src/client/java/minicraft/gfx/Dimension.java index 8b13c9f1b..374876ebc 100644 --- a/src/client/java/minicraft/gfx/Dimension.java +++ b/src/client/java/minicraft/gfx/Dimension.java @@ -1,21 +1,24 @@ package minicraft.gfx; public class Dimension { - + public int width, height; - - public Dimension() { this(0, 0); } + + public Dimension() { + this(0, 0); + } + public Dimension(int width, int height) { this.width = width; this.height = height; } - + public Dimension(Dimension model) { width = model.width; height = model.height; } - + public String toString() { - return width+"x"+height; + return width + "x" + height; } } diff --git a/src/client/java/minicraft/gfx/Ellipsis.java b/src/client/java/minicraft/gfx/Ellipsis.java index a26fbe971..5d6d9d456 100644 --- a/src/client/java/minicraft/gfx/Ellipsis.java +++ b/src/client/java/minicraft/gfx/Ellipsis.java @@ -5,30 +5,41 @@ import minicraft.gfx.Ellipsis.DotUpdater.TimeUpdater; public abstract class Ellipsis { - + private final DotUpdater updateMethod; - + protected Ellipsis(DotUpdater updateMethod, int intervalCount) { this.updateMethod = updateMethod; updateMethod.setIntervalCount(intervalCount); } - + public String updateAndGet() { updateMethod.update(); return get(); } + protected abstract String get(); - protected void nextInterval(int interval) {} - - protected int getInterval() { return updateMethod.getInterval(); } - protected int getIntervalCount() { return updateMethod.getIntervalCount(); } - + + protected void nextInterval(int interval) { + } + + protected int getInterval() { + return updateMethod.getInterval(); + } + + protected int getIntervalCount() { + return updateMethod.getIntervalCount(); + } + public static class SequentialEllipsis extends Ellipsis { - public SequentialEllipsis() { this(new CallUpdater(Updater.normSpeed*2/3)); } + public SequentialEllipsis() { + this(new CallUpdater(Updater.normSpeed * 2 / 3)); + } + public SequentialEllipsis(DotUpdater updater) { super(updater, 3); } - + @Override public String get() { StringBuilder dots = new StringBuilder(); @@ -39,70 +50,82 @@ public String get() { else dots.append(" "); } - + return dots.toString(); } } - + public static class SmoothEllipsis extends Ellipsis { - + private static final String dotString = " "; - + private final char[] dots = dotString.toCharArray(); - - public SmoothEllipsis() { this(new TimeUpdater()); } + + public SmoothEllipsis() { + this(new TimeUpdater()); + } + public SmoothEllipsis(DotUpdater updater) { - super(updater, dotString.length()*2); + super(updater, dotString.length() * 2); updater.setEllipsis(this); } - + @Override - public String get() { return new String(dots); } - + public String get() { + return new String(dots); + } + @Override protected void nextInterval(int interval) { int epos = interval % dots.length; - char set = interval < getIntervalCount()/2 ? '.' : ' '; + char set = interval < getIntervalCount() / 2 ? '.' : ' '; dots[epos] = set; } } - - + + public static abstract class DotUpdater { private final int countPerCycle; private int intervalCount; private int curInterval; private int countPerInterval; private int counter; - + private Ellipsis ellipsis = null; - + private boolean started = false; - + protected DotUpdater(int countPerCycle) { this.countPerCycle = countPerCycle; } - - void setEllipsis(Ellipsis ellipsis) { this.ellipsis = ellipsis; } - + + void setEllipsis(Ellipsis ellipsis) { + this.ellipsis = ellipsis; + } + // Called by Ellipsis classes, passing their value. void setIntervalCount(int numIntervals) { intervalCount = numIntervals; - countPerInterval = Math.max(1, Math.round(countPerCycle / (float)intervalCount)); + countPerInterval = Math.max(1, Math.round(countPerCycle / (float) intervalCount)); + } + + public int getInterval() { + return curInterval; + } + + public int getIntervalCount() { + return intervalCount; } - - public int getInterval() { return curInterval; } - public int getIntervalCount() { return intervalCount; } - + private void incInterval(int amt) { if (ellipsis != null) - for (int i = curInterval+1; i <= curInterval+amt; i++) - ellipsis.nextInterval(i%intervalCount); - + for (int i = curInterval + 1; i <= curInterval + amt; i++) + ellipsis.nextInterval(i % intervalCount); + curInterval += amt; curInterval %= intervalCount; } - + protected void incCounter(int amt) { counter += amt; int intervals = counter / countPerInterval; @@ -111,24 +134,33 @@ protected void incCounter(int amt) { counter -= intervals * countPerInterval; } } - - void start() { started = true; } + + void start() { + started = true; + } + void update() { if (!started) start(); } - + public static class TickUpdater extends DotUpdater { private int lastTick; - - public TickUpdater() { this(Updater.normSpeed); } + + public TickUpdater() { + this(Updater.normSpeed); + } + public TickUpdater(int ticksPerCycle) { super(ticksPerCycle); } - + @Override - void start() { super.start(); lastTick = Updater.tickCount; } - + void start() { + super.start(); + lastTick = Updater.tickCount; + } + @Override void update() { super.update(); @@ -138,18 +170,24 @@ void update() { incCounter(ticksPassed); } } - + public static class TimeUpdater extends DotUpdater { private long lastTime; - - public TimeUpdater() { this(750); } + + public TimeUpdater() { + this(750); + } + public TimeUpdater(int millisPerCycle) { super(millisPerCycle); } - + @Override - void start() { super.start(); lastTime = System.nanoTime(); } - + void start() { + super.start(); + lastTime = System.nanoTime(); + } + @Override void update() { super.update(); @@ -159,15 +197,18 @@ void update() { incCounter(diffMillis); } } - + public static class CallUpdater extends DotUpdater { - + public CallUpdater(int callsPerCycle) { super(callsPerCycle); } - + @Override - void update() { super.update(); incCounter(1); } + void update() { + super.update(); + incCounter(1); + } } } } diff --git a/src/client/java/minicraft/gfx/Font.java b/src/client/java/minicraft/gfx/Font.java index d9e108623..dc8eb1766 100644 --- a/src/client/java/minicraft/gfx/Font.java +++ b/src/client/java/minicraft/gfx/Font.java @@ -10,27 +10,31 @@ public class Font { // These are all the characters that will be translated to the screen. (The spaces are important) private static final String chars = - "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"+ - "6789.,!?'\"-+=/\\%()<>:;^@ÁÉÍÓÚÑÂŋÂĄ"+ - "ÃÊÇÔÕĞÇÜİÖŞÆØÅŰŐ[]#|{}_АБВГДЕЁЖЗ"+ - "ИЙКЛМНОПРСĐĸĐŖФĐĨĐĻЧШЊĐĒĐĢĐŦĐ­ĐŽĐ¯Ã€Ã‚Ã„ÃˆÃŽÃŒÃÃ’"+ - "ÙÛÝ*ÂĢÂģÂŖ$&â‚Ŧ§ÂĒÂēabcdefghijklmnopqrs"+ - "tuvwxyzÃĄÃ ÃŖÃĸäÊèÃĒÃĢíÃŦÎïÃŗÃ˛ÃĩôÃļÃēÚÃģÃŧÃ§ÃąÃŊ"+ - "ÃŋайвĐŗĐ´ĐĩŅ‘ĐļСиКĐēĐģĐŧĐŊĐžĐŋŅ€ŅŅ‚ŅƒŅ„Ņ…Ņ†Ņ‡ŅˆŅ‰ŅŠŅ‹ŅŒŅ"+ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345" + + "6789.,!?'\"-+=/\\%()<>:;^@ÁÉÍÓÚÑÂŋÂĄ" + + "ÃÊÇÔÕĞÇÜİÖŞÆØÅŰŐ[]#|{}_АБВГДЕЁЖЗ" + + "ИЙКЛМНОПРСĐĸĐŖФĐĨĐĻЧШЊĐĒĐĢĐŦĐ­ĐŽĐ¯Ã€Ã‚Ã„ÃˆÃŽÃŒÃÃ’" + + "ÙÛÝ*ÂĢÂģÂŖ$&â‚Ŧ§ÂĒÂēabcdefghijklmnopqrs" + + "tuvwxyzÃĄÃ ÃŖÃĸäÊèÃĒÃĢíÃŦÎïÃŗÃ˛ÃĩôÃļÃēÚÃģÃŧÃ§ÃąÃŊ" + + "ÃŋайвĐŗĐ´ĐĩŅ‘ĐļСиКĐēĐģĐŧĐŊĐžĐŋŅ€ŅŅ‚ŅƒŅ„Ņ…Ņ†Ņ‡ŅˆŅ‰ŅŠŅ‹ŅŒŅ" + "ŅŽŅÄąÅŸÅ‘"; /* The order of the letters in the chars string is represented in the order that they appear in the sprite-sheet. */ - public static void draw(String msg, Screen screen, int x, int y) { draw(msg, screen, x, y, -1); } + public static void draw(String msg, Screen screen, int x, int y) { + draw(msg, screen, x, y, -1); + } - /** Draws the message to the x & y coordinates on the screen. */ + /** + * Draws the message to the x & y coordinates on the screen. + */ public static void draw(String msg, Screen screen, int x, int y, int whiteTint) { for (int i = 0; i < msg.length(); i++) { // Loops through all the characters that you typed int ix = chars.indexOf(msg.charAt(i)); // The current letter in the message loop if (ix >= 0) { // If that character's position is larger than or equal to 0, then render the character on the screen. - screen.render(x + i * textWidth(msg.substring(i, i+1)), y, ix % 32, ix / 32, 0, Renderer.spriteLinker.getSheet(SpriteType.Gui, "font"), whiteTint); + screen.render(x + i * textWidth(msg.substring(i, i + 1)), y, ix % 32, ix / 32, 0, Renderer.spriteLinker.getSheet(SpriteType.Gui, "font"), whiteTint); } } } @@ -64,11 +68,13 @@ public static void drawColor(String message, Screen screen, int x, int y) { } } - public static void drawBackground(String msg, Screen screen, int x, int y) { drawBackground(msg, screen, x, y, -1); } + public static void drawBackground(String msg, Screen screen, int x, int y) { + drawBackground(msg, screen, x, y, -1); + } public static void drawBackground(String msg, Screen screen, int x, int y, int whiteTint) { for (int i = 0; i < msg.length(); i++) { // Renders the black boxes under the text - screen.render(x + i * textWidth(msg.substring(i, i+1)), y, 5, 2, 0, Renderer.spriteLinker.getSheet(SpriteType.Gui, "hud")); + screen.render(x + i * textWidth(msg.substring(i, i + 1)), y, 5, 2, 0, Renderer.spriteLinker.getSheet(SpriteType.Gui, "hud")); } // Renders the text @@ -101,7 +107,10 @@ public static void drawCentered(String msg, Screen screen, int y, int color) { /// note: the y centering values in the FontStyle object will be used as a paragraph y centering value instead. - public static void drawParagraph(String para, Screen screen, FontStyle style, int lineSpacing) { drawParagraph(para, screen, Screen.w, Screen.h, style, lineSpacing); } + public static void drawParagraph(String para, Screen screen, FontStyle style, int lineSpacing) { + drawParagraph(para, screen, Screen.w, Screen.h, style, lineSpacing); + } + public static void drawParagraph(String para, Screen screen, int w, int h, FontStyle style, int lineSpacing) { drawParagraph(screen, style, lineSpacing, getLines(para, w, h, lineSpacing)); } @@ -110,12 +119,16 @@ public static void drawParagraph(String para, Screen screen, int w, int h, FontS public static void drawParagraph(List lines, Screen screen, FontStyle style, int lineSpacing) { drawParagraph(screen, style, lineSpacing, lines.toArray(new String[0])); } + public static void drawParagraph(Screen screen, FontStyle style, int lineSpacing, String... lines) { - for(int i = 0; i < lines.length; i++) + for (int i = 0; i < lines.length; i++) style.drawParagraphLine(lines, i, lineSpacing, screen); } - public static String[] getLines(String para, int w, int h, int lineSpacing) { return getLines(para, w, h, lineSpacing, false); } + public static String[] getLines(String para, int w, int h, int lineSpacing) { + return getLines(para, w, h, lineSpacing, false); + } + public static String[] getLines(String para, int w, int h, int lineSpacing, boolean keepEmptyRemainder) { ArrayList lines = new ArrayList<>(); @@ -124,21 +137,21 @@ public static String[] getLines(String para, int w, int h, int lineSpacing, bool // then I reset the para String at the index, and do it again until para is an empty string. int height = textHeight(); - while(para.length() > 0) { // continues to loop as long as there are more characters to parse. + while (para.length() > 0) { // continues to loop as long as there are more characters to parse. int splitIndex = getLine(para, w); // determine how many letters can be fit on to this line. lines.add(para.substring(0, splitIndex)); // add the specified number of characters. - if(splitIndex < para.length() && para.substring(splitIndex, splitIndex+1).matches("[ \n]")) + if (splitIndex < para.length() && para.substring(splitIndex, splitIndex + 1).matches("[ \n]")) splitIndex++; // if there are more characters to do, and the next character is a space or newline, skip it (because the getLine() method will always break before newlines, and will usually otherwise break before spaces. para = para.substring(splitIndex); // remove the characters that have now been added on to the line height += lineSpacing + textHeight(); // move y pos down a line - if(height > h) + if (height > h) break; // If we've run out of space to draw lines, then there's no point in parsing more characters, so we should break out of the loop. } - if(para.length() > 0 || keepEmptyRemainder) + if (para.length() > 0 || keepEmptyRemainder) lines.add(para); // add remainder, but don't add empty lines unintentionally. return lines.toArray(new String[0]); @@ -147,7 +160,7 @@ public static String[] getLines(String para, int w, int h, int lineSpacing, bool // this returns the position index at which the given string should be split so that the first part is the longest line possible. // note, the index returned is exclusive; it should not be included in the line. private static int getLine(String text, int maxWidth) { - if(maxWidth <= 0) return 0; // just to pass the monkey test. :P + if (maxWidth <= 0) return 0; // just to pass the monkey test. :P text = text.replaceAll(" ?\n ?", " \n "); @@ -155,22 +168,22 @@ private static int getLine(String text, int maxWidth) { int curWidth = textWidth(words[0]); - if(curWidth > maxWidth) { + if (curWidth > maxWidth) { // we can't even fit the first word on to the line, even by itself. So we'll have to fit what we can. int i; - for(i = 1; i < words[0].length(); i++) // find how many characters do fit - if(textWidth(words[0].substring(0, i+1)) > maxWidth) + for (i = 1; i < words[0].length(); i++) // find how many characters do fit + if (textWidth(words[0].substring(0, i + 1)) > maxWidth) break; return i; // stop here and return, because we know we can't fit more so we can ignore all that's below } int i; - for(i = 1; i < words.length; i++) { - if(words[i].equals("\n")) break; + for (i = 1; i < words.length; i++) { + if (words[i].equals("\n")) break; - curWidth += textWidth(" "+words[i]); - if(curWidth > maxWidth) + curWidth += textWidth(" " + words[i]); + if (curWidth > maxWidth) break; } // i now contains the number of words that fit on the line. diff --git a/src/client/java/minicraft/gfx/FontStyle.java b/src/client/java/minicraft/gfx/FontStyle.java index 5b70e4c1d..3435770a2 100644 --- a/src/client/java/minicraft/gfx/FontStyle.java +++ b/src/client/java/minicraft/gfx/FontStyle.java @@ -8,13 +8,13 @@ public class FontStyle { /// this specifies the x and y offsets for each binary value in the "shadow location byte", and is what causes each value to progress in a circle. - private static int[] shadowPosMap = { 0, 1, 1, 1, 0, -1, -1, -1, - -1, -1, 0, 1, 1, 1, 0, -1}; + private static int[] shadowPosMap = {0, 1, 1, 1, 0, -1, -1, -1, + -1, -1, 0, 1, 1, 1, 0, -1}; /** - The shadowing technique uses binary strings to specify where to outline a string of text. It was going to be a straight byte, since there are 8 positions, but since it's going to be a string anyway, I decided to make it accept a string. - Each position is specified fairly simply: it goes clockwise, starting from the top. Then it goes top right, right, bottom right, bottom, etc. up to top left. It's kind of like a compass, with a position for N, NE, E, etc. - For an example, for the default shadow, the string is "00010000". though, becuase of the way it's designed, the trailing zeros may be dropped, so it could just be "0001". This doesn't quite read like binary, but it doesn't have to, so whatever. :P - */ + * The shadowing technique uses binary strings to specify where to outline a string of text. It was going to be a straight byte, since there are 8 positions, but since it's going to be a string anyway, I decided to make it accept a string. + * Each position is specified fairly simply: it goes clockwise, starting from the top. Then it goes top right, right, bottom right, bottom, etc. up to top left. It's kind of like a compass, with a position for N, NE, E, etc. + * For an example, for the default shadow, the string is "00010000". though, becuase of the way it's designed, the trailing zeros may be dropped, so it could just be "0001". This doesn't quite read like binary, but it doesn't have to, so whatever. :P + */ private int mainColor; @@ -29,12 +29,15 @@ public class FontStyle { private Rectangle paraBounds; private int padX = 0, padY = 0; - public FontStyle() { this(Color.WHITE); } + public FontStyle() { + this(Color.WHITE); + } + public FontStyle(int mainColor) { this.mainColor = mainColor; shadowColor = Color.get(-1, -1); shadowType = ""; - anchor = new Point(Screen.w/2, Screen.h/2); + anchor = new Point(Screen.w / 2, Screen.h / 2); /// By default, the styling is set so as to center the text in the middle of the screen, with no shadow. } @@ -81,14 +84,14 @@ public void configureForParagraph(String[] para, int spacing) { // In a paragraph, it could be the left side, or right, or top... it depends. // Either way, the draw method needs to use a different position. - Dimension size = new Dimension(Font.textWidth(para), para.length*(Font.textHeight()+spacing)); + Dimension size = new Dimension(Font.textWidth(para), para.length * (Font.textHeight() + spacing)); paraBounds = relTextPos.positionRect(size, anchor, new Rectangle()); } public void setupParagraphLine(String[] para, int line, int spacing) { if (para == null || line < 0 || line >= para.length) { Logger.tag("FontStyle").error("FontStyle.java: " + - (para == null ? "paragraph is null" : "index "+line+" is invalid") + "; can't draw line."); + (para == null ? "paragraph is null" : "index " + line + " is invalid") + "; can't draw line."); return; } @@ -96,8 +99,8 @@ public void setupParagraphLine(String[] para, int line, int spacing) { configureForParagraph(para, spacing); Rectangle textArea = new Rectangle(paraBounds); - textArea.setSize(textArea.getWidth(), Font.textHeight()+spacing, RelPos.TOP_LEFT); - textArea.translate(0, line*textArea.getHeight()); + textArea.setSize(textArea.getWidth(), Font.textHeight() + spacing, RelPos.TOP_LEFT); + textArea.translate(0, line * textArea.getHeight()); anchor = textArea.getPosition(relTextPos.getOpposite()); // For the relpos to put the rect in the correct pos, the anchor should be fetched using to opposite relpos. @@ -114,14 +117,21 @@ public void drawParagraphLine(String[] para, int line, int spacing, Screen scree /* -- All the font modifier methods are below. They all return the current FontStyle instance for chaining. -- */ - /** Sets the color of the text itself. */ + /** + * Sets the color of the text itself. + */ public FontStyle setColor(int col) { mainColor = col; return this; } - /** sets the x position of the text anchor. This causes the text to be left-justified, if alignment is reset. */ - public FontStyle setXPos(int pos) { return setXPos(pos, true); } + /** + * sets the x position of the text anchor. This causes the text to be left-justified, if alignment is reset. + */ + public FontStyle setXPos(int pos) { + return setXPos(pos, true); + } + public FontStyle setXPos(int pos, boolean resetAlignment) { anchor.x = pos; if (resetAlignment) { @@ -130,8 +140,14 @@ public FontStyle setXPos(int pos, boolean resetAlignment) { } return this; } - /** sets the y position of the text anchor. This sets the y pos to be the top of the block, if alignment is reset. */ - public FontStyle setYPos(int pos) { return setYPos(pos, true); } + + /** + * sets the y position of the text anchor. This sets the y pos to be the top of the block, if alignment is reset. + */ + public FontStyle setYPos(int pos) { + return setYPos(pos, true); + } + public FontStyle setYPos(int pos, boolean resetAlignment) { anchor.y = pos; if (resetAlignment) { @@ -146,33 +162,46 @@ public FontStyle setAnchor(int x, int y) { return this; } - /** Sets the position of the text box relative to the anchor. */ - public FontStyle setRelTextPos(RelPos relPos) { return setRelTextPos(relPos, true); } + /** + * Sets the position of the text box relative to the anchor. + */ + public FontStyle setRelTextPos(RelPos relPos) { + return setRelTextPos(relPos, true); + } + public FontStyle setRelTextPos(RelPos relPos, boolean setBoth) { this.relTextPos = relPos; if (setBoth) relLinePos = relTextPos.getOpposite(); return this; } - /** Sets the position of a paragraph of text relative to the anchor. */ + /** + * Sets the position of a paragraph of text relative to the anchor. + */ public FontStyle setRelLinePos(RelPos relPos) { relLinePos = relPos; return this; } - /** This enables text shadowing, and sets the shadow color and type. It is a convenience method that offers a preset for text outlines, and a single shadow in a standard direction. */ + /** + * This enables text shadowing, and sets the shadow color and type. It is a convenience method that offers a preset for text outlines, and a single shadow in a standard direction. + */ public FontStyle setShadowType(int color, boolean full) { String type = full ? "10101010" : "00010000"; setShadowType(color, type); return this; } - /** This is what acutally sets the values described above. It also allows custom shadows. */ + /** + * This is what acutally sets the values described above. It also allows custom shadows. + */ public FontStyle setShadowType(int color, String type) { shadowColor = color; shadowType = type; return this; } - public int getColor() { return mainColor; } + public int getColor() { + return mainColor; + } } diff --git a/src/client/java/minicraft/gfx/Insets.java b/src/client/java/minicraft/gfx/Insets.java index 3728f22ec..1e156e691 100644 --- a/src/client/java/minicraft/gfx/Insets.java +++ b/src/client/java/minicraft/gfx/Insets.java @@ -1,40 +1,49 @@ package minicraft.gfx; public class Insets { - + public int left, top, right, bottom; - - public Insets() { this(0); } - public Insets(int dist) { this(dist, dist, dist, dist); } + + public Insets() { + this(0); + } + + public Insets(int dist) { + this(dist, dist, dist, dist); + } + public Insets(int left, int top, int right, int bottom) { this.left = left; this.top = top; this.right = right; this.bottom = bottom; } - + public Rectangle addTo(Rectangle r) { - return new Rectangle(r.getLeft()-left, r.getTop()-top, r.getRight()+right, r.getBottom()+bottom, Rectangle.CORNERS); + return new Rectangle(r.getLeft() - left, r.getTop() - top, r.getRight() + right, r.getBottom() + bottom, Rectangle.CORNERS); } + public Rectangle subtractFrom(Rectangle r) { - return new Rectangle(r.getLeft()+left, r.getTop()+top, r.getRight()-right, r.getBottom()-bottom, Rectangle.CORNERS); + return new Rectangle(r.getLeft() + left, r.getTop() + top, r.getRight() - right, r.getBottom() - bottom, Rectangle.CORNERS); } - + public Dimension addTo(Dimension d) { return new Dimension(d.width + left + right, d.height + top + bottom); } + public Dimension subtractFrom(Dimension d) { return new Dimension(d.width - left - right, d.height - top - bottom); } - + public Insets addInsets(Insets s) { - return new Insets(left+s.left, top+s.top, right+s.right, bottom+s.bottom); + return new Insets(left + s.left, top + s.top, right + s.right, bottom + s.bottom); } + public Insets subtractInsets(Insets s) { - return new Insets(left-s.left, top-s.top, right-s.right, bottom-s.bottom); + return new Insets(left - s.left, top - s.top, right - s.right, bottom - s.bottom); } - + public String toString() { - return super.toString()+"[left=" + left + ",top=" + top + ",right=" + right + ",bottom=" + bottom + "]"; + return super.toString() + "[left=" + left + ",top=" + top + ",right=" + right + ",bottom=" + bottom + "]"; } } diff --git a/src/client/java/minicraft/gfx/MinicraftImage.java b/src/client/java/minicraft/gfx/MinicraftImage.java index 9ef850960..45651abc8 100644 --- a/src/client/java/minicraft/gfx/MinicraftImage.java +++ b/src/client/java/minicraft/gfx/MinicraftImage.java @@ -11,7 +11,9 @@ * As BufferedImage is heavy. Our current rendering system still depends on this array. */ public class MinicraftImage { - /** Each sprite tile size. */ + /** + * Each sprite tile size. + */ public static final int boxWidth = 8; public final int width, height; // Width and height of the sprite sheet @@ -19,19 +21,22 @@ public class MinicraftImage { /** * Default with maximum size of image. + * * @param image The image to be added. * @throws IOException if I/O exception occurs. */ public MinicraftImage(BufferedImage image) throws IOException { - this(image, image.getWidth(), image.getHeight()); + this(image, image.getWidth(), image.getHeight()); } + /** * Custom size. - * @param image The image to be added. - * @param width The width of the {@link MinicraftImage} to be applied to the {@link LinkedSprite}. + * + * @param image The image to be added. + * @param width The width of the {@link MinicraftImage} to be applied to the {@link LinkedSprite}. * @param height The height of the {@link MinicraftImage} to be applied to the {@link LinkedSprite}. * @throws IOException - */ + */ public MinicraftImage(BufferedImage image, int width, int height) throws IOException { if (width % 8 != 0) CrashHandler.errorHandle(new IllegalArgumentException("Invalid width of SpriteSheet."), new CrashHandler.ErrorInfo( diff --git a/src/client/java/minicraft/gfx/Point.java b/src/client/java/minicraft/gfx/Point.java index b1c756bec..feea0c624 100644 --- a/src/client/java/minicraft/gfx/Point.java +++ b/src/client/java/minicraft/gfx/Point.java @@ -1,36 +1,41 @@ package minicraft.gfx; public class Point { - + public int x, y; - - public Point() { this(0, 0); } + + public Point() { + this(0, 0); + } + public Point(int x, int y) { this.x = x; this.y = y; } - + public Point(Point model) { x = model.x; y = model.y; } - + public void translate(int xoff, int yoff) { x += xoff; y += yoff; } - + public String toString() { - return "("+x+","+y+")"; + return "(" + x + "," + y + ")"; } - + @Override public boolean equals(Object other) { if (!(other instanceof Point)) return false; Point o = (Point) other; return x == o.x && y == o.y; } - + @Override - public int hashCode() { return x * 71 + y; } + public int hashCode() { + return x * 71 + y; + } } diff --git a/src/client/java/minicraft/gfx/Rectangle.java b/src/client/java/minicraft/gfx/Rectangle.java index e1c7b38b5..3aeeb0d4d 100644 --- a/src/client/java/minicraft/gfx/Rectangle.java +++ b/src/client/java/minicraft/gfx/Rectangle.java @@ -3,25 +3,27 @@ import minicraft.screen.RelPos; public class Rectangle { - + public static final int CORNER_DIMS = 0; public static final int CORNERS = 1; public static final int CENTER_DIMS = 2; - + private int x, y, w, h; - - public Rectangle() {} // 0 all. + + public Rectangle() { + } // 0 all. + public Rectangle(int x, int y, int x1, int y1, int type) { - if(type < 0 || type > 2) type = 0; - + if (type < 0 || type > 2) type = 0; + if (type != CENTER_DIMS) { // x and y are the coords of the top left corner. this.x = x; this.y = y; } else { // x and y are the coords of the center. - this.x = x - x1/2; - this.y = y - y1/2; + this.x = x - x1 / 2; + this.y = y - y1 / 2; } - + if (type != CORNERS) { // x1 and y1 are the width and height. this.w = x1; this.h = y1; @@ -30,63 +32,95 @@ public Rectangle(int x, int y, int x1, int y1, int type) { this.h = y1 - y; } } - - public Rectangle(Point p, Dimension d) { this(false, p, d); } + + public Rectangle(Point p, Dimension d) { + this(false, p, d); + } + public Rectangle(boolean isCenter, Point p, Dimension d) { this(p.x, p.y, d.width, d.height, isCenter ? CENTER_DIMS : CORNER_DIMS); } - + public Rectangle(Rectangle model) { x = model.x; y = model.y; w = model.w; h = model.h; } - - public int getLeft() { return x; } - public int getRight() { return x + w; } - public int getTop() { return y; } - public int getBottom() { return y + h; } - - public int getWidth() { return w; } - public int getHeight() { return h; } - - public Point getCenter() { return new Point(x + w/2, y + h/2); } - public Dimension getSize() { return new Dimension(w, h); } - + + public int getLeft() { + return x; + } + + public int getRight() { + return x + w; + } + + public int getTop() { + return y; + } + + public int getBottom() { + return y + h; + } + + public int getWidth() { + return w; + } + + public int getHeight() { + return h; + } + + public Point getCenter() { + return new Point(x + w / 2, y + h / 2); + } + + public Dimension getSize() { + return new Dimension(w, h); + } + public Point getPosition(RelPos relPos) { Point p = new Point(x, y); - p.x += relPos.xIndex * w/2; - p.y += relPos.yIndex * h/2; + p.x += relPos.xIndex * w / 2; + p.y += relPos.yIndex * h / 2; return p; } - + public boolean intersects(Rectangle other) { - return !( getLeft() > other.getRight() // Left side is past the other right side - || other.getLeft() > getRight() // Other left side is past the right side - || getBottom() < other.getTop() // Other top is below the bottom - || other.getBottom() < getTop() // Top is below the other bottom + return !(getLeft() > other.getRight() // Left side is past the other right side + || other.getLeft() > getRight() // Other left side is past the right side + || getBottom() < other.getTop() // Other top is below the bottom + || other.getBottom() < getTop() // Top is below the other bottom ); } - - public void setPosition(Point p, RelPos relPos) { setPosition(p.x, p.y, relPos); } + + public void setPosition(Point p, RelPos relPos) { + setPosition(p.x, p.y, relPos); + } + public void setPosition(int x, int y, RelPos relPos) { - this.x = x - relPos.xIndex*w/2; - this.y = y - relPos.yIndex*h/2; + this.x = x - relPos.xIndex * w / 2; + this.y = y - relPos.yIndex * h / 2; } - + public void translate(int xoff, int yoff) { x += xoff; y += yoff; } - - public void setSize(Dimension d, RelPos anchor) { setSize(d.width, d.height, anchor); } + + public void setSize(Dimension d, RelPos anchor) { + setSize(d.width, d.height, anchor); + } + public void setSize(int width, int height, RelPos anchor) { Point p = getPosition(anchor); this.w = width; this.h = height; setPosition(p, anchor); } - - public String toString() { return super.toString()+"[center=" + getCenter() + "; size=" + getSize() + "]"; } + + public String toString() { + return super.toString() + "[center=" + getCenter() + "; size=" + getSize() + "]"; + } } diff --git a/src/client/java/minicraft/gfx/Screen.java b/src/client/java/minicraft/gfx/Screen.java index 8491cd62b..43b679ccc 100644 --- a/src/client/java/minicraft/gfx/Screen.java +++ b/src/client/java/minicraft/gfx/Screen.java @@ -11,7 +11,7 @@ public class Screen { public static final int w = Renderer.WIDTH; // Width of the screen public static final int h = Renderer.HEIGHT; // Height of the screen - public static final Point center = new Point(w/2, h/2); + public static final Point center = new Point(w / 2, h / 2); private static final int MAXDARK = 128; @@ -35,23 +35,45 @@ public Screen() { pixels = new int[Screen.w * Screen.h]; // Makes new integer array for all the pixels on the screen. } - /** Clears all the colors on the screen */ + /** + * Clears all the colors on the screen + */ public void clear(int color) { // Turns each pixel into a single color (clearing the screen!) Arrays.fill(pixels, color); } - public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet) { render(xp, yp, xt, yt, bits, sheet, -1); } - public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint) { render(xp, yp, xt, yt, bits, sheet, whiteTint, false); } - /** This method takes care of assigning the correct spritesheet to assign to the sheet variable **/ - public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint, boolean fullbright) { + public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet) { + render(xp, yp, xt, yt, bits, sheet, -1); + } + + public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint) { + render(xp, yp, xt, yt, bits, sheet, whiteTint, false); + } + + /** + * This method takes care of assigning the correct spritesheet to assign to the sheet variable + **/ + public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint, boolean fullbright) { render(xp, yp, xt, yt, bits, sheet, whiteTint, fullbright, 0); - } + } + + public void render(int xp, int yp, LinkedSprite sprite) { + render(xp, yp, sprite.getSprite()); + } + + public void render(int xp, int yp, Sprite sprite) { + render(xp, yp, sprite, false); + } + + public void render(int xp, int yp, Sprite sprite, boolean fullbright) { + render(xp, yp, sprite, 0, fullbright, 0); + } + + public void render(int xp, int yp, Sprite sprite, int mirror, boolean fullbright) { + render(xp, yp, sprite, mirror, fullbright, 0); + } - public void render(int xp, int yp, LinkedSprite sprite) { render(xp, yp, sprite.getSprite()); } - public void render(int xp, int yp, Sprite sprite) { render(xp, yp, sprite, false); } - public void render(int xp, int yp, Sprite sprite, boolean fullbright) { render(xp, yp, sprite, 0, fullbright, 0); } - public void render(int xp, int yp, Sprite sprite, int mirror, boolean fullbright) { render(xp, yp, sprite, mirror, fullbright, 0); } public void render(int xp, int yp, Sprite sprite, int mirror, boolean fullbright, int color) { for (int r = 0; r < sprite.spritePixels.length; r++) { for (int c = 0; c < sprite.spritePixels[r].length; c++) { @@ -61,16 +83,30 @@ public void render(int xp, int yp, Sprite sprite, int mirror, boolean fullbright } } - public void render(int xp, int yp, Sprite.Px pixel) { render(xp, yp, pixel, -1); } - public void render(int xp, int yp, Sprite.Px pixel, int whiteTint) { render(xp, yp, pixel, 0, whiteTint); } - public void render(int xp, int yp, Sprite.Px pixel, int mirror, int whiteTint) { render(xp, yp, pixel, mirror, whiteTint, false); } - public void render(int xp, int yp, Sprite.Px pixel, int mirror, int whiteTint, boolean fullbright) { render(xp, yp, pixel, mirror, whiteTint, fullbright, 0); } + public void render(int xp, int yp, Sprite.Px pixel) { + render(xp, yp, pixel, -1); + } + + public void render(int xp, int yp, Sprite.Px pixel, int whiteTint) { + render(xp, yp, pixel, 0, whiteTint); + } + + public void render(int xp, int yp, Sprite.Px pixel, int mirror, int whiteTint) { + render(xp, yp, pixel, mirror, whiteTint, false); + } + + public void render(int xp, int yp, Sprite.Px pixel, int mirror, int whiteTint, boolean fullbright) { + render(xp, yp, pixel, mirror, whiteTint, fullbright, 0); + } + public void render(int xp, int yp, Sprite.Px pixel, int mirror, int whiteTint, boolean fullbright, int color) { render(xp, yp, pixel.x, pixel.y, pixel.mirror ^ mirror, pixel.sheet, whiteTint, fullbright, color); } - /** Renders an object from the sprite sheet based on screen coordinates, tile (SpriteSheet location), colors, and bits (for mirroring). I believe that xp and yp refer to the desired position of the upper-left-most pixel. */ - public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint, boolean fullbright, int color) { + /** + * Renders an object from the sprite sheet based on screen coordinates, tile (SpriteSheet location), colors, and bits (for mirroring). I believe that xp and yp refer to the desired position of the upper-left-most pixel. + */ + public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage sheet, int whiteTint, boolean fullbright, int color) { if (sheet == null) return; // Verifying that sheet is not null. // xp and yp are originally in level coordinates, but offset turns them to screen coordinates. @@ -131,7 +167,9 @@ public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage shee } } - /** Sets the offset of the screen */ + /** + * Sets the offset of the screen + */ public void setOffset(int xOffset, int yOffset) { // This is called in few places, one of which is level.renderBackground, right before all the tiles are rendered. The offset is determined by the Game class (this only place renderBackground is called), by using the screen's width and the player's position in the level. // In other words, the offset is a conversion factor from level coordinates to screen coordinates. It makes a certain coord in the level the upper left corner of the screen, when subtracted from the tile coord. @@ -147,55 +185,64 @@ public void setOffset(int xOffset, int yOffset) { In the end, "every other every row", will need, for example in column 1, 15 light to be lit, then 0 light to be lit, then 12 light to be lit, then 3 light to be lit. So, the pixels of lower light levels will generally be lit every other pixel, while the brighter ones appear more often. The reason for the variance in values is to provide EVERY number between 0 and 15, so that all possible light levels (below 16) are represented fittingly with their own pattern of lit and not lit. 16 is the minimum pixel lighness required to ensure that the pixel will always remain lit. */ - private static final int[] dither = new int[] { + private static final int[] dither = new int[]{ 0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5 }; - /** Overlays the screen with pixels */ - public void overlay(Screen screen2, int currentLevel, int xa, int ya) { + /** + * Overlays the screen with pixels + */ + public void overlay(Screen screen2, int currentLevel, int xa, int ya) { double tintFactor = 0; if (currentLevel >= 3 && currentLevel < 5) { int transTime = Updater.dayLength / 4; double relTime = (Updater.tickCount % transTime) * 1.0 / transTime; switch (Updater.getTime()) { - case Morning: tintFactor = Updater.pastDay1 ? (1-relTime) * MAXDARK : 0; break; - case Day: tintFactor = 0; break; - case Evening: tintFactor = relTime * MAXDARK; break; - case Night: tintFactor = MAXDARK; break; + case Morning: + tintFactor = Updater.pastDay1 ? (1 - relTime) * MAXDARK : 0; + break; + case Day: + tintFactor = 0; + break; + case Evening: + tintFactor = relTime * MAXDARK; + break; + case Night: + tintFactor = MAXDARK; + break; } if (currentLevel > 3) tintFactor -= (tintFactor < 10 ? tintFactor : 10); tintFactor *= -1; // All previous operations were assuming this was a darkening factor. - } - else if(currentLevel >= 5) + } else if (currentLevel >= 5) tintFactor = -MAXDARK; int[] oPixels = screen2.pixels; // The Integer array of pixels to overlay the screen with. int i = 0; // Current pixel on the screen for (int y = 0; y < h; y++) { // loop through height of screen - for (int x = 0; x < w; x++) { // loop through width of screen + for (int x = 0; x < w; x++) { // loop through width of screen if (oPixels[i] / 10 <= dither[((x + xa) & 3) + ((y + ya) & 3) * 4]) { - /// The above if statement is simply comparing the light level stored in oPixels with the minimum light level stored in dither. if it is determined that the oPixels[i] is less than the minimum requirements, the pixel is considered "dark", and the below is executed... + /// The above if statement is simply comparing the light level stored in oPixels with the minimum light level stored in dither. if it is determined that the oPixels[i] is less than the minimum requirements, the pixel is considered "dark", and the below is executed... if (currentLevel < 3) { // if in caves... - /// in the caves, not being lit means being pitch black. + /// in the caves, not being lit means being pitch black. pixels[i] = 0; - } else { + } else { /// Outside the caves, not being lit simply means being darker. - pixels[i] = Color.tintColor(pixels[i], (int)tintFactor); // darkens the color one shade. - } - } + pixels[i] = Color.tintColor(pixels[i], (int) tintFactor); // darkens the color one shade. + } + } // Increase the tinting of all colors by 20. pixels[i] = Color.tintColor(pixels[i], 20); - i++; // Moves to the next pixel. - } - } - } + i++; // Moves to the next pixel. + } + } + } public void renderLight(int x, int y, int r) { // Applies offsets: @@ -224,7 +271,8 @@ public void renderLight(int x, int y, int r) { // If the distance from the center (x,y) is less or equal to the radius... int br = 255 - dist * 255 / (r * r); // area where light will be rendered. // r*r is becuase dist is still x*x+y*y, of pythag theorem. // br = brightness... literally. from 0 to 255. - if (pixels[xx + yy * w] < br) pixels[xx + yy * w] = br; // Pixel cannot be smaller than br; in other words, the pixel color (brightness) cannot be less than br. + if (pixels[xx + yy * w] < br) + pixels[xx + yy * w] = br; // Pixel cannot be smaller than br; in other words, the pixel color (brightness) cannot be less than br. } } } diff --git a/src/client/java/minicraft/gfx/Sprite.java b/src/client/java/minicraft/gfx/Sprite.java index c913a82f3..e5484cf88 100644 --- a/src/client/java/minicraft/gfx/Sprite.java +++ b/src/client/java/minicraft/gfx/Sprite.java @@ -1,15 +1,17 @@ package minicraft.gfx; -/** This class represents a group of pixels on their sprite sheet(s). */ +/** + * This class represents a group of pixels on their sprite sheet(s). + */ public class Sprite { /** - This class needs to store a list of similar segments that make up a sprite, just once for everything. There's usually four groups, but the components are: - -spritesheet location (x, y) - -mirror type - - That's it! - The screen's render method only draws one 8x8 pixel of the spritesheet at a time, so the "sprite size" will be determined by how many repetitions of the above group there are. - */ + * This class needs to store a list of similar segments that make up a sprite, just once for everything. There's usually four groups, but the components are: + * -spritesheet location (x, y) + * -mirror type + *

+ * That's it! + * The screen's render method only draws one 8x8 pixel of the spritesheet at a time, so the "sprite size" will be determined by how many repetitions of the above group there are. + */ public Px[][] spritePixels; public int color = -1; @@ -21,15 +23,17 @@ public Sprite(Px[][] pixels) { public String toString() { StringBuilder out = new StringBuilder(getClass().getName().replace("minicraft.gfx.", "") + "; pixels:"); - for (Px[] row: spritePixels) - for (Px pixel: row) + for (Px[] row : spritePixels) + for (Px pixel : row) out.append("\n").append(pixel.toString()); out.append("\n"); return out.toString(); } - /** This class represents a pixel on the sprite sheet. */ + /** + * This class represents a pixel on the sprite sheet. + */ public static class Px { protected int x, y, mirror; protected MinicraftImage sheet; diff --git a/src/client/java/minicraft/gfx/SpriteAnimation.java b/src/client/java/minicraft/gfx/SpriteAnimation.java index 3b5782676..caeea0fdc 100644 --- a/src/client/java/minicraft/gfx/SpriteAnimation.java +++ b/src/client/java/minicraft/gfx/SpriteAnimation.java @@ -17,7 +17,9 @@ import java.util.HashMap; import java.util.function.BiFunction; -/** This is not applicable for mob sprite animations. Only for generic sprite animations. */ +/** + * This is not applicable for mob sprite animations. Only for generic sprite animations. + */ public class SpriteAnimation implements Destroyable { private static final ArrayList spriteAnimations = new ArrayList<>(); private static final HashMap metas = new HashMap<>(); @@ -34,7 +36,9 @@ public static SpriteMeta getMetadata(String key) { return metas.get(key); } - /** Refreshing all currently registered animations. */ + /** + * Refreshing all currently registered animations. + */ public static void refreshAnimations() { spriteAnimations.forEach(a -> a.refreshAnimation(metas.get(a.key))); } @@ -59,15 +63,20 @@ public static void refreshAnimations() { /** * Constructing animations with the provided key. The meta is given by default. + * * @param type The sprite category. - * @param key The sprite resource key. + * @param key The sprite resource key. */ - public SpriteAnimation(SpriteType type, String key) { this(metas.get(key), type, key); } + public SpriteAnimation(SpriteType type, String key) { + this(metas.get(key), type, key); + } + /** * Constructing animations with the provided metadata and key. It should already be validated. + * * @param meta The metadata of the sprite sheet. * @param type The sprite category. - * @param key The sprite resource key. + * @param key The sprite resource key. */ public SpriteAnimation(SpriteMeta meta, SpriteType type, String key) { this.type = type; @@ -79,6 +88,7 @@ public SpriteAnimation(SpriteMeta meta, SpriteType type, String key) { /** * Setting the tile class of this animation used for tile connector rendering. + * * @param connectChecker The tile connection checker. * @return The instance itself. */ @@ -89,6 +99,7 @@ public SpriteAnimation setConnectChecker(BiFunction conn /** * Setting if the singleton sprite is used for other tile connective rendering. + * * @param connective If used for connective rendering. * @return The instance itself. */ @@ -99,6 +110,7 @@ public SpriteAnimation setSingletonWithConnective(boolean connective) { /** * Setting the color of all animation frames. + * * @param color The color of sprite. * @return The instance itself. */ @@ -112,6 +124,7 @@ public SpriteAnimation setColor(int color) { /** * Setting the color of the specific animation frame. + * * @param frame The specific frame. * @param color The color of sprite. * @return The instance itself. @@ -126,6 +139,7 @@ public SpriteAnimation setColor(int frame, int color) { /** * Setting the mirror of all animation frames. + * * @param mirror The mirror of sprite/ * @return The instance itself. */ @@ -139,7 +153,8 @@ public SpriteAnimation setMirror(int mirror) { /** * Setting the mirror of the specific animation frame. - * @param frame The specific frame. + * + * @param frame The specific frame. * @param mirror The mirror of sprite. * @return The instance itself. */ @@ -153,6 +168,7 @@ public SpriteAnimation setMirror(int frame, int mirror) { /** * Setting the sprite sheet mirror of all frames. + * * @param mirror The mirror of sprite sheet. * @return The instance itself. */ @@ -163,6 +179,7 @@ public SpriteAnimation setSpriteMirror(int mirror) { /** * Getting the current frame of animation. + * * @return The current frame sprite. */ public LinkedSprite getCurrentFrame() { @@ -171,6 +188,7 @@ public LinkedSprite getCurrentFrame() { /** * Getting the specific frame of animation. + * * @param frame The specific frame. * @return The frame sprite. */ @@ -180,10 +198,11 @@ public LinkedSprite getFrame(int frame) { /** * Rendering the animation on the screen. + * * @param screen The screen instance. - * @param level The level for rendering. - * @param x The x coordinate level tile. - * @param y The y coordinate level tile. + * @param level The level for rendering. + * @param x The x coordinate level tile. + * @param y The y coordinate level tile. */ public void render(Screen screen, Level level, int x, int y) { // If border and the tile class is set. @@ -266,14 +285,16 @@ public void render(Screen screen, Level level, int x, int y) { } } - /** Refreshing the animation data for this instance. */ + /** + * Refreshing the animation data for this instance. + */ public void refreshAnimation(SpriteMeta metadata) { frame = 0; frametick = 0; this.metadata = metadata; MinicraftImage sheet = Renderer.spriteLinker.getSheet(type, key); if (sheet == null) { - animations = new LinkedSprite[] {SpriteLinker.missingTexture(type)}; + animations = new LinkedSprite[]{SpriteLinker.missingTexture(type)}; border = null; corner = null; return; @@ -301,7 +322,7 @@ public void refreshAnimation(SpriteMeta metadata) { if (metadata.border != null) border = new LinkedSprite(type, metadata.border); if (metadata.corner != null) corner = new LinkedSprite(type, metadata.corner); } else { - animations = new LinkedSprite[] {new LinkedSprite(type, key).setSpriteSize(width, width)}; + animations = new LinkedSprite[]{new LinkedSprite(type, key).setSpriteSize(width, width)}; border = null; corner = null; } diff --git a/src/client/java/minicraft/gfx/SpriteLinker.java b/src/client/java/minicraft/gfx/SpriteLinker.java index cd987ac6f..12b1909fe 100644 --- a/src/client/java/minicraft/gfx/SpriteLinker.java +++ b/src/client/java/minicraft/gfx/SpriteLinker.java @@ -10,14 +10,20 @@ import java.util.HashMap; public class SpriteLinker { - /** Buffering SpriteSheet for caching. */ + /** + * Buffering SpriteSheet for caching. + */ private final HashMap entitySheets = new HashMap<>(), - guiSheets = new HashMap<>(), itemSheets = new HashMap<>(), tileSheets = new HashMap<>(); + guiSheets = new HashMap<>(), itemSheets = new HashMap<>(), tileSheets = new HashMap<>(); - /** Storing all exist in-used LinkedSprite. */ + /** + * Storing all exist in-used LinkedSprite. + */ private final ArrayList linkedSheets = new ArrayList<>(); - /** Clearing all Sprite buffers for the upcoming resource pack application. */ + /** + * Clearing all Sprite buffers for the upcoming resource pack application. + */ public void resetSprites() { entitySheets.clear(); guiSheets.clear(); @@ -28,37 +34,53 @@ public void resetSprites() { /** * The safe size check which will be required for the higher resolution sprites must be used * before this method invoked. But in new rendering engine. - * @param t The sheet type. - * @param key The sheet key. + * + * @param t The sheet type. + * @param key The sheet key. * @param spriteSheet The sheet. */ public void setSprite(SpriteType t, String key, MinicraftImage spriteSheet) { switch (t) { - case Entity: entitySheets.put(key, spriteSheet); break; - case Gui: guiSheets.put(key, spriteSheet); break; - case Item: itemSheets.put(key, spriteSheet); break; - case Tile: tileSheets.put(key, spriteSheet); break; + case Entity: + entitySheets.put(key, spriteSheet); + break; + case Gui: + guiSheets.put(key, spriteSheet); + break; + case Item: + itemSheets.put(key, spriteSheet); + break; + case Tile: + tileSheets.put(key, spriteSheet); + break; } } /** * Getting the sprite sheet with the category and key. - * @param t The sprite category + * + * @param t The sprite category * @param key The resource key. * @return The sprite sheet. null if not found. */ public MinicraftImage getSheet(SpriteType t, String key) { switch (t) { - case Entity: return entitySheets.get(key); - case Gui: return guiSheets.get(key); - case Item: return itemSheets.get(key); - case Tile: return tileSheets.get(key); + case Entity: + return entitySheets.get(key); + case Gui: + return guiSheets.get(key); + case Item: + return itemSheets.get(key); + case Tile: + return tileSheets.get(key); } return null; } - /** Cleaing all skin sheets in entity sheets. */ + /** + * Cleaing all skin sheets in entity sheets. + */ public void clearSkins() { for (String k : new ArrayList<>(entitySheets.keySet())) { if (k.startsWith("skin.")) entitySheets.remove(k); @@ -67,7 +89,8 @@ public void clearSkins() { /** * Setting the skin in entity sheet. - * @param key The key of the sheet. + * + * @param key The key of the sheet. * @param spriteSheet The sheet to be added. */ public void setSkin(String key, MinicraftImage spriteSheet) { @@ -76,72 +99,105 @@ public void setSkin(String key, MinicraftImage spriteSheet) { /** * Getting the missing texture texture with the specific sprite type. + * * @param type The sprite category. * @return The missing texture or null if invalid sprite type. */ public static LinkedSprite missingTexture(SpriteType type) { switch (type) { - case Entity: return new LinkedSprite(SpriteType.Entity, "missing_entity"); - case Item: return new LinkedSprite(SpriteType.Item, "missing_item"); - case Tile: return new LinkedSprite(SpriteType.Tile, "missing_tile"); - default: return null; + case Entity: + return new LinkedSprite(SpriteType.Entity, "missing_entity"); + case Item: + return new LinkedSprite(SpriteType.Item, "missing_item"); + case Tile: + return new LinkedSprite(SpriteType.Tile, "missing_tile"); + default: + return null; } } /** * Getting the sheet of missing texture with the specific sprite type. + * * @param type The sprite category. * @return Ths missing texture sprite sheet or null if invalid sprite type. */ public MinicraftImage missingSheet(SpriteType type) { switch (type) { // The sheets should be found. - case Entity: return entitySheets.get("missing_entity"); - case Item: return itemSheets.get("missing_item"); - case Tile: return tileSheets.get("missing_tile"); - default: return null; + case Entity: + return entitySheets.get("missing_entity"); + case Item: + return itemSheets.get("missing_item"); + case Tile: + return tileSheets.get("missing_tile"); + default: + return null; } } - /** Updating all existing LinkedSheet for resource pack application. */ + /** + * Updating all existing LinkedSheet for resource pack application. + */ public void updateLinkedSheets() { Logging.SPRITE.debug("Updating all LinkedSprite."); linkedSheets.forEach(s -> s.reload()); } - /** The metadata of the sprite sheet. */ + /** + * The metadata of the sprite sheet. + */ public static class SpriteMeta { - /** The sprite animation configuration. */ + /** + * The sprite animation configuration. + */ public int frames = 1, // Minimum with 1. - frametime = 0; // 0 if no animation. - /** The sprite connector configuration. */ + frametime = 0; // 0 if no animation. + /** + * The sprite connector configuration. + */ public String border = null, corner = null; } - /** The sprite categories in the image resources. TODO Removed for the new save system */ + /** + * The sprite categories in the image resources. TODO Removed for the new save system + */ public static enum SpriteType { Item, Gui, Tile, Entity; // Only for resource packs; Skin is not applied. } /** * Linking the LinkedSprite into specific sheet map. This should only be used by {@link LinkedSprite}. + * * @param sheet The sprite to be linked. - * @param type The sprite type to be linked. + * @param type The sprite type to be linked. */ public void linkSpriteSheet(LinkedSprite sheet, SpriteType type) { // Because of the private access. switch (type) { - case Entity: sheet.linkedMap = Renderer.spriteLinker.entitySheets; break; - case Gui: sheet.linkedMap = Renderer.spriteLinker.guiSheets; break; - case Item: sheet.linkedMap = Renderer.spriteLinker.itemSheets; break; - case Tile: sheet.linkedMap = Renderer.spriteLinker.tileSheets; break; + case Entity: + sheet.linkedMap = Renderer.spriteLinker.entitySheets; + break; + case Gui: + sheet.linkedMap = Renderer.spriteLinker.guiSheets; + break; + case Item: + sheet.linkedMap = Renderer.spriteLinker.itemSheets; + break; + case Tile: + sheet.linkedMap = Renderer.spriteLinker.tileSheets; + break; } } - /** A sprite collector with resource collector. */ + /** + * A sprite collector with resource collector. + */ public static class LinkedSprite implements Destroyable { private final String key; // The resource key. - /** The sprite configuration. */ + /** + * The sprite configuration. + */ private int x, y, w, h, color = -1, mirror = 0, flip = 0; // Sprite data. @@ -153,7 +209,8 @@ public static class LinkedSprite implements Destroyable { /** * Create new LinkedSprite for the specific category and resource key. - * @param t The category of the sprite. + * + * @param t The category of the sprite. * @param key The resource key of the sprite. */ public LinkedSprite(SpriteType t, String key) { @@ -165,6 +222,7 @@ public LinkedSprite(SpriteType t, String key) { /** * Getting the sprite sheet of the linked sprite. + * * @return The current linked sprite. */ public MinicraftImage getSheet() { @@ -173,6 +231,7 @@ public MinicraftImage getSheet() { /** * Setting the sprite size. + * * @param w The sprite width. * @param h The sprite height * @return The instance itself. @@ -183,8 +242,10 @@ public LinkedSprite setSpriteSize(int w, int h) { reloaded = false; // Reload this. return this; } + /** * Setting the sprite position. + * * @param x The x position of the sprite. * @param y The y position of the sprite. * @return The instance itself. @@ -195,8 +256,10 @@ public LinkedSprite setSpritePos(int x, int y) { reloaded = false; // Reload this. return this; } + /** * Setting the sprite position and size. + * * @param x The x position of the sprite. * @param y The y position of the sprite. * @param w The sprite width. @@ -209,8 +272,10 @@ public LinkedSprite setSpriteDim(int x, int y, int w, int h) { reloaded = false; // Reload this. return this; } + /** * Setting the white tint. + * * @param color The color of the white tint. * @return The instance itself. */ @@ -219,8 +284,10 @@ public LinkedSprite setColor(int color) { reloaded = false; // Reload this. return this; } + /** * Setting the mirror of the sprite. + * * @param mirror The mirror of the sprite. * @return The instance itself. */ @@ -229,8 +296,10 @@ public LinkedSprite setMirror(int mirror) { reloaded = false; // Reload this. return this; } + /** * Setting the flip of the sprite sheet. + * * @param flip The mirror of the sprite sheet. * @return The instance itself. */ @@ -242,6 +311,7 @@ public LinkedSprite setFlip(int flip) { /** * Getting the sprite with the configuration. + * * @return The generated sprite. */ public Sprite getSprite() { @@ -252,9 +322,16 @@ public Sprite getSprite() { return sprite; } - /** Requiring the sprite to be reloaded when the next time generated. */ - public void reload() { reloaded = false; } - /** Reloading the sprite with the configuration. */ + /** + * Requiring the sprite to be reloaded when the next time generated. + */ + public void reload() { + reloaded = false; + } + + /** + * Reloading the sprite with the configuration. + */ private void reloadSprite() { MinicraftImage sheet = linkedMap.get(key); if (sheet != null) { @@ -267,8 +344,8 @@ private void reloadSprite() { for (int r = 0; r < h; r++) { for (int c = 0; c < w; c++) { // The offsets are there to determine the pixel that will be there: the one in order, or on the opposite side. - int xOffset = flipX ? w-1 - c : c; - int yOffset = flipY ? h-1 - r : r; + int xOffset = flipX ? w - 1 - c : c; + int yOffset = flipY ? h - 1 - r : r; pixels[r][c] = new Sprite.Px(x + xOffset, y + yOffset, mirror, sheet); } } @@ -283,13 +360,18 @@ private void reloadSprite() { reloaded = true; } - /** Unlink this LinkedSprite from SpriteLinker. */ + /** + * Unlink this LinkedSprite from SpriteLinker. + */ @Override public void destroy() throws DestroyFailedException { Renderer.spriteLinker.linkedSheets.remove(this); // Unlink this instance. destoryed = true; } - /** If this LinkedSprite is unlinked from SpriteLinker. */ + + /** + * If this LinkedSprite is unlinked from SpriteLinker. + */ @Override public boolean isDestroyed() { return destoryed; diff --git a/src/client/java/minicraft/item/ArmorItem.java b/src/client/java/minicraft/item/ArmorItem.java index 430fc3b85..80304ef3f 100644 --- a/src/client/java/minicraft/item/ArmorItem.java +++ b/src/client/java/minicraft/item/ArmorItem.java @@ -28,7 +28,10 @@ protected static ArrayList getAllInstances() { private final int staminaCost; public final int level; - private ArmorItem(String name, LinkedSprite sprite, float health, int level) { this(name, sprite, 1, health, level); } + private ArmorItem(String name, LinkedSprite sprite, float health, int level) { + this(name, sprite, 1, health, level); + } + private ArmorItem(String name, LinkedSprite sprite, int count, float health, int level) { super(name, sprite, count); this.armor = health; @@ -48,7 +51,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull ArmorItem copy() { return new ArmorItem(getName(), sprite, count, armor, level); diff --git a/src/client/java/minicraft/item/BookItem.java b/src/client/java/minicraft/item/BookItem.java index f5f1c911c..73867b703 100644 --- a/src/client/java/minicraft/item/BookItem.java +++ b/src/client/java/minicraft/item/BookItem.java @@ -30,7 +30,10 @@ public static interface BookContent { protected BookContent book; // TODO this is not saved yet; it could be, for editable books. private final boolean hasTitlePage; - private BookItem(String title, LinkedSprite sprite, BookContent book) { this(title, sprite, book, false); } + private BookItem(String title, LinkedSprite sprite, BookContent book) { + this(title, sprite, book, false); + } + private BookItem(String title, LinkedSprite sprite, BookContent book, boolean hasTitlePage) { super(title, sprite); this.book = book; @@ -43,7 +46,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull BookItem copy() { return new BookItem(getName(), sprite, book, hasTitlePage); diff --git a/src/client/java/minicraft/item/BucketItem.java b/src/client/java/minicraft/item/BucketItem.java index 81e8ad6f1..244c4bf40 100644 --- a/src/client/java/minicraft/item/BucketItem.java +++ b/src/client/java/minicraft/item/BucketItem.java @@ -15,9 +15,9 @@ public class BucketItem extends StackableItem { public enum Fill { - Empty (Tiles.get("hole"), 2), - Water (Tiles.get("water"), 0), - Lava (Tiles.get("lava"), 1); + Empty(Tiles.get("hole"), 2), + Water(Tiles.get("water"), 0), + Lava(Tiles.get("lava"), 1); public Tile contained; public int offset; @@ -31,14 +31,14 @@ public enum Fill { protected static ArrayList getAllInstances() { ArrayList items = new ArrayList<>(); - for (Fill fill: Fill.values()) + for (Fill fill : Fill.values()) items.add(new BucketItem(fill)); return items; } private static Fill getFilling(Tile tile) { - for (Fill fill: Fill.values()) + for (Fill fill : Fill.values()) if (fill.contained.id == tile.id) return fill; @@ -47,7 +47,10 @@ private static Fill getFilling(Tile tile) { private Fill filling; - private BucketItem(Fill fill) { this(fill, 1); } + private BucketItem(Fill fill) { + this(fill, 1); + } + private BucketItem(Fill fill, int count) { super(fill.toString() + " Bucket", new LinkedSprite(SpriteType.Item, fill == Fill.Empty ? "bucket" : fill == Fill.Lava ? "lava_bucket" : "water_bucket"), count); @@ -61,11 +64,13 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, if (filling != Fill.Empty) { if (fill == Fill.Empty) { level.setTile(xt, yt, filling.contained); - if (!Game.isMode("minicraft.settings.mode.creative")) player.activeItem = editBucket(player, Fill.Empty); + if (!Game.isMode("minicraft.settings.mode.creative")) + player.activeItem = editBucket(player, Fill.Empty); return true; } else if (fill == Fill.Lava && filling == Fill.Water) { level.setTile(xt, yt, Tiles.get("Obsidian")); - if (!Game.isMode("minicraft.settings.mode.creative")) player.activeItem = editBucket(player, Fill.Empty); + if (!Game.isMode("minicraft.settings.mode.creative")) + player.activeItem = editBucket(player, Fill.Empty); return true; } } else { // This is an empty bucket @@ -77,7 +82,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, return false; } - /** This method exists due to the fact that buckets are stackable, but only one should be changed at one time. */ + /** + * This method exists due to the fact that buckets are stackable, but only one should be changed at one time. + */ private BucketItem editBucket(Player player, Fill newFill) { if (count == 0) return null; // This honestly should never happen... if (count == 1) return new BucketItem(newFill); @@ -91,11 +98,13 @@ private BucketItem editBucket(Player player, Fill newFill) { } public boolean equals(Item other) { - return super.equals(other) && filling == ((BucketItem)other).filling; + return super.equals(other) && filling == ((BucketItem) other).filling; } @Override - public int hashCode() { return super.hashCode() + filling.offset * 31; } + public int hashCode() { + return super.hashCode() + filling.offset * 31; + } public @NotNull BucketItem copy() { return new BucketItem(filling, count); diff --git a/src/client/java/minicraft/item/ClothingItem.java b/src/client/java/minicraft/item/ClothingItem.java index 6340ded44..49711a92a 100644 --- a/src/client/java/minicraft/item/ClothingItem.java +++ b/src/client/java/minicraft/item/ClothingItem.java @@ -19,20 +19,23 @@ protected static ArrayList getAllInstances() { items.add(new ClothingItem("Red Clothes", new LinkedSprite(SpriteType.Item, "red_clothes"), Color.get(1, 204, 0, 0))); items.add(new ClothingItem("Blue Clothes", new LinkedSprite(SpriteType.Item, "blue_clothes"), Color.get(1, 0, 0, 204))); - items.add(new ClothingItem("Green Clothes", new LinkedSprite(SpriteType.Item, "green_clothes"), Color.get(1, 0, 204, 0))); - items.add(new ClothingItem("Yellow Clothes", new LinkedSprite(SpriteType.Item, "yellow_clothes"), Color.get(1, 204, 204, 0))); - items.add(new ClothingItem("Black Clothes", new LinkedSprite(SpriteType.Item, "black_clothes"), Color.get(1, 51))); - items.add(new ClothingItem("Orange Clothes", new LinkedSprite(SpriteType.Item, "orange_clothes"), Color.get(1, 255, 102, 0))); - items.add(new ClothingItem("Purple Clothes", new LinkedSprite(SpriteType.Item, "purple_clothes"), Color.get(1, 102, 0, 153))); - items.add(new ClothingItem("Cyan Clothes", new LinkedSprite(SpriteType.Item, "cyan_clothes"), Color.get(1, 0, 102, 153))); - items.add(new ClothingItem("Reg Clothes", new LinkedSprite(SpriteType.Item, "reg_clothes"), Color.get(1, 51, 51, 0))); + items.add(new ClothingItem("Green Clothes", new LinkedSprite(SpriteType.Item, "green_clothes"), Color.get(1, 0, 204, 0))); + items.add(new ClothingItem("Yellow Clothes", new LinkedSprite(SpriteType.Item, "yellow_clothes"), Color.get(1, 204, 204, 0))); + items.add(new ClothingItem("Black Clothes", new LinkedSprite(SpriteType.Item, "black_clothes"), Color.get(1, 51))); + items.add(new ClothingItem("Orange Clothes", new LinkedSprite(SpriteType.Item, "orange_clothes"), Color.get(1, 255, 102, 0))); + items.add(new ClothingItem("Purple Clothes", new LinkedSprite(SpriteType.Item, "purple_clothes"), Color.get(1, 102, 0, 153))); + items.add(new ClothingItem("Cyan Clothes", new LinkedSprite(SpriteType.Item, "cyan_clothes"), Color.get(1, 0, 102, 153))); + items.add(new ClothingItem("Reg Clothes", new LinkedSprite(SpriteType.Item, "reg_clothes"), Color.get(1, 51, 51, 0))); return items; } private int playerCol; - private ClothingItem(String name, LinkedSprite sprite, int pcol) { this(name, 1, sprite, pcol); } + private ClothingItem(String name, LinkedSprite sprite, int pcol) { + this(name, 1, sprite, pcol); + } + private ClothingItem(String name, int count, LinkedSprite sprite, int pcol) { super(name, sprite, count); playerCol = pcol; @@ -58,7 +61,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull ClothingItem copy() { return new ClothingItem(getName(), count, sprite, playerCol); diff --git a/src/client/java/minicraft/item/FishingData.java b/src/client/java/minicraft/item/FishingData.java index 4f74224c7..2d0928c33 100644 --- a/src/client/java/minicraft/item/FishingData.java +++ b/src/client/java/minicraft/item/FishingData.java @@ -8,22 +8,22 @@ public class FishingData { - public static final List fishData = getData("fish"); + public static final List fishData = getData("fish"); - public static final List toolData = getData("tool"); + public static final List toolData = getData("tool"); - public static final List junkData = getData("junk"); + public static final List junkData = getData("junk"); - public static final List rareData = getData("rare"); + public static final List rareData = getData("rare"); - public static List getData(String name) { - List data; - try { - data = Load.loadFile("/resources/data/fishing/" + name + "_loot.txt"); - } catch (IOException e) { - e.printStackTrace(); - data = new ArrayList<>(); - } - return data; - } + public static List getData(String name) { + List data; + try { + data = Load.loadFile("/resources/data/fishing/" + name + "_loot.txt"); + } catch (IOException e) { + e.printStackTrace(); + data = new ArrayList<>(); + } + return data; + } } diff --git a/src/client/java/minicraft/item/FishingRodItem.java b/src/client/java/minicraft/item/FishingRodItem.java index 5a8fade64..7aed8ec8c 100644 --- a/src/client/java/minicraft/item/FishingRodItem.java +++ b/src/client/java/minicraft/item/FishingRodItem.java @@ -15,75 +15,78 @@ public class FishingRodItem extends Item { - protected static ArrayList getAllInstances() { - ArrayList items = new ArrayList<>(); - - for (int i = 0; i < 4; i++) { - items.add(new FishingRodItem(i)); - } - - return items; - } - private int uses = 0; // The more uses, the higher the chance of breaking - public int level; // The higher the level the lower the chance of breaking - - private Random random = new Random(); - - /* These numbers are a bit confusing, so here's an explanation - * If you want to know the percent chance of a category (let's say tool, which is third) - * You have to subtract 1 + the "tool" number from the number before it (for the first number subtract from 100)*/ - private static final int[][] LEVEL_CHANCES = { - {44, 14, 9, 4}, // They're in the order "fish", "junk", "tools", "rare" - {24, 14, 9, 4}, // Iron has very high chance of fish - {59, 49, 9, 4}, // Gold has very high chance of tools - {79, 69, 59, 4} // Gem has very high chance of rare items - }; - - private static final String[] LEVEL_NAMES = { - "Wood", - "Iron", - "Gold", - "Gem" - }; - - public FishingRodItem(int level) { - super(LEVEL_NAMES[level] + " Fishing Rod", new LinkedSprite(SpriteType.Item, + protected static ArrayList getAllInstances() { + ArrayList items = new ArrayList<>(); + + for (int i = 0; i < 4; i++) { + items.add(new FishingRodItem(i)); + } + + return items; + } + + private int uses = 0; // The more uses, the higher the chance of breaking + public int level; // The higher the level the lower the chance of breaking + + private Random random = new Random(); + + /* These numbers are a bit confusing, so here's an explanation + * If you want to know the percent chance of a category (let's say tool, which is third) + * You have to subtract 1 + the "tool" number from the number before it (for the first number subtract from 100)*/ + private static final int[][] LEVEL_CHANCES = { + {44, 14, 9, 4}, // They're in the order "fish", "junk", "tools", "rare" + {24, 14, 9, 4}, // Iron has very high chance of fish + {59, 49, 9, 4}, // Gold has very high chance of tools + {79, 69, 59, 4} // Gem has very high chance of rare items + }; + + private static final String[] LEVEL_NAMES = { + "Wood", + "Iron", + "Gold", + "Gem" + }; + + public FishingRodItem(int level) { + super(LEVEL_NAMES[level] + " Fishing Rod", new LinkedSprite(SpriteType.Item, LEVEL_NAMES[level].toLowerCase().replace("wood", "wooden") + "_fishing_rod")); - this.level = level; - } - - public static int getChance(int idx, int level) { - return LEVEL_CHANCES[level][idx]; - } - - @Override - public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { - if (tile == Tiles.get("water") && !player.isSwimming()) { // Make sure not to use it if swimming - uses++; - player.isFishing = true; - player.fishingLevel = this.level; - return true; - } - - return false; - } - - @Override - public boolean canAttack() { return false; } - - @Override - public boolean isDepleted() { - if (random.nextInt(100) > 120 - uses + level * 6) { // Breaking is random, the lower the level, and the more times you use it, the higher the chance - Game.notifications.add("Your Fishing rod broke."); - return true; - } - return false; - } - - @Override - public @NotNull Item copy() { - FishingRodItem item = new FishingRodItem(this.level); - item.uses = this.uses; - return item; - } + this.level = level; + } + + public static int getChance(int idx, int level) { + return LEVEL_CHANCES[level][idx]; + } + + @Override + public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { + if (tile == Tiles.get("water") && !player.isSwimming()) { // Make sure not to use it if swimming + uses++; + player.isFishing = true; + player.fishingLevel = this.level; + return true; + } + + return false; + } + + @Override + public boolean canAttack() { + return false; + } + + @Override + public boolean isDepleted() { + if (random.nextInt(100) > 120 - uses + level * 6) { // Breaking is random, the lower the level, and the more times you use it, the higher the chance + Game.notifications.add("Your Fishing rod broke."); + return true; + } + return false; + } + + @Override + public @NotNull Item copy() { + FishingRodItem item = new FishingRodItem(this.level); + item.uses = this.uses; + return item; + } } diff --git a/src/client/java/minicraft/item/FoodItem.java b/src/client/java/minicraft/item/FoodItem.java index d3d02d7aa..1be9c9e81 100644 --- a/src/client/java/minicraft/item/FoodItem.java +++ b/src/client/java/minicraft/item/FoodItem.java @@ -32,13 +32,18 @@ protected static ArrayList getAllInstances() { private final int feed; // The amount of hunger the food "satisfies" you by. private static final int staminaCost = 2; // The amount of stamina it costs to consume the food. - private FoodItem(String name, LinkedSprite sprite, int feed) { this(name, sprite, 1, feed); } + private FoodItem(String name, LinkedSprite sprite, int feed) { + this(name, sprite, 1, feed); + } + private FoodItem(String name, LinkedSprite sprite, int count, int feed) { super(name, sprite, count); this.feed = feed; } - /** What happens when the player uses the item on a tile */ + /** + * What happens when the player uses the item on a tile + */ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { boolean success = false; if (count > 0 && player.hunger < Player.maxHunger && player.payStamina(staminaCost)) { // If the player has hunger to fill, and stamina to pay... @@ -50,7 +55,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull FoodItem copy() { return new FoodItem(getName(), sprite, count, feed); diff --git a/src/client/java/minicraft/item/FurnitureItem.java b/src/client/java/minicraft/item/FurnitureItem.java index b65ad2920..278c99cd3 100644 --- a/src/client/java/minicraft/item/FurnitureItem.java +++ b/src/client/java/minicraft/item/FurnitureItem.java @@ -48,12 +48,12 @@ protected static ArrayList getAllInstances() { items.add(new FurnitureItem(new DungeonChest(false, true))); // Add the various types of crafting furniture - for (Crafter.Type type: Crafter.Type.values()) { + for (Crafter.Type type : Crafter.Type.values()) { items.add(new FurnitureItem(new Crafter(type))); } // Add the various lanterns - for (Lantern.Type type: Lantern.Type.values()) { - items.add(new FurnitureItem(new Lantern(type))); + for (Lantern.Type type : Lantern.Type.values()) { + items.add(new FurnitureItem(new Lantern(type))); } items.add(new FurnitureItem(new Tnt())); @@ -72,12 +72,16 @@ public FurnitureItem(Furniture furniture) { placed = false; } - /** Determines if you can attack enemies with furniture (you can't) */ + /** + * Determines if you can attack enemies with furniture (you can't) + */ public boolean canAttack() { return false; } - /** What happens when you press the "Attack" key with the furniture in your hands */ + /** + * What happens when you press the "Attack" key with the furniture in your hands + */ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { if (tile.mayPass(level, xt, yt, furniture)) { // If the furniture can go on the tile Sound.play("craft"); diff --git a/src/client/java/minicraft/item/HeartItem.java b/src/client/java/minicraft/item/HeartItem.java index 320fec1ed..a8297c178 100644 --- a/src/client/java/minicraft/item/HeartItem.java +++ b/src/client/java/minicraft/item/HeartItem.java @@ -22,14 +22,19 @@ protected static ArrayList getAllInstances() { private int health; // The amount of health to increase by. private int staminaCost; // The amount of stamina it costs to consume. - private HeartItem(String name, SpriteLinker.LinkedSprite sprite, int health) { this(name, sprite, 1, health); } + private HeartItem(String name, SpriteLinker.LinkedSprite sprite, int health) { + this(name, sprite, 1, health); + } + private HeartItem(String name, SpriteLinker.LinkedSprite sprite, int count, int health) { super(name, sprite, count); this.health = health; staminaCost = 7; } - /** What happens when the player uses the item on a tile */ + /** + * What happens when the player uses the item on a tile + */ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { boolean success = false; @@ -37,8 +42,7 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Player.extraHealth += health; // Permanent increase of health by health variable (Basically 5) player.health += health; // Adds health to the player when used. (Almost like absorbing the item's power first time) success = true; - } - else { + } else { Updater.notifyAll("Health increase is at max!"); // When at max, health cannot be increased more and doesn't consume item return false; } @@ -47,7 +51,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public HeartItem clone() { return new HeartItem(getName(), sprite, count, health); diff --git a/src/client/java/minicraft/item/Inventory.java b/src/client/java/minicraft/item/Inventory.java index 106d6b26c..c0ca6b756 100644 --- a/src/client/java/minicraft/item/Inventory.java +++ b/src/client/java/minicraft/item/Inventory.java @@ -21,27 +21,44 @@ public int getMaxSlots() { /** * Returns all the items which are in this inventory. + * * @return ArrayList containing all the items in the inventory. */ - public List getItems() { return new ArrayList<>(items); } - public void clearInv() { items.clear(); } - public int invSize() { return items.size(); } + public List getItems() { + return new ArrayList<>(items); + } + + public void clearInv() { + items.clear(); + } + + public int invSize() { + return items.size(); + } /** * Get one item in this inventory. + * * @param idx The index of the item in the inventory's item array. * @return The specified item. */ - public Item get(int idx) { return items.get(idx); } + public Item get(int idx) { + return items.get(idx); + } /** * Remove an item in this inventory. + * * @param idx The index of the item in the inventory's item array. * @return The removed item. */ - public Item remove(int idx) { return items.remove(idx); } + public Item remove(int idx) { + return items.remove(idx); + } - /** Adds an item to the inventory */ + /** + * Adds an item to the inventory + */ public int add(@Nullable Item item) { if (item != null) return add(items.size(), item); // Adds the item to the end of the inventory list @@ -50,8 +67,9 @@ public int add(@Nullable Item item) { /** * Adds several copies of the same item to the end of the inventory. + * * @param item Item to be added. - * @param num Amount of items to add. + * @param num Amount of items to add. */ public int add(Item item, int num) { int total = 0; @@ -62,6 +80,7 @@ public int add(Item item, int num) { /** * Adds an item to a specific spot in the inventory. + * * @param slot Index to place item at. * @param item Item to be added. * @return The number of items added. @@ -103,7 +122,7 @@ public int add(int slot, Item item) { if (!unlimited) { if (items.size() < maxItem) { - int c = (int) Math.ceil(toTake.count/100.0); + int c = (int) Math.ceil(toTake.count / 100.0); for (int i = 0; i < c; i++) { StackableItem adding = toTake.copy(); adding.count = i + 1 == c && toTake.count % 100 > 0 ? toTake.count % 100 : 100; @@ -135,7 +154,9 @@ public int add(int slot, Item item) { } } - /** Removes items from your inventory; looks for stacks, and removes from each until reached count. returns amount removed. */ + /** + * Removes items from your inventory; looks for stacks, and removes from each until reached count. returns amount removed. + */ private int removeFromStack(StackableItem given, int count) { int removed = 0; // To keep track of amount removed. for (int i = 0; i < items.size(); i++) { @@ -143,7 +164,7 @@ private int removeFromStack(StackableItem given, int count) { StackableItem curItem = (StackableItem) items.get(i); if (!curItem.stacksWith(given)) continue; // Can't do equals, becuase that includes the stack size. // equals; and current item is stackable. - int amountRemoving = Math.min(count-removed, curItem.count); // This is the number of items that are being removed from the stack this run-through. + int amountRemoving = Math.min(count - removed, curItem.count); // This is the number of items that are being removed from the stack this run-through. curItem.count -= amountRemoving; if (curItem.count == 0) { // Remove the item from the inventory if its stack is empty. remove(i); @@ -152,13 +173,14 @@ private int removeFromStack(StackableItem given, int count) { removed += amountRemoving; if (removed == count) break; if (removed > count) { // Just in case... - Logging.INVENTORY.info("SCREW UP while removing items from stack: " + (removed-count) + " too many."); + Logging.INVENTORY.info("SCREW UP while removing items from stack: " + (removed - count) + " too many."); break; } // If not all have been removed, look for another stack. } - if (removed < count) Logging.INVENTORY.info("Inventory: could not remove all items; " + (count-removed) + " left."); + if (removed < count) + Logging.INVENTORY.info("Inventory: could not remove all items; " + (count - removed) + " left."); return removed; } @@ -168,19 +190,20 @@ private int removeFromStack(StackableItem given, int count) { public void removeItem(Item i) { //if (Game.debug) System.out.println("original item: " + i); if (i instanceof StackableItem) - removeItems(i.copy(), ((StackableItem)i).count); + removeItems(i.copy(), ((StackableItem) i).count); else removeItems(i.copy(), 1); } /** * Removes items from this inventory. Note, if passed a stackable item, this will only remove a max of count from the stack. + * * @param given Item to remove. * @param count Max amount of the item to remove. */ public void removeItems(Item given, int count) { if (given instanceof StackableItem) - count -= removeFromStack((StackableItem)given, count); + count -= removeFromStack((StackableItem) given, count); else { for (int i = 0; i < items.size(); i++) { Item curItem = items.get(i); @@ -193,10 +216,12 @@ public void removeItems(Item given, int count) { } if (count > 0) - Logging.INVENTORY.warn("Could not remove " + count + " " + given + (count>1?"s":"") + " from inventory"); + Logging.INVENTORY.warn("Could not remove " + count + " " + given + (count > 1 ? "s" : "") + " from inventory"); } - /** Returns the how many of an item you have in the inventory. */ + /** + * Returns the how many of an item you have in the inventory. + */ public int count(Item given) { if (given == null) return 0; // null requests get no items. :) @@ -216,11 +241,12 @@ else if (curItem.equals(given)) /** * Generates a string representation of all the items in the inventory which can be sent * over the network. + * * @return String representation of all the items in the inventory. */ public String getItemData() { StringBuilder itemdata = new StringBuilder(); - for (Item i: items) + for (Item i : items) itemdata.append(i.getData()).append(":"); if (itemdata.length() > 0) @@ -231,6 +257,7 @@ public String getItemData() { /** * Replaces all the items in the inventory with the items in the string. + * * @param items String representation of an inventory. */ public void updateInv(String items) { @@ -238,17 +265,18 @@ public void updateInv(String items) { if (items.length() == 0) return; // There are no items to add. - for (String item: items.split(":")) // This still generates a 1-item array when "items" is blank... [""]. + for (String item : items.split(":")) // This still generates a 1-item array when "items" is blank... [""]. add(Items.get(item)); } /** * Tries to add an item to the inventory. - * @param chance Chance for the item to be added. - * @param item Item to be added. - * @param num How many of the item. + * + * @param chance Chance for the item to be added. + * @param item Item to be added. + * @param num How many of the item. * @param allOrNothing if true, either all items will be added or none, if false its possible to add - * between 0-num items. + * between 0-num items. */ public void tryAdd(int chance, Item item, int num, boolean allOrNothing) { if (!allOrNothing || random.nextInt(chance) == 0) @@ -256,23 +284,29 @@ public void tryAdd(int chance, Item item, int num, boolean allOrNothing) { if (allOrNothing || random.nextInt(chance) == 0) add(item.copy()); } + public void tryAdd(int chance, @Nullable Item item, int num) { if (item == null) return; if (item instanceof StackableItem) { - ((StackableItem)item).count *= num; + ((StackableItem) item).count *= num; tryAdd(chance, item, 1, true); } else tryAdd(chance, item, num, false); } - public void tryAdd(int chance, @Nullable Item item) { tryAdd(chance, item, 1); } + + public void tryAdd(int chance, @Nullable Item item) { + tryAdd(chance, item, 1); + } + public void tryAdd(int chance, ToolType type, int lvl) { tryAdd(chance, new ToolItem(type, lvl)); } /** * Tries to add an Furniture to the inventory. + * * @param chance Chance for the item to be added. - * @param type Type of furniture to add. + * @param type Type of furniture to add. */ public void tryAdd(int chance, Furniture type) { tryAdd(chance, new FurnitureItem(type)); diff --git a/src/client/java/minicraft/item/Item.java b/src/client/java/minicraft/item/Item.java index a7fed6f38..2761d3b2c 100644 --- a/src/client/java/minicraft/item/Item.java +++ b/src/client/java/minicraft/item/Item.java @@ -25,42 +25,57 @@ protected Item(String name) { sprite = SpriteLinker.missingTexture(SpriteType.Item); this.name = name; } + protected Item(String name, LinkedSprite sprite) { this.name = name; this.sprite = sprite; } - /** Renders an item on the HUD */ + /** + * Renders an item on the HUD + */ public void renderHUD(Screen screen, int x, int y, int fontColor) { String dispName = getDisplayName(); screen.render(x, y, sprite); Font.drawBackground(dispName, screen, x + 8, y, fontColor); } - /** Determines what happens when the player interacts with a tile */ + /** + * Determines what happens when the player interacts with a tile + */ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { return false; } - /** Returning true causes this item to be removed from the player's active item slot */ + /** + * Returning true causes this item to be removed from the player's active item slot + */ public boolean isDepleted() { return false; } - /** Returns if the item can attack mobs or not */ + /** + * Returns if the item can attack mobs or not + */ public boolean canAttack() { return false; } - /** Sees if an item equals another item */ + /** + * Sees if an item equals another item + */ public boolean equals(Item item) { return item != null && item.getClass().equals(getClass()) && item.name.equals(name); } @Override - public int hashCode() { return name.hashCode(); } + public int hashCode() { + return name.hashCode(); + } - /** This returns a copy of this item, in all necessary detail. */ + /** + * This returns a copy of this item, in all necessary detail. + */ @NotNull public abstract Item copy(); @@ -69,22 +84,30 @@ public String toString() { return name + "-Item"; } - /** Gets the necessary data to send over a connection. This data should always be directly input-able into Items.get() to create a valid item with the given properties. */ + /** + * Gets the necessary data to send over a connection. This data should always be directly input-able into Items.get() to create a valid item with the given properties. + */ public String getData() { return name; } - /** Gets the description used for display item information. */ + /** + * Gets the description used for display item information. + */ public String getDescription() { return getName(); } - public final String getName() { return name; } + public final String getName() { + return name; + } // Returns the String that should be used to display this item in a menu or list. public String getDisplayName() { return " " + Localization.getLocalized(getName()); } - public boolean interactsWithWorld() { return true; } + public boolean interactsWithWorld() { + return true; + } } diff --git a/src/client/java/minicraft/item/Items.java b/src/client/java/minicraft/item/Items.java index ce9bbee5b..9612527f4 100644 --- a/src/client/java/minicraft/item/Items.java +++ b/src/client/java/minicraft/item/Items.java @@ -12,19 +12,20 @@ public class Items { // ...well, that used to be true... /** - Ok, so here's the actual big idea: - - This class is meant to define all the different kinds of items in minicraft. Item(Type).java might be what maps the different item sprites in the spritesheet to a name, but it doesn't really define anything final. This class has all the items you could possibly have, and every form of them, more or less. - - If you want to access one of those items, you do it through this class, by calling get("item name"); casing does not matter. + * Ok, so here's the actual big idea: + *

+ * This class is meant to define all the different kinds of items in minicraft. Item(Type).java might be what maps the different item sprites in the spritesheet to a name, but it doesn't really define anything final. This class has all the items you could possibly have, and every form of them, more or less. + *

+ * If you want to access one of those items, you do it through this class, by calling get("item name"); casing does not matter. */ private static final ArrayList items = new ArrayList<>(); private static void add(Item i) { items.add(i); } + private static void addAll(ArrayList items) { - for (Item i: items) add(i); + for (Item i : items) add(i); } static { @@ -50,13 +51,16 @@ public static ArrayList getAll() { return new ArrayList<>(items); } - /** fetches an item from the list given its name. */ + /** + * fetches an item from the list given its name. + */ @NotNull public static Item get(String name) { Item i = get(name, false); if (i == null) return new UnknownItem("NULL"); // Technically shouldn't ever happen return i; } + @Nullable public static Item get(String name, boolean allowNull) { name = name.toUpperCase(); @@ -66,16 +70,15 @@ public static Item get(String name, boolean allowNull) { if (name.contains("_")) { hadUnderscore = true; try { - data = Integer.parseInt(name.substring(name.indexOf("_")+1)); + data = Integer.parseInt(name.substring(name.indexOf("_") + 1)); } catch (Exception ex) { ex.printStackTrace(); } name = name.substring(0, name.indexOf("_")); - } - else if (name.contains(";")) { + } else if (name.contains(";")) { hadUnderscore = true; try { - data = Integer.parseInt(name.substring(name.indexOf(";")+1)); + data = Integer.parseInt(name.substring(name.indexOf(";") + 1)); } catch (Exception ex) { ex.printStackTrace(); } @@ -94,7 +97,7 @@ public static Item get(String name, boolean allowNull) { return new UnknownItem("BLANK"); Item i = null; - for (Item cur: items) { + for (Item cur : items) { if (cur.getName().equalsIgnoreCase(name)) { i = cur; break; @@ -104,9 +107,9 @@ public static Item get(String name, boolean allowNull) { if (i != null) { i = i.copy(); if (i instanceof StackableItem) - ((StackableItem)i).count = data; + ((StackableItem) i).count = data; if (i instanceof ToolItem && hadUnderscore) - ((ToolItem)i).dur = data; + ((ToolItem) i).dur = data; if (i instanceof WateringCanItem) ((WateringCanItem) i).content = data; return i; diff --git a/src/client/java/minicraft/item/PotionItem.java b/src/client/java/minicraft/item/PotionItem.java index c0ef3396d..55ca3775e 100644 --- a/src/client/java/minicraft/item/PotionItem.java +++ b/src/client/java/minicraft/item/PotionItem.java @@ -17,7 +17,7 @@ public class PotionItem extends StackableItem { protected static ArrayList getAllInstances() { ArrayList items = new ArrayList<>(); - for(PotionType type: PotionType.values()) + for (PotionType type : PotionType.values()) items.add(new PotionItem(type)); return items; @@ -25,7 +25,10 @@ protected static ArrayList getAllInstances() { public PotionType type; - private PotionItem(PotionType type) { this(type, 1); } + private PotionItem(PotionType type) { + this(type, 1); + } + private PotionItem(PotionType type, int count) { super(type.name, new LinkedSprite(SpriteType.Item, "potion").setColor(type.dispColor), count); this.type = type; @@ -34,7 +37,7 @@ private PotionItem(PotionType type, int count) { // The return value is used to determine if the potion was used, which means being discarded. public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { if (type.equals(PotionType.Lava)) { - AchievementsDisplay.setAchievement("minicraft.achievement.lava",true); + AchievementsDisplay.setAchievement("minicraft.achievement.lava", true); } return interactOn(applyPotion(player, type, true), player); } @@ -51,6 +54,7 @@ public static boolean applyPotion(Player player, PotionType type, int time) { if (result && time > 0) player.addPotionEffect(type, time); // Overrides time return result; } + /// Main apply potion method public static boolean applyPotion(Player player, PotionType type, boolean addEffect) { if (player.getPotionEffects().containsKey(type) != addEffect) { // If hasEffect, and is disabling, or doesn't have effect, and is enabling... @@ -66,14 +70,18 @@ public static boolean applyPotion(Player player, PotionType type, boolean addEff @Override public boolean equals(Item other) { - return super.equals(other) && ((PotionItem)other).type == type; + return super.equals(other) && ((PotionItem) other).type == type; } @Override - public int hashCode() { return super.hashCode() + type.name.hashCode(); } + public int hashCode() { + return super.hashCode() + type.name.hashCode(); + } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull PotionItem copy() { return new PotionItem(type, count); diff --git a/src/client/java/minicraft/item/PotionType.java b/src/client/java/minicraft/item/PotionType.java index 51bad8ba3..67714a2be 100644 --- a/src/client/java/minicraft/item/PotionType.java +++ b/src/client/java/minicraft/item/PotionType.java @@ -7,33 +7,33 @@ import minicraft.level.Level; public enum PotionType { - Awkward (Color.get(1, 41, 51, 255), 0), + Awkward(Color.get(1, 41, 51, 255), 0), - Speed (Color.get(1, 105, 209, 105), 4200) { + Speed(Color.get(1, 105, 209, 105), 4200) { public boolean toggleEffect(Player player, boolean addEffect) { - player.moveSpeed += (double)( addEffect ? 1 : (player.moveSpeed > 1 ? -1 : 0) ); + player.moveSpeed += (double) (addEffect ? 1 : (player.moveSpeed > 1 ? -1 : 0)); return true; } }, - Light (Color.get(1, 183, 183, 91), 6000), - Swim (Color.get(1, 51, 51, 255), 4800), - Energy (Color.get(1, 237, 110, 78), 8400), - Regen (Color.get(1, 219, 70, 189), 1800), + Light(Color.get(1, 183, 183, 91), 6000), + Swim(Color.get(1, 51, 51, 255), 4800), + Energy(Color.get(1, 237, 110, 78), 8400), + Regen(Color.get(1, 219, 70, 189), 1800), - Health (Color.get(1, 194, 56, 84), 0) { + Health(Color.get(1, 194, 56, 84), 0) { public boolean toggleEffect(Player player, boolean addEffect) { if (addEffect) player.heal(5); return true; } }, - Time (Color.get(1, 163), 1800), - Lava (Color.get(1, 199, 58, 58), 7200), - Shield (Color.get(1, 84, 84, 204), 5400), - Haste (Color.get(1, 201, 71, 201), 4800), + Time(Color.get(1, 163), 1800), + Lava(Color.get(1, 199, 58, 58), 7200), + Shield(Color.get(1, 84, 84, 204), 5400), + Haste(Color.get(1, 201, 71, 201), 4800), - Escape (Color.get(1, 222, 162, 162), 0) { + Escape(Color.get(1, 222, 162, 162), 0) { public boolean toggleEffect(Player player, boolean addEffect) { if (addEffect) { int playerDepth = player.getLevel().depth; diff --git a/src/client/java/minicraft/item/Recipe.java b/src/client/java/minicraft/item/Recipe.java index 9ab4f1dd5..630191c51 100644 --- a/src/client/java/minicraft/item/Recipe.java +++ b/src/client/java/minicraft/item/Recipe.java @@ -41,19 +41,31 @@ public Recipe(String createdItem, String... reqItems) { public Item getProduct() { return Items.get(product); } - public Map getCosts() { return new HashMap<>(costs); } - public int getAmount() { return amount; } - public boolean getCanCraft() { return canCraft; } + public Map getCosts() { + return new HashMap<>(costs); + } + + public int getAmount() { + return amount; + } + + public boolean getCanCraft() { + return canCraft; + } + public boolean checkCanCraft(Player player) { canCraft = getCanCraft(player); return canCraft; } - /** Checks if the player can craft the recipe */ + + /** + * Checks if the player can craft the recipe + */ private boolean getCanCraft(Player player) { if (Game.isMode("minicraft.settings.mode.creative")) return true; - for (String cost: costs.keySet().toArray(new String[0])) { // Cycles through the costs list + for (String cost : costs.keySet().toArray(new String[0])) { // Cycles through the costs list /// This method ONLY WORKS if costs does not contain two elements such that inventory.count will count an item it contains as matching more than once. if (player.getInventory().count(Items.get(cost)) < costs.get(cost)) { return false; @@ -69,7 +81,7 @@ public boolean craft(Player player) { if (!Game.isMode("minicraft.settings.mode.creative")) { // Remove the cost items from the inventory. - for (String cost: costs.keySet().toArray(new String[0])) { + for (String cost : costs.keySet().toArray(new String[0])) { player.getInventory().removeItems(Items.get(cost), costs.get(cost)); } } diff --git a/src/client/java/minicraft/item/Recipes.java b/src/client/java/minicraft/item/Recipes.java index 534561380..1c28699d2 100644 --- a/src/client/java/minicraft/item/Recipes.java +++ b/src/client/java/minicraft/item/Recipes.java @@ -1,140 +1,140 @@ -package minicraft.item; - -import java.util.ArrayList; - -public class Recipes { - - public static final ArrayList anvilRecipes = new ArrayList<>(); - public static final ArrayList ovenRecipes = new ArrayList<>(); - public static final ArrayList furnaceRecipes = new ArrayList<>(); - public static final ArrayList workbenchRecipes = new ArrayList<>(); - public static final ArrayList enchantRecipes = new ArrayList<>(); - public static final ArrayList craftRecipes = new ArrayList<>(); - public static final ArrayList loomRecipes = new ArrayList<>(); - - static { - craftRecipes.add(new Recipe("Workbench_1", "Wood_10")); - craftRecipes.add(new Recipe("Torch_2", "Wood_1", "coal_1")); - craftRecipes.add(new Recipe("plank_2", "Wood_1")); - craftRecipes.add(new Recipe("Plank Wall_1", "plank_3")); - craftRecipes.add(new Recipe("Wood Door_1", "plank_5")); - - workbenchRecipes.add(new Recipe("Workbench_1", "Wood_10")); - workbenchRecipes.add(new Recipe("Torch_2", "Wood_1", "coal_1")); - workbenchRecipes.add(new Recipe("plank_2", "Wood_1")); - workbenchRecipes.add(new Recipe("Plank Wall_1", "plank_3")); - workbenchRecipes.add(new Recipe("Wood Door_1", "plank_5")); - workbenchRecipes.add(new Recipe("Lantern_1", "Wood_8", "slime_4", "glass_3")); - workbenchRecipes.add(new Recipe("Stone Brick_1", "Stone_2")); - workbenchRecipes.add(new Recipe("Ornate Stone_1", "Stone_2")); - workbenchRecipes.add(new Recipe("Stone Wall_1", "Stone Brick_3")); - workbenchRecipes.add(new Recipe("Stone Door_1", "Stone Brick_5")); - workbenchRecipes.add(new Recipe("Obsidian Brick_1", "Raw Obsidian_2")); - workbenchRecipes.add(new Recipe("Ornate Obsidian_1", "Raw Obsidian_2")); - workbenchRecipes.add(new Recipe("Obsidian Wall_1", "Obsidian Brick_3")); - workbenchRecipes.add(new Recipe("Obsidian Door_1", "Obsidian Brick_5")); - workbenchRecipes.add(new Recipe("Oven_1", "Stone_15")); - workbenchRecipes.add(new Recipe("Furnace_1", "Stone_20")); - workbenchRecipes.add(new Recipe("Enchanter_1", "Wood_5", "String_2", "Lapis_10")); - workbenchRecipes.add(new Recipe("Chest_1", "Wood_20")); - workbenchRecipes.add(new Recipe("Anvil_1", "iron_5")); - workbenchRecipes.add(new Recipe("Tnt_1", "Gunpowder_10", "Sand_8")); - workbenchRecipes.add(new Recipe("Loom_1", "Wood_10", "Wool_5")); - workbenchRecipes.add(new Recipe("Wood Fishing Rod_1", "Wood_10", "String_3")); - workbenchRecipes.add(new Recipe("Iron Fishing Rod_1", "Iron_10", "String_3")); - workbenchRecipes.add(new Recipe("Gold Fishing Rod_1", "Gold_10", "String_3")); - workbenchRecipes.add(new Recipe("Gem Fishing Rod_1", "Gem_10", "String_3")); - - workbenchRecipes.add(new Recipe("Wood Sword_1", "Wood_5")); - workbenchRecipes.add(new Recipe("Wood Axe_1", "Wood_5")); - workbenchRecipes.add(new Recipe("Wood Hoe_1", "Wood_5")); - workbenchRecipes.add(new Recipe("Wood Pickaxe_1", "Wood_5")); - workbenchRecipes.add(new Recipe("Wood Shovel_1", "Wood_5")); - workbenchRecipes.add(new Recipe("Wood Bow_1", "Wood_5", "string_2")); - workbenchRecipes.add(new Recipe("Rock Sword_1", "Wood_5", "Stone_5")); - workbenchRecipes.add(new Recipe("Rock Axe_1", "Wood_5", "Stone_5")); - workbenchRecipes.add(new Recipe("Rock Hoe_1", "Wood_5", "Stone_5")); - workbenchRecipes.add(new Recipe("Rock Pickaxe_1", "Wood_5", "Stone_5")); - workbenchRecipes.add(new Recipe("Rock Shovel_1", "Wood_5", "Stone_5")); - workbenchRecipes.add(new Recipe("Rock Bow_1", "Wood_5", "Stone_5", "string_2")); - - workbenchRecipes.add(new Recipe("arrow_3", "Wood_2", "Stone_2")); - workbenchRecipes.add(new Recipe("Leather Armor_1", "leather_10")); - workbenchRecipes.add(new Recipe("Snake Armor_1", "scale_15")); - - loomRecipes.add(new Recipe("String_2", "Wool_1")); - loomRecipes.add(new Recipe("red wool_1", "Wool_1", "rose_1")); - loomRecipes.add(new Recipe("blue wool_1", "Wool_1", "Lapis_1")); - loomRecipes.add(new Recipe("green wool_1", "Wool_1", "Cactus_1")); - loomRecipes.add(new Recipe("yellow wool_1", "Wool_1", "Flower_1")); - loomRecipes.add(new Recipe("black wool_1", "Wool_1", "coal_1")); - loomRecipes.add(new Recipe("Bed_1", "Wood_5", "Wool_3")); - - loomRecipes.add(new Recipe("blue clothes_1", "cloth_5", "Lapis_1")); - loomRecipes.add(new Recipe("green clothes_1", "cloth_5", "Cactus_1")); - loomRecipes.add(new Recipe("yellow clothes_1", "cloth_5", "Flower_1")); - loomRecipes.add(new Recipe("black clothes_1", "cloth_5", "coal_1")); - loomRecipes.add(new Recipe("orange clothes_1", "cloth_5", "rose_1", "Flower_1")); - loomRecipes.add(new Recipe("purple clothes_1", "cloth_5", "Lapis_1", "rose_1")); - loomRecipes.add(new Recipe("cyan clothes_1", "cloth_5", "Lapis_1", "Cactus_1")); - loomRecipes.add(new Recipe("reg clothes_1", "cloth_5")); - - loomRecipes.add(new Recipe("Leather Armor_1", "leather_10")); - - anvilRecipes.add(new Recipe("Iron Armor_1", "iron_10")); - anvilRecipes.add(new Recipe("Gold Armor_1", "gold_10")); - anvilRecipes.add(new Recipe("Gem Armor_1", "gem_65")); - anvilRecipes.add(new Recipe("Empty Bucket_1", "iron_5")); - anvilRecipes.add(new Recipe("Iron Lantern_1", "iron_8", "slime_5", "glass_4")); - anvilRecipes.add(new Recipe("Gold Lantern_1", "gold_10", "slime_5", "glass_4")); - anvilRecipes.add(new Recipe("Iron Sword_1", "Wood_5", "iron_5")); - anvilRecipes.add(new Recipe("Iron Claymore_1", "Iron Sword_1", "shard_15")); - anvilRecipes.add(new Recipe("Iron Axe_1", "Wood_5", "iron_5")); - anvilRecipes.add(new Recipe("Iron Hoe_1", "Wood_5", "iron_5")); - anvilRecipes.add(new Recipe("Iron Pickaxe_1", "Wood_5", "iron_5")); - anvilRecipes.add(new Recipe("Iron Shovel_1", "Wood_5", "iron_5")); - anvilRecipes.add(new Recipe("Iron Bow_1", "Wood_5", "iron_5", "string_2")); - anvilRecipes.add(new Recipe("Gold Sword_1", "Wood_5", "gold_5")); - anvilRecipes.add(new Recipe("Gold Claymore_1", "Gold Sword_1", "shard_15")); - anvilRecipes.add(new Recipe("Gold Axe_1", "Wood_5", "gold_5")); - anvilRecipes.add(new Recipe("Gold Hoe_1", "Wood_5", "gold_5")); - anvilRecipes.add(new Recipe("Gold Pickaxe_1", "Wood_5", "gold_5")); - anvilRecipes.add(new Recipe("Gold Shovel_1", "Wood_5", "gold_5")); - anvilRecipes.add(new Recipe("Gold Bow_1", "Wood_5", "gold_5", "string_2")); - anvilRecipes.add(new Recipe("Gem Sword_1", "Wood_5", "gem_50")); - anvilRecipes.add(new Recipe("Gem Claymore_1", "Gem Sword_1", "shard_15")); - anvilRecipes.add(new Recipe("Gem Axe_1", "Wood_5", "gem_50")); - anvilRecipes.add(new Recipe("Gem Hoe_1", "Wood_5", "gem_50")); - anvilRecipes.add(new Recipe("Gem Pickaxe_1", "Wood_5", "gem_50")); - anvilRecipes.add(new Recipe("Gem Shovel_1", "Wood_5", "gem_50")); - anvilRecipes.add(new Recipe("Gem Bow_1", "Wood_5", "gem_50", "string_2")); - anvilRecipes.add(new Recipe("Shears_1", "Iron_4")); - anvilRecipes.add(new Recipe("Watering Can_1", "Iron_3")); - - furnaceRecipes.add(new Recipe("iron_1", "iron Ore_4", "coal_1")); - furnaceRecipes.add(new Recipe("gold_1", "gold Ore_4", "coal_1")); - furnaceRecipes.add(new Recipe("glass_1", "sand_4", "coal_1")); - furnaceRecipes.add(new Recipe("glass bottle_1", "glass_3")); - - ovenRecipes.add(new Recipe("cooked pork_1", "raw pork_1", "coal_1")); - ovenRecipes.add(new Recipe("steak_1", "raw beef_1", "coal_1")); - ovenRecipes.add(new Recipe("cooked fish_1", "raw fish_1", "coal_1")); - ovenRecipes.add(new Recipe("bread_1", "wheat_4")); - ovenRecipes.add(new Recipe("Baked Potato_1", "Potato_1")); - - enchantRecipes.add(new Recipe("Gold Apple_1", "apple_1", "gold_8")); - enchantRecipes.add(new Recipe("awkward potion_1", "glass bottle_1", "Lapis_3")); - enchantRecipes.add(new Recipe("speed potion_1", "awkward potion_1", "Cactus_5")); - enchantRecipes.add(new Recipe("light potion_1", "awkward potion_1", "slime_5")); - enchantRecipes.add(new Recipe("swim potion_1", "awkward potion_1", "raw fish_5")); - enchantRecipes.add(new Recipe("haste potion_1", "awkward potion_1", "Wood_5", "Stone_5")); - enchantRecipes.add(new Recipe("lava potion_1", "awkward potion_1", "Lava Bucket_1")); - enchantRecipes.add(new Recipe("energy potion_1", "awkward potion_1", "gem_25")); - enchantRecipes.add(new Recipe("regen potion_1", "awkward potion_1", "Gold Apple_1")); - enchantRecipes.add(new Recipe("Health Potion_1", "awkward potion_1", "GunPowder_2", "Leather Armor_1")); - enchantRecipes.add(new Recipe("Escape Potion_1", "awkward potion_1", "GunPowder_3", "Lapis_7")); - enchantRecipes.add(new Recipe("Totem of Air_1", "gold_10", "gem_10", "Lapis_5", "Cloud Ore_5")); - enchantRecipes.add(new Recipe("Obsidian Poppet_1", "gold_10", "gem_10", "Lapis_5", "Shard_15")); - enchantRecipes.add(new Recipe("Arcane Fertilizer_3", "Lapis_6", "Bone_2")); - } -} +package minicraft.item; + +import java.util.ArrayList; + +public class Recipes { + + public static final ArrayList anvilRecipes = new ArrayList<>(); + public static final ArrayList ovenRecipes = new ArrayList<>(); + public static final ArrayList furnaceRecipes = new ArrayList<>(); + public static final ArrayList workbenchRecipes = new ArrayList<>(); + public static final ArrayList enchantRecipes = new ArrayList<>(); + public static final ArrayList craftRecipes = new ArrayList<>(); + public static final ArrayList loomRecipes = new ArrayList<>(); + + static { + craftRecipes.add(new Recipe("Workbench_1", "Wood_10")); + craftRecipes.add(new Recipe("Torch_2", "Wood_1", "coal_1")); + craftRecipes.add(new Recipe("plank_2", "Wood_1")); + craftRecipes.add(new Recipe("Plank Wall_1", "plank_3")); + craftRecipes.add(new Recipe("Wood Door_1", "plank_5")); + + workbenchRecipes.add(new Recipe("Workbench_1", "Wood_10")); + workbenchRecipes.add(new Recipe("Torch_2", "Wood_1", "coal_1")); + workbenchRecipes.add(new Recipe("plank_2", "Wood_1")); + workbenchRecipes.add(new Recipe("Plank Wall_1", "plank_3")); + workbenchRecipes.add(new Recipe("Wood Door_1", "plank_5")); + workbenchRecipes.add(new Recipe("Lantern_1", "Wood_8", "slime_4", "glass_3")); + workbenchRecipes.add(new Recipe("Stone Brick_1", "Stone_2")); + workbenchRecipes.add(new Recipe("Ornate Stone_1", "Stone_2")); + workbenchRecipes.add(new Recipe("Stone Wall_1", "Stone Brick_3")); + workbenchRecipes.add(new Recipe("Stone Door_1", "Stone Brick_5")); + workbenchRecipes.add(new Recipe("Obsidian Brick_1", "Raw Obsidian_2")); + workbenchRecipes.add(new Recipe("Ornate Obsidian_1", "Raw Obsidian_2")); + workbenchRecipes.add(new Recipe("Obsidian Wall_1", "Obsidian Brick_3")); + workbenchRecipes.add(new Recipe("Obsidian Door_1", "Obsidian Brick_5")); + workbenchRecipes.add(new Recipe("Oven_1", "Stone_15")); + workbenchRecipes.add(new Recipe("Furnace_1", "Stone_20")); + workbenchRecipes.add(new Recipe("Enchanter_1", "Wood_5", "String_2", "Lapis_10")); + workbenchRecipes.add(new Recipe("Chest_1", "Wood_20")); + workbenchRecipes.add(new Recipe("Anvil_1", "iron_5")); + workbenchRecipes.add(new Recipe("Tnt_1", "Gunpowder_10", "Sand_8")); + workbenchRecipes.add(new Recipe("Loom_1", "Wood_10", "Wool_5")); + workbenchRecipes.add(new Recipe("Wood Fishing Rod_1", "Wood_10", "String_3")); + workbenchRecipes.add(new Recipe("Iron Fishing Rod_1", "Iron_10", "String_3")); + workbenchRecipes.add(new Recipe("Gold Fishing Rod_1", "Gold_10", "String_3")); + workbenchRecipes.add(new Recipe("Gem Fishing Rod_1", "Gem_10", "String_3")); + + workbenchRecipes.add(new Recipe("Wood Sword_1", "Wood_5")); + workbenchRecipes.add(new Recipe("Wood Axe_1", "Wood_5")); + workbenchRecipes.add(new Recipe("Wood Hoe_1", "Wood_5")); + workbenchRecipes.add(new Recipe("Wood Pickaxe_1", "Wood_5")); + workbenchRecipes.add(new Recipe("Wood Shovel_1", "Wood_5")); + workbenchRecipes.add(new Recipe("Wood Bow_1", "Wood_5", "string_2")); + workbenchRecipes.add(new Recipe("Rock Sword_1", "Wood_5", "Stone_5")); + workbenchRecipes.add(new Recipe("Rock Axe_1", "Wood_5", "Stone_5")); + workbenchRecipes.add(new Recipe("Rock Hoe_1", "Wood_5", "Stone_5")); + workbenchRecipes.add(new Recipe("Rock Pickaxe_1", "Wood_5", "Stone_5")); + workbenchRecipes.add(new Recipe("Rock Shovel_1", "Wood_5", "Stone_5")); + workbenchRecipes.add(new Recipe("Rock Bow_1", "Wood_5", "Stone_5", "string_2")); + + workbenchRecipes.add(new Recipe("arrow_3", "Wood_2", "Stone_2")); + workbenchRecipes.add(new Recipe("Leather Armor_1", "leather_10")); + workbenchRecipes.add(new Recipe("Snake Armor_1", "scale_15")); + + loomRecipes.add(new Recipe("String_2", "Wool_1")); + loomRecipes.add(new Recipe("red wool_1", "Wool_1", "rose_1")); + loomRecipes.add(new Recipe("blue wool_1", "Wool_1", "Lapis_1")); + loomRecipes.add(new Recipe("green wool_1", "Wool_1", "Cactus_1")); + loomRecipes.add(new Recipe("yellow wool_1", "Wool_1", "Flower_1")); + loomRecipes.add(new Recipe("black wool_1", "Wool_1", "coal_1")); + loomRecipes.add(new Recipe("Bed_1", "Wood_5", "Wool_3")); + + loomRecipes.add(new Recipe("blue clothes_1", "cloth_5", "Lapis_1")); + loomRecipes.add(new Recipe("green clothes_1", "cloth_5", "Cactus_1")); + loomRecipes.add(new Recipe("yellow clothes_1", "cloth_5", "Flower_1")); + loomRecipes.add(new Recipe("black clothes_1", "cloth_5", "coal_1")); + loomRecipes.add(new Recipe("orange clothes_1", "cloth_5", "rose_1", "Flower_1")); + loomRecipes.add(new Recipe("purple clothes_1", "cloth_5", "Lapis_1", "rose_1")); + loomRecipes.add(new Recipe("cyan clothes_1", "cloth_5", "Lapis_1", "Cactus_1")); + loomRecipes.add(new Recipe("reg clothes_1", "cloth_5")); + + loomRecipes.add(new Recipe("Leather Armor_1", "leather_10")); + + anvilRecipes.add(new Recipe("Iron Armor_1", "iron_10")); + anvilRecipes.add(new Recipe("Gold Armor_1", "gold_10")); + anvilRecipes.add(new Recipe("Gem Armor_1", "gem_65")); + anvilRecipes.add(new Recipe("Empty Bucket_1", "iron_5")); + anvilRecipes.add(new Recipe("Iron Lantern_1", "iron_8", "slime_5", "glass_4")); + anvilRecipes.add(new Recipe("Gold Lantern_1", "gold_10", "slime_5", "glass_4")); + anvilRecipes.add(new Recipe("Iron Sword_1", "Wood_5", "iron_5")); + anvilRecipes.add(new Recipe("Iron Claymore_1", "Iron Sword_1", "shard_15")); + anvilRecipes.add(new Recipe("Iron Axe_1", "Wood_5", "iron_5")); + anvilRecipes.add(new Recipe("Iron Hoe_1", "Wood_5", "iron_5")); + anvilRecipes.add(new Recipe("Iron Pickaxe_1", "Wood_5", "iron_5")); + anvilRecipes.add(new Recipe("Iron Shovel_1", "Wood_5", "iron_5")); + anvilRecipes.add(new Recipe("Iron Bow_1", "Wood_5", "iron_5", "string_2")); + anvilRecipes.add(new Recipe("Gold Sword_1", "Wood_5", "gold_5")); + anvilRecipes.add(new Recipe("Gold Claymore_1", "Gold Sword_1", "shard_15")); + anvilRecipes.add(new Recipe("Gold Axe_1", "Wood_5", "gold_5")); + anvilRecipes.add(new Recipe("Gold Hoe_1", "Wood_5", "gold_5")); + anvilRecipes.add(new Recipe("Gold Pickaxe_1", "Wood_5", "gold_5")); + anvilRecipes.add(new Recipe("Gold Shovel_1", "Wood_5", "gold_5")); + anvilRecipes.add(new Recipe("Gold Bow_1", "Wood_5", "gold_5", "string_2")); + anvilRecipes.add(new Recipe("Gem Sword_1", "Wood_5", "gem_50")); + anvilRecipes.add(new Recipe("Gem Claymore_1", "Gem Sword_1", "shard_15")); + anvilRecipes.add(new Recipe("Gem Axe_1", "Wood_5", "gem_50")); + anvilRecipes.add(new Recipe("Gem Hoe_1", "Wood_5", "gem_50")); + anvilRecipes.add(new Recipe("Gem Pickaxe_1", "Wood_5", "gem_50")); + anvilRecipes.add(new Recipe("Gem Shovel_1", "Wood_5", "gem_50")); + anvilRecipes.add(new Recipe("Gem Bow_1", "Wood_5", "gem_50", "string_2")); + anvilRecipes.add(new Recipe("Shears_1", "Iron_4")); + anvilRecipes.add(new Recipe("Watering Can_1", "Iron_3")); + + furnaceRecipes.add(new Recipe("iron_1", "iron Ore_4", "coal_1")); + furnaceRecipes.add(new Recipe("gold_1", "gold Ore_4", "coal_1")); + furnaceRecipes.add(new Recipe("glass_1", "sand_4", "coal_1")); + furnaceRecipes.add(new Recipe("glass bottle_1", "glass_3")); + + ovenRecipes.add(new Recipe("cooked pork_1", "raw pork_1", "coal_1")); + ovenRecipes.add(new Recipe("steak_1", "raw beef_1", "coal_1")); + ovenRecipes.add(new Recipe("cooked fish_1", "raw fish_1", "coal_1")); + ovenRecipes.add(new Recipe("bread_1", "wheat_4")); + ovenRecipes.add(new Recipe("Baked Potato_1", "Potato_1")); + + enchantRecipes.add(new Recipe("Gold Apple_1", "apple_1", "gold_8")); + enchantRecipes.add(new Recipe("awkward potion_1", "glass bottle_1", "Lapis_3")); + enchantRecipes.add(new Recipe("speed potion_1", "awkward potion_1", "Cactus_5")); + enchantRecipes.add(new Recipe("light potion_1", "awkward potion_1", "slime_5")); + enchantRecipes.add(new Recipe("swim potion_1", "awkward potion_1", "raw fish_5")); + enchantRecipes.add(new Recipe("haste potion_1", "awkward potion_1", "Wood_5", "Stone_5")); + enchantRecipes.add(new Recipe("lava potion_1", "awkward potion_1", "Lava Bucket_1")); + enchantRecipes.add(new Recipe("energy potion_1", "awkward potion_1", "gem_25")); + enchantRecipes.add(new Recipe("regen potion_1", "awkward potion_1", "Gold Apple_1")); + enchantRecipes.add(new Recipe("Health Potion_1", "awkward potion_1", "GunPowder_2", "Leather Armor_1")); + enchantRecipes.add(new Recipe("Escape Potion_1", "awkward potion_1", "GunPowder_3", "Lapis_7")); + enchantRecipes.add(new Recipe("Totem of Air_1", "gold_10", "gem_10", "Lapis_5", "Cloud Ore_5")); + enchantRecipes.add(new Recipe("Obsidian Poppet_1", "gold_10", "gem_10", "Lapis_5", "Shard_15")); + enchantRecipes.add(new Recipe("Arcane Fertilizer_3", "Lapis_6", "Bone_2")); + } +} diff --git a/src/client/java/minicraft/item/StackableItem.java b/src/client/java/minicraft/item/StackableItem.java index 73b0634e5..b66dfac8b 100644 --- a/src/client/java/minicraft/item/StackableItem.java +++ b/src/client/java/minicraft/item/StackableItem.java @@ -52,12 +52,15 @@ protected StackableItem(String name, LinkedSprite sprite) { super(name, sprite); count = 1; } + protected StackableItem(String name, LinkedSprite sprite, int count) { this(name, sprite); this.count = count; } - public boolean stacksWith(Item other) { return other instanceof StackableItem && other.getName().equals(getName()); } + public boolean stacksWith(Item other) { + return other instanceof StackableItem && other.getName().equals(getName()); + } // This is used by (most) subclasses, to standardize the count decrement behavior. This is not the normal interactOn method. protected boolean interactOn(boolean subClassSuccess) { @@ -66,7 +69,9 @@ protected boolean interactOn(boolean subClassSuccess) { return subClassSuccess; } - /** Called to determine if this item should be removed from an inventory. */ + /** + * Called to determine if this item should be removed from an inventory. + */ @Override public boolean isDepleted() { return count <= 0; @@ -79,7 +84,7 @@ public boolean isDepleted() { @Override public String toString() { - return super.toString() + "-Stack_Size:"+count; + return super.toString() + "-Stack_Size:" + count; } public String getData() { diff --git a/src/client/java/minicraft/item/SummonItem.java b/src/client/java/minicraft/item/SummonItem.java index 15c0d286e..bf0d73df0 100644 --- a/src/client/java/minicraft/item/SummonItem.java +++ b/src/client/java/minicraft/item/SummonItem.java @@ -31,13 +31,18 @@ protected static ArrayList getAllInstances() { private final String mob; - private SummonItem(String name, LinkedSprite sprite, String mob) { this(name, sprite, 1, mob); } + private SummonItem(String name, LinkedSprite sprite, String mob) { + this(name, sprite, 1, mob); + } + private SummonItem(String name, LinkedSprite sprite, int count, String mob) { super(name, sprite, count); this.mob = mob; } - /** What happens when the player uses the item on a tile */ + /** + * What happens when the player uses the item on a tile + */ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { boolean success = false; @@ -54,8 +59,7 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Logger.tag("SummonItem").debug("Summoned new Air Wizard"); success = true; } - } - else { + } else { Game.notifications.add(Localization.getLocalized("minicraft.notification.boss_limit")); } } else { @@ -67,7 +71,7 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, // Check if we are on the right level and tile if (level.depth == -4) { // If the player nears the center. - if (new Rectangle(level.w/2-3, level.h/2-3, 7, 7).contains(player.x >> 4, player.y >> 4)) { + if (new Rectangle(level.w / 2 - 3, level.h / 2 - 3, 7, 7).contains(player.x >> 4, player.y >> 4)) { if (!ObsidianKnight.active) { boolean exists = false; for (Entity e : level.getEntityArray()) { @@ -80,7 +84,7 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, if (!exists) { // Prevent unintended behaviors // Pay stamina if (player.payStamina(2)) { - level.add(new KnightStatue(5000), level.w/2, level.h/2, true); + level.add(new KnightStatue(5000), level.w / 2, level.h / 2, true); Logger.tag("SummonItem").debug("Summoned new Knight Statue"); success = true; } @@ -106,7 +110,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } @Override - public boolean interactsWithWorld() { return false; } + public boolean interactsWithWorld() { + return false; + } public @NotNull SummonItem copy() { return new SummonItem(getName(), sprite, count, mob); diff --git a/src/client/java/minicraft/item/TileItem.java b/src/client/java/minicraft/item/TileItem.java index dad79ffee..2c6a39862 100644 --- a/src/client/java/minicraft/item/TileItem.java +++ b/src/client/java/minicraft/item/TileItem.java @@ -42,7 +42,7 @@ protected static ArrayList getAllInstances() { items.add(new TileItem("Stone Door", new LinkedSprite(SpriteType.Item, "stone_wall"), new TileModel("Stone Door"), "Stone Bricks")); items.add(new TileItem("Raw Obsidian", new LinkedSprite(SpriteType.Item, "obsidian"), new TileModel("Raw Obsidian"), "hole", "water", "cloud", "lava")); items.add(new TileItem("Obsidian Brick", new LinkedSprite(SpriteType.Item, "obsidian_brick"), new TileModel("Obsidian"), "hole", "water", "cloud", "lava")); - items.add(new TileItem("Ornate Obsidian", new LinkedSprite(SpriteType.Item, "obsidian_brick"), new TileModel("Ornate Obsidian"),"hole", "water", "cloud", "lava")); + items.add(new TileItem("Ornate Obsidian", new LinkedSprite(SpriteType.Item, "obsidian_brick"), new TileModel("Ornate Obsidian"), "hole", "water", "cloud", "lava")); items.add(new TileItem("Obsidian Wall", new LinkedSprite(SpriteType.Item, "obsidian_wall"), new TileModel("Obsidian Wall"), "Obsidian")); items.add(new TileItem("Obsidian Door", new LinkedSprite(SpriteType.Item, "obsidian_door"), new TileModel("Obsidian Door"), "Obsidian")); @@ -85,15 +85,17 @@ protected static ArrayList getAllInstances() { protected TileItem(String name, LinkedSprite sprite, TileModel model, String... validTiles) { this(name, sprite, 1, model, Arrays.asList(validTiles)); } + protected TileItem(String name, LinkedSprite sprite, int count, TileModel model, String... validTiles) { this(name, sprite, count, model, Arrays.asList(validTiles)); } + protected TileItem(String name, LinkedSprite sprite, int count, @Nullable TileModel model, List validTiles) { super(name, sprite, count); this.model = model; this.validTiles = new ArrayList<>(); - for (String tile: validTiles) - this.validTiles.add(tile.toUpperCase()); + for (String tile : validTiles) + this.validTiles.add(tile.toUpperCase()); } public static class TileModel { @@ -108,7 +110,10 @@ interface TileDataGetter { int getTileData(Tile model, Tile target, Level level, int xt, int yt, Player player, Direction attackDir); } - public TileModel(String tile) { this(tile, DEFAULT_DATA); } + public TileModel(String tile) { + this(tile, DEFAULT_DATA); + } + public TileModel(String tile, TileDataGetter data) { this.tile = tile.toUpperCase(); this.data = data; @@ -145,11 +150,9 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, String note = ""; if (model.tile.contains("WALL")) { note = Localization.getLocalized("minicraft.notification.invalid_placement", Tiles.getName(validTiles.get(0))); - } - else if (model.tile.contains("DOOR")) { + } else if (model.tile.contains("DOOR")) { note = Localization.getLocalized("minicraft.notification.invalid_placement", Tiles.getName(validTiles.get(0))); - } - else if ((model.tile.contains("BRICK") || model.tile.contains("PLANK") || model.tile.equals("STONE") || model.tile.contains("ORNATE"))) { + } else if ((model.tile.contains("BRICK") || model.tile.contains("PLANK") || model.tile.equals("STONE") || model.tile.contains("ORNATE"))) { note = Localization.getLocalized("minicraft.notification.dig_hole"); } @@ -163,11 +166,13 @@ else if ((model.tile.contains("BRICK") || model.tile.contains("PLANK") || model. @Override public boolean equals(Item other) { - return super.equals(other) && (model == null || model.equals(((TileItem)other).model)); + return super.equals(other) && (model == null || model.equals(((TileItem) other).model)); } @Override - public int hashCode() { return super.hashCode() + (model == null ? 0xFF123 : model.hashCode()); } + public int hashCode() { + return super.hashCode() + (model == null ? 0xFF123 : model.hashCode()); + } public @NotNull TileItem copy() { return new TileItem(getName(), sprite, count, model, validTiles); diff --git a/src/client/java/minicraft/item/ToolItem.java b/src/client/java/minicraft/item/ToolItem.java index 297760fd1..9a105c3b2 100644 --- a/src/client/java/minicraft/item/ToolItem.java +++ b/src/client/java/minicraft/item/ToolItem.java @@ -42,7 +42,9 @@ private static String getSpriteName(String typeName, String level) { return level + typeName.toLowerCase(); } - /** Tool Item, requires a tool type (ToolType.Sword, ToolType.Axe, ToolType.Hoe, etc) and a level (0 = wood, 2 = iron, 4 = gem, etc) */ + /** + * Tool Item, requires a tool type (ToolType.Sword, ToolType.Axe, ToolType.Hoe, etc) and a level (0 = wood, 2 = iron, 4 = gem, etc) + */ public ToolItem(ToolType type, int level) { super(LEVEL_NAMES[level] + " " + type.name(), new LinkedSprite(SpriteType.Item, getSpriteName(type.toString(), LEVEL_NAMES[level] + "_"))); @@ -60,10 +62,13 @@ public ToolItem(ToolType type) { dur = type.durability; } - /** Gets the name of this tool (and it's type) as a display string. */ + /** + * Gets the name of this tool (and it's type) as a display string. + */ @Override public String getDisplayName() { - if (!type.noLevel) return " " + Localization.getLocalized(LEVEL_NAMES[level]) + " " + Localization.getLocalized(type.toString()); + if (!type.noLevel) + return " " + Localization.getLocalized(LEVEL_NAMES[level]) + " " + Localization.getLocalized(type.toString()); else return " " + Localization.getLocalized(type.toString()); } @@ -71,7 +76,9 @@ public boolean isDepleted() { return dur <= 0 && type.durability > 0; } - /** You can attack mobs with tools. */ + /** + * You can attack mobs with tools. + */ public boolean canAttack() { return type != ToolType.Shears; } @@ -86,7 +93,9 @@ public int getDamage() { return random.nextInt(5) + damage; } - /** Gets the attack damage bonus from an item/tool (sword/axe) */ + /** + * Gets the attack damage bonus from an item/tool (sword/axe) + */ public int getAttackDamageBonus(Entity e) { if (!payDurability()) return 0; @@ -111,7 +120,9 @@ public String getData() { return super.getData() + "_" + dur; } - /** Sees if this item equals another. */ + /** + * Sees if this item equals another. + */ @Override public boolean equals(Item item) { if (item instanceof ToolItem) { @@ -122,7 +133,9 @@ public boolean equals(Item item) { } @Override - public int hashCode() { return type.name().hashCode() + level; } + public int hashCode() { + return type.name().hashCode() + level; + } public @NotNull ToolItem copy() { ToolItem ti; diff --git a/src/client/java/minicraft/item/ToolType.java b/src/client/java/minicraft/item/ToolType.java index 242a82e31..932ec62d7 100644 --- a/src/client/java/minicraft/item/ToolType.java +++ b/src/client/java/minicraft/item/ToolType.java @@ -1,14 +1,14 @@ package minicraft.item; public enum ToolType { - Shovel (0, 34), // If there's a second number, it specifies durability. - Hoe (1, 30), - Sword (2, 52), - Pickaxe (3, 38), - Axe (4, 34), - Bow (5, 30), - Claymore (6, 44), - Shears (0, 42, true); + Shovel(0, 34), // If there's a second number, it specifies durability. + Hoe(1, 30), + Sword(2, 52), + Pickaxe(3, 38), + Axe(4, 34), + Bow(5, 30), + Claymore(6, 44), + Shears(0, 42, true); public final int xPos; // X Position of origin public final int yPos; // Y position of origin @@ -19,8 +19,9 @@ public enum ToolType { * Create a tool with four levels: wood, stone, iron, gold, and gem. * All these levels are added automatically but sprites have to be added manually. * Uses line 14 in the item spritesheet. + * * @param xPos X position of the starting sprite in the spritesheet. - * @param dur Durabiltity of the tool. + * @param dur Durabiltity of the tool. */ ToolType(int xPos, int dur) { this.xPos = xPos; @@ -32,8 +33,9 @@ public enum ToolType { /** * Create a tool without a specified level. * Uses line 13 in the items spritesheet. - * @param xPos X position of the sprite in the spritesheet. - * @param dur Durabiltity of the tool. + * + * @param xPos X position of the sprite in the spritesheet. + * @param dur Durabiltity of the tool. * @param noLevel If the tool has only one level. */ ToolType(int xPos, int dur, boolean noLevel) { diff --git a/src/client/java/minicraft/item/TorchItem.java b/src/client/java/minicraft/item/TorchItem.java index 2eee762eb..ff13c7c63 100644 --- a/src/client/java/minicraft/item/TorchItem.java +++ b/src/client/java/minicraft/item/TorchItem.java @@ -19,9 +19,12 @@ public static ArrayList getAllInstances() { return items; } - private TorchItem() { this(1); } + private TorchItem() { + this(1); + } + private TorchItem(int count) { - super("Torch", new LinkedSprite(SpriteType.Item, "torch"), count, null, "dirt", "Wood Planks", "Stone Bricks", "Obsidian", "Wool", "Red Wool", "Blue Wool", "Green Wool", "Yellow Wool", "Black Wool", "grass", "sand","path","ornate stone","ornate obsidian"); + super("Torch", new LinkedSprite(SpriteType.Item, "torch"), count, null, "dirt", "Wood Planks", "Stone Bricks", "Obsidian", "Wool", "Red Wool", "Blue Wool", "Green Wool", "Yellow Wool", "Black Wool", "grass", "sand", "path", "ornate stone", "ornate obsidian"); } public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, Direction attackDir) { @@ -38,7 +41,9 @@ public boolean equals(Item other) { } @Override - public int hashCode() { return 8931; } + public int hashCode() { + return 8931; + } public @NotNull TorchItem copy() { return new TorchItem(count); diff --git a/src/client/java/minicraft/item/WateringCanItem.java b/src/client/java/minicraft/item/WateringCanItem.java index 7ef7d1dd0..181b34745 100644 --- a/src/client/java/minicraft/item/WateringCanItem.java +++ b/src/client/java/minicraft/item/WateringCanItem.java @@ -15,9 +15,7 @@ import minicraft.level.tile.farming.CropTile; import org.jetbrains.annotations.NotNull; -import java.util.AbstractMap; import java.util.ArrayList; -import java.util.Map; import java.util.Random; public class WateringCanItem extends Item { @@ -31,7 +29,7 @@ protected static ArrayList getAllInstances() { private static final SpriteLinker.LinkedSprite spriteFilled = new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Item, "watering_can_filled"); private static final SpriteLinker.LinkedSprite particleSprite = new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Entity, "glint"); - private static final SpriteLinker.LinkedSprite[] spriteSplash = new SpriteLinker.LinkedSprite[] { + private static final SpriteLinker.LinkedSprite[] spriteSplash = new SpriteLinker.LinkedSprite[]{ new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Entity, "splash_0"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Entity, "splash_1"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Entity, "splash_2"), @@ -75,15 +73,15 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, ((CropTile) tile).fertilize(level, xt, yt, 1); } if (random.nextInt(5) == 0) { - double x = (double)xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; - double y = (double)yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double x = (double) xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double y = (double) yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; level.add(new Particle((int) x, (int) y, 120 + random.nextInt(21) - 40, particleSprite)); } } else if (tile instanceof DirtTile || tile instanceof GrassTile) { if (tile instanceof GrassTile) { if (random.nextInt(15) == 0) { - double x = (double)xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; - double y = (double)yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double x = (double) xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double y = (double) yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; level.add(new Particle((int) x, (int) y, 120 + random.nextInt(21) - 40, particleSprite)); } if (random.nextInt(60) == 0) { // Small chance for growing flowers @@ -96,8 +94,8 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, if (tile instanceof DirtTile) { if (t instanceof GrassTile) { // Grass tile exists. if (random.nextInt(5) == 0) { - double x = (double)xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; - double y = (double)yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double x = (double) xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double y = (double) yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; level.add(new Particle((int) x, (int) y, 120 + random.nextInt(21) - 40, particleSprite)); } if (random.nextInt(10) == 0) @@ -107,8 +105,8 @@ public boolean interactOn(Tile tile, Level level, int xt, int yt, Player player, } else { // tile instanceof GrassTile if (t instanceof DirtTile) { // Dirt tile exists. if (random.nextInt(5) == 0) { - double x = (double)xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; - double y = (double)yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double x = (double) xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double y = (double) yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; level.add(new Particle((int) x, (int) y, 120 + random.nextInt(21) - 40, particleSprite)); } if (random.nextInt(15) == 0) diff --git a/src/client/java/minicraft/level/Level.java b/src/client/java/minicraft/level/Level.java index 2b5dfba35..d2fb45869 100644 --- a/src/client/java/minicraft/level/Level.java +++ b/src/client/java/minicraft/level/Level.java @@ -2,7 +2,6 @@ import minicraft.core.Game; import minicraft.core.Updater; -import minicraft.core.World; import minicraft.core.io.Localization; import minicraft.core.io.Settings; import minicraft.entity.Entity; @@ -53,8 +52,14 @@ public class Level { private final Random random; private static final String[] levelNames = {"Sky", "Surface", "Iron", "Gold", "Lava", "Dungeon"}; - public static String getLevelName(int depth) { return levelNames[-1 * depth + 1]; } - public static String getDepthString(int depth) { return Localization.getLocalized("minicraft.displays.loading.message.level", depth < 0 ? "B" + (-depth) : depth); } + + public static String getLevelName(int depth) { + return levelNames[-1 * depth + 1]; + } + + public static String getDepthString(int depth) { + return Localization.getLocalized("minicraft.displays.loading.message.level", depth < 0 ? "B" + (-depth) : depth); + } private static final int MOB_SPAWN_FACTOR = 100; // The chance of a mob actually trying to spawn when trySpawn is called equals: mobCount / maxMobCount * MOB_SPAWN_FACTOR. so, it basically equals the chance, 1/number, of a mob spawning when the mob cap is reached. I hope that makes sense... @@ -83,7 +88,9 @@ public class Level { @SuppressWarnings("Convert2Lambda") private static Comparator spriteSorter = Comparator.comparingInt(new ToIntFunction() { @Override - public int applyAsInt(Entity e) { return e.y; } + public int applyAsInt(Entity e) { + return e.y; + } }); public Entity[] getEntitiesToSave() { @@ -98,7 +105,10 @@ public Entity[] getEntitiesToSave() { // This is a solely a debug method I made, to make printing repetitive stuff easier. // Should be changed to accept prepend and entity, or a tile (as an Object). It will get the coordinates and class name from the object, and will divide coords by 16 if passed an entity. - public void printLevelLoc(String prefix, int x, int y) { printLevelLoc(prefix, x, y, ""); } + public void printLevelLoc(String prefix, int x, int y) { + printLevelLoc(prefix, x, y, ""); + } + public void printLevelLoc(String prefix, int x, int y, String suffix) { String levelName = getLevelName(depth); @@ -111,9 +121,10 @@ public void printTileLocs(Tile t) { if (getTile(x, y).id == t.id) printLevelLoc(t.name, x, y); } + public void printEntityLocs(Class c) { int numfound = 0; - for (Entity entity: getEntityArray()) { + for (Entity entity : getEntityArray()) { if (c.isAssignableFrom(entity.getClass())) { printLevelLoc(entity.toString(), entity.x >> 4, entity.y >> 4); numfound++; @@ -155,12 +166,12 @@ public Level(int w, int h, long seed, int level, Level parentLevel, boolean make double dist = Math.max(xd, yd); dist = dist * dist * dist * dist; dist = dist * dist * dist * dist; - val += 1 - dist*20; + val += 1 - dist * 20; val += 1.5; // Assuming the range of value is from 0 to 2. val *= types.length / 2.0; val += 1; // Incrementing index. // The original val mainly falls in small interval instead of averagely. - val = 1.0/(3 * types.length) * Math.pow(val - 5, 2); // Quadratically bloating the value. + val = 1.0 / (3 * types.length) * Math.pow(val - 5, 2); // Quadratically bloating the value. int idx = (int) Math.round(val - 1); // Decrementing index. treeTypes[x + y * w] = (idx >= types.length || idx < 0) ? TreeTile.TreeType.OAK // Oak by default. : types[idx]; @@ -173,7 +184,7 @@ public Level(int w, int h, long seed, int level, Level parentLevel, boolean make updateMobCap(); - if(!makeWorld) { + if (!makeWorld) { int arrsize = w * h; tiles = new short[arrsize]; data = new short[arrsize]; @@ -207,13 +218,11 @@ public Level(int w, int h, long seed, int level, Level parentLevel, boolean make if (parentLevel.getTile(x, y) == Tiles.get("Stairs Down")) { // If the tile in the level above the current one is a stairs down then... if (level == -4) { /// Make the obsidian wall formation around the stair in the dungeon level Structure.dungeonGate.draw(this, x, y); // Te gate should not intersect with the boss room. - Structure.dungeonBossRoom.draw(this, w/2, h/2); // Generating the boss room at the center. - } - else if (level == 0) { // Surface + Structure.dungeonBossRoom.draw(this, w / 2, h / 2); // Generating the boss room at the center. + } else if (level == 0) { // Surface Logging.WORLD.trace("Setting tiles around " + x + "," + y + " to hard rock"); setAreaTiles(x, y, 1, Tiles.get("Hard Rock"), 0); // surround the sky stairs with hard rock - } - else // Any other level, the up-stairs should have dirt on all sides. + } else // Any other level, the up-stairs should have dirt on all sides. setAreaTiles(x, y, 1, Tiles.get("dirt"), 0); setTile(x, y, Tiles.get("Stairs Up")); // Set a stairs up tile in the same position on the current level @@ -248,7 +257,9 @@ public Level(int w, int h, int level, Level parentLevel, boolean makeWorld) { this(w, h, 0, level, parentLevel, makeWorld); } - /** Level which the world is contained in */ + /** + * Level which the world is contained in + */ public Level(int w, int h, int level, Level parentLevel) { this(w, h, level, parentLevel, true); } @@ -260,17 +271,18 @@ public long getSeed() { public void checkAirWizard() { checkAirWizard(true); } + private void checkAirWizard(boolean check) { if (depth == 1 && !AirWizard.beaten) { // Add the airwizard to the surface boolean found = false; if (check) { - for (Entity e: entitiesToAdd) + for (Entity e : entitiesToAdd) if (e instanceof AirWizard) { found = true; break; } - for (Entity e: entities) + for (Entity e : entities) if (e instanceof AirWizard) { found = true; break; @@ -279,7 +291,7 @@ private void checkAirWizard(boolean check) { if (!found) { AirWizard aw = new AirWizard(); - add(aw, w/2, h/2, true); + add(aw, w / 2, h / 2, true); } } } @@ -287,6 +299,7 @@ private void checkAirWizard(boolean check) { public void checkChestCount() { checkChestCount(true); } + private void checkChestCount(boolean check) { // If the level is the dungeon, and we're not just loading the world... if (depth != -4) return; @@ -294,10 +307,10 @@ private void checkChestCount(boolean check) { int numChests = 0; if (check) { - for (Entity e: entitiesToAdd) + for (Entity e : entitiesToAdd) if (e instanceof DungeonChest) numChests++; - for (Entity e: entities) + for (Entity e : entities) if (e instanceof DungeonChest) numChests++; Logging.WORLDNAMED.debug("Found " + numChests + " chests."); @@ -368,7 +381,8 @@ public void tick(boolean fullTick) { boolean inLevel = entities.contains(entity); if (!inLevel) { - if (Logging.logLevel) printEntityStatus("Adding ", entity, "furniture.DungeonChest", "mob.AirWizard", "mob.Player"); + if (Logging.logLevel) + printEntityStatus("Adding ", entity, "furniture.DungeonChest", "mob.AirWizard", "mob.Player"); synchronized (entityLock) { entities.add(entity); @@ -440,8 +454,8 @@ public double distanceOfClosestPlayer(Entity entity) { public void printEntityStatus(String entityMessage, Entity entity, String... searching) { // "searching" can contain any number of class names I want to print when found. String clazz = entity.getClass().getCanonicalName(); - clazz = clazz.substring(clazz.lastIndexOf(".")+1); - for (String search: searching) { + clazz = clazz.substring(clazz.lastIndexOf(".") + 1); + for (String search : searching) { try { if (Class.forName("minicraft.entity." + search).isAssignableFrom(entity.getClass())) { printLevelLoc(entityMessage + clazz, entity.x >> 4, entity.y >> 4, ": " + entity); @@ -454,16 +468,19 @@ public void printEntityStatus(String entityMessage, Entity entity, String... sea } public void dropItem(int x, int y, int mincount, int maxcount, Item... items) { - dropItem(x, y, mincount+random.nextInt(maxcount - mincount + 1), items); + dropItem(x, y, mincount + random.nextInt(maxcount - mincount + 1), items); } + public void dropItem(int x, int y, int count, Item... items) { for (int i = 0; i < count; i++) dropItem(x, y, items); } + public void dropItem(int x, int y, Item... items) { - for (Item i: items) + for (Item i : items) dropItem(x, y, i); } + public ItemEntity dropItem(int x, int y, Item i) { int ranx, rany; @@ -514,7 +531,7 @@ public void renderLight(Screen screen, int xScroll, int yScroll, int brightness) int r = 8; List entities = getEntitiesInTiles(xo - r, yo - r, w + xo + r, h + yo + r); - for (Entity e: entities) { + for (Entity e : entities) { int lr = e.getLightRadius(); if (lr > 0) screen.renderLight(e.x - 1, e.y - 4, lr * brightness); } @@ -541,9 +558,9 @@ private void sortAndRender(Screen screen, List list) { } public Tile getTile(int x, int y) { - if (x < 0 || y < 0 || x >= w || y >= h /* || (x + y * w) >= tiles.length*/ ) return Tiles.get("connector tile"); + if (x < 0 || y < 0 || x >= w || y >= h /* || (x + y * w) >= tiles.length*/) return Tiles.get("connector tile"); int id = tiles[x + y * w]; - if(id < 0) id += 256; + if (id < 0) id += 256; return Tiles.get(id); } @@ -553,7 +570,7 @@ public void setTile(int x, int y, String tilewithdata) { return; } String name = tilewithdata.substring(0, tilewithdata.indexOf("_")); - int data = Tiles.get(name).getData(tilewithdata.substring(name.length()+1)); + int data = Tiles.get(name).getData(tilewithdata.substring(name.length() + 1)); setTile(x, y, Tiles.get(name), data); } @@ -578,11 +595,18 @@ public void setData(int x, int y, int val) { data[x + y * w] = (short) val; } - public void add(Entity e) { if(e==null) return; add(e, e.x, e.y); } - public void add(Entity entity, int x, int y) { add(entity, x, y, false); } + public void add(Entity e) { + if (e == null) return; + add(e, e.x, e.y); + } + + public void add(Entity entity, int x, int y) { + add(entity, x, y, false); + } + public void add(Entity entity, int x, int y, boolean tileCoords) { - if(entity == null) return; - if(tileCoords) { + if (entity == null) return; + if (tileCoords) { x = x * 16 + 8; y = y * 16 + 8; } @@ -599,7 +623,9 @@ public void remove(Entity e) { entitiesToRemove.add(e); } - /** Natural spawn. */ + /** + * Natural spawn. + */ private void trySpawn() { int spawnSkipChance = (int) (MOB_SPAWN_FACTOR * Math.pow(mobCount, 2) / Math.pow(maxMobCount, 2)); if (spawnSkipChance > 0 && random.nextInt(spawnSkipChance) != 0) @@ -652,7 +678,7 @@ private void trySpawn() { } public void removeAllEnemies() { - for (Entity e: getEntityArray()) { + for (Entity e : getEntityArray()) { if (e instanceof EnemyMob) if (!(e instanceof AirWizard) || Game.isMode("minicraft.settings.mode.creative")) // Don't remove the airwizard bosses! Unless in creative, since you can spawn more. e.remove(); @@ -677,34 +703,42 @@ public Entity[] getEntityArray() { return entityArray; } - public List getEntitiesInTiles(int xt, int yt, int radius) { return getEntitiesInTiles(xt, yt, radius, false); } + public List getEntitiesInTiles(int xt, int yt, int radius) { + return getEntitiesInTiles(xt, yt, radius, false); + } @SafeVarargs - public final List getEntitiesInTiles(int xt, int yt, int radius, boolean includeGiven, Class... entityClasses) { return getEntitiesInTiles(xt-radius, yt-radius, xt+radius, yt+radius, includeGiven, entityClasses); } + public final List getEntitiesInTiles(int xt, int yt, int radius, boolean includeGiven, Class... entityClasses) { + return getEntitiesInTiles(xt - radius, yt - radius, xt + radius, yt + radius, includeGiven, entityClasses); + } /** * Get entities in a certain area on the level. + * * @param xt0 Left * @param yt0 Top * @param xt1 Right * @param yt1 Bottom */ - public List getEntitiesInTiles(int xt0, int yt0, int xt1, int yt1) { return getEntitiesInTiles(xt0, yt0, xt1, yt1, false); } + public List getEntitiesInTiles(int xt0, int yt0, int xt1, int yt1) { + return getEntitiesInTiles(xt0, yt0, xt1, yt1, false); + } /** * Get entities in a certain area on the level, and filter them by class. - * @param xt0 Left - * @param yt0 Top - * @param xt1 Right - * @param yt1 Bottom - * @param includeGiven If we should accept entities that match the provided entityClasses. If false, we ignore the provided entityClasses. + * + * @param xt0 Left + * @param yt0 Top + * @param xt1 Right + * @param yt1 Bottom + * @param includeGiven If we should accept entities that match the provided entityClasses. If false, we ignore the provided entityClasses. * @param entityClasses Entities to accept. * @return A list of entities in the area. */ @SafeVarargs public final List getEntitiesInTiles(int xt0, int yt0, int xt1, int yt1, boolean includeGiven, Class... entityClasses) { List contained = new ArrayList<>(); - for (Entity e: getEntityArray()) { + for (Entity e : getEntityArray()) { int xt = e.x >> 4; int yt = e.y >> 4; @@ -729,12 +763,13 @@ public final List getEntitiesInTiles(int xt0, int yt0, int xt1, int yt1, /** * Check if there is an entity on the specified tile. + * * @param x The x position of the tile. * @param y The y position of the tile * @return True if there is an entity on the tile. */ public final boolean isEntityOnTile(int x, int y) { - for (Entity e: getEntityArray()) { + for (Entity e : getEntityArray()) { int xt = e.x >> 4; int yt = e.y >> 4; @@ -747,7 +782,7 @@ public final boolean isEntityOnTile(int x, int y) { public List getEntitiesInRect(Rectangle area) { List result = new ArrayList<>(); - for (Entity e: getEntityArray()) { + for (Entity e : getEntityArray()) { if (e.isTouching(area)) result.add(e); } @@ -767,7 +802,7 @@ public List getEntitiesInRect(Predicate filter, Rectangle area) /// Finds all entities that are an instance of the given entity. public Entity[] getEntitiesOfClass(Class targetClass) { ArrayList matches = new ArrayList<>(); - for (Entity e: getEntityArray()) { + for (Entity e : getEntityArray()) { if (targetClass.isAssignableFrom(e.getClass())) matches.add(e); } @@ -790,7 +825,7 @@ public Player getClosestPlayer(int x, int y) { for (int i = 1; i < players.length; i++) { int curxd = players[i].x - x; int curyd = players[i].y - y; - if(xd*xd + yd*yd > curxd*curxd + curyd*curyd) { + if (xd * xd + yd * yd > curxd * curxd + curyd * curyd) { closest = players[i]; xd = curxd; yd = curyd; @@ -802,11 +837,12 @@ public Player getClosestPlayer(int x, int y) { /** * Calculates maximum position can be reached by an entity with the front boundary of hit box by tile hit box. - * @param sgn One-dimensional direction of displacement - * @param d Displacement vector - * @param hitBoxLeft The left boundary of hit box - * @param hitBoxRight The right boundary of hit box - * @param hitBoxFront The front boundary of hit box + * + * @param sgn One-dimensional direction of displacement + * @param d Displacement vector + * @param hitBoxLeft The left boundary of hit box + * @param hitBoxRight The right boundary of hit box + * @param hitBoxFront The front boundary of hit box * @param frontTilePassableCheck The check of whether the front boundary of hit box hits the tile hit box; * the first parameter takes the front tile position and second one takes the horizontal position * @return The maximum front position can be reached by tile hit box check @@ -834,31 +870,40 @@ public static int calculateMaxFrontClosestTile(int sgn, int d, int hitBoxLeft, i (sgn > 0 ? Math.min(d, (maxFrontTile << 4) - hitBoxFront + (1 << 4) - 1) : Math.max(d, (maxFrontTile << 4) - hitBoxFront)); } - public Point[] getAreaTilePositions(int x, int y, int r) { return getAreaTilePositions(x, y, r, r); } + public Point[] getAreaTilePositions(int x, int y, int r) { + return getAreaTilePositions(x, y, r, r); + } + public Point[] getAreaTilePositions(int x, int y, int rx, int ry) { ArrayList local = new ArrayList<>(); - for (int yp = y-ry; yp <= y+ry; yp++) - for (int xp = x-rx; xp <= x+rx; xp++) + for (int yp = y - ry; yp <= y + ry; yp++) + for (int xp = x - rx; xp <= x + rx; xp++) if (xp >= 0 && xp < w && yp >= 0 && yp < h) local.add(new Point(xp, yp)); return local.toArray(new Point[0]); } - public Tile[] getAreaTiles(int x, int y, int r) { return getAreaTiles(x, y, r, r); } + public Tile[] getAreaTiles(int x, int y, int r) { + return getAreaTiles(x, y, r, r); + } + public Tile[] getAreaTiles(int x, int y, int rx, int ry) { ArrayList local = new ArrayList<>(); - for (Point p: getAreaTilePositions(x, y, rx, ry)) + for (Point p : getAreaTilePositions(x, y, rx, ry)) local.add(getTile(p.x, p.y)); return local.toArray(new Tile[0]); } - public void setAreaTiles(int xt, int yt, int r, Tile tile, int data) { setAreaTiles(xt, yt, r, tile, data, false); } + public void setAreaTiles(int xt, int yt, int r, Tile tile, int data) { + setAreaTiles(xt, yt, r, tile, data, false); + } + public void setAreaTiles(int xt, int yt, int r, Tile tile, int data, boolean overwriteStairs) { - for(int y = yt - r; y <= yt + r; y++) { + for (int y = yt - r; y <= yt + r; y++) { for (int x = xt - r; x <= xt + r; x++) { - if(overwriteStairs || (!getTile(x, y).name.toLowerCase().contains("stairs"))) + if (overwriteStairs || (!getTile(x, y).name.toLowerCase().contains("stairs"))) setTile(x, y, tile, data); } } @@ -878,15 +923,19 @@ public interface TileCheck { boolean check(Tile t, int x, int y); } - public List getMatchingTiles(Tile search) { return getMatchingTiles((t, x, y) -> t.equals(search)); } + public List getMatchingTiles(Tile search) { + return getMatchingTiles((t, x, y) -> t.equals(search)); + } + public List getMatchingTiles(Tile... search) { return getMatchingTiles((t, x, y) -> { - for (Tile poss: search) + for (Tile poss : search) if (t.equals(poss)) return true; return false; }); } + public List getMatchingTiles(TileCheck condition) { List matches = new ArrayList<>(); for (int y = 0; y < h; y++) @@ -898,7 +947,7 @@ public List getMatchingTiles(TileCheck condition) { } public boolean isLight(int x, int y) { - for (Tile t: getAreaTiles(x, y, 3)) + for (Tile t : getAreaTiles(x, y, 3)) if (t instanceof TorchTile) return true; for (Entity e : getEntitiesInRect(e -> e instanceof Lantern, new Rectangle(x, y, 8, 8, Rectangle.CENTER_DIMS))) { @@ -983,8 +1032,7 @@ private void generateSpawnerStructures() { } } } - } - else { + } else { for (int i = 0; i < 18 * (w / 128); i++) { /// For generating spawner dungeons @@ -1126,9 +1174,9 @@ private void generateDungeonStructures() { */ public void regenerateBossRoom() { if (depth == -4) { - Structure.dungeonBossRoom.draw(tiles, w/2, h/2, w); // Generating the boss room at the center. - for (int x = w/2-4; x < w/2+5; x++) { // Resetting tile data. - for (int y = h/2-4; y < h/2+5; y++) { + Structure.dungeonBossRoom.draw(tiles, w / 2, h / 2, w); // Generating the boss room at the center. + for (int x = w / 2 - 4; x < w / 2 + 5; x++) { // Resetting tile data. + for (int y = h / 2 - 4; y < h / 2 + 5; y++) { setData(x, y, 0); } } diff --git a/src/client/java/minicraft/level/LevelGen.java b/src/client/java/minicraft/level/LevelGen.java index 794e5eec9..579a13147 100644 --- a/src/client/java/minicraft/level/LevelGen.java +++ b/src/client/java/minicraft/level/LevelGen.java @@ -22,7 +22,9 @@ public class LevelGen { private final int w, h; // Width and height of the map private static final int stairRadius = 15; - /** This creates noise to create random values for level generation */ + /** + * This creates noise to create random values for level generation + */ public LevelGen(int w, int h, int featureSize) { this.w = w; this.h = h; @@ -244,7 +246,7 @@ private static short[][] createTopMap(int w, int h) { // Create surface map double dist = Math.max(xd, yd); dist = dist * dist * dist * dist; dist = dist * dist * dist * dist; - val += 1 - dist*20; + val += 1 - dist * 20; switch ((String) Settings.get("Type")) { case "minicraft.settings.type.island": @@ -502,7 +504,8 @@ private static short[][] createDungeon(int w, int h) { if (val < -0.05) { map[i] = Tiles.get("Obsidian Wall").id; - }else if(val>=-0.05 && val<-0.03){map[i] = Tiles.get("Lava").id; + } else if (val >= -0.05 && val < -0.03) { + map[i] = Tiles.get("Lava").id; } else { if (random.nextInt(2) == 1) { if (random.nextInt(2) == 1) { @@ -510,8 +513,7 @@ private static short[][] createDungeon(int w, int h) { } else { map[i] = Tiles.get("Raw Obsidian").id; } - } - else { + } else { map[i] = Tiles.get("dirt").id; } } @@ -629,10 +631,10 @@ private static short[][] createUndergroundMap(int w, int h, int depth) { if (depth > 2) { // The level above dungeon. int r = 1; - int xm = w/2; - int ym = h/2; + int xm = w / 2; + int ym = h / 2; int side = 6; // The side of the lock is 5, and pluses margin with 1. - int edgeMargin = w/20; // The distance between the world enge and the lock sides. + int edgeMargin = w / 20; // The distance between the world enge and the lock sides. Rectangle lockRect = new Rectangle(0, 0, side, side, 0); Rectangle bossRoomRect = new Rectangle(xm, ym, 20, 20, Rectangle.CENTER_DIMS); do { // Trying to generate a lock not intersecting to the boss room in the dungeon. @@ -820,8 +822,8 @@ public static void main(String[] args) { } } img.setRGB(0, 0, w, h, pixels, 0, w); - int op = JOptionPane.showOptionDialog(null, null, "Map With Seed "+worldSeed, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, - new ImageIcon(img.getScaledInstance(w * 4, h * 4, Image.SCALE_AREA_AVERAGING)), new String[] {"Next", "0x100", "0xAAFF20"}, "Next"); + int op = JOptionPane.showOptionDialog(null, null, "Map With Seed " + worldSeed, JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, + new ImageIcon(img.getScaledInstance(w * 4, h * 4, Image.SCALE_AREA_AVERAGING)), new String[]{"Next", "0x100", "0xAAFF20"}, "Next"); if (op == 1) LevelGen.worldSeed = 0x100; else if (op == 2) LevelGen.worldSeed = 0xAAFF20; else LevelGen.worldSeed++; diff --git a/src/client/java/minicraft/level/Structure.java b/src/client/java/minicraft/level/Structure.java index 8175ece84..a56be98d0 100644 --- a/src/client/java/minicraft/level/Structure.java +++ b/src/client/java/minicraft/level/Structure.java @@ -22,6 +22,7 @@ public Structure() { tiles = new HashSet<>(); furniture = new HashMap<>(); } + public Structure(Structure struct) { this.tiles = struct.tiles; this.furniture = struct.furniture; @@ -30,20 +31,21 @@ public Structure(Structure struct) { public void setTile(int x, int y, Tile tile) { tiles.add(new TilePoint(x, y, tile)); } + public void addFurniture(int x, int y, Furniture furniture) { this.furniture.put(new Point(x, y), furniture); } public void draw(Level level, int xt, int yt) { - for (TilePoint p: tiles) - level.setTile(xt+p.x, yt+p.y, p.t); + for (TilePoint p : tiles) + level.setTile(xt + p.x, yt + p.y, p.t); - for (Point p: furniture.keySet()) - level.add(furniture.get(p).copy(), xt+p.x, yt+p.y, true); + for (Point p : furniture.keySet()) + level.add(furniture.get(p).copy(), xt + p.x, yt + p.y, true); } public void draw(short[] map, int xt, int yt, int mapWidth) { - for (TilePoint p: tiles) + for (TilePoint p : tiles) map[(xt + p.x) + (yt + p.y) * mapWidth] = p.t.id; } @@ -66,7 +68,7 @@ public void setData(String keys, String data) { for (int c = 0; c < dataLines[i].length(); c++) { if (dataLines[i].charAt(c) != '*') { Tile tile = Tiles.get(keyPairs.get(String.valueOf(dataLines[i].charAt(c)))); - this.setTile(-width / 2 + i, - height / 2 + c, tile); + this.setTile(-width / 2 + i, -height / 2 + c, tile); } } } @@ -125,21 +127,21 @@ public int hashCode() { static { dungeonGate = new Structure(); dungeonGate.setData("O:Obsidian,D:Obsidian Door,W:Obsidian Wall", - "WWDWW\n" + - "WOOOW\n" + - "DOOOD\n" + - "WOOOW\n" + - "WWDWW" + "WWDWW\n" + + "WOOOW\n" + + "DOOOD\n" + + "WOOOW\n" + + "WWDWW" ); dungeonGate.addFurniture(-1, -1, new Lantern(Lantern.Type.IRON)); dungeonLock = new Structure(); dungeonLock.setData("O:Obsidian,W:Obsidian Wall", - "WWWWW\n" + - "WOOOW\n" + - "WOOOW\n" + - "WOOOW\n" + - "WWWWW" + "WWWWW\n" + + "WOOOW\n" + + "WOOOW\n" + + "WOOOW\n" + + "WWWWW" ); dungeonBossRoom = new Structure(); dungeonBossRoom.setData("O:Obsidian Boss Floor,D:Obsidian Boss Door,W:Obsidian Boss Wall", @@ -153,7 +155,7 @@ public int hashCode() { "WOOOOOOOW\n" + "WWWWDWWWW" ); - dungeonBossRoom.addFurniture(0,0,new KnightStatue(5000)); + dungeonBossRoom.addFurniture(0, 0, new KnightStatue(5000)); dungeonSpawner = new Structure(); dungeonSpawner.setData("F:Grass,W:Obsidian Wall,O:Ornate Obsidian,D:Obsidian Door", @@ -168,8 +170,8 @@ public int hashCode() { lavaPool = new Structure(); lavaPool.setData("L:Lava", - "LL\n" + - "LL" + "LL\n" + + "LL" ); ornateLavaPool = new Structure(); @@ -204,94 +206,94 @@ public int hashCode() { "WOOOOOW\n" + "WWWDWWW" ); - dungeonChest.addFurniture(0,0, new DungeonChest(true)); + dungeonChest.addFurniture(0, 0, new DungeonChest(true)); mobDungeonCenter = new Structure(); mobDungeonCenter.setData("B:Stone Bricks,W:Stone Wall", - "WWBWW\n" + - "WBBBW\n" + - "BBBBB\n" + - "WBBBW\n" + - "WWBWW" + "WWBWW\n" + + "WBBBW\n" + + "BBBBB\n" + + "WBBBW\n" + + "WWBWW" ); mobDungeonNorth = new Structure(); mobDungeonNorth.setData("B:Stone Bricks,W:Stone Wall", - "WWWWW\n" + - "WBBBB\n" + - "BBBBB\n" + - "WBBBB\n" + - "WWWWW" + "WWWWW\n" + + "WBBBB\n" + + "BBBBB\n" + + "WBBBB\n" + + "WWWWW" ); mobDungeonSouth = new Structure(); mobDungeonSouth.setData("B:Stone Bricks,W:Stone Wall", - "WWWWW\n" + - "BBBBW\n" + - "BBBBB\n" + - "BBBBW\n" + - "WWWWW" + "WWWWW\n" + + "BBBBW\n" + + "BBBBB\n" + + "BBBBW\n" + + "WWWWW" ); mobDungeonEast = new Structure(); mobDungeonEast.setData("B:Stone Bricks,W:Stone Wall", - "WBBBW\n" + - "WBBBW\n" + - "WBBBW\n" + - "WBBBW\n" + - "WWBWW" + "WBBBW\n" + + "WBBBW\n" + + "WBBBW\n" + + "WBBBW\n" + + "WWBWW" ); mobDungeonWest = new Structure(); mobDungeonWest.setData("B:Stone Bricks,W:Stone Wall", - "WWBWW\n" + - "WBBBW\n" + - "WBBBW\n" + - "WBBBW\n" + - "WBBBW" + "WWBWW\n" + + "WBBBW\n" + + "WBBBW\n" + + "WBBBW\n" + + "WBBBW" ); airWizardHouse = new Structure(); airWizardHouse.setData("F:Wood Planks,W:Wood Wall,D:Wood Door", - "WWWWWWW\n" + - "WFFFFFW\n" + - "DFFFFFW\n" + - "WFFFFFW\n" + - "WWWWWWW" + "WWWWWWW\n" + + "WFFFFFW\n" + + "DFFFFFW\n" + + "WFFFFFW\n" + + "WWWWWWW" ); airWizardHouse.addFurniture(-2, 0, new Lantern(Lantern.Type.GOLD)); airWizardHouse.addFurniture(0, 0, new Crafter(Crafter.Type.Enchanter)); villageHouseNormal = new Structure(); villageHouseNormal.setData("F:Wood Planks,W:Wood Wall,D:Wood Door,G:Grass", - "WWWWW\n" + - "WFFFW\n" + - "WFFFD\n" + - "WFFFG\n" + - "WWWWW" + "WWWWW\n" + + "WFFFW\n" + + "WFFFD\n" + + "WFFFG\n" + + "WWWWW" ); villageHouseTwoDoor = new Structure(); villageHouseTwoDoor.setData("F:Wood Planks,W:Wood Wall,D:Wood Door,G:Grass", - "WWWWW\n" + - "WFFFW\n" + - "DFFFW\n" + - "WFFFW\n" + - "WWDWW" + "WWWWW\n" + + "WFFFW\n" + + "DFFFW\n" + + "WFFFW\n" + + "WWDWW" ); villageRuinedOverlay1 = new Structure(); villageRuinedOverlay1.setData("G:Grass,F:Wood Planks", - "**FG*\n" + - "F*GG*\n" + - "*G**F\n" + - "G*G**\n" + - "***G*" + "**FG*\n" + + "F*GG*\n" + + "*G**F\n" + + "G*G**\n" + + "***G*" ); villageRuinedOverlay2 = new Structure(); villageRuinedOverlay2.setData("G:Grass,F:Wood Planks", - "F**G*\n" + - "*****\n" + - "*GG**\n" + - "F**G*\n" + - "*F**G" + "F**G*\n" + + "*****\n" + + "*GG**\n" + + "F**G*\n" + + "*F**G" ); } } diff --git a/src/client/java/minicraft/level/tile/CactusTile.java b/src/client/java/minicraft/level/tile/CactusTile.java index 3fa2c59f7..8dceb499f 100644 --- a/src/client/java/minicraft/level/tile/CactusTile.java +++ b/src/client/java/minicraft/level/tile/CactusTile.java @@ -52,7 +52,7 @@ public void render(Screen screen, Level level, int x, int y) { } public void bumpedInto(Level level, int x, int y, Entity entity) { - if(!(entity instanceof Mob)) return; + if (!(entity instanceof Mob)) return; Mob m = (Mob) entity; if (Settings.get("diff").equals("minicraft.settings.difficulty.easy")) { m.hurt(this, x, y, 1); diff --git a/src/client/java/minicraft/level/tile/ConnectTile.java b/src/client/java/minicraft/level/tile/ConnectTile.java index c6db32812..f46f1a197 100644 --- a/src/client/java/minicraft/level/tile/ConnectTile.java +++ b/src/client/java/minicraft/level/tile/ConnectTile.java @@ -9,17 +9,17 @@ // TODO Remove this. // IMPORTANT: This tile should never be used for anything, it only exists to allow tiles right next to the edge of the world to connect to it public class ConnectTile extends Tile { - public ConnectTile() { - super("connector tile", new SpriteAnimation(SpriteType.Tile, "missing_tile")); - } + public ConnectTile() { + super("connector tile", new SpriteAnimation(SpriteType.Tile, "missing_tile")); + } - @Override - public boolean mayPass(Level level, int x, int y, Entity e) { - return false; - } + @Override + public boolean mayPass(Level level, int x, int y, Entity e) { + return false; + } - @Override - public boolean maySpawn() { - return false; - } + @Override + public boolean maySpawn() { + return false; + } } diff --git a/src/client/java/minicraft/level/tile/DecorTile.java b/src/client/java/minicraft/level/tile/DecorTile.java index a40f13f2a..b4266bd94 100644 --- a/src/client/java/minicraft/level/tile/DecorTile.java +++ b/src/client/java/minicraft/level/tile/DecorTile.java @@ -38,9 +38,14 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D } Item drop; switch (type) { - case Stone: drop = Items.get("Ornate Stone"); break; - case Obsidian: drop = Items.get("Ornate Obsidian"); break; - default: throw new IllegalStateException("Unexpected value: " + type); + case Stone: + drop = Items.get("Ornate Stone"); + break; + case Obsidian: + drop = Items.get("Ornate Obsidian"); + break; + default: + throw new IllegalStateException("Unexpected value: " + type); } Sound.play("monsterhurt"); level.dropItem(xt * 16 + 8, yt * 16 + 8, drop); diff --git a/src/client/java/minicraft/level/tile/DirtTile.java b/src/client/java/minicraft/level/tile/DirtTile.java index 090f19ff4..2ee791f7f 100644 --- a/src/client/java/minicraft/level/tile/DirtTile.java +++ b/src/client/java/minicraft/level/tile/DirtTile.java @@ -15,7 +15,7 @@ import minicraft.util.AdvancementElement; public class DirtTile extends Tile { - private static SpriteAnimation[] levelSprite = new SpriteAnimation[] { + private static SpriteAnimation[] levelSprite = new SpriteAnimation[]{ new SpriteAnimation(SpriteType.Tile, "dirt"), new SpriteAnimation(SpriteType.Tile, "gray_dirt"), new SpriteAnimation(SpriteType.Tile, "purple_dirt") @@ -28,18 +28,25 @@ protected DirtTile(String name) { protected static int dCol(int depth) { switch (depth) { - case 1: return Color.get(1, 194, 194, 194); // Sky. - case 0: return Color.get(1, 129, 105, 83); // Surface. - case -4: return Color.get(1, 76, 30, 100); // Dungeons. - default: return Color.get(1, 102); // Caves. + case 1: + return Color.get(1, 194, 194, 194); // Sky. + case 0: + return Color.get(1, 129, 105, 83); // Surface. + case -4: + return Color.get(1, 76, 30, 100); // Dungeons. + default: + return Color.get(1, 102); // Caves. } } protected static int dIdx(int depth) { switch (depth) { - case 0: return 0; // Surface - case -4: return 2; // Dungeons - default: return 1; // Caves + case 0: + return 0; // Surface + case -4: + return 2; // Dungeons + default: + return 1; // Caves } } diff --git a/src/client/java/minicraft/level/tile/DoorTile.java b/src/client/java/minicraft/level/tile/DoorTile.java index e01b023cc..dec7bd4c8 100644 --- a/src/client/java/minicraft/level/tile/DoorTile.java +++ b/src/client/java/minicraft/level/tile/DoorTile.java @@ -19,7 +19,10 @@ public class DoorTile extends Tile { private SpriteAnimation closedSprite; private SpriteAnimation openSprite; - protected DoorTile(Material type) { this(type, null); } + protected DoorTile(Material type) { + this(type, null); + } + protected DoorTile(Material type, String name) { super(type.name() + " " + (name == null ? "Door" : name), null); this.type = type; diff --git a/src/client/java/minicraft/level/tile/FloorTile.java b/src/client/java/minicraft/level/tile/FloorTile.java index a3cbd60da..d7190a48f 100644 --- a/src/client/java/minicraft/level/tile/FloorTile.java +++ b/src/client/java/minicraft/level/tile/FloorTile.java @@ -15,15 +15,24 @@ public class FloorTile extends Tile { protected Material type; - protected FloorTile(Material type) { this(type, null); } + protected FloorTile(Material type) { + this(type, null); + } + protected FloorTile(Material type, String name) { - super((type == Material.Wood ? "Wood Planks" : type == Material.Obsidian ? "Obsidian" + (name == null ? "" : " "+name) : type.name() + " " + (name == null ? "Bricks" : name)), null); + super((type == Material.Wood ? "Wood Planks" : type == Material.Obsidian ? "Obsidian" + (name == null ? "" : " " + name) : type.name() + " " + (name == null ? "Bricks" : name)), null); this.type = type; maySpawn = true; switch (type) { - case Wood: sprite = new SpriteAnimation(SpriteType.Tile, "wood_floor"); break; - case Stone: sprite = new SpriteAnimation(SpriteType.Tile, "stone_floor"); break; - case Obsidian: sprite = new SpriteAnimation(SpriteType.Tile, "obsidian_floor"); break; + case Wood: + sprite = new SpriteAnimation(SpriteType.Tile, "wood_floor"); + break; + case Stone: + sprite = new SpriteAnimation(SpriteType.Tile, "stone_floor"); + break; + case Obsidian: + sprite = new SpriteAnimation(SpriteType.Tile, "obsidian_floor"); + break; } } @@ -40,8 +49,12 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D } Item drop; switch (type) { - case Wood: drop = Items.get("Plank"); break; - default: drop = Items.get(type.name() + " Brick"); break; + case Wood: + drop = Items.get("Plank"); + break; + default: + drop = Items.get(type.name() + " Brick"); + break; } Sound.play("monsterhurt"); level.dropItem(xt * 16 + 8, yt * 16 + 8, drop); diff --git a/src/client/java/minicraft/level/tile/FlowerTile.java b/src/client/java/minicraft/level/tile/FlowerTile.java index 51be31527..df085249b 100644 --- a/src/client/java/minicraft/level/tile/FlowerTile.java +++ b/src/client/java/minicraft/level/tile/FlowerTile.java @@ -68,8 +68,8 @@ public boolean interact(Level level, int x, int y, Player player, Item item, Dir } public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction attackDir) { - level.dropItem(x *16 + 8, y * 16 + 8, 0, 1, Items.get("Flower")); - level.dropItem(x *16 + 8, y * 16 + 8, 0, 1, Items.get("Rose")); + level.dropItem(x * 16 + 8, y * 16 + 8, 0, 1, Items.get("Flower")); + level.dropItem(x * 16 + 8, y * 16 + 8, 0, 1, Items.get("Rose")); level.setTile(x, y, Tiles.get("Grass")); return true; } diff --git a/src/client/java/minicraft/level/tile/GrassTile.java b/src/client/java/minicraft/level/tile/GrassTile.java index 9c916353e..3012a9daf 100644 --- a/src/client/java/minicraft/level/tile/GrassTile.java +++ b/src/client/java/minicraft/level/tile/GrassTile.java @@ -13,10 +13,6 @@ import minicraft.level.Level; import minicraft.util.AdvancementElement; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Map; - public class GrassTile extends Tile { private static final SpriteAnimation sprite = new SpriteAnimation(SpriteType.Tile, "grass") .setConnectChecker((tile, side) -> !side || tile.connectsToGrass) diff --git a/src/client/java/minicraft/level/tile/HardRockTile.java b/src/client/java/minicraft/level/tile/HardRockTile.java index 07c18c4d2..c8d4b2137 100644 --- a/src/client/java/minicraft/level/tile/HardRockTile.java +++ b/src/client/java/minicraft/level/tile/HardRockTile.java @@ -39,7 +39,7 @@ public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction at } public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if(Game.isMode("minicraft.settings.mode.creative")) + if (Game.isMode("minicraft.settings.mode.creative")) return false; // Go directly to hurt method if (item instanceof ToolItem) { ToolItem tool = (ToolItem) item; diff --git a/src/client/java/minicraft/level/tile/InfiniteFallTile.java b/src/client/java/minicraft/level/tile/InfiniteFallTile.java index 19c798890..4b660d852 100644 --- a/src/client/java/minicraft/level/tile/InfiniteFallTile.java +++ b/src/client/java/minicraft/level/tile/InfiniteFallTile.java @@ -12,14 +12,17 @@ public class InfiniteFallTile extends Tile { protected InfiniteFallTile(String name) { - super(name, (SpriteAnimation)null); + super(name, (SpriteAnimation) null); } @Override - public void render(Screen screen, Level level, int x, int y) { } + public void render(Screen screen, Level level, int x, int y) { + } @Override - public boolean tick(Level level, int xt, int yt) { return false; } + public boolean tick(Level level, int xt, int yt) { + return false; + } @Override public boolean mayPass(Level level, int x, int y, Entity e) { diff --git a/src/client/java/minicraft/level/tile/LavaBrickTile.java b/src/client/java/minicraft/level/tile/LavaBrickTile.java index 13508f7db..5400df3ae 100644 --- a/src/client/java/minicraft/level/tile/LavaBrickTile.java +++ b/src/client/java/minicraft/level/tile/LavaBrickTile.java @@ -37,9 +37,11 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D } public void bumpedInto(Level level, int x, int y, Entity entity) { - if(entity instanceof Mob) - ((Mob)entity).hurt(this, x, y, 3); + if (entity instanceof Mob) + ((Mob) entity).hurt(this, x, y, 3); } - public boolean mayPass(Level level, int x, int y, Entity e) { return e.canWool(); } + public boolean mayPass(Level level, int x, int y, Entity e) { + return e.canWool(); + } } diff --git a/src/client/java/minicraft/level/tile/MaterialTile.java b/src/client/java/minicraft/level/tile/MaterialTile.java index 53df6a95b..83b8ff3f2 100644 --- a/src/client/java/minicraft/level/tile/MaterialTile.java +++ b/src/client/java/minicraft/level/tile/MaterialTile.java @@ -16,12 +16,16 @@ public class MaterialTile extends Tile { protected Material type; protected MaterialTile(Material type) { - super((type == Material.Stone ? "Stone" : type == Material.Obsidian ? "Raw Obsidian" :type.name()), (SpriteAnimation) null); + super((type == Material.Stone ? "Stone" : type == Material.Obsidian ? "Raw Obsidian" : type.name()), (SpriteAnimation) null); this.type = type; maySpawn = true; switch (type) { - case Stone: sprite = new SpriteAnimation(SpriteType.Tile, "stone"); break; - case Obsidian: sprite = new SpriteAnimation(SpriteType.Tile, "obsidian"); break; + case Stone: + sprite = new SpriteAnimation(SpriteType.Tile, "stone"); + break; + case Obsidian: + sprite = new SpriteAnimation(SpriteType.Tile, "obsidian"); + break; default: } } @@ -39,9 +43,14 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D } Item drop; switch (type) { - case Stone: drop = Items.get("Stone"); break; - case Obsidian: drop = Items.get("Raw Obsidian"); break; - default: throw new IllegalStateException("Unexpected value: " + type); + case Stone: + drop = Items.get("Stone"); + break; + case Obsidian: + drop = Items.get("Raw Obsidian"); + break; + default: + throw new IllegalStateException("Unexpected value: " + type); } Sound.play("monsterhurt"); level.dropItem(xt * 16 + 8, yt * 16 + 8, drop); diff --git a/src/client/java/minicraft/level/tile/OreTile.java b/src/client/java/minicraft/level/tile/OreTile.java index 2bfe1506a..23c374a42 100644 --- a/src/client/java/minicraft/level/tile/OreTile.java +++ b/src/client/java/minicraft/level/tile/OreTile.java @@ -25,11 +25,11 @@ public class OreTile extends Tile { private final OreType type; public enum OreType { - Iron (Items.get("Iron Ore"), new SpriteAnimation(SpriteType.Tile, "iron_ore")), - Lapis (Items.get("Lapis"), new SpriteAnimation(SpriteType.Tile, "lapis_ore")), - Gold (Items.get("Gold Ore"), new SpriteAnimation(SpriteType.Tile, "gold_ore")), - Gem (Items.get("Gem"), new SpriteAnimation(SpriteType.Tile, "gem_ore")), - Cloud (Items.get("Cloud Ore"), new SpriteAnimation(SpriteType.Tile, "cloud_ore")); + Iron(Items.get("Iron Ore"), new SpriteAnimation(SpriteType.Tile, "iron_ore")), + Lapis(Items.get("Lapis"), new SpriteAnimation(SpriteType.Tile, "lapis_ore")), + Gold(Items.get("Gold Ore"), new SpriteAnimation(SpriteType.Tile, "gold_ore")), + Gem(Items.get("Gem"), new SpriteAnimation(SpriteType.Tile, "gem_ore")), + Cloud(Items.get("Cloud Ore"), new SpriteAnimation(SpriteType.Tile, "cloud_ore")); private final Item drop; public final SpriteAnimation sheet; @@ -42,11 +42,11 @@ public enum OreType { private Item getOre() { return drop.copy(); } - } + } protected OreTile(OreType o) { super((o == OreTile.OreType.Lapis ? "Lapis" : o == OreType.Cloud ? "Cloud Cactus" : o.name() + " Ore"), o.sheet); - this.type = o; + this.type = o; } public void render(Screen screen, Level level, int x, int y) { @@ -67,7 +67,7 @@ public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction at } public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if(Game.isMode("minicraft.settings.mode.creative")) + if (Game.isMode("minicraft.settings.mode.creative")) return false; // Go directly to hurt method if (item instanceof ToolItem) { ToolItem tool = (ToolItem) item; @@ -85,9 +85,9 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D return false; } - public Item getOre() { - return type.getOre(); - } + public Item getOre() { + return type.getOre(); + } public void hurt(Level level, int x, int y, int dmg) { int damage = level.getData(x, y) + dmg; @@ -110,7 +110,7 @@ public void hurt(Level level, int x, int y, int dmg) { } else { level.setData(x, y, damage); } - if (type.drop.equals(Items.get("gem"))){ + if (type.drop.equals(Items.get("gem"))) { AchievementsDisplay.setAchievement("minicraft.achievement.find_gem", true); } level.dropItem(x * 16 + 8, y * 16 + 8, count, type.getOre()); diff --git a/src/client/java/minicraft/level/tile/PathTile.java b/src/client/java/minicraft/level/tile/PathTile.java index dea91f486..a216813f6 100644 --- a/src/client/java/minicraft/level/tile/PathTile.java +++ b/src/client/java/minicraft/level/tile/PathTile.java @@ -13,30 +13,30 @@ import minicraft.util.AdvancementElement; public class PathTile extends Tile { - private static SpriteAnimation sprite = new SpriteAnimation(SpriteType.Tile, "path"); + private static SpriteAnimation sprite = new SpriteAnimation(SpriteType.Tile, "path"); - public PathTile(String name) { - super(name, sprite); - connectsToGrass = true; - maySpawn = true; - } + public PathTile(String name) { + super(name, sprite); + connectsToGrass = true; + maySpawn = true; + } - public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if (item instanceof ToolItem) { - ToolItem tool = (ToolItem) item; - if (tool.type == ToolType.Shovel) { - if (player.payStamina(4 - tool.level) && tool.payDurability()) { + public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { + if (item instanceof ToolItem) { + ToolItem tool = (ToolItem) item; + if (tool.type == ToolType.Shovel) { + if (player.payStamina(4 - tool.level) && tool.payDurability()) { int data = level.getData(xt, yt); - level.setTile(xt, yt, Tiles.get("Hole")); - Sound.play("monsterhurt"); - level.dropItem(xt * 16 + 8, yt * 16 + 8, Items.get("Dirt")); + level.setTile(xt, yt, Tiles.get("Hole")); + Sound.play("monsterhurt"); + level.dropItem(xt * 16 + 8, yt * 16 + 8, Items.get("Dirt")); AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.INSTANCE.trigger( new AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.ItemUsedOnTileTriggerConditionHandler.ItemUsedOnTileTriggerConditions( item, this, data, xt, yt, level.depth)); - return true; - } - } - } - return false; - } + return true; + } + } + } + return false; + } } diff --git a/src/client/java/minicraft/level/tile/RockTile.java b/src/client/java/minicraft/level/tile/RockTile.java index b5f7e69b7..ee78ced54 100644 --- a/src/client/java/minicraft/level/tile/RockTile.java +++ b/src/client/java/minicraft/level/tile/RockTile.java @@ -86,7 +86,7 @@ public void hurt(Level level, int x, int y, int dmg) { stone += random.nextInt(3) + 1; int coal = 1; - if(!Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { + if (!Settings.get("diff").equals("minicraft.settings.difficulty.hard")) { coal += 1; } diff --git a/src/client/java/minicraft/level/tile/SandTile.java b/src/client/java/minicraft/level/tile/SandTile.java index 2e2a036f8..07728dcd5 100644 --- a/src/client/java/minicraft/level/tile/SandTile.java +++ b/src/client/java/minicraft/level/tile/SandTile.java @@ -39,20 +39,20 @@ public boolean tick(Level level, int x, int y) { public void steppedOn(Level level, int x, int y, Entity entity) { if (entity instanceof Mob) { if (random.nextInt(3) == 0) { - int spawnX = entity.x - 8 + random.nextInt(5)-2; - int spawnY = entity.y - 8 + random.nextInt(5)-2; + int spawnX = entity.x - 8 + random.nextInt(5) - 2; + int spawnY = entity.y - 8 + random.nextInt(5) - 2; for (Direction dir : Direction.values()) { Tile neighbour = level.getTile(x + dir.getX(), y + dir.getY()); if (neighbour != null) { if (!(neighbour instanceof SandTile)) { // Particles only spawn on sand tiles. if (dir.getX() < 0) // Offsets - if (entity.x%16 < 8) spawnX += 8 - entity.x%16; + if (entity.x % 16 < 8) spawnX += 8 - entity.x % 16; if (dir.getX() > 0) - if (entity.x%16 > 7) spawnX -= entity.x%16 - 8; + if (entity.x % 16 > 7) spawnX -= entity.x % 16 - 8; if (dir.getY() < 0) - if (entity.y%16 < 8) spawnY += 8 - entity.y%16; + if (entity.y % 16 < 8) spawnY += 8 - entity.y % 16; if (dir.getY() > 0) - if (entity.y%16 > 7) spawnY -= entity.y%16 - 8; + if (entity.y % 16 > 7) spawnY -= entity.y % 16 - 8; } } } diff --git a/src/client/java/minicraft/level/tile/Tile.java b/src/client/java/minicraft/level/tile/Tile.java index fe52cf1e1..a13979448 100644 --- a/src/client/java/minicraft/level/tile/Tile.java +++ b/src/client/java/minicraft/level/tile/Tile.java @@ -55,67 +55,93 @@ protected Tile(String name, SpriteAnimation sprite) { } - /** This method is used by tiles to specify the default "data" they have in a level's data array. - Used for starting health, color/type of tile, etc. */ + /** + * This method is used by tiles to specify the default "data" they have in a level's data array. + * Used for starting health, color/type of tile, etc. + */ // At least, that was the idea at first... public int getDefaultData() { return 0; } - /** Render method, used in sub-classes */ + /** + * Render method, used in sub-classes + */ public void render(Screen screen, Level level, int x, int y) { sprite.render(screen, level, x, y); } - public boolean maySpawn() { return maySpawn; } + public boolean maySpawn() { + return maySpawn; + } - /** Returns if the player can walk on it, overrides in sub-classes */ + /** + * Returns if the player can walk on it, overrides in sub-classes + */ public boolean mayPass(Level level, int x, int y, Entity e) { return true; } - /** Gets the light radius of a tile, Bigger number = bigger circle */ + /** + * Gets the light radius of a tile, Bigger number = bigger circle + */ public int getLightRadius(Level level, int x, int y) { return 0; } /** * Hurt the tile with a specified amount of damage. - * @param level The level this happened on. - * @param x X pos of the tile. - * @param y Y pos of the tile. - * @param source The mob that damaged the tile. - * @param dmg Damage to taken. + * + * @param level The level this happened on. + * @param x X pos of the tile. + * @param y Y pos of the tile. + * @param source The mob that damaged the tile. + * @param dmg Damage to taken. * @param attackDir The direction of the player hitting. * @return If the damage was applied. */ - public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction attackDir) { return false; } + public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction attackDir) { + return false; + } /** * Hurt the tile with a specified amount of damage. + * * @param level The level this happened on. - * @param x X position of the tile. - * @param y Y position of the tile. - * @param dmg The damage taken. + * @param x X position of the tile. + * @param y Y position of the tile. + * @param dmg The damage taken. */ - public void hurt(Level level, int x, int y, int dmg) {} + public void hurt(Level level, int x, int y, int dmg) { + } - /** What happens when you run into the tile (ex: run into a cactus) */ - public void bumpedInto(Level level, int xt, int yt, Entity entity) {} + /** + * What happens when you run into the tile (ex: run into a cactus) + */ + public void bumpedInto(Level level, int xt, int yt, Entity entity) { + } - /** Update method */ - public boolean tick(Level level, int xt, int yt) { return false; } + /** + * Update method + */ + public boolean tick(Level level, int xt, int yt) { + return false; + } - /** What happens when you are inside the tile (ex: lava) */ - public void steppedOn(Level level, int xt, int yt, Entity entity) {} + /** + * What happens when you are inside the tile (ex: lava) + */ + public void steppedOn(Level level, int xt, int yt, Entity entity) { + } /** * Called when you hit an item on a tile (ex: Pickaxe on rock). - * @param level The level the player is on. - * @param xt X position of the player in tile coordinates (32x per tile). - * @param yt Y position of the player in tile coordinates (32px per tile). - * @param player The player who called this method. - * @param item The item the player is currently holding. + * + * @param level The level the player is on. + * @param xt X position of the player in tile coordinates (32x per tile). + * @param yt Y position of the player in tile coordinates (32px per tile). + * @param player The player who called this method. + * @param item The item the player is currently holding. * @param attackDir The direction of the player attacking. * @return Was the operation successful? */ @@ -126,17 +152,22 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D /** * Executed when the tile is exploded. * The call for this method is done just before the tiles are changed to exploded tiles. + * * @param level The level we are on. - * @param xt X position of the tile. - * @param yt Y position of the tile. + * @param xt X position of the tile. + * @param yt Y position of the tile. * @return true if successful. */ public boolean onExplode(Level level, int xt, int yt) { return false; } - /** Sees if the tile connects to a fluid. */ - public boolean connectsToLiquid() { return connectsToFluid; } + /** + * Sees if the tile connects to a fluid. + */ + public boolean connectsToLiquid() { + return connectsToFluid; + } public int getData(String data) { try { @@ -164,7 +195,7 @@ public static String getData(int depth, int x, int y) { int tiledata = curLevel.data[pos]; return lvlidx + ";" + pos + ";" + tileid + ";" + tiledata; - } catch(NullPointerException | IndexOutOfBoundsException ignored) { + } catch (NullPointerException | IndexOutOfBoundsException ignored) { } return ""; @@ -178,5 +209,7 @@ public boolean equals(Object other) { } @Override - public int hashCode() { return name.hashCode(); } + public int hashCode() { + return name.hashCode(); + } } diff --git a/src/client/java/minicraft/level/tile/Tiles.java b/src/client/java/minicraft/level/tile/Tiles.java index d138b227a..9f9653e3c 100644 --- a/src/client/java/minicraft/level/tile/Tiles.java +++ b/src/client/java/minicraft/level/tile/Tiles.java @@ -1,12 +1,12 @@ package minicraft.level.tile; import minicraft.core.CrashHandler; -import minicraft.level.tile.farming.HeavenlyBerriesTile; -import minicraft.level.tile.farming.HellishBerriesTile; -import minicraft.level.tile.farming.TomatoTile; import minicraft.level.tile.farming.CarrotTile; import minicraft.level.tile.farming.FarmTile; +import minicraft.level.tile.farming.HeavenlyBerriesTile; +import minicraft.level.tile.farming.HellishBerriesTile; import minicraft.level.tile.farming.PotatoTile; +import minicraft.level.tile.farming.TomatoTile; import minicraft.level.tile.farming.WheatTile; import minicraft.util.Logging; @@ -24,81 +24,81 @@ public final class Tiles { public static void initTileList() { Logging.TILES.debug("Initializing tile list..."); - tiles.put((short)0, new GrassTile("Grass")); - tiles.put((short)1, new DirtTile("Dirt")); - tiles.put((short)2, new FlowerTile("Flower")); - tiles.put((short)3, new HoleTile("Hole")); - tiles.put((short)4, new StairsTile("Stairs Up", true)); - tiles.put((short)5, new StairsTile("Stairs Down", false)); - tiles.put((short)6, new WaterTile("Water")); + tiles.put((short) 0, new GrassTile("Grass")); + tiles.put((short) 1, new DirtTile("Dirt")); + tiles.put((short) 2, new FlowerTile("Flower")); + tiles.put((short) 3, new HoleTile("Hole")); + tiles.put((short) 4, new StairsTile("Stairs Up", true)); + tiles.put((short) 5, new StairsTile("Stairs Down", false)); + tiles.put((short) 6, new WaterTile("Water")); // This is out of order because of lava buckets - tiles.put((short)17, new LavaTile("Lava")); - - tiles.put((short)7, new RockTile("Rock")); - tiles.put((short)8, new TreeTile("Tree")); - tiles.put((short)9, new SaplingTile("Tree Sapling", Tiles.get("Grass"), Tiles.get("Tree"))); - tiles.put((short)10, new SandTile("Sand")); - tiles.put((short)11, new CactusTile("Cactus")); - tiles.put((short)12, new SaplingTile("Cactus Sapling", Tiles.get("Sand"), Tiles.get("Cactus"))); - tiles.put((short)13, new OreTile(OreTile.OreType.Iron)); - tiles.put((short)14, new OreTile(OreTile.OreType.Gold)); - tiles.put((short)15, new OreTile(OreTile.OreType.Gem)); - tiles.put((short)16, new OreTile(OreTile.OreType.Lapis)); - tiles.put((short)18, new LavaBrickTile("Lava Brick")); - tiles.put((short)19, new ExplodedTile("Explode")); - tiles.put((short)20, new FarmTile("Farmland")); - tiles.put((short)21, new WheatTile("Wheat")); - tiles.put((short)22, new HardRockTile("Hard Rock")); - tiles.put((short)23, new InfiniteFallTile("Infinite Fall")); - tiles.put((short)24, new CloudTile("Cloud")); - tiles.put((short)25, new OreTile(OreTile.OreType.Cloud)); - tiles.put((short)26, new DoorTile(Tile.Material.Wood)); - tiles.put((short)27, new DoorTile(Tile.Material.Stone)); - tiles.put((short)28, new DoorTile(Tile.Material.Obsidian)); - tiles.put((short)29, new FloorTile(Tile.Material.Wood)); - tiles.put((short)30, new FloorTile(Tile.Material.Stone)); - tiles.put((short)31, new FloorTile(Tile.Material.Obsidian)); - tiles.put((short)32, new WallTile(Tile.Material.Wood)); - tiles.put((short)33, new WallTile(Tile.Material.Stone)); - tiles.put((short)34, new WallTile(Tile.Material.Obsidian)); - tiles.put((short)35, new WoolTile(WoolTile.WoolType.NORMAL)); - tiles.put((short)36, new PathTile("Path")); - tiles.put((short)37, new WoolTile(WoolTile.WoolType.RED)); - tiles.put((short)38, new WoolTile(WoolTile.WoolType.BLUE)); - tiles.put((short)39, new WoolTile(WoolTile.WoolType.GREEN)); - tiles.put((short)40, new WoolTile(WoolTile.WoolType.YELLOW)); - tiles.put((short)41, new WoolTile(WoolTile.WoolType.BLACK)); - tiles.put((short)42, new PotatoTile("Potato")); - tiles.put((short)43, new MaterialTile(Tile.Material.Stone)); - tiles.put((short)44, new MaterialTile(Tile.Material.Obsidian)); - tiles.put((short)45, new DecorTile(Tile.Material.Stone)); - tiles.put((short)46, new DecorTile(Tile.Material.Obsidian)); - tiles.put((short)47, new BossWallTile()); - tiles.put((short)48, new BossFloorTile()); - tiles.put((short)49, new BossDoorTile()); - tiles.put((short)50, new TomatoTile("Tomato")); - tiles.put((short)51, new CarrotTile("Carrot")); - tiles.put((short)52, new HeavenlyBerriesTile("Heavenly Berries")); - tiles.put((short)53, new HellishBerriesTile("Hellish Berries")); + tiles.put((short) 17, new LavaTile("Lava")); + + tiles.put((short) 7, new RockTile("Rock")); + tiles.put((short) 8, new TreeTile("Tree")); + tiles.put((short) 9, new SaplingTile("Tree Sapling", Tiles.get("Grass"), Tiles.get("Tree"))); + tiles.put((short) 10, new SandTile("Sand")); + tiles.put((short) 11, new CactusTile("Cactus")); + tiles.put((short) 12, new SaplingTile("Cactus Sapling", Tiles.get("Sand"), Tiles.get("Cactus"))); + tiles.put((short) 13, new OreTile(OreTile.OreType.Iron)); + tiles.put((short) 14, new OreTile(OreTile.OreType.Gold)); + tiles.put((short) 15, new OreTile(OreTile.OreType.Gem)); + tiles.put((short) 16, new OreTile(OreTile.OreType.Lapis)); + tiles.put((short) 18, new LavaBrickTile("Lava Brick")); + tiles.put((short) 19, new ExplodedTile("Explode")); + tiles.put((short) 20, new FarmTile("Farmland")); + tiles.put((short) 21, new WheatTile("Wheat")); + tiles.put((short) 22, new HardRockTile("Hard Rock")); + tiles.put((short) 23, new InfiniteFallTile("Infinite Fall")); + tiles.put((short) 24, new CloudTile("Cloud")); + tiles.put((short) 25, new OreTile(OreTile.OreType.Cloud)); + tiles.put((short) 26, new DoorTile(Tile.Material.Wood)); + tiles.put((short) 27, new DoorTile(Tile.Material.Stone)); + tiles.put((short) 28, new DoorTile(Tile.Material.Obsidian)); + tiles.put((short) 29, new FloorTile(Tile.Material.Wood)); + tiles.put((short) 30, new FloorTile(Tile.Material.Stone)); + tiles.put((short) 31, new FloorTile(Tile.Material.Obsidian)); + tiles.put((short) 32, new WallTile(Tile.Material.Wood)); + tiles.put((short) 33, new WallTile(Tile.Material.Stone)); + tiles.put((short) 34, new WallTile(Tile.Material.Obsidian)); + tiles.put((short) 35, new WoolTile(WoolTile.WoolType.NORMAL)); + tiles.put((short) 36, new PathTile("Path")); + tiles.put((short) 37, new WoolTile(WoolTile.WoolType.RED)); + tiles.put((short) 38, new WoolTile(WoolTile.WoolType.BLUE)); + tiles.put((short) 39, new WoolTile(WoolTile.WoolType.GREEN)); + tiles.put((short) 40, new WoolTile(WoolTile.WoolType.YELLOW)); + tiles.put((short) 41, new WoolTile(WoolTile.WoolType.BLACK)); + tiles.put((short) 42, new PotatoTile("Potato")); + tiles.put((short) 43, new MaterialTile(Tile.Material.Stone)); + tiles.put((short) 44, new MaterialTile(Tile.Material.Obsidian)); + tiles.put((short) 45, new DecorTile(Tile.Material.Stone)); + tiles.put((short) 46, new DecorTile(Tile.Material.Obsidian)); + tiles.put((short) 47, new BossWallTile()); + tiles.put((short) 48, new BossFloorTile()); + tiles.put((short) 49, new BossDoorTile()); + tiles.put((short) 50, new TomatoTile("Tomato")); + tiles.put((short) 51, new CarrotTile("Carrot")); + tiles.put((short) 52, new HeavenlyBerriesTile("Heavenly Berries")); + tiles.put((short) 53, new HellishBerriesTile("Hellish Berries")); // WARNING: don't use this tile for anything! - tiles.put((short)255, new ConnectTile()); + tiles.put((short) 255, new ConnectTile()); - for(short i = 0; i < 256; i++) { - if(tiles.get(i) == null) continue; - tiles.get(i).id = (short)i; + for (short i = 0; i < 256; i++) { + if (tiles.get(i) == null) continue; + tiles.get(i).id = (short) i; } } static void add(int id, Tile tile) { - tiles.put((short)id, tile); + tiles.put((short) id, tile); Logging.TILES.debug("Adding " + tile.name + " to tile list with id " + id); tile.id = (short) id; } static { - for(int i = 0; i < 32768; i++) + for (int i = 0; i < 32768; i++) oldids.add(null); oldids.set(0, "grass"); @@ -190,6 +190,7 @@ static void add(int id, Tile tile) { } private static int overflowCheck = 0; + public static Tile get(String name) { //System.out.println("Getting from tile list: " + name); @@ -197,7 +198,7 @@ public static Tile get(String name) { overflowCheck++; - if(overflowCheck > 50) { + if (overflowCheck > 50) { CrashHandler.crashHandle(new StackOverflowError("Tiles#get: " + name), new CrashHandler.ErrorInfo("Tile fetching Stacking", CrashHandler.ErrorInfo.ErrorType.SERIOUS, "STACKOVERFLOW prevented in Tiles.get(), on: " + name)); } @@ -207,29 +208,29 @@ public static Tile get(String name) { Tile getting = null; boolean isTorch = false; - if(name.startsWith("TORCH")) { + if (name.startsWith("TORCH")) { isTorch = true; name = name.substring(6); // Cuts off torch prefix. } - if(name.contains("_")) { + if (name.contains("_")) { name = name.substring(0, name.indexOf("_")); } - for(Tile t: tiles.values()) { - if(t == null) continue; - if(t.name.equals(name)) { + for (Tile t : tiles.values()) { + if (t == null) continue; + if (t.name.equals(name)) { getting = t; break; } } - if(getting == null) { + if (getting == null) { Logging.TILES.info("Invalid tile requested: " + name); - getting = tiles.get((short)0); + getting = tiles.get((short) 0); } - if(isTorch) { + if (isTorch) { getting = TorchTile.getTorchTile(getting); } @@ -239,26 +240,24 @@ public static Tile get(String name) { public static Tile get(int id) { //System.out.println("Requesting tile by id: " + id); - if(id < 0) id += 32768; + if (id < 0) id += 32768; - if(tiles.get((short)id) != null) { - return tiles.get((short)id); - } - else if(id >= 32767) { + if (tiles.get((short) id) != null) { + return tiles.get((short) id); + } else if (id >= 32767) { return TorchTile.getTorchTile(get(id - 32767)); - } - else { + } else { Logging.TILES.info("Unknown tile id requested: " + id); - return tiles.get((short)0); + return tiles.get((short) 0); } } public static boolean containsTile(int id) { - return tiles.get((short)id) != null; + return tiles.get((short) id) != null; } public static String getName(String descriptName) { - if(!descriptName.contains("_")) return descriptName; + if (!descriptName.contains("_")) return descriptName; int data; String[] parts = descriptName.split("_"); descriptName = parts[0]; diff --git a/src/client/java/minicraft/level/tile/TorchTile.java b/src/client/java/minicraft/level/tile/TorchTile.java index 52353ac45..bb8dbd840 100644 --- a/src/client/java/minicraft/level/tile/TorchTile.java +++ b/src/client/java/minicraft/level/tile/TorchTile.java @@ -18,11 +18,11 @@ public class TorchTile extends Tile { public static TorchTile getTorchTile(Tile onTile) { int id = onTile.id & 0xFFFF; - if(id < 16384) id += 16384; + if (id < 16384) id += 16384; else Logger.tag("TorchTile").info("Tried to place torch on torch tile..."); - if(Tiles.containsTile(id)) - return (TorchTile)Tiles.get(id); + if (Tiles.containsTile(id)) + return (TorchTile) Tiles.get(id); else { TorchTile tile = new TorchTile(onTile); Tiles.add(id, tile); @@ -31,7 +31,7 @@ public static TorchTile getTorchTile(Tile onTile) { } private TorchTile(Tile onType) { - super("Torch "+ onType.name, new SpriteAnimation(SpriteType.Tile, "torch")); + super("Torch " + onType.name, new SpriteAnimation(SpriteType.Tile, "torch")); this.onType = onType; this.connectsToSand = onType.connectsToSand; this.connectsToGrass = onType.connectsToGrass; @@ -48,11 +48,11 @@ public int getLightRadius(Level level, int x, int y) { } public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if(item instanceof PowerGloveItem) { + if (item instanceof PowerGloveItem) { int data = level.getData(xt, yt); level.setTile(xt, yt, this.onType); Sound.play("monsterhurt"); - level.dropItem(xt*16+8, yt*16+8, Items.get("Torch")); + level.dropItem(xt * 16 + 8, yt * 16 + 8, Items.get("Torch")); AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.INSTANCE.trigger( new AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.ItemUsedOnTileTriggerConditionHandler.ItemUsedOnTileTriggerConditions( item, this, data, xt, yt, level.depth)); diff --git a/src/client/java/minicraft/level/tile/TreeTile.java b/src/client/java/minicraft/level/tile/TreeTile.java index c4e5c8f3a..d9e68cf6d 100644 --- a/src/client/java/minicraft/level/tile/TreeTile.java +++ b/src/client/java/minicraft/level/tile/TreeTile.java @@ -21,11 +21,6 @@ import minicraft.screen.AchievementsDisplay; import minicraft.util.AdvancementElement; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Random; - public class TreeTile extends Tile { private static final LinkedSprite oakSprite = new LinkedSprite(SpriteType.Tile, "oak"); private static final LinkedSprite oakSpriteFull = new LinkedSprite(SpriteType.Tile, "oak_full"); @@ -129,7 +124,7 @@ public boolean hurt(Level level, int x, int y, Mob source, int dmg, Direction at @Override public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if(Game.isMode("minicraft.settings.mode.creative")) + if (Game.isMode("minicraft.settings.mode.creative")) return false; // Go directly to hurt method if (item instanceof ToolItem) { ToolItem tool = (ToolItem) item; @@ -155,13 +150,13 @@ public void hurt(Level level, int x, int y, int dmg) { int treeHealth = 20; if (Game.isMode("minicraft.settings.mode.creative")) dmg = damage = treeHealth; - level.add(new SmashParticle(x*16, y*16)); + level.add(new SmashParticle(x * 16, y * 16)); Sound.play("monsterhurt"); level.add(new TextParticle("" + dmg, x * 16 + 8, y * 16 + 8, Color.RED)); if (damage >= treeHealth) { level.dropItem(x * 16 + 8, y * 16 + 8, 1, 3, Items.get("Wood")); - level.dropItem(x * 16 + 8, y * 16 + 8, 0, 2, Items.get("Acorn")); + level.dropItem(x * 16 + 8, y * 16 + 8, 0, 2, Items.get("Acorn")); level.setTile(x, y, Tiles.get("Grass")); AchievementsDisplay.setAchievement("minicraft.achievement.woodcutter", true); } else { diff --git a/src/client/java/minicraft/level/tile/WallTile.java b/src/client/java/minicraft/level/tile/WallTile.java index df986e62a..48222f1da 100644 --- a/src/client/java/minicraft/level/tile/WallTile.java +++ b/src/client/java/minicraft/level/tile/WallTile.java @@ -30,14 +30,23 @@ public class WallTile extends Tile { private static final String obrickMsg = "minicraft.notification.defeat_air_wizard_first"; protected Material type; - protected WallTile(Material type) { this(type, null); } + protected WallTile(Material type) { + this(type, null); + } + protected WallTile(Material type, String name) { super(type.name() + " " + (name == null ? "Wall" : name), null); this.type = type; switch (type) { - case Wood: sprite = wood; break; - case Stone: sprite = stone; break; - case Obsidian: sprite = obsidian; break; + case Wood: + sprite = wood; + break; + case Stone: + sprite = stone; + break; + case Obsidian: + sprite = obsidian; + break; } } diff --git a/src/client/java/minicraft/level/tile/farming/CarrotTile.java b/src/client/java/minicraft/level/tile/farming/CarrotTile.java index 542fee7d6..de8cfc7b4 100644 --- a/src/client/java/minicraft/level/tile/farming/CarrotTile.java +++ b/src/client/java/minicraft/level/tile/farming/CarrotTile.java @@ -7,7 +7,7 @@ import minicraft.level.tile.Tiles; public class CarrotTile extends CropTile { - private final LinkedSprite[] spritStages = new LinkedSprite[] { + private final LinkedSprite[] spritStages = new LinkedSprite[]{ new LinkedSprite(SpriteType.Tile, "carrot_stage0"), new LinkedSprite(SpriteType.Tile, "carrot_stage1"), new LinkedSprite(SpriteType.Tile, "carrot_stage2"), diff --git a/src/client/java/minicraft/level/tile/farming/CropTile.java b/src/client/java/minicraft/level/tile/farming/CropTile.java index 89b368dd7..6291fa75b 100644 --- a/src/client/java/minicraft/level/tile/farming/CropTile.java +++ b/src/client/java/minicraft/level/tile/farming/CropTile.java @@ -86,13 +86,13 @@ public boolean tick(Level level, int xt, int yt) { if (downRight) points *= 0.98125; } - if (random.nextInt((int) (100/points) + 1) < (fertilization/30 + 1)) // fertilization >= 0 + if (random.nextInt((int) (100 / points) + 1) < (fertilization / 30 + 1)) // fertilization >= 0 level.setData(xt, yt, data = (data & ~(maxAge << 3)) + ((stage + 1) << 3)); // Incrementing the stage by 1. successful = true; } if (fertilization > 0) { - level.setData(xt, yt, (data & (0b111 + (maxAge << 3))) + ((fertilization - 1) << (3 + (maxAge + 1)/2))); + level.setData(xt, yt, (data & (0b111 + (maxAge << 3))) + ((fertilization - 1) << (3 + (maxAge + 1) / 2))); successful = true; } @@ -107,8 +107,8 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D ((StackableItem) item).count--; Random random = new Random(); for (int i = 0; i < 2; ++i) { - double x = (double)xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; - double y = (double)yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double x = (double) xt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; + double y = (double) yt * 16 + 8 + (random.nextGaussian() * 0.5) * 8; level.add(new Particle((int) x, (int) y, 120 + random.nextInt(21) - 40, particleSprite)); } int fertilization = getFertilization(level.getData(xt, yt)); @@ -130,7 +130,9 @@ public boolean interact(Level level, int xt, int yt, Player player, Item item, D return super.interact(level, xt, yt, player, item, attackDir); } - /** Default harvest method, used for everything that doesn't really need any special behavior. */ + /** + * Default harvest method, used for everything that doesn't really need any special behavior. + */ protected void harvest(Level level, int x, int y, Entity entity) { int data = level.getData(x, y); int age = (data >> 3) & maxAge; @@ -145,7 +147,7 @@ protected void harvest(Level level, int x, int y, Entity entity) { } if (age == maxAge && entity instanceof Player) { - ((Player)entity).addScore(random.nextInt(5) + 1); + ((Player) entity).addScore(random.nextInt(5) + 1); } // Play sound. @@ -155,7 +157,7 @@ protected void harvest(Level level, int x, int y, Entity entity) { } public int getFertilization(int data) { - return data >> (3 + (maxAge + 1)/2); + return data >> (3 + (maxAge + 1) / 2); } /** @@ -170,6 +172,6 @@ public void fertilize(Level level, int x, int y, int amount) { if (fertilization < 0) fertilization = 0; if (fertilization > 511) fertilization = 511; // The maximum possible value to be reached. // If this value exceeds 511, the final value would be greater than the hard maximum value that short can be. - level.setData(x, y, (data & (0b111 + (maxAge << 3))) + (fertilization << (3 + (maxAge + 1)/2))); + level.setData(x, y, (data & (0b111 + (maxAge << 3))) + (fertilization << (3 + (maxAge + 1) / 2))); } } diff --git a/src/client/java/minicraft/level/tile/farming/FarmTile.java b/src/client/java/minicraft/level/tile/farming/FarmTile.java index c28bef21e..6205714dd 100644 --- a/src/client/java/minicraft/level/tile/farming/FarmTile.java +++ b/src/client/java/minicraft/level/tile/farming/FarmTile.java @@ -2,8 +2,6 @@ import minicraft.core.io.Sound; import minicraft.entity.Direction; -import minicraft.entity.Entity; -import minicraft.entity.ItemEntity; import minicraft.entity.mob.Player; import minicraft.gfx.Screen; import minicraft.gfx.SpriteAnimation; @@ -26,28 +24,29 @@ public class FarmTile extends Tile { public FarmTile(String name) { super(name, sprite); } + protected FarmTile(String name, SpriteAnimation sprite) { super(name, sprite); } - @Override - public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { - if (item instanceof ToolItem) { - ToolItem tool = (ToolItem) item; - if (tool.type == ToolType.Shovel) { - if (player.payStamina(4 - tool.level) && tool.payDurability()) { + @Override + public boolean interact(Level level, int xt, int yt, Player player, Item item, Direction attackDir) { + if (item instanceof ToolItem) { + ToolItem tool = (ToolItem) item; + if (tool.type == ToolType.Shovel) { + if (player.payStamina(4 - tool.level) && tool.payDurability()) { int data = level.getData(xt, yt); - level.setTile(xt, yt, Tiles.get("Dirt")); - Sound.play("monsterhurt"); + level.setTile(xt, yt, Tiles.get("Dirt")); + Sound.play("monsterhurt"); AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.INSTANCE.trigger( new AdvancementElement.AdvancementTrigger.ItemUsedOnTileTrigger.ItemUsedOnTileTriggerConditionHandler.ItemUsedOnTileTriggerConditions( item, this, data, xt, yt, level.depth)); - return true; - } - } - } - return false; - } + return true; + } + } + } + return false; + } @Override public boolean tick(Level level, int xt, int yt) { diff --git a/src/client/java/minicraft/level/tile/farming/HeavenlyBerriesTile.java b/src/client/java/minicraft/level/tile/farming/HeavenlyBerriesTile.java index c4fc57100..70b7e3fc8 100644 --- a/src/client/java/minicraft/level/tile/farming/HeavenlyBerriesTile.java +++ b/src/client/java/minicraft/level/tile/farming/HeavenlyBerriesTile.java @@ -6,7 +6,7 @@ import minicraft.level.tile.Tiles; public class HeavenlyBerriesTile extends CropTile { - private final SpriteLinker.LinkedSprite[] spritStages = new SpriteLinker.LinkedSprite[] { + private final SpriteLinker.LinkedSprite[] spritStages = new SpriteLinker.LinkedSprite[]{ new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "heavenly_berries_stage0"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "heavenly_berries_stage1"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "heavenly_berries_stage2"), diff --git a/src/client/java/minicraft/level/tile/farming/HellishBerriesTile.java b/src/client/java/minicraft/level/tile/farming/HellishBerriesTile.java index 6d4f7bcb5..bbad34091 100644 --- a/src/client/java/minicraft/level/tile/farming/HellishBerriesTile.java +++ b/src/client/java/minicraft/level/tile/farming/HellishBerriesTile.java @@ -6,7 +6,7 @@ import minicraft.level.tile.Tiles; public class HellishBerriesTile extends CropTile { - private final SpriteLinker.LinkedSprite[] spritStages = new SpriteLinker.LinkedSprite[] { + private final SpriteLinker.LinkedSprite[] spritStages = new SpriteLinker.LinkedSprite[]{ new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "hellish_berries_stage0"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "hellish_berries_stage1"), new SpriteLinker.LinkedSprite(SpriteLinker.SpriteType.Tile, "hellish_berries_stage2"), diff --git a/src/client/java/minicraft/level/tile/farming/PotatoTile.java b/src/client/java/minicraft/level/tile/farming/PotatoTile.java index 9a5c44798..08b757173 100644 --- a/src/client/java/minicraft/level/tile/farming/PotatoTile.java +++ b/src/client/java/minicraft/level/tile/farming/PotatoTile.java @@ -7,7 +7,7 @@ import minicraft.level.tile.Tiles; public class PotatoTile extends CropTile { - private final LinkedSprite[] spritStages = new LinkedSprite[] { + private final LinkedSprite[] spritStages = new LinkedSprite[]{ new LinkedSprite(SpriteType.Tile, "potato_stage0"), new LinkedSprite(SpriteType.Tile, "potato_stage1"), new LinkedSprite(SpriteType.Tile, "potato_stage2"), @@ -16,15 +16,15 @@ public class PotatoTile extends CropTile { new LinkedSprite(SpriteType.Tile, "potato_stage5") }; - public PotatoTile(String name) { - super(name, null); - } + public PotatoTile(String name) { + super(name, null); + } - @Override - public void render(Screen screen, Level level, int x, int y) { - int age = (level.getData(x, y) >> 3) & maxAge; - Tiles.get("Farmland").render(screen, level, x, y); + @Override + public void render(Screen screen, Level level, int x, int y) { + int age = (level.getData(x, y) >> 3) & maxAge; + Tiles.get("Farmland").render(screen, level, x, y); int stage = (int) ((float) age / maxAge * 5); screen.render(x * 16, y * 16, spritStages[stage]); - } + } } diff --git a/src/client/java/minicraft/level/tile/farming/TomatoTile.java b/src/client/java/minicraft/level/tile/farming/TomatoTile.java index a8329ae63..1abe88c04 100644 --- a/src/client/java/minicraft/level/tile/farming/TomatoTile.java +++ b/src/client/java/minicraft/level/tile/farming/TomatoTile.java @@ -7,7 +7,7 @@ import minicraft.level.tile.Tiles; public class TomatoTile extends CropTile { - private final LinkedSprite[] spritStages = new LinkedSprite[] { + private final LinkedSprite[] spritStages = new LinkedSprite[]{ new LinkedSprite(SpriteType.Tile, "tomato_stage0"), new LinkedSprite(SpriteType.Tile, "tomato_stage1"), new LinkedSprite(SpriteType.Tile, "tomato_stage2"), diff --git a/src/client/java/minicraft/level/tile/farming/WheatTile.java b/src/client/java/minicraft/level/tile/farming/WheatTile.java index 39f585bf4..b56d751e3 100644 --- a/src/client/java/minicraft/level/tile/farming/WheatTile.java +++ b/src/client/java/minicraft/level/tile/farming/WheatTile.java @@ -7,7 +7,7 @@ import minicraft.level.tile.Tiles; public class WheatTile extends CropTile { - private final LinkedSprite[] spritStages = new LinkedSprite[] { + private final LinkedSprite[] spritStages = new LinkedSprite[]{ new LinkedSprite(SpriteType.Tile, "wheat_stage0"), new LinkedSprite(SpriteType.Tile, "wheat_stage1"), new LinkedSprite(SpriteType.Tile, "wheat_stage2"), diff --git a/src/client/java/minicraft/network/Analytics.java b/src/client/java/minicraft/network/Analytics.java index d922454ef..94222a2a4 100644 --- a/src/client/java/minicraft/network/Analytics.java +++ b/src/client/java/minicraft/network/Analytics.java @@ -50,9 +50,14 @@ public enum Analytics { this.token = token; } - @Nullable public Future> ping() { return ping(1); } - @Nullable public Future> ping(int value) { - final String url = "https://pingdat.io?t="+token+"&v="+value; + @Nullable + public Future> ping() { + return ping(1); + } + + @Nullable + public Future> ping(int value) { + final String url = "https://pingdat.io?t=" + token + "&v=" + value; return Unirest.get(url).asEmptyAsync(new Callback() { @Override diff --git a/src/client/java/minicraft/network/MinicraftProtocol.java b/src/client/java/minicraft/network/MinicraftProtocol.java index 044e86f2f..d5473b788 100644 --- a/src/client/java/minicraft/network/MinicraftProtocol.java +++ b/src/client/java/minicraft/network/MinicraftProtocol.java @@ -5,12 +5,12 @@ import java.util.List; public interface MinicraftProtocol { - + int PORT = 4225; - + enum InputType { INVALID, PING, USERNAMES, LOGIN, GAME, INIT, LOAD, TILES, ENTITIES, TILE, ENTITY, PLAYER, MOVE, ADD, REMOVE, DISCONNECT, SAVE, NOTIFY, INTERACT, PUSH, PICKUP, CHESTIN, CHESTOUT, ADDITEMS, BED, POTION, HURT, DIE, RESPAWN, DROP, STAMINA, SHIRT, STOPFISHING; - + public static final InputType[] values = InputType.values(); public static final List serverOnly = Arrays.asList(INIT, TILES, ENTITIES, ADD, REMOVE, HURT, GAME, ADDITEMS, STAMINA, STOPFISHING); public static final List entityUpdates = Arrays.asList(ENTITY, ADD, REMOVE); diff --git a/src/client/java/minicraft/network/Network.java b/src/client/java/minicraft/network/Network.java index ff181f41c..e179f00e8 100644 --- a/src/client/java/minicraft/network/Network.java +++ b/src/client/java/minicraft/network/Network.java @@ -16,7 +16,8 @@ import java.util.Random; public class Network extends Game { - private Network() {} + private Network() { + } private static final Random random = new Random(); @@ -24,7 +25,9 @@ private Network() {} @Nullable - public static VersionInfo getLatestVersion() { return latestVersion; } + public static VersionInfo getLatestVersion() { + return latestVersion; + } public static void findLatestVersion(Action callback) { new Thread(() -> { @@ -49,9 +52,9 @@ public static void findLatestVersion(Action callback) { @Nullable public static Entity getEntity(int eid) { - for (Level level: levels) { + for (Level level : levels) { if (level == null) continue; - for (Entity e: level.getEntityArray()) + for (Entity e : level.getEntityArray()) if (e.eid == eid) return e; } @@ -77,9 +80,9 @@ public static boolean idIsAvailable(int eid) { if (eid == 0) return false; // This is reserved for the main player... kind of... if (eid < 0) return false; // ID's must be positive numbers. - for (Level level: levels) { + for (Level level : levels) { if (level == null) continue; - for (Entity e: level.getEntityArray()) { + for (Entity e : level.getEntityArray()) { if (e.eid == eid) return false; } diff --git a/src/client/java/minicraft/saveload/LegacyLoad.java b/src/client/java/minicraft/saveload/LegacyLoad.java index 46dcb4f5b..b902c3775 100644 --- a/src/client/java/minicraft/saveload/LegacyLoad.java +++ b/src/client/java/minicraft/saveload/LegacyLoad.java @@ -112,7 +112,8 @@ public void loadFromFile(String filename) { try { br = new BufferedReader(new FileReader(filename)); - String curLine;StringBuilder total = new StringBuilder(); + String curLine; + StringBuilder total = new StringBuilder(); ArrayList curData; while ((curLine = br.readLine()) != null) total.append(curLine); @@ -166,8 +167,8 @@ protected void updateUnlocks(File file) { try { java.io.BufferedWriter writer = new java.io.BufferedWriter(new java.io.FileWriter(path)); - for (String unlock: data) { - writer.write(","+unlock); + for (String unlock : data) { + writer.write("," + unlock); } writer.flush(); writer.close(); @@ -195,8 +196,7 @@ public void loadGame(String filename) { Settings.setIdx("diff", Integer.parseInt(data.get(3))); AirWizard.beaten = Boolean.parseBoolean(data.get(4)); } - } - else { + } else { if (data.size() == 5) { worldVer = new Version("1.9"); Updater.setTime(Integer.parseInt(data.get(0))); @@ -256,7 +256,7 @@ public void loadPlayer(String filename, Player player) { if (data.size() >= 14) { if (worldVer == null) worldVer = new Version("1.9.1-pre1"); player.armorDamageBuffer = Integer.parseInt(data.get(13)); - player.curArmor = (ArmorItem)Items.get(data.get(14)); + player.curArmor = (ArmorItem) Items.get(data.get(14)); } else player.armor = 0; Game.currentLevel = Integer.parseInt(data.get(8)); @@ -276,8 +276,7 @@ public void loadPlayer(String filename, Player player) { mode = Integer.parseInt(modedata.substring(0, modedata.indexOf(";"))); if (mode == 4) Updater.scoreTime = Integer.parseInt(modedata.substring(modedata.indexOf(";") + 1)); - } - else { + } else { mode = Integer.parseInt(modedata); if (mode == 4) Updater.scoreTime = 300; } @@ -287,7 +286,7 @@ public void loadPlayer(String filename, Player player) { boolean hasEffects; int potionIdx = 10; if (oldSave) { - hasEffects = data.size() > 10 && data.get(data.size()-2).contains("PotionEffects["); + hasEffects = data.size() > 10 && data.get(data.size() - 2).contains("PotionEffects["); potionIdx = data.size() - 2; } else hasEffects = !data.get(10).equals("PotionEffects[]"); // Newer save @@ -303,9 +302,9 @@ public void loadPlayer(String filename, Player player) { } } - String colors = data.get(oldSave ? data.size() -1 : 11).replace("[", "").replace("]", ""); + String colors = data.get(oldSave ? data.size() - 1 : 11).replace("[", "").replace("]", ""); String[] color = colors.split(";"); - player.shirtColor = Integer.parseInt(color[0]+color[1]+color[2]); + player.shirtColor = Integer.parseInt(color[0] + color[1] + color[2]); } public void loadInventory(String filename, Inventory inventory) { @@ -330,7 +329,7 @@ public void loadItemToInventory(String item, Inventory inventory) { if (item.contains(";")) { String[] curData = item.split(";"); String itemName = curData[0]; - if(oldSave) itemName = subOldName(itemName); + if (oldSave) itemName = subOldName(itemName); //System.out.println("Item to fetch: " + itemName + "; count=" + curData[1]); Item newItem = Items.get(itemName); @@ -379,23 +378,24 @@ public void loadEntities(String filename, Player player) { int mobLvl = 0; try { if (Class.forName("EnemyMob").isAssignableFrom(Class.forName(entityName))) - mobLvl = Integer.parseInt(info.get(info.size()-2)); - } catch (ClassNotFoundException ignored) {} + mobLvl = Integer.parseInt(info.get(info.size() - 2)); + } catch (ClassNotFoundException ignored) { + } Entity newEntity = getEntity(entityName, player, mobLvl); if (newEntity != null) { // the method never returns null, but... int currentlevel; if (newEntity instanceof Mob) { - Mob mob = (Mob)newEntity; + Mob mob = (Mob) newEntity; mob.health = Integer.parseInt(info.get(2)); - currentlevel = Integer.parseInt(info.get(info.size()-1)); + currentlevel = Integer.parseInt(info.get(info.size() - 1)); World.levels[currentlevel].add(mob, x, y); } else if (newEntity instanceof Chest) { - Chest chest = (Chest)newEntity; + Chest chest = (Chest) newEntity; boolean isDeathChest = chest instanceof DeathChest; boolean isDungeonChest = chest instanceof DungeonChest; - List chestInfo = info.subList(2, info.size()-1); + List chestInfo = info.subList(2, info.size() - 1); int endIdx = chestInfo.size() - (isDeathChest || isDungeonChest ? 1 : 0); for (int idx = 0; idx < endIdx; idx++) { @@ -406,13 +406,13 @@ public void loadEntities(String filename, Player player) { } if (isDeathChest) { - ((DeathChest)chest).time = Integer.parseInt(chestInfo.get(chestInfo.size()-1).replace("tl;", "")); // "tl;" is only for old save support + ((DeathChest) chest).time = Integer.parseInt(chestInfo.get(chestInfo.size() - 1).replace("tl;", "")); // "tl;" is only for old save support } else if (isDungeonChest) { - ((DungeonChest)chest).setLocked(Boolean.parseBoolean(chestInfo.get(chestInfo.size()-1))); + ((DungeonChest) chest).setLocked(Boolean.parseBoolean(chestInfo.get(chestInfo.size() - 1))); } currentlevel = Integer.parseInt(info.get(info.size() - 1)); - World.levels[currentlevel].add(chest instanceof DeathChest ? chest : chest instanceof DungeonChest ? (DungeonChest)chest : chest, x, y); + World.levels[currentlevel].add(chest instanceof DeathChest ? chest : chest instanceof DungeonChest ? (DungeonChest) chest : chest, x, y); } else if (newEntity instanceof Spawner) { MobAi mob = (MobAi) getEntity(info.get(2), player, Integer.parseInt(info.get(3))); currentlevel = Integer.parseInt(info.get(info.size() - 1)); @@ -428,35 +428,61 @@ public void loadEntities(String filename, Player player) { public Entity getEntity(String string, Player player, int mobLevel) { switch (string) { - case "Player": return player; - case "Cow": return new Cow(); - case "Sheep": return new Sheep(); - case "Pig": return new Pig(); - case "Zombie": return new Zombie(mobLevel); - case "Slime": return new Slime(mobLevel); - case "Creeper": return new Creeper(mobLevel); - case "Skeleton": return new Skeleton(mobLevel); - case "Knight": return new Knight(mobLevel); - case "Snake": return new Snake(mobLevel); + case "Player": + return player; + case "Cow": + return new Cow(); + case "Sheep": + return new Sheep(); + case "Pig": + return new Pig(); + case "Zombie": + return new Zombie(mobLevel); + case "Slime": + return new Slime(mobLevel); + case "Creeper": + return new Creeper(mobLevel); + case "Skeleton": + return new Skeleton(mobLevel); + case "Knight": + return new Knight(mobLevel); + case "Snake": + return new Snake(mobLevel); case "AirWizard": if (mobLevel > 1) return null; return new AirWizard(); - case "Spawner": return new Spawner(new Zombie(1)); - case "Workbench": return new Crafter(Crafter.Type.Workbench); - case "Chest": return new Chest(); - case "DeathChest": return new DeathChest(); - case "DungeonChest": return new DungeonChest(false); - case "Anvil": return new Crafter(Crafter.Type.Anvil); - case "Enchanter": return new Crafter(Crafter.Type.Enchanter); - case "Loom": return new Crafter(Crafter.Type.Loom); - case "Furnace": return new Crafter(Crafter.Type.Furnace); - case "Oven": return new Crafter(Crafter.Type.Oven); - case "Bed": return new Bed(); - case "Tnt": return new Tnt(); - case "Lantern": return new Lantern(Lantern.Type.NORM); - case "IronLantern": return new Lantern(Lantern.Type.IRON); - case "GoldLantern": return new Lantern(Lantern.Type.GOLD); - default : Logger.tag("SaveLoad/LegacyLoad").warn("Unknown or outdated entity requested: " + string); + case "Spawner": + return new Spawner(new Zombie(1)); + case "Workbench": + return new Crafter(Crafter.Type.Workbench); + case "Chest": + return new Chest(); + case "DeathChest": + return new DeathChest(); + case "DungeonChest": + return new DungeonChest(false); + case "Anvil": + return new Crafter(Crafter.Type.Anvil); + case "Enchanter": + return new Crafter(Crafter.Type.Enchanter); + case "Loom": + return new Crafter(Crafter.Type.Loom); + case "Furnace": + return new Crafter(Crafter.Type.Furnace); + case "Oven": + return new Crafter(Crafter.Type.Oven); + case "Bed": + return new Bed(); + case "Tnt": + return new Tnt(); + case "Lantern": + return new Lantern(Lantern.Type.NORM); + case "IronLantern": + return new Lantern(Lantern.Type.IRON); + case "GoldLantern": + return new Lantern(Lantern.Type.GOLD); + default: + Logger.tag("SaveLoad/LegacyLoad").warn("Unknown or outdated entity requested: " + string); return null; } } diff --git a/src/client/java/minicraft/saveload/Load.java b/src/client/java/minicraft/saveload/Load.java index 7909495b3..efc17809a 100644 --- a/src/client/java/minicraft/saveload/Load.java +++ b/src/client/java/minicraft/saveload/Load.java @@ -105,7 +105,10 @@ public class Load { extradata = new ArrayList<>(); } - public Load(String worldname) { this(worldname, true); } + public Load(String worldname) { + this(worldname, true); + } + public Load(String worldname, boolean loadGame) { loadFromFile(location + "/saves/" + worldname + "/Game" + extension); if (data.get(0).contains(".")) worldVer = new Version(data.get(0)); @@ -121,7 +124,7 @@ public Load(String worldname, boolean loadGame) { else { location += "/saves/" + worldname + "/"; - percentInc = 5 + World.levels.length-1; // For the methods below, and world. + percentInc = 5 + World.levels.length - 1; // For the methods below, and world. percentInc = 100f / percentInc; @@ -191,11 +194,15 @@ public Load(String worldname, boolean loadGame) { } } - public Load() { this(Game.VERSION); } + public Load() { + this(Game.VERSION); + } + public Load(Version worldVersion) { this(false); worldVer = worldVersion; } + public Load(boolean loadConfig) { if (!loadConfig) return; boolean resave = false; @@ -248,7 +255,9 @@ public Load(boolean loadConfig) { } } - public Version getWorldVersion() { return worldVer; } + public Version getWorldVersion() { + return worldVer; + } public static ArrayList loadFile(String filename) throws IOException { ArrayList lines = new ArrayList<>(); @@ -292,7 +301,9 @@ private void loadFromFile(String filename) { LoadingDisplay.progress(percentInc); } - /** Source: Note: This method is copied from MiniMods. */ + /** + * Source: Note: This method is copied from MiniMods. + */ private static ArrayList splitUnwrappedCommas(String input) { ArrayList out = new ArrayList<>(); int lastIdx = 0; @@ -319,17 +330,20 @@ private static ArrayList splitUnwrappedCommas(String input) { } else if (ch == openBracket0) { bracketCounter.push(0); } else if (ch == closeBracket0) { - if (checkDiff.test(0)) throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); + if (checkDiff.test(0)) + throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); bracketCounter.pop(); } else if (ch == openBracket1) { bracketCounter.push(1); } else if (ch == closeBracket1) { - if (checkDiff.test(1)) throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); + if (checkDiff.test(1)) + throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); bracketCounter.pop(); } else if (ch == openBracket2) { bracketCounter.push(2); } else if (ch == closeBracket2) { - if (checkDiff.test(2)) throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); + if (checkDiff.test(2)) + throw new RuntimeException(String.format("Invalid closing char %s index %s. Input: \"%s\"", ch, i, input)); bracketCounter.pop(); } } @@ -429,7 +443,7 @@ private void loadPrefsOld(String filename) { loadFromFile(location + filename + extension); Version prefVer = new Version("2.0.2"); // the default, b/c this doesn't really matter much being specific past this if it's not set below. - if(!data.get(2).contains(";")) // signifies that this file was last written to by a version after 2.0.2. + if (!data.get(2).contains(";")) // signifies that this file was last written to by a version after 2.0.2. prefVer = new Version(data.remove(0)); Settings.set("sound", Boolean.parseBoolean(data.remove(0))); @@ -446,7 +460,7 @@ private void loadPrefsOld(String filename) { subdata = data; } else { MultiplayerDisplay.savedIP = data.remove(0); - if(prefVer.compareTo(new Version("2.0.3-dev3")) > 0) { + if (prefVer.compareTo(new Version("2.0.3-dev3")) > 0) { MultiplayerDisplay.savedUUID = data.remove(0); MultiplayerDisplay.savedUsername = data.remove(0); } @@ -558,7 +572,7 @@ private void loadPrefs(String filename) { private void loadUnlocksOld(String filename) { loadFromFile(location + filename + extension); - for (String unlock: data) { + for (String unlock : data) { unlock = unlock.replace("HOURMODE", "H_ScoreTime").replace("MINUTEMODE", "M_ScoreTime").replace("M_ScoreTime", "_ScoreTime").replace("2H_ScoreTime", "120_ScoreTime"); if (unlock.contains("_ScoreTime")) @@ -585,7 +599,7 @@ private void loadUnlocks(String filename) { } private void loadWorld(String filename) { - for(int l = World.maxLevelDepth; l >= World.minLevelDepth; l--) { + for (int l = World.maxLevelDepth; l >= World.minLevelDepth; l--) { LoadingDisplay.setMessage(Level.getDepthString(l)); int lvlidx = World.lvlIdx(l); loadFromFile(location + filename + lvlidx + extension); @@ -635,7 +649,7 @@ private void loadWorld(String filename) { default: tilename = "Wool"; } - } else if (l == World.minLevelDepth+1 && tilename.equalsIgnoreCase("Lapis") && worldVer.compareTo(new Version("2.0.3-dev6")) < 0) { + } else if (l == World.minLevelDepth + 1 && tilename.equalsIgnoreCase("Lapis") && worldVer.compareTo(new Version("2.0.3-dev6")) < 0) { if (Math.random() < 0.8) // don't replace *all* the lapis tilename = "Gem Ore"; } else if (tilename.equalsIgnoreCase("Cloud Cactus")) { @@ -656,7 +670,7 @@ private void loadWorld(String filename) { } } - Level parent = World.levels[World.lvlIdx(l+1)]; + Level parent = World.levels[World.lvlIdx(l + 1)]; World.levels[lvlidx] = new Level(lvlw, lvlh, seed, l, parent, false); Level curLevel = World.levels[lvlidx]; @@ -667,13 +681,13 @@ private void loadWorld(String filename) { if (parent == null) continue; /// confirm that there are stairs in all the places that should have stairs. - for (minicraft.gfx.Point p: parent.getMatchingTiles(Tiles.get("Stairs Down"))) { + for (minicraft.gfx.Point p : parent.getMatchingTiles(Tiles.get("Stairs Down"))) { if (curLevel.getTile(p.x, p.y) != Tiles.get("Stairs Up")) { curLevel.printLevelLoc("INCONSISTENT STAIRS detected; placing stairsUp", p.x, p.y); curLevel.setTile(p.x, p.y, Tiles.get("Stairs Up")); } } - for (minicraft.gfx.Point p: curLevel.getMatchingTiles(Tiles.get("Stairs Up"))) { + for (minicraft.gfx.Point p : curLevel.getMatchingTiles(Tiles.get("Stairs Up"))) { if (parent.getTile(p.x, p.y) != Tiles.get("Stairs Down")) { parent.printLevelLoc("INCONSISTENT STAIRS detected; placing stairsDown", p.x, p.y); parent.setTile(p.x, p.y, Tiles.get("Stairs Down")); @@ -683,7 +697,7 @@ private void loadWorld(String filename) { LoadingDisplay.setMessage("minicraft.displays.loading.message.quests"); - if (new File(location+"Quests.json").exists()){ + if (new File(location + "Quests.json").exists()) { Logging.SAVELOAD.warn("Quest.json exists and it has been deprecated; renaming..."); try { Files.move(Paths.get(location, "Quests.json"), Paths.get(location, "Quests.json_old"), StandardCopyOption.REPLACE_EXISTING); @@ -693,7 +707,7 @@ private void loadWorld(String filename) { } boolean advancementsLoadSucceeded = false; - if (new File(location+"advancements.json").exists()) { + if (new File(location + "advancements.json").exists()) { try { JSONObject questsObj = new JSONObject(loadFromFile(location + "advancements.json", true)); @SuppressWarnings("unused") @@ -721,6 +735,7 @@ public void loadPlayer(String filename, Player player) { loadFromFile(location + filename + extension); loadPlayer(player, data); } + public void loadPlayer(Player player, List origData) { List data = new ArrayList<>(origData); player.x = Integer.parseInt(data.remove(0)); @@ -735,12 +750,11 @@ public void loadPlayer(Player player, List origData) { player.armor = Integer.parseInt(data.remove(0)); if (worldVer.compareTo(new Version("2.0.5-dev5")) >= 0 || player.armor > 0 || worldVer.compareTo(new Version("2.0.5-dev4")) == 0 && data.size() > 5) { - if(worldVer.compareTo(new Version("2.0.4-dev7")) < 0) { + if (worldVer.compareTo(new Version("2.0.4-dev7")) < 0) { // Reverse order b/c we are taking from the end - player.curArmor = (ArmorItem) Items.get(data.remove(data.size()-1)); - player.armorDamageBuffer = Integer.parseInt(data.remove(data.size()-1)); - } - else { + player.curArmor = (ArmorItem) Items.get(data.remove(data.size() - 1)); + player.armorDamageBuffer = Integer.parseInt(data.remove(data.size() - 1)); + } else { player.armorDamageBuffer = Integer.parseInt(data.remove(0)); player.curArmor = (ArmorItem) Items.get(data.remove(0), true); } @@ -755,8 +769,9 @@ public void loadPlayer(Player player, List origData) { Game.currentLevel = Integer.parseInt(data.remove(0)); Level level = World.levels[Game.currentLevel]; - if (!player.isRemoved()) player.remove(); // Removes the user player from the level, in case they would be added twice. - if(level != null) + if (!player.isRemoved()) + player.remove(); // Removes the user player from the level, in case they would be added twice. + if (level != null) level.add(player); else Logging.SAVELOAD.trace("Game level to add player {} to is null.", player); @@ -794,8 +809,7 @@ public void loadPlayer(Player player, List origData) { for (int i = 0; i < 3; i++) colors[i] = Integer.parseInt(String.valueOf(color.charAt(i))); player.shirtColor = Color.get(1, colors[0] * 51, colors[1] * 51, colors[2] * 51); - } - else + } else player.shirtColor = Integer.parseInt(data.remove(0)); // Just delete the slot reserved for loading legacy skins. @@ -865,6 +879,7 @@ public void loadInventory(String filename, Inventory inventory) { loadFromFile(location + filename + extension); loadInventory(inventory, data); } + public void loadInventory(Inventory inventory, List data) { inventory.clearInv(); @@ -962,7 +977,7 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL int awID = Integer.parseInt(info.get(2)); Entity sparkOwner = Network.getEntity(awID); if (sparkOwner instanceof AirWizard) - newEntity = new Spark((AirWizard)sparkOwner, x, y); + newEntity = new Spark((AirWizard) sparkOwner, x, y); else { Logging.SAVELOAD.error("Failed to load Spark; owner id doesn't point to a correct entity"); return null; @@ -972,22 +987,23 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL if (!Crafter.names.contains(entityName)) { // Entity missing debugging try { Class.forName("minicraft.entity.mob." + entityName); - } catch (ClassNotFoundException ignored) {} + } catch (ClassNotFoundException ignored) { + } } // Check for level of AirWizard - if(entityName.equals("AirWizard")) { + if (entityName.equals("AirWizard")) { mobLvl = Integer.parseInt(stuff[3]); } - newEntity = getEntity(entityName.substring(entityName.lastIndexOf(".")+1), mobLvl); + newEntity = getEntity(entityName.substring(entityName.lastIndexOf(".") + 1), mobLvl); } if (entityName.equals("FireSpark") && !isLocalSave) { int obID = Integer.parseInt(info.get(2)); Entity sparkOwner = Network.getEntity(obID); if (sparkOwner instanceof ObsidianKnight) - newEntity = new FireSpark((ObsidianKnight)sparkOwner, x, y); + newEntity = new FireSpark((ObsidianKnight) sparkOwner, x, y); else { Logging.SAVELOAD.error("Failed to load FireSpark; owner id doesn't point to a correct entity"); return null; @@ -998,7 +1014,7 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL return null; if (newEntity instanceof Mob) { // This is structured the same way as in Save.java. - Mob mob = (Mob)newEntity; + Mob mob = (Mob) newEntity; mob.health = Integer.parseInt(info.get(2)); Class c = null; @@ -1010,7 +1026,7 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL if (EnemyMob.class.isAssignableFrom(c)) { EnemyMob enemyMob = ((EnemyMob) mob); - enemyMob.lvl = Integer.parseInt(info.get(info.size()-2)); + enemyMob.lvl = Integer.parseInt(info.get(info.size() - 2)); if (enemyMob.lvl == 0) { Logging.SAVELOAD.debug("Level 0 mob: " + entityName); @@ -1034,10 +1050,10 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL newEntity = mob; } else if (newEntity instanceof Chest) { - Chest chest = (Chest)newEntity; + Chest chest = (Chest) newEntity; boolean isDeathChest = chest instanceof DeathChest; boolean isDungeonChest = chest instanceof DungeonChest; - List chestInfo = info.subList(2, info.size()-1); + List chestInfo = info.subList(2, info.size() - 1); int endIdx = chestInfo.size() - (isDeathChest || isDungeonChest ? 1 : 0); for (int idx = 0; idx < endIdx; idx++) { @@ -1051,10 +1067,11 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL } if (isDeathChest) { - ((DeathChest)chest).time = Integer.parseInt(chestInfo.get(chestInfo.size()-1)); + ((DeathChest) chest).time = Integer.parseInt(chestInfo.get(chestInfo.size() - 1)); } else if (isDungeonChest) { - ((DungeonChest)chest).setLocked(Boolean.parseBoolean(chestInfo.get(chestInfo.size()-1))); - if (((DungeonChest)chest).isLocked()) World.levels[Integer.parseInt(info.get(info.size()-1))].chestCount++; + ((DungeonChest) chest).setLocked(Boolean.parseBoolean(chestInfo.get(chestInfo.size() - 1))); + if (((DungeonChest) chest).isLocked()) + World.levels[Integer.parseInt(info.get(info.size() - 1))].chestCount++; } newEntity = chest; @@ -1072,7 +1089,7 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL if (!isLocalSave) { if (newEntity instanceof Arrow) { int ownerID = Integer.parseInt(info.get(2)); - Mob m = (Mob)Network.getEntity(ownerID); + Mob m = (Mob) Network.getEntity(ownerID); if (m != null) { Direction dir = Direction.values[Integer.parseInt(info.get(3))]; int dmg = Integer.parseInt(info.get(5)); @@ -1100,7 +1117,7 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL if (newEntity instanceof ItemEntity && eid == -1) Logging.SAVELOAD.warn("Item entity was loaded with no eid"); - int curLevel = Integer.parseInt(info.get(info.size()-1)); + int curLevel = Integer.parseInt(info.get(info.size() - 1)); if (World.levels[curLevel] != null) { World.levels[curLevel].add(newEntity, x, y); } @@ -1111,41 +1128,73 @@ public static Entity loadEntity(String entityData, Version worldVer, boolean isL @Nullable private static Entity getEntity(String string, int mobLevel) { switch (string) { - case "Player": return null; - case "RemotePlayer": return null; - case "Cow": return new Cow(); - case "Sheep": return new Sheep(); - case "Pig": return new Pig(); - case "Zombie": return new Zombie(mobLevel); - case "Slime": return new Slime(mobLevel); - case "Creeper": return new Creeper(mobLevel); - case "Skeleton": return new Skeleton(mobLevel); - case "Knight": return new Knight(mobLevel); - case "Snake": return new Snake(mobLevel); + case "Player": + return null; + case "RemotePlayer": + return null; + case "Cow": + return new Cow(); + case "Sheep": + return new Sheep(); + case "Pig": + return new Pig(); + case "Zombie": + return new Zombie(mobLevel); + case "Slime": + return new Slime(mobLevel); + case "Creeper": + return new Creeper(mobLevel); + case "Skeleton": + return new Skeleton(mobLevel); + case "Knight": + return new Knight(mobLevel); + case "Snake": + return new Snake(mobLevel); case "AirWizard": if (mobLevel > 1) return null; return new AirWizard(); - case "Spawner": return new Spawner(new Zombie(1)); - case "Workbench": return new Crafter(Crafter.Type.Workbench); - case "Chest": return new Chest(); - case "DeathChest": return new DeathChest(); - case "DungeonChest": return new DungeonChest(false); - case "Anvil": return new Crafter(Crafter.Type.Anvil); - case "Enchanter": return new Crafter(Crafter.Type.Enchanter); - case "Loom": return new Crafter(Crafter.Type.Loom); - case "Furnace": return new Crafter(Crafter.Type.Furnace); - case "Oven": return new Crafter(Crafter.Type.Oven); - case "Bed": return new Bed(); - case "Tnt": return new Tnt(); - case "Lantern": return new Lantern(Lantern.Type.NORM); - case "Arrow": return new Arrow(new Skeleton(0), 0, 0, Direction.NONE, 0); - case "ItemEntity": return new ItemEntity(Items.get("unknown"), 0, 0); - case "FireParticle": return new FireParticle(0, 0); - case "SmashParticle": return new SmashParticle(0, 0); - case "TextParticle": return new TextParticle("", 0, 0, 0); - case "KnightStatue": return new KnightStatue(0); - case "ObsidianKnight": return new ObsidianKnight(0); - default : Logging.SAVELOAD.error("LOAD ERROR: Unknown or outdated entity requested: " + string); + case "Spawner": + return new Spawner(new Zombie(1)); + case "Workbench": + return new Crafter(Crafter.Type.Workbench); + case "Chest": + return new Chest(); + case "DeathChest": + return new DeathChest(); + case "DungeonChest": + return new DungeonChest(false); + case "Anvil": + return new Crafter(Crafter.Type.Anvil); + case "Enchanter": + return new Crafter(Crafter.Type.Enchanter); + case "Loom": + return new Crafter(Crafter.Type.Loom); + case "Furnace": + return new Crafter(Crafter.Type.Furnace); + case "Oven": + return new Crafter(Crafter.Type.Oven); + case "Bed": + return new Bed(); + case "Tnt": + return new Tnt(); + case "Lantern": + return new Lantern(Lantern.Type.NORM); + case "Arrow": + return new Arrow(new Skeleton(0), 0, 0, Direction.NONE, 0); + case "ItemEntity": + return new ItemEntity(Items.get("unknown"), 0, 0); + case "FireParticle": + return new FireParticle(0, 0); + case "SmashParticle": + return new SmashParticle(0, 0); + case "TextParticle": + return new TextParticle("", 0, 0, 0); + case "KnightStatue": + return new KnightStatue(0); + case "ObsidianKnight": + return new ObsidianKnight(0); + default: + Logging.SAVELOAD.error("LOAD ERROR: Unknown or outdated entity requested: " + string); return null; } } diff --git a/src/client/java/minicraft/saveload/Save.java b/src/client/java/minicraft/saveload/Save.java index a5096b15e..b9a08424e 100644 --- a/src/client/java/minicraft/saveload/Save.java +++ b/src/client/java/minicraft/saveload/Save.java @@ -65,6 +65,7 @@ public class Save { /** * This is the main save method. Called by all Save() methods. + * * @param worldFolder The folder of where to save */ private Save(File worldFolder) { @@ -93,10 +94,11 @@ private Save(File worldFolder) { /** * This will save world options + * * @param worldname The name of the world. */ public Save(String worldname) { - this(new File(Game.gameDir+"/saves/" + worldname + "/")); + this(new File(Game.gameDir + "/saves/" + worldname + "/")); writeGame("Game"); writeWorld("Level"); @@ -111,9 +113,11 @@ public Save(String worldname) { Updater.saving = false; } - /** This will save the settings in the settings menu. */ + /** + * This will save the settings in the settings menu. + */ public Save() { - this(new File(Game.gameDir+"/")); + this(new File(Game.gameDir + "/")); Logging.SAVELOAD.debug("Writing preferences and unlocks..."); writePrefs(); writeUnlocks(); @@ -121,7 +125,7 @@ public Save() { public Save(Player player, boolean writePlayer) { // This is simply for access to writeToFile. - this(new File(Game.gameDir+"/saves/"+WorldSelectDisplay.getWorldName() + "/")); + this(new File(Game.gameDir + "/saves/" + WorldSelectDisplay.getWorldName() + "/")); if (writePlayer) { writePlayer("Player", player); writeInventory("Inventory", player); @@ -144,7 +148,7 @@ public void writeToFile(String filename, List savedata) { data.clear(); LoadingDisplay.progress(7); - if(LoadingDisplay.getPercentage() > 100) { + if (LoadingDisplay.getPercentage() > 100) { LoadingDisplay.setPercentage(100); } @@ -294,7 +298,7 @@ public static void writePlayer(Player player, List data) { StringBuilder subdata = new StringBuilder("PotionEffects["); - for (java.util.Map.Entry potion: player.potioneffects.entrySet()) + for (java.util.Map.Entry potion : player.potioneffects.entrySet()) subdata.append(potion.getKey()).append(";").append(potion.getValue()).append(":"); if (player.potioneffects.size() > 0) @@ -317,6 +321,7 @@ private void writeInventory(String filename, Player player) { writeInventory(player, data); writeToFile(location + filename + extension, data); } + public static void writeInventory(Player player, List data) { data.clear(); if (player.activeItem != null) { @@ -333,7 +338,7 @@ public static void writeInventory(Player player, List data) { private void writeEntities(String filename) { LoadingDisplay.setMessage("minicraft.displays.loading.message.entities"); for (int l = 0; l < World.levels.length; l++) { - for (Entity e: World.levels[l].getEntitiesToSave()) { + for (Entity e : World.levels[l].getEntitiesToSave()) { String saved = writeEntity(e, true); if (saved.length() > 0) data.add(saved); @@ -345,19 +350,19 @@ private void writeEntities(String filename) { public static String writeEntity(Entity e, boolean isLocalSave) { String name = e.getClass().getName(); - name = name.substring(name.lastIndexOf('.')+1); + name = name.substring(name.lastIndexOf('.') + 1); StringBuilder extradata = new StringBuilder(); // Don't even write ItemEntities or particle effects; Spark... will probably is saved, eventually; it presents an unfair cheat to remove the sparks by reloading the Game. - if (isLocalSave && (e instanceof ItemEntity || e instanceof Arrow || e instanceof Spark || e instanceof FireSpark || e instanceof Particle)) // Write these only when sending a world, not writing it. (RemotePlayers are saved separately, when their info is received.) + if (isLocalSave && (e instanceof ItemEntity || e instanceof Arrow || e instanceof Spark || e instanceof FireSpark || e instanceof Particle)) // Write these only when sending a world, not writing it. (RemotePlayers are saved separately, when their info is received.) return ""; if (!isLocalSave) extradata.append(":").append(e.eid); if (e instanceof Mob) { - Mob m = (Mob)e; + Mob m = (Mob) e; extradata.append(":").append(m.health); if (e instanceof EnemyMob) extradata.append(":").append(((EnemyMob) m).lvl); @@ -366,21 +371,21 @@ else if (e instanceof Sheep) } if (e instanceof Chest) { - Chest chest = (Chest)e; + Chest chest = (Chest) e; - for(int ii = 0; ii < chest.getInventory().invSize(); ii++) { + for (int ii = 0; ii < chest.getInventory().invSize(); ii++) { Item item = chest.getInventory().get(ii); extradata.append(":").append(item.getData()); } - if(chest instanceof DeathChest) extradata.append(":").append(((DeathChest) chest).time); - if(chest instanceof DungeonChest) extradata.append(":").append(((DungeonChest) chest).isLocked()); + if (chest instanceof DeathChest) extradata.append(":").append(((DeathChest) chest).time); + if (chest instanceof DungeonChest) extradata.append(":").append(((DungeonChest) chest).isLocked()); } if (e instanceof Spawner) { - Spawner egg = (Spawner)e; + Spawner egg = (Spawner) e; String mobname = egg.mob.getClass().getName(); - mobname = mobname.substring(mobname.lastIndexOf(".")+1); + mobname = mobname.substring(mobname.lastIndexOf(".") + 1); extradata.append(":").append(mobname).append(":").append(egg.mob instanceof EnemyMob ? ((EnemyMob) egg.mob).lvl : 1); } @@ -389,7 +394,7 @@ else if (e instanceof Sheep) } if (e instanceof Crafter) { - name = ((Crafter)e).type.name(); + name = ((Crafter) e).type.name(); } if (e instanceof KnightStatue) { diff --git a/src/client/java/minicraft/saveload/Version.java b/src/client/java/minicraft/saveload/Version.java index 247a8318c..b388134be 100644 --- a/src/client/java/minicraft/saveload/Version.java +++ b/src/client/java/minicraft/saveload/Version.java @@ -7,7 +7,10 @@ public class Version implements Comparable { private int make, major, minor, dev; private boolean valid = true; - public Version(String version) { this(version, true); } + public Version(String version) { + this(version, true); + } + private Version(String version, boolean printError) { String[] nums = version.split("\\."); try { @@ -39,12 +42,18 @@ private Version(String version, boolean printError) { } } - public boolean isValid() { return valid; } - public static boolean isValid(String version) { return new Version(version, false).isValid(); } + public boolean isValid() { + return valid; + } + + public static boolean isValid(String version) { + return new Version(version, false).isValid(); + } /** * The returned value of this method (-1, 0, or 1) is determined by whether this object is less than, equal to, or greater than the specified object, ov. * (this.compareTo(new Version("1.0.0") < 0 is the same as this < 1.0.0) + * * @param ov The version to compare to. */ public int compareTo(@NotNull Version ov) { @@ -54,9 +63,10 @@ public int compareTo(@NotNull Version ov) { /** * The returned value of this method (-1, 0, or 1) is determined by whether this object is less than, equal to, or greater than the specified object, ov. * (this.compareTo(new Version("1.0.0") < 0 is the same as this < 1.0.0) - * @param ov The version to compare to. + * + * @param ov The version to compare to. * @param ignoreDev If we should ignore dev versions in this comparison. - */ + */ public int compareTo(@NotNull Version ov, boolean ignoreDev) { if (make != ov.make) return Integer.compare(make, ov.make); if (major != ov.major) return Integer.compare(major, ov.major); @@ -73,7 +83,11 @@ public int compareTo(@NotNull Version ov, boolean ignoreDev) { } @Override - public String toString() { return make + "." + major + "." + minor + (dev == 0 ? "" : "-dev" + dev); } + public String toString() { + return make + "." + major + "." + minor + (dev == 0 ? "" : "-dev" + dev); + } - public int[] toArray() { return new int[]{ make, major, minor, dev }; } + public int[] toArray() { + return new int[]{make, major, minor, dev}; + } } diff --git a/src/client/java/minicraft/screen/AchievementsDisplay.java b/src/client/java/minicraft/screen/AchievementsDisplay.java index aceab7e75..c54ce2e29 100644 --- a/src/client/java/minicraft/screen/AchievementsDisplay.java +++ b/src/client/java/minicraft/screen/AchievementsDisplay.java @@ -30,200 +30,204 @@ public class AchievementsDisplay extends Display { - private static final HashMap achievements = new HashMap<>(); - - private static Achievement selectedAchievement; - private static int achievementScore; - - static { - // Get achievements from a json file stored in resources. Relative to project root. - try (InputStream stream = Game.class.getResourceAsStream("/resources/achievements.json")) { - if (stream != null) { - BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); - - // Read lines and combine into a string. - String achievementsJson = reader.lines().collect(Collectors.joining("\n")); - - // Load json. - JSONArray json = new JSONArray(achievementsJson); - for (Object object : json) { - JSONObject obj = (JSONObject) object; - - // Create an achievement with the data. - Achievement a = new Achievement( - Localization.getLocalized(obj.getString("id")), - obj.getString("desc"), - obj.getInt("score") - ); - - achievements.put(obj.getString("id"), a); - } - } else { - Logging.ACHIEVEMENT.error("Could not find achievements json."); - } - } catch (IOException ex) { - Logging.ACHIEVEMENT.error("Could not read achievements from json file."); - ex.printStackTrace(); - } catch (JSONException e) { - Logging.ACHIEVEMENT.error("Achievements json contains invalid json."); - } - } - - public AchievementsDisplay() { - super(true, true, - new Menu.Builder(false, 2, RelPos.CENTER, getAchievemensAsEntries()).setSize(48, 48).createMenu(), - new Menu.Builder(false, 2, RelPos.BOTTOM, new StringEntry("")).setSize(200, 32).setPositioning(new Point(Screen.w / 2, Screen.h / 2 + 32), RelPos.BOTTOM).createMenu()); - } - - @Override - public void init(@Nullable Display parent) { - super.init(parent); - if (achievements.isEmpty()) { - Game.setDisplay(new TitleDisplay()); - Logging.ACHIEVEMENT.error("Could not open achievements menu because no achievements could be found."); - return; - } - - ListEntry curEntry = menus[0].getCurEntry(); - if (curEntry instanceof SelectEntry) { - selectedAchievement = achievements.get(((SelectEntry) curEntry).getText()); - } - } - - @Override - public void onExit() { - // Play confirm sound. - Sound.play("confirm"); - new Save(); - } - - @Override + private static final HashMap achievements = new HashMap<>(); + + private static Achievement selectedAchievement; + private static int achievementScore; + + static { + // Get achievements from a json file stored in resources. Relative to project root. + try (InputStream stream = Game.class.getResourceAsStream("/resources/achievements.json")) { + if (stream != null) { + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + + // Read lines and combine into a string. + String achievementsJson = reader.lines().collect(Collectors.joining("\n")); + + // Load json. + JSONArray json = new JSONArray(achievementsJson); + for (Object object : json) { + JSONObject obj = (JSONObject) object; + + // Create an achievement with the data. + Achievement a = new Achievement( + Localization.getLocalized(obj.getString("id")), + obj.getString("desc"), + obj.getInt("score") + ); + + achievements.put(obj.getString("id"), a); + } + } else { + Logging.ACHIEVEMENT.error("Could not find achievements json."); + } + } catch (IOException ex) { + Logging.ACHIEVEMENT.error("Could not read achievements from json file."); + ex.printStackTrace(); + } catch (JSONException e) { + Logging.ACHIEVEMENT.error("Achievements json contains invalid json."); + } + } + + public AchievementsDisplay() { + super(true, true, + new Menu.Builder(false, 2, RelPos.CENTER, getAchievemensAsEntries()).setSize(48, 48).createMenu(), + new Menu.Builder(false, 2, RelPos.BOTTOM, new StringEntry("")).setSize(200, 32).setPositioning(new Point(Screen.w / 2, Screen.h / 2 + 32), RelPos.BOTTOM).createMenu()); + } + + @Override + public void init(@Nullable Display parent) { + super.init(parent); + if (achievements.isEmpty()) { + Game.setDisplay(new TitleDisplay()); + Logging.ACHIEVEMENT.error("Could not open achievements menu because no achievements could be found."); + return; + } + + ListEntry curEntry = menus[0].getCurEntry(); + if (curEntry instanceof SelectEntry) { + selectedAchievement = achievements.get(((SelectEntry) curEntry).getText()); + } + } + + @Override + public void onExit() { + // Play confirm sound. + Sound.play("confirm"); + new Save(); + } + + @Override public void tick(InputHandler input) { super.tick(input); - ListEntry curEntry = menus[0].getCurEntry(); - if (curEntry instanceof SelectEntry) { - selectedAchievement = achievements.get(((SelectEntry) curEntry).getText()); - } - } - - @Override - public void render(Screen screen) { - super.render(screen); - - // Title. - Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements"), screen, 8, Color.WHITE); - - // Achievement score. - Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.score", achievementScore), screen, 32, Color.GRAY); - - if (selectedAchievement != null) { - - // Render Achievement Info. - if (selectedAchievement.getUnlocked()) { - Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.achieved"), screen, 48, Color.GREEN); - } else { - Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.not_achieved"), screen, 48, Color.RED); - } - - // Achievement description. - menus[1].setEntries(StringEntry.useLines(Font.getLines(Localization.getLocalized(selectedAchievement.description), menus[1].getBounds().getSize().width, menus[1].getBounds().getSize().height, 2))); - } - - // Help text. - Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.help", Game.input.getMapping("cursor-down"), Game.input.getMapping("cursor-up")), screen, Screen.h - 8, Color.DARK_GRAY); - } - - /** - * Use this to lock or unlock an achievement. - * @param id Achievement ID. - * @param unlocked Whether this achievement should be locked or unlocked. - * @return True if setting the achievement was successful. - */ - public static boolean setAchievement(String id, boolean unlocked) { - return setAchievement(id, unlocked, true, false); - } - public static boolean setAchievement(boolean allowCreative, String id, boolean unlocked) { return setAchievement(id, unlocked, true, allowCreative); } + ListEntry curEntry = menus[0].getCurEntry(); + if (curEntry instanceof SelectEntry) { + selectedAchievement = achievements.get(((SelectEntry) curEntry).getText()); + } + } + + @Override + public void render(Screen screen) { + super.render(screen); + + // Title. + Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements"), screen, 8, Color.WHITE); + + // Achievement score. + Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.score", achievementScore), screen, 32, Color.GRAY); + + if (selectedAchievement != null) { + + // Render Achievement Info. + if (selectedAchievement.getUnlocked()) { + Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.achieved"), screen, 48, Color.GREEN); + } else { + Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.not_achieved"), screen, 48, Color.RED); + } + + // Achievement description. + menus[1].setEntries(StringEntry.useLines(Font.getLines(Localization.getLocalized(selectedAchievement.description), menus[1].getBounds().getSize().width, menus[1].getBounds().getSize().height, 2))); + } + + // Help text. + Font.drawCentered(Localization.getLocalized("minicraft.displays.achievements.display.help", Game.input.getMapping("cursor-down"), Game.input.getMapping("cursor-up")), screen, Screen.h - 8, Color.DARK_GRAY); + } + + /** + * Use this to lock or unlock an achievement. + * + * @param id Achievement ID. + * @param unlocked Whether this achievement should be locked or unlocked. + * @return True if setting the achievement was successful. + */ + public static boolean setAchievement(String id, boolean unlocked) { + return setAchievement(id, unlocked, true, false); + } + + public static boolean setAchievement(boolean allowCreative, String id, boolean unlocked) { + return setAchievement(id, unlocked, true, allowCreative); + } private static boolean setAchievement(String id, boolean unlocked, boolean save, boolean allowCreative) { - Achievement a = achievements.get(id); + Achievement a = achievements.get(id); // Return if it is in creative mode if (!allowCreative && Game.isMode("minicraft.settings.mode.creative")) return false; - // Return if we didn't find any achievements. - if (a == null) return false; - - if (a.getUnlocked() && unlocked) return false; // Return if it is already unlocked. - if (!a.getUnlocked() && !unlocked) return false; // Return if it is already locked. - - // Make the achievement unlocked in memory. - a.setUnlocked(unlocked); - Logging.ACHIEVEMENT.debug("Updating data of achievement with id: {}.", id); - - // Add or subtract from score - if (unlocked) { - achievementScore += a.score; - - // Tells the player that they got an achievement. - Game.notifications.add(Localization.getLocalized("minicraft.notification.achievement_unlocked", Localization.getLocalized(id))); - } - else - achievementScore -= a.score; - - // Save the new list of achievements stored in memory. - if (save) new Save(); - - return true; - } - - /** - * Gets an array of all the unlocked achievements. - * @return A string array with each unlocked achievement's id in it. - */ - public static String[] getUnlockedAchievements() { - ArrayList strings = new ArrayList<>(); - - for (String id : achievements.keySet()) { - if (achievements.get(id).getUnlocked()) { - strings.add(id); - } - } - - return strings.toArray(new String[0]); - } - - public static List getAchievemensAsEntries() { - List l = new ArrayList<>(); - for (String id : achievements.keySet()) { - // Add entry to list. - l.add(new SelectEntry(id, null, true) - { - /** - * Change the color of the selection. - */ - @Override - public int getColor(boolean isSelected) { - if (achievements.get(id).getUnlocked()) { - return Color.GREEN; - } else { - return Color.WHITE; - } - } - }); - } - - return l; - } - - /** - * Unlocks a list of achievements. - * @param unlockedAchievements An array of all the achievements we want to load, ids. - */ - public static void unlockAchievements(JSONArray unlockedAchievements) { - for (Object id : unlockedAchievements.toList()) { - if (!setAchievement(id.toString(), true, false, false)) { - Logging.ACHIEVEMENT.warn("Could not load unlocked achievement with name {}.", id.toString()); - } - } - } + // Return if we didn't find any achievements. + if (a == null) return false; + + if (a.getUnlocked() && unlocked) return false; // Return if it is already unlocked. + if (!a.getUnlocked() && !unlocked) return false; // Return if it is already locked. + + // Make the achievement unlocked in memory. + a.setUnlocked(unlocked); + Logging.ACHIEVEMENT.debug("Updating data of achievement with id: {}.", id); + + // Add or subtract from score + if (unlocked) { + achievementScore += a.score; + + // Tells the player that they got an achievement. + Game.notifications.add(Localization.getLocalized("minicraft.notification.achievement_unlocked", Localization.getLocalized(id))); + } else + achievementScore -= a.score; + + // Save the new list of achievements stored in memory. + if (save) new Save(); + + return true; + } + + /** + * Gets an array of all the unlocked achievements. + * + * @return A string array with each unlocked achievement's id in it. + */ + public static String[] getUnlockedAchievements() { + ArrayList strings = new ArrayList<>(); + + for (String id : achievements.keySet()) { + if (achievements.get(id).getUnlocked()) { + strings.add(id); + } + } + + return strings.toArray(new String[0]); + } + + public static List getAchievemensAsEntries() { + List l = new ArrayList<>(); + for (String id : achievements.keySet()) { + // Add entry to list. + l.add(new SelectEntry(id, null, true) { + /** + * Change the color of the selection. + */ + @Override + public int getColor(boolean isSelected) { + if (achievements.get(id).getUnlocked()) { + return Color.GREEN; + } else { + return Color.WHITE; + } + } + }); + } + + return l; + } + + /** + * Unlocks a list of achievements. + * + * @param unlockedAchievements An array of all the achievements we want to load, ids. + */ + public static void unlockAchievements(JSONArray unlockedAchievements) { + for (Object id : unlockedAchievements.toList()) { + if (!setAchievement(id.toString(), true, false, false)) { + Logging.ACHIEVEMENT.warn("Could not load unlocked achievement with name {}.", id.toString()); + } + } + } } diff --git a/src/client/java/minicraft/screen/BookDisplay.java b/src/client/java/minicraft/screen/BookDisplay.java index 0b462add1..0810fa1e9 100644 --- a/src/client/java/minicraft/screen/BookDisplay.java +++ b/src/client/java/minicraft/screen/BookDisplay.java @@ -18,7 +18,7 @@ public class BookDisplay extends Display { private static final String defaultBook = "This book has no text."; private static final int spacing = 3; - private static final int minX = 15, maxX = 15+8 * 32, minY = 8*5, maxY = 8*5 + 8*16; + private static final int minX = 15, maxX = 15 + 8 * 32, minY = 8 * 5, maxY = 8 * 5 + 8 * 16; // First array is page and second is line. private String[][] lines; @@ -28,9 +28,12 @@ public class BookDisplay extends Display { private final boolean showPageCount; private final int pageOffset; - public BookDisplay(String book) { this(book, false); } + public BookDisplay(String book) { + this(book, false); + } + public BookDisplay(String book, boolean hasTitle) {// this(book, hasTitle, !hasTitle); } - //public BookDisplay(String book, boolean hasTitle, boolean hideCountIfOnePage) { + //public BookDisplay(String book, boolean hasTitle, boolean hideCountIfOnePage) { page = 0; if (book == null) { @@ -42,11 +45,11 @@ public class BookDisplay extends Display { ArrayList pages = new ArrayList<>(); String[] splitContents = book.split("\0"); - for (String content: splitContents) { + for (String content : splitContents) { String[] remainder = {content}; - while (remainder[remainder.length-1].length() > 0) { - remainder = Font.getLines(remainder[remainder.length-1], maxX-minX, maxY-minY, spacing, true); - pages.add(Arrays.copyOf(remainder, remainder.length-1)); // Removes the last element of remainder, which is the leftover. + while (remainder[remainder.length - 1].length() > 0) { + remainder = Font.getLines(remainder[remainder.length - 1], maxX - minX, maxY - minY, spacing, true); + pages.add(Arrays.copyOf(remainder, remainder.length - 1)); // Removes the last element of remainder, which is the leftover. } } @@ -58,31 +61,32 @@ public class BookDisplay extends Display { Menu.Builder builder = new Menu.Builder(true, spacing, RelPos.CENTER); Menu pageCount = builder // The small rect for the title - .setPositioning(new Point(Screen.w/2, 0), RelPos.BOTTOM) + .setPositioning(new Point(Screen.w / 2, 0), RelPos.BOTTOM) .setEntries(StringEntry.useLines(Color.BLACK, "Page", hasTitle ? "Title" : "1/" + lines.length)) .setSelection(1) .createMenu(); builder - .setPositioning(new Point(Screen.w/2, pageCount.getBounds().getBottom() + spacing), RelPos.BOTTOM) - .setSize(maxX-minX + MinicraftImage.boxWidth*2, maxY-minY + MinicraftImage.boxWidth*2) + .setPositioning(new Point(Screen.w / 2, pageCount.getBounds().getBottom() + spacing), RelPos.BOTTOM) + .setSize(maxX - minX + MinicraftImage.boxWidth * 2, maxY - minY + MinicraftImage.boxWidth * 2) .setShouldRender(false); menus = new Menu[lines.length + pageOffset]; if (showPageCount) menus[0] = pageCount; for (int i = 0; i < lines.length; i++) { - menus[i+pageOffset] = builder.setEntries(StringEntry.useLines(Color.WHITE, lines[i])).createMenu(); + menus[i + pageOffset] = builder.setEntries(StringEntry.useLines(Color.WHITE, lines[i])).createMenu(); } - menus[page+pageOffset].shouldRender = true; + menus[page + pageOffset].shouldRender = true; } private void turnPage(int dir) { if (page + dir >= 0 && page + dir < lines.length) { - menus[page+pageOffset].shouldRender = false; + menus[page + pageOffset].shouldRender = false; page += dir; - if (showPageCount) menus[0].updateSelectedEntry(new StringEntry(page == 0 && hasTitle ? "Title" : (page + 1) + "/" + lines.length, Color.BLACK)); - menus[page+pageOffset].shouldRender = true; + if (showPageCount) + menus[0].updateSelectedEntry(new StringEntry(page == 0 && hasTitle ? "Title" : (page + 1) + "/" + lines.length, Color.BLACK)); + menus[page + pageOffset].shouldRender = true; } } diff --git a/src/client/java/minicraft/screen/ContainerDisplay.java b/src/client/java/minicraft/screen/ContainerDisplay.java index 5fc031384..21b71f2b7 100644 --- a/src/client/java/minicraft/screen/ContainerDisplay.java +++ b/src/client/java/minicraft/screen/ContainerDisplay.java @@ -45,19 +45,22 @@ public ContainerDisplay(Player player, Chest chest) { protected void onSelectionChange(int oldSel, int newSel) { super.onSelectionChange(oldSel, newSel); - if (oldSel == newSel) return; // this also serves as a protection against access to menus[0] when such may not exist. + if (oldSel == newSel) + return; // this also serves as a protection against access to menus[0] when such may not exist. int shift = 0; if (newSel == 0) shift = padding - menus[0].getBounds().getLeft(); if (newSel == 1) shift = (Screen.w - padding) - menus[1].getBounds().getRight(); - for (Menu m: menus) { + for (Menu m : menus) { m.translate(shift, 0); } } - private int getOtherIdx() { return selection ^ 1; } + private int getOtherIdx() { + return selection ^ 1; + } @Override public void render(Screen screen) { @@ -128,23 +131,23 @@ public void tick(InputHandler input) { Item fromItem = from.get(fromSel); - boolean transferAll = input.getMappedKey("shift").isDown() || !(fromItem instanceof StackableItem) || ((StackableItem)fromItem).count == 1; + boolean transferAll = input.getMappedKey("shift").isDown() || !(fromItem instanceof StackableItem) || ((StackableItem) fromItem).count == 1; Item toItem = fromItem.copy(); if (fromItem instanceof StackableItem) { int move = 1; if (!transferAll) { - ((StackableItem)toItem).count = 1; + ((StackableItem) toItem).count = 1; } else { - move = ((StackableItem)fromItem).count; + move = ((StackableItem) fromItem).count; } int moved = to.add(toSel, toItem); if (moved < move) { - ((StackableItem)fromItem).count -= moved; + ((StackableItem) fromItem).count -= moved; } else if (!transferAll) { - ((StackableItem)fromItem).count--; + ((StackableItem) fromItem).count--; } else { from.remove(fromSel); } diff --git a/src/client/java/minicraft/screen/ControlsDisplay.java b/src/client/java/minicraft/screen/ControlsDisplay.java index 842105ba0..8e028156a 100644 --- a/src/client/java/minicraft/screen/ControlsDisplay.java +++ b/src/client/java/minicraft/screen/ControlsDisplay.java @@ -22,7 +22,7 @@ public class ControlsDisplay extends Display { public ControlsDisplay() { super(true, true, new Menu.Builder(false, 0, RelPos.CENTER) .setSelectable(true) - .setPositioning(new Point(Screen.w/2, 20), RelPos.BOTTOM) + .setPositioning(new Point(Screen.w / 2, 20), RelPos.BOTTOM) .setDisplayLength(17) .createMenu() ); @@ -51,7 +51,7 @@ private void initControllerControls() { } private void switchingControls() { - menus[0].setEntries(displaying == 0? keyControls: controllerControls); + menus[0].setEntries(displaying == 0 ? keyControls : controllerControls); menus[0].setSelection(0); } @@ -60,7 +60,7 @@ public void render(Screen screen) { super.render(screen); Font.drawCentered(Localization.getLocalized("minicraft.displays.controls"), screen, 0, Color.WHITE); - Font.drawCentered(Localization.getLocalized(displaying == 0? "minicraft.displays.controls.display.keyboard": "minicraft.displays.controls.display.controller"), screen, 10, Color.WHITE); + Font.drawCentered(Localization.getLocalized(displaying == 0 ? "minicraft.displays.controls.display.keyboard" : "minicraft.displays.controls.display.controller"), screen, 10, Color.WHITE); if (displaying == 0) { // If displaying keyboard mappings. Font.drawCentered(Localization.getLocalized("minicraft.displays.controls.display.keyboard.desc"), screen, Screen.h - 16, Color.GRAY); diff --git a/src/client/java/minicraft/screen/CraftingDisplay.java b/src/client/java/minicraft/screen/CraftingDisplay.java index 2432335e8..fa92751c4 100644 --- a/src/client/java/minicraft/screen/CraftingDisplay.java +++ b/src/client/java/minicraft/screen/CraftingDisplay.java @@ -36,9 +36,12 @@ public class CraftingDisplay extends Display { private static final HashSet unlockedRecipes = new HashSet<>(); - public CraftingDisplay(List recipes, String title, Player player) { this(recipes, title, player, false); } + public CraftingDisplay(List recipes, String title, Player player) { + this(recipes, title, player, false); + } + public CraftingDisplay(List recipes, String title, Player player, boolean isPersonal) { - for(Recipe recipe: recipes) + for (Recipe recipe : recipes) recipe.checkCanCraft(player); this.player = player; this.title = title; @@ -59,10 +62,10 @@ private void refreshDisplayRecipes() { List recipes = availableRecipes.stream().filter(unlockedRecipes::contains).collect(Collectors.toList()); recipeMenu = new RecipeMenu(recipes, title, player); this.recipes = recipes.toArray(new Recipe[0]); - itemCountMenu.setPositioning(new Point(recipeMenu.getBounds().getRight()+MinicraftImage.boxWidth, recipeMenu.getBounds().getTop()), RelPos.BOTTOM_RIGHT); + itemCountMenu.setPositioning(new Point(recipeMenu.getBounds().getRight() + MinicraftImage.boxWidth, recipeMenu.getBounds().getTop()), RelPos.BOTTOM_RIGHT); costsMenu.setPositioning(new Point(itemCountMenu.createMenu().getBounds().getLeft(), recipeMenu.getBounds().getBottom()), RelPos.TOP_RIGHT); - menus = new Menu[] {recipeMenu, itemCountMenu.createMenu(), costsMenu.createMenu()}; + menus = new Menu[]{recipeMenu, itemCountMenu.createMenu(), costsMenu.createMenu()}; refreshData(); onScreenKeyboardMenu = OnScreenKeyboardMenu.checkAndCreateMenu(); @@ -94,7 +97,7 @@ private ItemListing[] getCurItemCosts() { if (recipes.length == 0) return new ItemListing[0]; Map costMap = recipes[recipeMenu.getSelection()].getCosts(); - for(String itemName: costMap.keySet()) { + for (String itemName : costMap.keySet()) { Item cost = Items.get(itemName); costList.add(new ItemListing(cost, player.getInventory().count(cost) + "/" + costMap.get(itemName))); } @@ -160,12 +163,12 @@ public void tick(InputHandler input) { if (recipes.length == 0) return; Recipe selectedRecipe = recipes[recipeMenu.getSelection()]; if (selectedRecipe.getCanCraft()) { - if (selectedRecipe.getProduct().equals(Items.get("Workbench"))){ - AchievementsDisplay.setAchievement("minicraft.achievement.benchmarking",true); - } else if (selectedRecipe.getProduct().equals(Items.get("Plank"))){ - AchievementsDisplay.setAchievement("minicraft.achievement.planks",true); - } else if (selectedRecipe.getProduct().equals(Items.get("Wood Door"))){ - AchievementsDisplay.setAchievement("minicraft.achievement.doors",true); + if (selectedRecipe.getProduct().equals(Items.get("Workbench"))) { + AchievementsDisplay.setAchievement("minicraft.achievement.benchmarking", true); + } else if (selectedRecipe.getProduct().equals(Items.get("Plank"))) { + AchievementsDisplay.setAchievement("minicraft.achievement.planks", true); + } else if (selectedRecipe.getProduct().equals(Items.get("Wood Door"))) { + AchievementsDisplay.setAchievement("minicraft.achievement.doors", true); } else if (selectedRecipe.getProduct().equals(Items.get("Rock Sword")) || selectedRecipe.getProduct().equals(Items.get("Rock Pickaxe")) || selectedRecipe.getProduct().equals(Items.get("Rock Axe")) || diff --git a/src/client/java/minicraft/screen/Display.java b/src/client/java/minicraft/screen/Display.java index d02ecdc31..88ec10cf0 100644 --- a/src/client/java/minicraft/screen/Display.java +++ b/src/client/java/minicraft/screen/Display.java @@ -16,11 +16,26 @@ public class Display { private final boolean canExit, clearScreen; - public Display() { this(new Menu[0]); } - public Display(Menu... menus) { this(false, true, menus); } - public Display(boolean clearScreen) { this(clearScreen, true, new Menu[0]); } - public Display(boolean clearScreen, Menu... menus) { this(clearScreen, true, menus); } - public Display(boolean clearScreen, boolean canExit) { this(clearScreen, canExit, new Menu[0]); } + public Display() { + this(new Menu[0]); + } + + public Display(Menu... menus) { + this(false, true, menus); + } + + public Display(boolean clearScreen) { + this(clearScreen, true, new Menu[0]); + } + + public Display(boolean clearScreen, Menu... menus) { + this(clearScreen, true, menus); + } + + public Display(boolean clearScreen, boolean canExit) { + this(clearScreen, canExit, new Menu[0]); + } + public Display(boolean clearScreen, boolean canExit, Menu... menus) { this.menus = menus; this.canExit = canExit; @@ -29,7 +44,10 @@ public Display(boolean clearScreen, boolean canExit, Menu... menus) { } private boolean setParent = false; - /** Called during {@link Game#setDisplay} */ + + /** + * Called during {@link Game#setDisplay} + */ public void init(@Nullable Display parent) { if (!setParent) { setParent = true; @@ -37,9 +55,12 @@ public void init(@Nullable Display parent) { } } - public void onExit() {} + public void onExit() { + } - public Display getParent() { return parent; } + public Display getParent() { + return parent; + } public void tick(InputHandler input) { @@ -56,8 +77,8 @@ public void tick(InputHandler input) { int prevSel = selection; String shift = menus[selection].getCurEntry() instanceof ArrayEntry ? "shift-" : ""; - if (input.getMappedKey(shift+"left").isClicked() || input.leftTriggerPressed()) selection--; - if (input.getMappedKey(shift+"right").isClicked() || input.rightTriggerPressed()) selection++; + if (input.getMappedKey(shift + "left").isClicked() || input.leftTriggerPressed()) selection--; + if (input.getMappedKey(shift + "right").isClicked() || input.rightTriggerPressed()) selection++; if (prevSel != selection) { Sound.play("select"); @@ -68,7 +89,7 @@ public void tick(InputHandler input) { selection += delta; if (selection < 0) selection = menus.length - 1; selection = selection % menus.length; - } while(!menus[selection].isSelectable() && selection != prevSel); + } while (!menus[selection].isSelectable() && selection != prevSel); changedSelection = prevSel != selection; } @@ -100,7 +121,7 @@ else if (setParent && parent != null) { do { idx++; idx = idx % menus.length; - if(menus[idx].shouldRender()) + if (menus[idx].shouldRender()) menus[idx].render(screen); } while (idx != selection); } diff --git a/src/client/java/minicraft/screen/EndGameDisplay.java b/src/client/java/minicraft/screen/EndGameDisplay.java index d1edc8972..61105f538 100644 --- a/src/client/java/minicraft/screen/EndGameDisplay.java +++ b/src/client/java/minicraft/screen/EndGameDisplay.java @@ -30,7 +30,7 @@ public class EndGameDisplay extends Display { static { int maxLength = 0; - for (String s: scoredItems) + for (String s : scoredItems) maxLength = Math.max(maxLength, s.length()); } @@ -38,7 +38,7 @@ public EndGameDisplay() { super(false, false); displayTimer = Updater.normSpeed; // wait 3 seconds before rendering the menu. - inputDelay = Updater.normSpeed/2; // wait a half-second after rendering before allowing user input. + inputDelay = Updater.normSpeed / 2; // wait a half-second after rendering before allowing user input. ArrayList entries = new ArrayList<>(); @@ -48,7 +48,7 @@ public EndGameDisplay() { entries.add(new StringEntry("minicraft.displays.end_game.display.bonuses", Color.YELLOW)); finalScore = Game.player.getScore(); - for(String item: scoredItems) + for (String item : scoredItems) addBonus(item); entries.add(new StringEntry(Localization.getLocalized("minicraft.displays.end_game.display.final_score", finalScore))); @@ -58,7 +58,7 @@ public EndGameDisplay() { entries.add(new SelectEntry("minicraft.displays.end_game.exit", () -> Game.setDisplay(new TitleDisplay()))); - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(true, 0, RelPos.LEFT, entries).createMenu() }; } @@ -78,7 +78,7 @@ public void tick(InputHandler input) { @Override public void render(Screen screen) { - if(displayTimer <= 0) + if (displayTimer <= 0) super.render(screen); } diff --git a/src/client/java/minicraft/screen/InfoDisplay.java b/src/client/java/minicraft/screen/InfoDisplay.java index 7e1feb2c3..9d801cd77 100644 --- a/src/client/java/minicraft/screen/InfoDisplay.java +++ b/src/client/java/minicraft/screen/InfoDisplay.java @@ -19,10 +19,10 @@ public InfoDisplay() { "----------------------------", Localization.getLocalized("minicraft.displays.info.display.exit_help", Game.input.getMapping("select"), Game.input.getMapping("exit")) )) - .setTitle("minicraft.displays.info.title") - .setTitlePos(RelPos.TOP_LEFT) - .setPositioning(new Point(MinicraftImage.boxWidth, MinicraftImage.boxWidth), RelPos.BOTTOM_RIGHT) - .createMenu() + .setTitle("minicraft.displays.info.title") + .setTitlePos(RelPos.TOP_LEFT) + .setPositioning(new Point(MinicraftImage.boxWidth, MinicraftImage.boxWidth), RelPos.BOTTOM_RIGHT) + .createMenu() ); } diff --git a/src/client/java/minicraft/screen/InventoryMenu.java b/src/client/java/minicraft/screen/InventoryMenu.java index 21bb8df9f..b924b9879 100644 --- a/src/client/java/minicraft/screen/InventoryMenu.java +++ b/src/client/java/minicraft/screen/InventoryMenu.java @@ -32,17 +32,17 @@ public void tick(InputHandler input) { boolean dropOne = input.inputPressed("drop-one"); - if(getNumOptions() > 0 && (dropOne || input.inputPressed("drop-stack"))) { - ItemEntry entry = ((ItemEntry)getCurEntry()); - if(entry == null) return; + if (getNumOptions() > 0 && (dropOne || input.inputPressed("drop-stack"))) { + ItemEntry entry = ((ItemEntry) getCurEntry()); + if (entry == null) return; Item invItem = entry.getItem(); Item drop = invItem.copy(); if (!creativeInv) { - if (dropOne && drop instanceof StackableItem && ((StackableItem)drop).count > 1) { + if (dropOne && drop instanceof StackableItem && ((StackableItem) drop).count > 1) { // just drop one from the stack - ((StackableItem)drop).count = 1; - ((StackableItem)invItem).count--; + ((StackableItem) drop).count = 1; + ((StackableItem) invItem).count--; } else { // drop the whole item. removeSelectedEntry(); diff --git a/src/client/java/minicraft/screen/ItemListMenu.java b/src/client/java/minicraft/screen/ItemListMenu.java index 6fea47075..2b7c96df9 100644 --- a/src/client/java/minicraft/screen/ItemListMenu.java +++ b/src/client/java/minicraft/screen/ItemListMenu.java @@ -5,7 +5,10 @@ class ItemListMenu extends Menu { - static Builder getBuilder() { return getBuilder(RelPos.LEFT); } + static Builder getBuilder() { + return getBuilder(RelPos.LEFT); + } + static Builder getBuilder(RelPos entryPos) { return new Builder(true, 0, entryPos) .setPositioning(new Point(9, 9), RelPos.BOTTOM_RIGHT) diff --git a/src/client/java/minicraft/screen/KeyInputDisplay.java b/src/client/java/minicraft/screen/KeyInputDisplay.java index 59759f9a8..f3c68612b 100644 --- a/src/client/java/minicraft/screen/KeyInputDisplay.java +++ b/src/client/java/minicraft/screen/KeyInputDisplay.java @@ -48,9 +48,9 @@ public KeyInputDisplay() { super(true); builder = new Menu.Builder(false, 0, RelPos.CENTER, getEntries()) .setTitle("minicraft.displays.key_input.title") - .setPositioning(new Point(Screen.w/2, Screen.h - Font.textHeight()*5), RelPos.TOP); + .setPositioning(new Point(Screen.w / 2, Screen.h - Font.textHeight() * 5), RelPos.TOP); - menus = new Menu[] { + menus = new Menu[]{ builder.createMenu() }; } @@ -103,7 +103,7 @@ public void render(Screen screen) { Localization.getLocalized("minicraft.displays.key_input.display.help.3", Game.input.getMapping("exit")) }; - for(int i = 0; i < lines.length; i++) - Font.drawCentered(lines[i], screen, Screen.h-Font.textHeight()*(4-i), Color.WHITE); + for (int i = 0; i < lines.length; i++) + Font.drawCentered(lines[i], screen, Screen.h - Font.textHeight() * (4 - i), Color.WHITE); } } diff --git a/src/client/java/minicraft/screen/LanguageSettingsDisplay.java b/src/client/java/minicraft/screen/LanguageSettingsDisplay.java index 90e9ec81f..44e06949d 100644 --- a/src/client/java/minicraft/screen/LanguageSettingsDisplay.java +++ b/src/client/java/minicraft/screen/LanguageSettingsDisplay.java @@ -14,7 +14,7 @@ import java.util.Map; public class LanguageSettingsDisplay extends Display { - private Map.Entry ,Integer> getEntries() { + private Map.Entry, Integer> getEntries() { Localization.LocaleInformation[] locales = Localization.getLocales(); ArrayList list = new ArrayList<>(Arrays.asList(locales)); list.sort((a, b) -> { // Debug language is always on top. @@ -44,12 +44,12 @@ public int getColor(boolean isSelected) { public LanguageSettingsDisplay() { super(true); - Map.Entry ,Integer> entries = getEntries(); - menus = new Menu[] { + Map.Entry, Integer> entries = getEntries(); + menus = new Menu[]{ new Menu.Builder(false, 2, RelPos.CENTER, entries.getKey()) .setTitle("minicraft.displays.language_settings.title") .setSelectable(true) - .setPositioning(new Point(Screen.w/2, 10), RelPos.BOTTOM) + .setPositioning(new Point(Screen.w / 2, 10), RelPos.BOTTOM) .setSize(Screen.w, Screen.h - 30) .setSelection(entries.getValue()) .createMenu() diff --git a/src/client/java/minicraft/screen/LevelTransitionDisplay.java b/src/client/java/minicraft/screen/LevelTransitionDisplay.java index 7681c5141..6f8a3a970 100644 --- a/src/client/java/minicraft/screen/LevelTransitionDisplay.java +++ b/src/client/java/minicraft/screen/LevelTransitionDisplay.java @@ -17,24 +17,26 @@ public class LevelTransitionDisplay extends Display { private LinkedSprite hudSheet = new LinkedSprite(SpriteType.Gui, "hud"); public LevelTransitionDisplay(int dir) { - super(false,false); + super(false, false); this.dir = dir; } @Override public void tick(InputHandler input) { time++; // Ticks up 2 times per tick - if (time == DURATION/2) World.changeLevel(dir); // When time equals 30, it will change the level + if (time == DURATION / 2) World.changeLevel(dir); // When time equals 30, it will change the level if (time == DURATION) Game.setDisplay(null); // When time equals 60, it will get out of this menu } public void render(Screen screen) { for (int x = 0; x < 200; x++) { // Loop however many times depending on the width (It's divided by 3 because the pixels are scaled up by 3) for (int y = 0; y < 150; y++) { // Loop however many times depending on the height (It's divided by 3 because the pixels are scaled up by 3) - int dd = (y + x % 2 * 2 + x / 3) - time*2; // Used as part of the positioning. + int dd = (y + x % 2 * 2 + x / 3) - time * 2; // Used as part of the positioning. if (dd < 0 && dd > -30) { - if (dir > 0) screen.render(x * 8, y * 8, 5, 2, 0, hudSheet.getSheet()); // If the direction is upwards then render the squares going up - else screen.render(x * 8, Screen.h - y * 8 - 8, 5, 2, 0, hudSheet.getSheet()); // If the direction is negative, then the squares will go down. + if (dir > 0) + screen.render(x * 8, y * 8, 5, 2, 0, hudSheet.getSheet()); // If the direction is upwards then render the squares going up + else + screen.render(x * 8, Screen.h - y * 8 - 8, 5, 2, 0, hudSheet.getSheet()); // If the direction is negative, then the squares will go down. } } } diff --git a/src/client/java/minicraft/screen/LoadingDisplay.java b/src/client/java/minicraft/screen/LoadingDisplay.java index 62c2e20d6..6315ace84 100644 --- a/src/client/java/minicraft/screen/LoadingDisplay.java +++ b/src/client/java/minicraft/screen/LoadingDisplay.java @@ -70,8 +70,14 @@ public void onExit() { public static void setPercentage(float percent) { percentage = percent; } - public static float getPercentage() { return percentage; } - public static void setMessage(String progressType) { LoadingDisplay.progressType = progressType; } + + public static float getPercentage() { + return percentage; + } + + public static void setMessage(String progressType) { + LoadingDisplay.progressType = progressType; + } public static void progress(float amt) { percentage = Math.min(100, percentage + amt); diff --git a/src/client/java/minicraft/screen/Menu.java b/src/client/java/minicraft/screen/Menu.java index 50701ec62..ca402bc4a 100644 --- a/src/client/java/minicraft/screen/Menu.java +++ b/src/client/java/minicraft/screen/Menu.java @@ -70,7 +70,9 @@ public class Menu { private LinkedSprite hudSheet = new LinkedSprite(SpriteType.Gui, "hud"); - private Menu() {} + private Menu() { + } + protected Menu(Menu m) { entries.addAll(m.entries); spacing = m.spacing; @@ -100,17 +102,17 @@ protected Menu(Menu m) { public void init() { - if(entries.size() == 0) { + if (entries.size() == 0) { selection = 0; dispSelection = 0; offset = 0; return; } - selection = Math.min(selection, entries.size()-1); + selection = Math.min(selection, entries.size() - 1); selection = Math.max(0, selection); - if(!entries.get(selection).isSelectable()) { + if (!entries.get(selection).isSelectable()) { int prevSel = selection; do { selection++; @@ -120,46 +122,76 @@ public void init() { } dispSelection = selection; - dispSelection = Math.min(dispSelection, displayLength-1); + dispSelection = Math.min(dispSelection, displayLength - 1); dispSelection = Math.max(0, dispSelection); doScroll(); } void setSelection(int idx) { - if(idx >= entries.size()) + if (idx >= entries.size()) idx = entries.size() - 1; - if(idx < 0) idx = 0; + if (idx < 0) idx = 0; this.selection = idx; doScroll(); } - int getSelection() { return selection; } - int getDispSelection() { return dispSelection; } - ListEntry[] getEntries() { return entries.toArray(new ListEntry[0]); } + int getSelection() { + return selection; + } + + int getDispSelection() { + return dispSelection; + } + + ListEntry[] getEntries() { + return entries.toArray(new ListEntry[0]); + } + protected void setEntries(ListEntry[] entries) { this.entries.clear(); this.entries.addAll(0, Arrays.asList(entries)); } + protected void setEntries(List entries) { this.entries.clear(); this.entries.addAll(entries); } - @Nullable ListEntry getCurEntry() { return entries.size() == 0 ? null : entries.get(selection); } - int getNumOptions() { return entries.size(); } - Rectangle getBounds() { return new Rectangle(bounds); } - String getTitle() { return title; } + @Nullable ListEntry getCurEntry() { + return entries.size() == 0 ? null : entries.get(selection); + } + + int getNumOptions() { + return entries.size(); + } + + Rectangle getBounds() { + return new Rectangle(bounds); + } + + String getTitle() { + return title; + } - boolean isSelectable() { return selectable; } - boolean shouldRender() { return shouldRender; } + boolean isSelectable() { + return selectable; + } - public boolean isSearcherBarActive() { return searcherBarActive; } + boolean shouldRender() { + return shouldRender; + } - /** @noinspection SameParameterValue*/ + public boolean isSearcherBarActive() { + return searcherBarActive; + } + + /** + * @noinspection SameParameterValue + */ void translate(int xoff, int yoff) { bounds.translate(xoff, yoff); entryBounds.translate(xoff, yoff); @@ -167,7 +199,7 @@ void translate(int xoff, int yoff) { } public void tick(InputHandler input) { - if(!selectable || entries.size() == 0) return; + if (!selectable || entries.size() == 0) return; int prevSel = selection; if (input.inputPressed("cursor-up")) selection--; @@ -238,7 +270,7 @@ public void tick(InputHandler input) { int delta = selection - prevSel; selection = prevSel; - if(delta == 0) { + if (delta == 0) { entries.get(selection).tick(input); // only ticks the entry on a frame where the selection cursor has not moved. return; } else @@ -248,13 +280,13 @@ public void tick(InputHandler input) { selection += delta; if (selection < 0) selection = entries.size() - 1; selection = selection % entries.size(); - } while(!entries.get(selection).isSelectable() && selection != prevSel); + } while (!entries.get(selection).isSelectable() && selection != prevSel); // update offset and selection displayed dispSelection += selection - prevSel; - if(dispSelection < 0) dispSelection = 0; - if(dispSelection >= displayLength) dispSelection = displayLength - 1; + if (dispSelection < 0) dispSelection = 0; + if (dispSelection >= displayLength) dispSelection = displayLength - 1; doScroll(); } @@ -266,20 +298,20 @@ private void doScroll() { int offset = this.offset; // for scrolling up - while((dispSelection < padding || !wrap && offset + displayLength > entries.size()) && (wrap || offset > 0)) { + while ((dispSelection < padding || !wrap && offset + displayLength > entries.size()) && (wrap || offset > 0)) { offset--; dispSelection++; } // for scrolling down - while((displayLength - dispSelection <= padding || !wrap && offset < 0) && (wrap || offset + displayLength < entries.size())) { + while ((displayLength - dispSelection <= padding || !wrap && offset < 0) && (wrap || offset + displayLength < entries.size())) { offset++; dispSelection--; } // only useful when wrap is true - if(offset < 0) offset += entries.size(); - if(offset > 0) offset = offset % entries.size(); + if (offset < 0) offset += entries.size(); + if (offset > 0) offset = offset % entries.size(); this.offset = offset; } @@ -288,15 +320,17 @@ public void render(Screen screen) { renderFrame(screen); // render the title - if(title.length() > 0) { + if (title.length() > 0) { if (drawVertically) { for (int i = 0; i < title.length(); i++) { - if (hasFrame) screen.render(titleLoc.x, titleLoc.y + i * Font.textHeight(), 3, 6, 0, hudSheet.getSheet()); + if (hasFrame) + screen.render(titleLoc.x, titleLoc.y + i * Font.textHeight(), 3, 6, 0, hudSheet.getSheet()); Font.draw(title.substring(i, i + 1), screen, titleLoc.x, titleLoc.y + i * Font.textHeight(), titleColor); } } else { for (int i = 0; i < title.length(); i++) { - if (hasFrame) screen.render(titleLoc.x + i * Font.textWidth(" "), titleLoc.y, 3, 6, 0, hudSheet.getSheet()); + if (hasFrame) + screen.render(titleLoc.x + i * Font.textWidth(" "), titleLoc.y, 3, 6, 0, hudSheet.getSheet()); Font.draw(title.substring(i, i + 1), screen, titleLoc.x + i * Font.textWidth(" "), titleLoc.y, titleColor); } } @@ -325,18 +359,18 @@ public void render(Screen screen) { // render the options int y = entryBounds.getTop(); boolean special = wrap && entries.size() < displayLength; - if(special) { + if (special) { int diff = displayLength - entries.size(); // we have to account for this many entry heights. - int extra = diff*(ListEntry.getHeight() + spacing) / 2; + int extra = diff * (ListEntry.getHeight() + spacing) / 2; y += extra; } - for(int i = offset; i < (wrap ? offset + displayLength : Math.min(offset + displayLength, entries.size())); i++) { - if(special && i-offset >= entries.size()) break; + for (int i = offset; i < (wrap ? offset + displayLength : Math.min(offset + displayLength, entries.size())); i++) { + if (special && i - offset >= entries.size()) break; int idx = i % entries.size(); ListEntry entry = entries.get(idx); - if(!(entry instanceof BlankEntry)) { + if (!(entry instanceof BlankEntry)) { Point pos = entryPos.positionRect(new Dimension(entry.getWidth(), ListEntry.getHeight()), new Rectangle(entryBounds.getLeft(), y, entryBounds.getWidth(), ListEntry.getHeight(), Rectangle.CORNER_DIMS)); boolean selected = idx == selection; if (searcherBarActive && useSearcherBar) { @@ -355,18 +389,21 @@ public void render(Screen screen) { } } - void updateSelectedEntry(ListEntry newEntry) { updateEntry(selection, newEntry); } + void updateSelectedEntry(ListEntry newEntry) { + updateEntry(selection, newEntry); + } + void updateEntry(int idx, ListEntry newEntry) { - if(idx >= 0 && idx < entries.size()) + if (idx >= 0 && idx < entries.size()) entries.set(idx, newEntry); } public void removeSelectedEntry() { entries.remove(selection); - if(selection >= entries.size()) + if (selection >= entries.size()) selection = entries.size() - 1; - if(selection < 0) + if (selection < 0) selection = 0; doScroll(); @@ -377,10 +414,10 @@ public void setColors(Menu model) { } private void renderFrame(Screen screen) { - if(!hasFrame) return; + if (!hasFrame) return; - int bottom = bounds.getBottom()-MinicraftImage.boxWidth; - int right = bounds.getRight()-MinicraftImage.boxWidth; + int bottom = bounds.getBottom() - MinicraftImage.boxWidth; + int right = bounds.getRight() - MinicraftImage.boxWidth; for (int y = bounds.getTop(); y <= bottom; y += MinicraftImage.boxWidth) { // loop through the height of the bounds for (int x = bounds.getLeft(); x <= right; x += MinicraftImage.boxWidth) { // loop through the width of the bounds @@ -388,42 +425,47 @@ private void renderFrame(Screen screen) { boolean xend = x == bounds.getLeft() || x == right; boolean yend = y == bounds.getTop() || y == bottom; int spriteoffset = (xend && yend ? 0 : (yend ? 1 : (xend ? 2 : 3))); // determines which sprite to use - int mirrors = ( x == right ? 1 : 0 ) + ( y == bottom ? 2 : 0 ); // gets mirroring + int mirrors = (x == right ? 1 : 0) + (y == bottom ? 2 : 0); // gets mirroring screen.render(x, y, spriteoffset, 6, mirrors, hudSheet.getSheet()); - if(x < right && x + MinicraftImage.boxWidth > right) + if (x < right && x + MinicraftImage.boxWidth > right) x = right - MinicraftImage.boxWidth; } - if(y < bottom && y + MinicraftImage.boxWidth > bottom) + if (y < bottom && y + MinicraftImage.boxWidth > bottom) y = bottom - MinicraftImage.boxWidth; } } - // This needs to be in the Menu class, to have access to the private constructor and fields. public static class Builder { - private static final Point center = new Point(Screen.w/2, Screen.h/2); + private static final Point center = new Point(Screen.w / 2, Screen.h / 2); private Menu menu; private boolean setSelectable = false; private float padding = 1; - @NotNull private RelPos titlePos = RelPos.TOP; + @NotNull + private RelPos titlePos = RelPos.TOP; private boolean fullTitleColor = false, setTitleColor = false; private int titleCol = Color.YELLOW; - @NotNull private Point anchor = center; - @NotNull private RelPos menuPos = RelPos.CENTER; + @NotNull + private Point anchor = center; + @NotNull + private RelPos menuPos = RelPos.CENTER; private Dimension menuSize = null; private boolean searcherBar; - public Builder(boolean hasFrame, int entrySpacing, RelPos entryPos, ListEntry... entries) { this(hasFrame, entrySpacing, entryPos, Arrays.asList(entries)); } + public Builder(boolean hasFrame, int entrySpacing, RelPos entryPos, ListEntry... entries) { + this(hasFrame, entrySpacing, entryPos, Arrays.asList(entries)); + } + public Builder(boolean hasFrame, int entrySpacing, RelPos entryPos, List entries) { menu = new Menu(); setEntries(entries); @@ -432,7 +474,10 @@ public Builder(boolean hasFrame, int entrySpacing, RelPos entryPos, List entries) { menu.entries.clear(); menu.entries.addAll(entries); @@ -445,8 +490,15 @@ public Builder setPositioning(Point anchor, RelPos menuPos) { return this; } - public Builder setSize(int width, int height) { menuSize = new Dimension(width, height); return this; } - public Builder setMenuSize(Dimension d) { menuSize = d; return this; } // can be used to set the size to null + public Builder setSize(int width, int height) { + menuSize = new Dimension(width, height); + return this; + } + + public Builder setMenuSize(Dimension d) { + menuSize = d; + return this; + } // can be used to set the size to null public Builder setBounds(Rectangle rect) { menuSize = rect.getSize(); @@ -454,20 +506,32 @@ public Builder setBounds(Rectangle rect) { return this; } - public Builder setDisplayLength(int numEntries) { menu.displayLength = numEntries; return this; } + public Builder setDisplayLength(int numEntries) { + menu.displayLength = numEntries; + return this; + } + + public Builder setTitlePos(RelPos rp) { + titlePos = (rp == null ? RelPos.TOP : rp); + return this; + } - public Builder setTitlePos(RelPos rp) { titlePos = (rp == null ? RelPos.TOP : rp); return this; } + public Builder setTitle(String title) { + menu.title = title; + return this; + } - public Builder setTitle(String title) { menu.title = title; return this; } + public Builder setTitle(String title, int color) { + return setTitle(title, color, false); + } - public Builder setTitle(String title, int color) { return setTitle(title, color, false); } public Builder setTitle(String title, int color, boolean fullColor) { menu.title = title; fullTitleColor = fullColor; setTitleColor = true; - if(fullColor) // this means that the color is the full 4 parts, abcd. Otherwise, it is assumed it is only the main component, the one that matters. + if (fullColor) // this means that the color is the full 4 parts, abcd. Otherwise, it is assumed it is only the main component, the one that matters. menu.titleColor = color; else titleCol = color; @@ -475,7 +539,10 @@ public Builder setTitle(String title, int color, boolean fullColor) { return this; } - public Builder setFrame(boolean hasFrame) { menu.hasFrame = hasFrame; return this; } + public Builder setFrame(boolean hasFrame) { + menu.hasFrame = hasFrame; + return this; + } public Builder setScrollPolicies(float padding, boolean wrap) { @@ -484,7 +551,10 @@ public Builder setScrollPolicies(float padding, boolean wrap) { return this; } - public Builder setShouldRender(boolean render) { menu.shouldRender = render; return this; } + public Builder setShouldRender(boolean render) { + menu.shouldRender = render; + return this; + } public Builder setSelectable(boolean selectable) { setSelectable = true; @@ -492,7 +562,11 @@ public Builder setSelectable(boolean selectable) { return this; } - public Builder setSelection(int sel) { menu.selection = sel; return this; } + public Builder setSelection(int sel) { + menu.selection = sel; + return this; + } + public Builder setSelection(int sel, int dispSel) { menu.selection = sel; menu.dispSelection = dispSel; @@ -509,17 +583,18 @@ public Menu createMenu() { // this way, I don't have to reference all the variables to a different var. return copy().createMenu(this); } + private Menu createMenu(Builder b) { - if(b == this) + if (b == this) return copy().createMenu(this); menu.title = Localization.getLocalized(menu.title); // set default selectability - if(!setSelectable) { - for(ListEntry entry: menu.entries) { + if (!setSelectable) { + for (ListEntry entry : menu.entries) { menu.selectable = menu.selectable || entry.isSelectable(); - if(menu.selectable) + if (menu.selectable) break; } } @@ -529,8 +604,8 @@ private Menu createMenu(Builder b) { menu.drawVertically = titlePos == RelPos.LEFT || titlePos == RelPos.RIGHT; Dimension titleDim = menu.drawVertically ? - new Dimension(Font.textHeight()*2, Font.textWidth(menu.title)) : - new Dimension(Font.textWidth(menu.title), Font.textHeight()*2); + new Dimension(Font.textHeight() * 2, Font.textWidth(menu.title)) : + new Dimension(Font.textWidth(menu.title), Font.textHeight() * 2); // find the area used by the title and/or frame, that can't be used by the entries @@ -547,7 +622,7 @@ private Menu createMenu(Builder b) { */ Insets border; - if(menu.hasFrame) + if (menu.hasFrame) border = new Insets(MinicraftImage.boxWidth); // add frame insets else { border = new Insets(); @@ -567,39 +642,38 @@ else if (c.xIndex == 2) // must be center right } } - if(menu.isSelectable()) { + if (menu.isSelectable()) { // add spacing for selection cursors border.left += MinicraftImage.boxWidth * 2; border.right += MinicraftImage.boxWidth * 2; } - if(menu.wrap && menu.displayLength > 0) + if (menu.wrap && menu.displayLength > 0) menu.displayLength = Math.min(menu.displayLength, menu.entries.size()); // I have anchor and menu's relative position to it, and may or may not have size. Dimension entrySize; - if(menuSize == null) { + if (menuSize == null) { int width = titleDim.width; - for(ListEntry entry: menu.entries) { + for (ListEntry entry : menu.entries) { int entryWidth = entry.getWidth(); - if(menu.isSelectable() && !entry.isSelectable()) + if (menu.isSelectable() && !entry.isSelectable()) entryWidth = Math.max(0, entryWidth - MinicraftImage.boxWidth * 4); width = Math.max(width, entryWidth); } - if(menu.displayLength > 0) { // has been set; use to determine entry bounds + if (menu.displayLength > 0) { // has been set; use to determine entry bounds int height = (ListEntry.getHeight() + menu.spacing) * menu.displayLength - menu.spacing; entrySize = new Dimension(width, height); - } - else { + } else { // no set size; just keep going to the edges of the screen int maxHeight; - if(menuPos.yIndex == 0) // anchor is lowest down coordinate (highest y value) + if (menuPos.yIndex == 0) // anchor is lowest down coordinate (highest y value) maxHeight = anchor.y; - else if(menuPos.yIndex == 2) + else if (menuPos.yIndex == 2) maxHeight = Screen.h - anchor.y; else // is centered; take the lowest value of the other two, and double it maxHeight = Math.min(anchor.y, Screen.h - anchor.y) * 2; @@ -614,13 +688,12 @@ else if(menuPos.yIndex == 2) } menuSize = border.addTo(entrySize); - } - else // menuSize was set manually + } else // menuSize was set manually entrySize = border.subtractFrom(menuSize); // set default max display length (needs size first) - if(menu.displayLength <= 0 && menu.entries.size() > 0) + if (menu.displayLength <= 0 && menu.entries.size() > 0) menu.displayLength = (entrySize.height + menu.spacing) / (ListEntry.getHeight() + menu.spacing); // based on the menu centering, and the anchor, determine the upper-left point from which to draw the menu. @@ -630,14 +703,14 @@ else if(menuPos.yIndex == 2) menu.titleLoc = titlePos.positionRect(titleDim, menu.bounds); - if(titlePos.xIndex == 0 && titlePos.yIndex != 1) + if (titlePos.xIndex == 0 && titlePos.yIndex != 1) menu.titleLoc.x += MinicraftImage.boxWidth; - if(titlePos.xIndex == 2 && titlePos.yIndex != 1) + if (titlePos.xIndex == 2 && titlePos.yIndex != 1) menu.titleLoc.x -= MinicraftImage.boxWidth; // set the menu title color - if(menu.title.length() > 0) { - if(fullTitleColor) + if (menu.title.length() > 0) { + if (fullTitleColor) menu.titleColor = titleCol; else { if (!setTitleColor) titleCol = menu.hasFrame ? Color.YELLOW : Color.WHITE; @@ -645,9 +718,9 @@ else if(menuPos.yIndex == 2) } } - if(padding < 0) padding = 0; - if(padding > 1) padding = 1; - menu.padding = (int)Math.floor(padding * menu.displayLength / 2); + if (padding < 0) padding = 0; + if (padding > 1) padding = 1; + menu.padding = (int) Math.floor(padding * menu.displayLength / 2); menu.useSearcherBar = searcherBar; @@ -679,6 +752,6 @@ public Builder copy() { } public String toString() { - return title+"-Menu["+bounds+"]"; + return title + "-Menu[" + bounds + "]"; } } diff --git a/src/client/java/minicraft/screen/MultiplayerDisplay.java b/src/client/java/minicraft/screen/MultiplayerDisplay.java index c130957f8..3a2a1c68c 100644 --- a/src/client/java/minicraft/screen/MultiplayerDisplay.java +++ b/src/client/java/minicraft/screen/MultiplayerDisplay.java @@ -18,12 +18,14 @@ import minicraft.network.Analytics; import minicraft.util.Logging; -/** @deprecated As multiplayer mode removed. This class is not localized. */ +/** + * @deprecated As multiplayer mode removed. This class is not localized. + */ @Deprecated public class MultiplayerDisplay extends Display { private static final String domain = "https://playminicraft.com"; - private static final String apiDomain = domain+"/api"; + private static final String apiDomain = domain + "/api"; public static String savedIP = ""; public static String savedUUID = ""; @@ -48,15 +50,19 @@ private enum State { private State curState; - public MultiplayerDisplay() { this(true); } + public MultiplayerDisplay() { + this(true); + } + public MultiplayerDisplay(boolean pingSite) { - if(savedUUID == null) savedUUID = ""; - if(email == null) email = ""; - if(savedUsername == null) savedUsername = ""; + if (savedUUID == null) savedUUID = ""; + if (email == null) email = ""; + if (savedUsername == null) savedUsername = ""; - if(pingSite) - contactAccountServer(() -> {}); + if (pingSite) + contactAccountServer(() -> { + }); } private void contactAccountServer(Action sitePingCallback) { @@ -65,23 +71,23 @@ private void contactAccountServer(Action sitePingCallback) { Unirest.get(domain).asEmptyAsync(new Callback() { @Override public void completed(HttpResponse response) { - if(response.getStatus() == 200) + if (response.getStatus() == 200) online = true; else System.err.println("Warning: Minicraft site ping returned status code " + response.getStatus()); - if(savedUUID.length() > 0) { + if (savedUUID.length() > 0) { setWaitMessage("attempting log in"); fetchName(savedUUID); } - if(curState == State.ERROR) + if (curState == State.ERROR) return; // at this point, the game is online, and either the player could log in automatically, or has to enter their // email and password. - if(savedUsername.length() == 0 || savedUUID.length() == 0) + if (savedUsername.length() == 0 || savedUUID.length() == 0) curState = State.LOGIN; // the player must log in manually. else { typing = savedIP; @@ -93,8 +99,8 @@ public void completed(HttpResponse response) { @Override public void failed(UnirestException e) { - System.err.println("Website ping failed: "+e.getMessage()); - if(!e.getMessage().equalsIgnoreCase("connection reset by peer")) + System.err.println("Website ping failed: " + e.getMessage()); + if (!e.getMessage().equalsIgnoreCase("connection reset by peer")) e.printStackTrace(); cancelled(); } @@ -102,7 +108,7 @@ public void failed(UnirestException e) { @Override public void cancelled() { System.err.println("Website ping cancelled."); - if(savedUsername.length() == 0 || savedUUID.length() == 0) { + if (savedUsername.length() == 0 || savedUUID.length() == 0) { // couldn't validate username, and can't enter offline mode b/c there is no username setError("could not connect to playminicraft account server, but no login data saved; cannot enter offline mode.", false); return; @@ -117,7 +123,8 @@ public void cancelled() { } @Override - public void tick(InputHandler input) {} + public void tick(InputHandler input) { + } private void fetchName(String uuid) { Analytics.LoginAttempt.ping(); @@ -125,16 +132,16 @@ private void fetchName(String uuid) { HttpResponse response = null; try { - response = Unirest.post(apiDomain+"/fetch-name") - .field("uuid", savedUUID) - .asJson(); + response = Unirest.post(apiDomain + "/fetch-name") + .field("uuid", savedUUID) + .asJson(); } catch (UnirestException e) { e.printStackTrace(); } - if(response != null) { + if (response != null) { kong.unirest.json.JSONObject json = response.getBody().getObject(); - switch(json.getString("status")) { + switch (json.getString("status")) { case "error": setError("problem with saved login data; please exit and login again.", false); savedUUID = ""; @@ -161,9 +168,12 @@ public void setLoadingMessage(String msg) { loadingMessage = msg; } - public void setError(String msg) { setError(msg, true); } + public void setError(String msg) { + setError(msg, true); + } + private void setError(String msg, boolean overrideMenu) { - if(curState == State.ERROR) return; // keep original message + if (curState == State.ERROR) return; // keep original message this.curState = State.ERROR; errorMessage = msg; } @@ -172,31 +182,31 @@ private void setError(String msg, boolean overrideMenu) { public void render(Screen screen) { screen.clear(0); - switch(curState) { + switch (curState) { case ENTERIP: Font.drawCentered("Logged in as: " + savedUsername, screen, 6, Color.get(1, 102, 255, 102)); - if(!online) - Font.drawCentered("Offline mode: local servers only", screen, Screen.h/2 - Font.textHeight()*6, Color.get(1, 153, 153, 255)); + if (!online) + Font.drawCentered("Offline mode: local servers only", screen, Screen.h / 2 - Font.textHeight() * 6, Color.get(1, 153, 153, 255)); - Font.drawCentered("Enter ip address to connect to:", screen, Screen.h/2-Font.textHeight()*2-2, Color.get(1, 255)); - Font.drawCentered(typing, screen, Screen.h/2-Font.textHeight(), Color.get(1, 255, 255, 102)); + Font.drawCentered("Enter ip address to connect to:", screen, Screen.h / 2 - Font.textHeight() * 2 - 2, Color.get(1, 255)); + Font.drawCentered(typing, screen, Screen.h / 2 - Font.textHeight(), Color.get(1, 255, 255, 102)); - Font.drawCentered("Press Shift-Escape to logout", screen, Screen.h-Font.textHeight()*7, Color.get(1, 204)); + Font.drawCentered("Press Shift-Escape to logout", screen, Screen.h - Font.textHeight() * 7, Color.get(1, 204)); break; case LOGIN: String msg = "Enter email:"; - if(!typingEmail) + if (!typingEmail) msg = "Enter password:"; Font.drawCentered(msg, screen, Screen.h / 2 - 6, Color.WHITE); msg = typing; - if(!typingEmail) + if (!typingEmail) //noinspection ReplaceAllDot msg = msg.replaceAll(".", "."); Font.drawCentered(msg, screen, Screen.h / 2 + 6, (inputIsValid ? Color.get(1, 204) : Color.RED)); - if(!inputIsValid) { + if (!inputIsValid) { Font.drawCentered("field is blank", screen, Screen.h / 2 + 20, Color.RED); } @@ -206,7 +216,7 @@ public void render(Screen screen) { break; case WAITING: - Font.drawCentered(waitingMessage+ ellipsis.updateAndGet(), screen, Screen.h/2, Color.WHITE); + Font.drawCentered(waitingMessage + ellipsis.updateAndGet(), screen, Screen.h / 2, Color.WHITE); break; case LOADING: @@ -216,15 +226,15 @@ public void render(Screen screen) { case ERROR: //if(Updater.tickCount % 10 == 0) System.out.println("error message: " + errorMessage); - Font.drawCentered("Could not connect to server:", screen, Screen.h/2-6, Color.RED); - FontStyle style = new FontStyle(Color.get(1, 255, 51, 51)).setYPos(Screen.h/2+6); + Font.drawCentered("Could not connect to server:", screen, Screen.h / 2 - 6, Color.RED); + FontStyle style = new FontStyle(Color.get(1, 255, 51, 51)).setYPos(Screen.h / 2 + 6); Font.drawParagraph(errorMessage, screen, style, 1); //Font.drawCentered(errorMessage, screen, Screen.h/2+6, Color.get(1, 255, 51, 51)); break; } - if(curState == State.ENTERIP || curState == State.ERROR) { - Font.drawCentered("Press "+Game.input.getMapping("exit")+" to return", screen, Screen.h-Font.textHeight()*2, Color.GRAY); + if (curState == State.ENTERIP || curState == State.ERROR) { + Font.drawCentered("Press " + Game.input.getMapping("exit") + " to return", screen, Screen.h - Font.textHeight() * 2, Color.GRAY); } } } diff --git a/src/client/java/minicraft/screen/OnScreenKeyboardMenu.java b/src/client/java/minicraft/screen/OnScreenKeyboardMenu.java index 82deee31c..d57379621 100644 --- a/src/client/java/minicraft/screen/OnScreenKeyboardMenu.java +++ b/src/client/java/minicraft/screen/OnScreenKeyboardMenu.java @@ -33,6 +33,7 @@ public OnScreenKeyboardMenu() { /** * This checks if there is any controller connected. If true, create the instance. No otherwise. + * * @return The created menu instance. `null` if there is no controller connected. */ @Nullable @@ -191,7 +192,7 @@ public void tick(InputHandler input) throws OnScreenKeyboardMenuTickActionComple // This is only controllable by controller. if (visible) { - VirtualKey[][] keys = shiftPressed? keysB: keysF; + VirtualKey[][] keys = shiftPressed ? keysB : keysF; if (input.buttonPressed(ControllerButton.A)) { // Select keys[y][x].press(); Sound.play("select"); // Lack of sounds. @@ -245,12 +246,13 @@ public void tick(InputHandler input) throws OnScreenKeyboardMenuTickActionComple public void setVisible(boolean visible) { if (this.visible != visible) { Rectangle rec = getBounds(); - translate(0, visible? -rec.getHeight(): rec.getHeight()); + translate(0, visible ? -rec.getHeight() : rec.getHeight()); this.visible = visible; } keyPressed = 0; } + public boolean isVisible() { return visible; } @@ -281,7 +283,7 @@ public void render(Screen screen) { } final int keyHeight = 14; - VirtualKey[][] keys = shiftPressed? keysB: keysF; + VirtualKey[][] keys = shiftPressed ? keysB : keysF; for (int r = 0; r < keys.length; r++) { final int defaultKeyWidth = 16; int keyWidth = defaultKeyWidth; @@ -299,72 +301,74 @@ else if (key == shiftKey) keyWidth = defaultKeyWidth * 2; else keyWidth = defaultKeyWidth; - int color = keyPressed > 0 && r == this.y && c == this.x? 0x1EFEFF0: 0x1FDFDFD; + int color = keyPressed > 0 && r == this.y && c == this.x ? 0x1EFEFF0 : 0x1FDFDFD; if (key == backspace) { // Rendering the backspace. // Rendering the cross. - colorPixel.accept(x + 1 + keyWidth/2 + (y + keyHeight/2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 1 + (y + keyHeight/2 + 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 1 + (y + keyHeight/2 - 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 1 + (y + keyHeight/2 - 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 1 + (y + keyHeight/2 + 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + (y + keyHeight / 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 1 + (y + keyHeight / 2 + 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 1 + (y + keyHeight / 2 - 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 1 + (y + keyHeight / 2 - 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 1 + (y + keyHeight / 2 + 1) * Screen.w, color); // Rendering the upper base. - colorPixel.accept(x + 1 + keyWidth/2 - 3 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 2 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 1 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 1 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 2 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 3 + (y + keyHeight/2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 3 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 2 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 1 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 1 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 2 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 3 + (y + keyHeight / 2 - 3) * Screen.w, color); // Rendering the lower base. - colorPixel.accept(x + 1 + keyWidth/2 - 3 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 2 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 1 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 1 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 2 + (y + keyHeight/2 + 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 3 + (y + keyHeight/2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 3 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 2 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 1 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 1 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 2 + (y + keyHeight / 2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 3 + (y + keyHeight / 2 + 3) * Screen.w, color); // Rendering the left angle. - colorPixel.accept(x + 1 + keyWidth/2 - 4 + (y + keyHeight/2 - 2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 5 + (y + keyHeight/2 - 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 6 + (y + keyHeight/2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 5 + (y + keyHeight/2 + 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 - 4 + (y + keyHeight/2 + 2) * Screen.w, color); - - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 - 3) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 - 2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 - 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 + 1) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 + 2) * Screen.w, color); - colorPixel.accept(x + 1 + keyWidth/2 + 4 + (y + keyHeight/2 + 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 4 + (y + keyHeight / 2 - 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 5 + (y + keyHeight / 2 - 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 6 + (y + keyHeight / 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 5 + (y + keyHeight / 2 + 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 - 4 + (y + keyHeight / 2 + 2) * Screen.w, color); + + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 - 3) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 - 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 - 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 + 1) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 + 2) * Screen.w, color); + colorPixel.accept(x + 1 + keyWidth / 2 + 4 + (y + keyHeight / 2 + 3) * Screen.w, color); } else if (key == shiftKey) { // Rendering "SYM". - Font.draw("S", screen, x + keyWidth/2 - 3 - defaultKeyWidth/2, y + keyHeight/2 - 3, color); - Font.draw("Y", screen, x + keyWidth/2 - 3, y + keyHeight/2 - 3, color); - Font.draw("M", screen, x + keyWidth/2 - 3 + defaultKeyWidth/2, y + keyHeight/2 - 3, color); + Font.draw("S", screen, x + keyWidth / 2 - 3 - defaultKeyWidth / 2, y + keyHeight / 2 - 3, color); + Font.draw("Y", screen, x + keyWidth / 2 - 3, y + keyHeight / 2 - 3, color); + Font.draw("M", screen, x + keyWidth / 2 - 3 + defaultKeyWidth / 2, y + keyHeight / 2 - 3, color); } else if (key == spaceBar) { // Rendering "underscore". for (int i = 1; i < 19; i++) { - colorPixel.accept(x + keyWidth/2 + i - 9 + (y + keyHeight/2 + 2) * Screen.w, color); + colorPixel.accept(x + keyWidth / 2 + i - 9 + (y + keyHeight / 2 + 2) * Screen.w, color); } } else - Font.draw(String.valueOf(key.output), screen, x + keyWidth/2 - 3, y + keyHeight/2 - 3, color); + Font.draw(String.valueOf(key.output), screen, x + keyWidth / 2 - 3, y + keyHeight / 2 - 3, color); for (int i = 0; i <= keyHeight; i++) { // Rendering left and right border. colorPixel.accept(x + (y + i) * Screen.w, 0x1BCBCBC); colorPixel.accept(x + keyWidth + (y + i) * Screen.w, 0x1BCBCBC); - } for (int i = 0; i <= keyWidth; i++) { // Rendering top and bottom border. + } + for (int i = 0; i <= keyWidth; i++) { // Rendering top and bottom border. colorPixel.accept(x + i + y * Screen.w, 0x1BCBCBC); colorPixel.accept(x + i + (y + keyHeight) * Screen.w, 0x1BCBCBC); } if (this.x == c && this.y == r) { - color = keyPressed > 0? 0x1EFEFF0: 0x1DFDFE0; + color = keyPressed > 0 ? 0x1EFEFF0 : 0x1DFDFE0; for (int i = 1; i < keyHeight; i++) { // Rendering left and right border. colorPixel.accept(x + 1 + (y + i) * Screen.w, color); colorPixel.accept(x - 1 + keyWidth + (y + i) * Screen.w, color); - } for (int i = 1; i < keyWidth; i++) { // Rendering top and bottom border. + } + for (int i = 1; i < keyWidth; i++) { // Rendering top and bottom border. colorPixel.accept(x + i + (y + 1) * Screen.w, color); colorPixel.accept(x + i + (y - 1 + keyHeight) * Screen.w, color); } @@ -375,6 +379,9 @@ else if (key == shiftKey) } } - public static class OnScreenKeyboardMenuTickActionCompleted extends RuntimeException {} - public static class OnScreenKeyboardMenuBackspaceButtonActed extends RuntimeException {} + public static class OnScreenKeyboardMenuTickActionCompleted extends RuntimeException { + } + + public static class OnScreenKeyboardMenuBackspaceButtonActed extends RuntimeException { + } } diff --git a/src/client/java/minicraft/screen/OptionsMainMenuDisplay.java b/src/client/java/minicraft/screen/OptionsMainMenuDisplay.java index 6182bf3e0..696a2ae62 100644 --- a/src/client/java/minicraft/screen/OptionsMainMenuDisplay.java +++ b/src/client/java/minicraft/screen/OptionsMainMenuDisplay.java @@ -7,8 +7,8 @@ public class OptionsMainMenuDisplay extends Display { - public OptionsMainMenuDisplay() { - super(true, new Menu.Builder(false, 6, RelPos.LEFT, + public OptionsMainMenuDisplay() { + super(true, new Menu.Builder(false, 6, RelPos.LEFT, Settings.getEntry("fps"), Settings.getEntry("sound"), Settings.getEntry("showquests"), @@ -20,11 +20,11 @@ public OptionsMainMenuDisplay() { ) .setTitle("minicraft.displays.options_main_menu") .createMenu()); - } + } - @Override - public void onExit() { - new Save(); - Game.MAX_FPS = (int) Settings.get("fps"); - } + @Override + public void onExit() { + new Save(); + Game.MAX_FPS = (int) Settings.get("fps"); + } } diff --git a/src/client/java/minicraft/screen/OptionsWorldDisplay.java b/src/client/java/minicraft/screen/OptionsWorldDisplay.java index 6a71e13d6..a72fbcee7 100644 --- a/src/client/java/minicraft/screen/OptionsWorldDisplay.java +++ b/src/client/java/minicraft/screen/OptionsWorldDisplay.java @@ -34,7 +34,8 @@ public OptionsWorldDisplay() { Game.exitDisplay(); try { Thread.sleep(50); - } catch (InterruptedException ignored) {} + } catch (InterruptedException ignored) { + } Game.exitDisplay(); }); return true; @@ -49,7 +50,7 @@ public OptionsWorldDisplay() { entries.add(4, Settings.getEntry("showquests")); } - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(false, 6, RelPos.LEFT, entries) .setTitle("minicraft.displays.options_world") .createMenu() diff --git a/src/client/java/minicraft/screen/PauseDisplay.java b/src/client/java/minicraft/screen/PauseDisplay.java index 34a158d33..330a54e0a 100644 --- a/src/client/java/minicraft/screen/PauseDisplay.java +++ b/src/client/java/minicraft/screen/PauseDisplay.java @@ -21,10 +21,10 @@ public PauseDisplay() { String selectString = Localization.getLocalized("minicraft.displays.pause.display.help.choose", Game.input.getMapping("select")); ArrayList entries = new ArrayList<>(Arrays.asList( - new BlankEntry(), - new SelectEntry("minicraft.displays.pause.return", () -> Game.setDisplay(null)), - new SelectEntry("minicraft.display.options_display", () -> Game.setDisplay(new OptionsWorldDisplay())), - new SelectEntry("minicraft.displays.achievements", () -> Game.setDisplay(new AchievementsDisplay())) + new BlankEntry(), + new SelectEntry("minicraft.displays.pause.return", () -> Game.setDisplay(null)), + new SelectEntry("minicraft.display.options_display", () -> Game.setDisplay(new OptionsWorldDisplay())), + new SelectEntry("minicraft.displays.achievements", () -> Game.setDisplay(new AchievementsDisplay())) )); if (TutorialDisplayHandler.inQuests()) @@ -56,7 +56,7 @@ public PauseDisplay() { new StringEntry(selectString, Color.GRAY) )); - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(true, 4, RelPos.CENTER, entries) .setTitle("minicraft.displays.pause", Color.YELLOW) .createMenu() diff --git a/src/client/java/minicraft/screen/PlayDisplay.java b/src/client/java/minicraft/screen/PlayDisplay.java index c33e3ac0f..5b554151e 100644 --- a/src/client/java/minicraft/screen/PlayDisplay.java +++ b/src/client/java/minicraft/screen/PlayDisplay.java @@ -6,23 +6,25 @@ import minicraft.screen.entry.SelectEntry; import minicraft.screen.entry.StringEntry; -/** @deprecated This class is not used as this is replaced by an anonymous class in {@link TitleDisplay}. */ +/** + * @deprecated This class is not used as this is replaced by an anonymous class in {@link TitleDisplay}. + */ @Deprecated public class PlayDisplay extends Display { public PlayDisplay() { super(true, true, new Menu.Builder(false, 2, RelPos.CENTER, - new StringEntry("Game Mode", Color.YELLOW), - new BlankEntry(), - new BlankEntry(), - new SelectEntry("Singleplayer", () -> { - if (WorldSelectDisplay.getWorldNames().size() > 0) - Game.setDisplay(new Display(true, new Menu.Builder(false, 2, RelPos.CENTER, - new SelectEntry("Load World", () -> Game.setDisplay(new WorldSelectDisplay())), - new SelectEntry("New World", () -> Game.setDisplay(new WorldGenDisplay())) - ).createMenu())); - else Game.setDisplay(new WorldGenDisplay()); - }), - new SelectEntry("Multiplayer", () -> Game.setDisplay(new MultiplayerDisplay())) + new StringEntry("Game Mode", Color.YELLOW), + new BlankEntry(), + new BlankEntry(), + new SelectEntry("Singleplayer", () -> { + if (WorldSelectDisplay.getWorldNames().size() > 0) + Game.setDisplay(new Display(true, new Menu.Builder(false, 2, RelPos.CENTER, + new SelectEntry("Load World", () -> Game.setDisplay(new WorldSelectDisplay())), + new SelectEntry("New World", () -> Game.setDisplay(new WorldGenDisplay())) + ).createMenu())); + else Game.setDisplay(new WorldGenDisplay()); + }), + new SelectEntry("Multiplayer", () -> Game.setDisplay(new MultiplayerDisplay())) ).createMenu()); } } diff --git a/src/client/java/minicraft/screen/PlayerDeathDisplay.java b/src/client/java/minicraft/screen/PlayerDeathDisplay.java index c464334b2..0761ec87d 100644 --- a/src/client/java/minicraft/screen/PlayerDeathDisplay.java +++ b/src/client/java/minicraft/screen/PlayerDeathDisplay.java @@ -27,7 +27,7 @@ public PlayerDeathDisplay() { new BlankEntry() )); - if(!Game.isMode("minicraft.settings.mode.hardcore")) { + if (!Game.isMode("minicraft.settings.mode.hardcore")) { entries.add(new SelectEntry("minicraft.displays.player_death.respawn", () -> { World.resetGame(); Game.setDisplay(null); diff --git a/src/client/java/minicraft/screen/PlayerInvDisplay.java b/src/client/java/minicraft/screen/PlayerInvDisplay.java index 9a89932a2..c5a709854 100644 --- a/src/client/java/minicraft/screen/PlayerInvDisplay.java +++ b/src/client/java/minicraft/screen/PlayerInvDisplay.java @@ -39,7 +39,7 @@ public PlayerInvDisplay(Player player) { .createMenu(); if (creativeMode) { creativeInv = Items.getCreativeModeInventory(); - menus = new Menu[] { + menus = new Menu[]{ menus[0], new InventoryMenu(player, creativeInv, "minicraft.displays.player_inv.container_title.items", RelPos.RIGHT) {{ creativeInv = true; @@ -50,10 +50,10 @@ public PlayerInvDisplay(Player player) { menus[1].translate(menus[0].getBounds().getWidth() + padding, 0); update(); - if(menus[0].getNumOptions() == 0) onSelectionChange(0, 1); + if (menus[0].getNumOptions() == 0) onSelectionChange(0, 1); } else { creativeInv = null; - menus = new Menu[] { menus[0], descriptionMenu }; + menus = new Menu[]{menus[0], descriptionMenu}; } onScreenKeyboardMenu = OnScreenKeyboardMenu.checkAndCreateMenu(); @@ -138,13 +138,13 @@ public void tick(InputHandler input) { if (input.getMappedKey("SHIFT-D").isClicked() || input.buttonPressed(ControllerButton.Y)) { deleteAll = true; } else if (input.getMappedKey("D").isClicked() || input.buttonPressed(ControllerButton.X)) { - deleteAll = !(fromItem instanceof StackableItem) || ((StackableItem)fromItem).count == 1; + deleteAll = !(fromItem instanceof StackableItem) || ((StackableItem) fromItem).count == 1; } else return; if (deleteAll) { from.remove(fromSel); } else { - ((StackableItem)fromItem).count--; // this is known to be valid. + ((StackableItem) fromItem).count--; // this is known to be valid. } update(); @@ -160,13 +160,13 @@ public void tick(InputHandler input) { boolean transferAll; if (input.inputPressed("attack")) { // If stack limit is available, this can transfer whole stack - transferAll = !(fromItem instanceof StackableItem) || ((StackableItem)fromItem).count == 1; + transferAll = !(fromItem instanceof StackableItem) || ((StackableItem) fromItem).count == 1; } else return; Item toItem = fromItem.copy(); if (!transferAll) { - ((StackableItem)toItem).count = 1; + ((StackableItem) toItem).count = 1; } to.add(toSel, toItem); @@ -208,18 +208,23 @@ protected void onSelectionChange(int oldSel, int newSel) { if (selection == 0) menus[1].shouldRender = false; else menus[1].shouldRender = true; - if(oldSel == newSel) return; // this also serves as a protection against access to menus[0] when such may not exist. + if (oldSel == newSel) + return; // this also serves as a protection against access to menus[0] when such may not exist. int shift = 0; - if(newSel == 0) shift = padding - menus[0].getBounds().getLeft(); - if(newSel == 1) shift = (Screen.w - padding) - menus[1].getBounds().getRight(); + if (newSel == 0) shift = padding - menus[0].getBounds().getLeft(); + if (newSel == 1) shift = (Screen.w - padding) - menus[1].getBounds().getRight(); menus[0].translate(shift, 0); menus[1].translate(shift, 0); - if (newSel == 0) descriptionMenuBuilder.setPositioning(new Point(padding, menus[0].getBounds().getBottom() + 8), RelPos.BOTTOM_RIGHT); - if (newSel == 1) descriptionMenuBuilder.setPositioning(new Point(Screen.w - padding, menus[1].getBounds().getBottom() + 8), RelPos.BOTTOM_LEFT); + if (newSel == 0) + descriptionMenuBuilder.setPositioning(new Point(padding, menus[0].getBounds().getBottom() + 8), RelPos.BOTTOM_RIGHT); + if (newSel == 1) + descriptionMenuBuilder.setPositioning(new Point(Screen.w - padding, menus[1].getBounds().getBottom() + 8), RelPos.BOTTOM_LEFT); } } - private int getOtherIdx() { return (selection+1) % 2; } + private int getOtherIdx() { + return (selection + 1) % 2; + } private void update() { menus[0] = new InventoryMenu((InventoryMenu) menus[0]); diff --git a/src/client/java/minicraft/screen/PopupDisplay.java b/src/client/java/minicraft/screen/PopupDisplay.java index d1597a2bf..028696760 100644 --- a/src/client/java/minicraft/screen/PopupDisplay.java +++ b/src/client/java/minicraft/screen/PopupDisplay.java @@ -12,17 +12,34 @@ import java.util.ArrayList; import java.util.stream.Stream; -/** Light-weighted exitable display with single menu. */ +/** + * Light-weighted exitable display with single menu. + */ public class PopupDisplay extends Display { // Using Color codes for coloring in title and plain text messages. private final ArrayList callbacks; - public PopupDisplay(@Nullable PopupConfig config, String... messages) { this(config, false, messages); } - public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, String... messages) { this(config, clearScreen, true, messages); } - public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, boolean menuFrame, String... messages) { this(config, clearScreen, menuFrame, StringEntry.useLines(messages)); } - public PopupDisplay(@Nullable PopupConfig config, ListEntry... entries) { this(config, false, entries); } - public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, ListEntry... entries) { this(config, clearScreen, true, entries); } + public PopupDisplay(@Nullable PopupConfig config, String... messages) { + this(config, false, messages); + } + + public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, String... messages) { + this(config, clearScreen, true, messages); + } + + public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, boolean menuFrame, String... messages) { + this(config, clearScreen, menuFrame, StringEntry.useLines(messages)); + } + + public PopupDisplay(@Nullable PopupConfig config, ListEntry... entries) { + this(config, false, entries); + } + + public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, ListEntry... entries) { + this(config, clearScreen, true, entries); + } + public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, boolean menuFrame, ListEntry... entries) { super(clearScreen, true); @@ -40,9 +57,9 @@ public PopupDisplay(@Nullable PopupConfig config, boolean clearScreen, boolean m if (Stream.of(entries).anyMatch(e -> e instanceof InputEntry)) onScreenKeyboardMenu = OnScreenKeyboardMenu.checkAndCreateMenu(); if (onScreenKeyboardMenu == null) - menus = new Menu[] { builder.createMenu() }; + menus = new Menu[]{builder.createMenu()}; else - menus = new Menu[] { onScreenKeyboardMenu, builder.createMenu() }; + menus = new Menu[]{onScreenKeyboardMenu, builder.createMenu()}; } OnScreenKeyboardMenu onScreenKeyboardMenu; @@ -128,9 +145,10 @@ public static interface ActionCallback { /** * The callback acts when the key clicked. - * @param key The key of the callback trigger. + * + * @param key The key of the callback trigger. * @param callback The callback, when the return value is {@code true}, no more input check - * will be done. It continues if {@code false}. + * will be done. It continues if {@code false}. */ public PopupActionCallback(String key, ActionCallback callback) { this.key = key; diff --git a/src/client/java/minicraft/screen/QuestsDisplay.java b/src/client/java/minicraft/screen/QuestsDisplay.java index 98841a634..c9afba033 100644 --- a/src/client/java/minicraft/screen/QuestsDisplay.java +++ b/src/client/java/minicraft/screen/QuestsDisplay.java @@ -37,7 +37,9 @@ import java.util.stream.Collectors; public class QuestsDisplay extends Display { - /** Unlocked but uncompleted. */ + /** + * Unlocked but uncompleted. + */ private final static HashSet displayableQuests = new HashSet<>(); // Temp set. Refreshed anytime. private final static HashSet series = new HashSet<>(); @@ -205,12 +207,12 @@ public int getColor(boolean isSelected) { } } - seriesEntries = new SelectEntry[][] { + seriesEntries = new SelectEntry[][]{ unlocked.toArray(new SelectEntry[0]), completed.toArray(new SelectEntry[0]) }; - entrySeries = new QuestSeries[][] { + entrySeries = new QuestSeries[][]{ unlockedSeries.toArray(new QuestSeries[0]), completedSeries.toArray(new QuestSeries[0]) }; @@ -220,7 +222,7 @@ public QuestsDisplay() { super(true, true); reloadEntries(); - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(false, 1, RelPos.CENTER) .setPositioning(new Point(Screen.w / 2, Screen.h / 2 - 20), RelPos.CENTER) .setDisplayLength(5) @@ -256,9 +258,9 @@ public SeriesInformationDisplay(QuestSeries series) { super(false, true); ArrayList entries = new ArrayList<>(); - entries.add(series.isCompleted() ? new StringEntry("Status: Completed", Color.GREEN): - series.isUnlocked() ? new StringEntry("Status: Unlocked", Color.WHITE): - new StringEntry("Status: Locked", Color.GRAY) // Locked series would not been shown...? + entries.add(series.isCompleted() ? new StringEntry("Status: Completed", Color.GREEN) : + series.isUnlocked() ? new StringEntry("Status: Unlocked", Color.WHITE) : + new StringEntry("Status: Locked", Color.GRAY) // Locked series would not been shown...? ); entries.add(new StringEntry("Quests completed: " + @@ -271,7 +273,7 @@ public SeriesInformationDisplay(QuestSeries series) { entries.add(new BlankEntry()); entries.add(new SelectEntry("View all quests of this series", () -> Game.setDisplay(new SeriesQuestViewerDisplay(series)))); - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(true, 0, RelPos.CENTER) .setPositioning(new Point(Screen.w / 2, 5), RelPos.BOTTOM) .setEntries(new StringEntry(Localization.getLocalized(series.key))) @@ -350,12 +352,12 @@ public void render(int xp, int yp, int xt, int yt, int bits, MinicraftImage shee public SeriesQuestViewerDisplay(QuestSeries series) { super(false, true); - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(true, 0, RelPos.CENTER, StringEntry.useLines("minicrat.displays.quests", series.key)) - .setPositioning(new Point(Screen.w/2, 6), RelPos.BOTTOM) + .setPositioning(new Point(Screen.w / 2, 6), RelPos.BOTTOM) .createMenu(), new Menu.Builder(true, 0, RelPos.CENTER) - .setPositioning(new Point(Screen.w/2, 40), RelPos.BOTTOM) + .setPositioning(new Point(Screen.w / 2, 40), RelPos.BOTTOM) .setSize(Screen.w - 16, Screen.h - 60) .createMenu() }; @@ -380,7 +382,7 @@ public SeriesQuestViewerDisplay(QuestSeries series) { }); while (childQuests.size() > 0) { - for (Iterator>> it = childQuests.entrySet().iterator(); it.hasNext();) { + for (Iterator>> it = childQuests.entrySet().iterator(); it.hasNext(); ) { Map.Entry> entry = it.next(); Quest parent = entry.getKey(); ArrayList questRow = questRowsList.stream().filter(quests1 -> quests1.contains(parent)).findAny().orElse(null); @@ -402,11 +404,11 @@ public SeriesQuestViewerDisplay(QuestSeries series) { int height = Font.textHeight(); for (int j = 0; j < questsTree[i].length; j++) { // x-axis int width = Font.textWidth(Localization.getLocalized(questsTree[i][j].key)); - treeDimensions[i][j] = new Rectangle(entryGap, entryGap, entryPadding*2 + width, entryPadding*2 + height, 0); + treeDimensions[i][j] = new Rectangle(entryGap, entryGap, entryPadding * 2 + width, entryPadding * 2 + height, 0); if (j > 0) - treeDimensions[i][j].translate(treeDimensions[i][j-1].getRight() + entryGap, 0); + treeDimensions[i][j].translate(treeDimensions[i][j - 1].getRight() + entryGap, 0); if (i > 0) - treeDimensions[i][j].translate(0, treeDimensions[i-1][0].getBottom() + entryGap*2); + treeDimensions[i][j].translate(0, treeDimensions[i - 1][0].getBottom() + entryGap * 2); } } } else { @@ -415,8 +417,8 @@ public SeriesQuestViewerDisplay(QuestSeries series) { } Rectangle menuBounds = menus[1].getBounds(); - rasterWidth = menuBounds.getWidth() - MinicraftImage.boxWidth*2; - rasterHeight = menuBounds.getHeight() - MinicraftImage.boxWidth*2; + rasterWidth = menuBounds.getWidth() - MinicraftImage.boxWidth * 2; + rasterHeight = menuBounds.getHeight() - MinicraftImage.boxWidth * 2; rasterPixels = new int[rasterWidth * rasterHeight]; rasterX = menuBounds.getLeft() + MinicraftImage.boxWidth; rasterY = menuBounds.getTop() + MinicraftImage.boxWidth; @@ -516,8 +518,8 @@ public void render(Screen screen) { private void renderRaster() { if (questsTree.length == 0) { String text = Localization.getLocalized("minicraft.displays.quests.display.no_quest"); - Font.draw(text, simulatedRasterScreen, xScroll + rasterWidth/2 - Font.textWidth(text)/2, - yScroll + rasterHeight/2 - Font.textHeight()/2, Color.GRAY); + Font.draw(text, simulatedRasterScreen, xScroll + rasterWidth / 2 - Font.textWidth(text) / 2, + yScroll + rasterHeight / 2 - Font.textHeight() / 2, Color.GRAY); return; } @@ -586,6 +588,7 @@ private void renderRaster() { } } } + private void renderRasterPixel(int x, int y, int color) { x -= xScroll; y -= yScroll; @@ -611,9 +614,10 @@ void plotLineLow(int x0, int y0, int x1, int y1, IntPredicate yRange, int color) y = y + yi; D = D + (2 * (dy - dx)); } else - D = D + 2*dy; + D = D + 2 * dy; } } + void plotLineHigh(int x0, int y0, int x1, int y1, IntPredicate yRange, int color) { int dx = x1 - x0; int dy = y1 - y0; @@ -631,9 +635,10 @@ void plotLineHigh(int x0, int y0, int x1, int y1, IntPredicate yRange, int color x = x + xi; D = D + (2 * (dx - dy)); } else - D = D + 2*dx; + D = D + 2 * dx; } } + void plotLine(int x0, int y0, int x1, int y1, IntPredicate yRange, int color) { if (Math.abs(y1 - y0) < Math.abs(x1 - x0)) { if (x0 > x1) @@ -653,7 +658,7 @@ public QuestInformationDisplay(Quest quest) { super(false, true); String state = quest.isCompleted() ? "Completed" : quest.isUnlocked() ? "Unlocked" : "Locked"; int color = quest.isCompleted() ? Color.GREEN : quest.isUnlocked() ? Color.WHITE : Color.GRAY; - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(true, 1, RelPos.CENTER) .setPositioning(new Point(Screen.w / 2, 5), RelPos.BOTTOM) .setEntries(new StringEntry(Localization.getLocalized(quest.getSeries().key)), @@ -678,7 +683,10 @@ public static HashSet getDisplayableQuests() { return new HashSet<>(displayableQuests); } - public static void resetGameQuests() { resetGameQuests(true); } + public static void resetGameQuests() { + resetGameQuests(true); + } + private static void resetGameQuests(boolean update) { series.forEach(AdvancementElement::reset); if (update) refreshDisplayableQuests(); @@ -701,7 +709,9 @@ public static void load(JSONObject json) { refreshDisplayableQuests(); } - /** Saving and writing all data into the given JSONObject. */ + /** + * Saving and writing all data into the given JSONObject. + */ public static void save(JSONObject json) { series.forEach(series1 -> { series1.save(json); @@ -733,12 +743,12 @@ public void tick(InputHandler input) { private void updateEntries() { menus[0].setEntries(seriesEntries[selectedEntry]); - String[] entryNames = new String[] { + String[] entryNames = new String[]{ "Unlocked", "Completed" }; for (int i = 0; i < 2; i++) { - menus[i+1].updateEntry(0, new StringEntry(entryNames[i], (i == selectedEntry) ? Color.WHITE : Color.GRAY)); + menus[i + 1].updateEntry(0, new StringEntry(entryNames[i], (i == selectedEntry) ? Color.WHITE : Color.GRAY)); } int select = previousSelection; diff --git a/src/client/java/minicraft/screen/RecipeMenu.java b/src/client/java/minicraft/screen/RecipeMenu.java index 95420f532..8d18e32c3 100644 --- a/src/client/java/minicraft/screen/RecipeMenu.java +++ b/src/client/java/minicraft/screen/RecipeMenu.java @@ -12,10 +12,10 @@ private static RecipeEntry[] getAndSortRecipes(List recipes, Player play recipes.sort((r1, r2) -> { boolean craft1 = r1.checkCanCraft(player); boolean craft2 = r2.checkCanCraft(player); - if(craft1 == craft2) + if (craft1 == craft2) return 0; - if(craft1) return -1; - if(craft2) return 1; + if (craft1) return -1; + if (craft2) return 1; return 0; // should never actually be reached }); diff --git a/src/client/java/minicraft/screen/RelPos.java b/src/client/java/minicraft/screen/RelPos.java index 7c20c86b8..eb1f51021 100644 --- a/src/client/java/minicraft/screen/RelPos.java +++ b/src/client/java/minicraft/screen/RelPos.java @@ -15,7 +15,7 @@ public enum RelPos { // I think this way, the enums will all be constructed before this gets called, so there won't be any mishaps with number of values. static { - for(RelPos rp: RelPos.values()) { + for (RelPos rp : RelPos.values()) { int ord = rp.ordinal(); rp.xIndex = ord % 3; rp.yIndex = ord / 3; @@ -23,20 +23,23 @@ public enum RelPos { } public static RelPos getPos(int xIndex, int yIndex) { - return values()[MyUtils.clamp(xIndex, 0, 2) + MyUtils.clamp(yIndex, 0, 2)*3]; + return values()[MyUtils.clamp(xIndex, 0, 2) + MyUtils.clamp(yIndex, 0, 2) * 3]; } public RelPos getOpposite() { - int nx = -(xIndex-1) + 1; - int ny = -(yIndex-1) + 1; + int nx = -(xIndex - 1) + 1; + int ny = -(yIndex - 1) + 1; return getPos(nx, ny); } - /** positions the given rect around the given anchor. The double size is what aligns it to a point rather than a rect. */ + /** + * positions the given rect around the given anchor. The double size is what aligns it to a point rather than a rect. + */ public Point positionRect(Dimension rectSize, Point anchor) { - Rectangle bounds = new Rectangle(anchor.x, anchor.y, rectSize.width*2, rectSize.height*2, Rectangle.CENTER_DIMS); + Rectangle bounds = new Rectangle(anchor.x, anchor.y, rectSize.width * 2, rectSize.height * 2, Rectangle.CENTER_DIMS); return positionRect(rectSize, bounds); } + // the point is returned as a rectangle with the given dimension and the found location, within the provided dummy rectangle. public Rectangle positionRect(Dimension rectSize, Point anchor, Rectangle dummy) { Point pos = positionRect(rectSize, anchor); @@ -45,13 +48,15 @@ public Rectangle positionRect(Dimension rectSize, Point anchor, Rectangle dummy) return dummy; } - /** positions the given rect to a relative position in the container. */ + /** + * positions the given rect to a relative position in the container. + */ public Point positionRect(Dimension rectSize, Rectangle container) { Point tlcorner = container.getCenter(); // this moves the inner box correctly - tlcorner.x += ((xIndex -1) * container.getWidth() / 2) - (xIndex * rectSize.width / 2); - tlcorner.y += ((yIndex -1) * container.getHeight() / 2) - (yIndex * rectSize.height / 2); + tlcorner.x += ((xIndex - 1) * container.getWidth() / 2) - (xIndex * rectSize.width / 2); + tlcorner.y += ((yIndex - 1) * container.getHeight() / 2) - (yIndex * rectSize.height / 2); return tlcorner; } diff --git a/src/client/java/minicraft/screen/ResourcePackDisplay.java b/src/client/java/minicraft/screen/ResourcePackDisplay.java index 039c89330..8e14e0320 100644 --- a/src/client/java/minicraft/screen/ResourcePackDisplay.java +++ b/src/client/java/minicraft/screen/ResourcePackDisplay.java @@ -161,7 +161,9 @@ public class ResourcePackDisplay extends Display { } } - /** Initializing the Display. */ + /** + * Initializing the Display. + */ public ResourcePackDisplay() { super(true, true); initPacks(); @@ -178,7 +180,7 @@ public ResourcePackDisplay() { reloadEntries(); - menus = new Menu[] { + menus = new Menu[]{ builder0.setEntries(entries0) .createMenu(), builder1.setEntries(entries1) @@ -194,7 +196,8 @@ public ResourcePackDisplay() { @Override protected void onSelectionChange(int oldSel, int newSel) { super.onSelectionChange(oldSel, newSel); - if (oldSel == newSel) return; // this also serves as a protection against access to menus[0] when such may not exist. + if (oldSel == newSel) + return; // this also serves as a protection against access to menus[0] when such may not exist. menus[0].translate(-menus[0].getBounds().getLeft(), 0); menus[1].translate(Screen.w - menus[1].getBounds().getRight(), 0); if (newSel == 0) { @@ -206,7 +209,9 @@ protected void onSelectionChange(int oldSel, int newSel) { } } - /** Reloading the entries to refresh the current pack list. */ + /** + * Reloading the entries to refresh the current pack list. + */ private void reloadEntries() { entries0.clear(); // First list: unloaded. for (ResourcePack pack : resourcePacks) { // First list: all available resource packs. @@ -231,10 +236,12 @@ public int getColor(boolean isSelected) { } } - /** Applying the reloaded entries into the display. */ + /** + * Applying the reloaded entries into the display. + */ private void refreshEntries() { reloadEntries(); - Menu[] newMenus = new Menu[] { + Menu[] newMenus = new Menu[]{ builder0.setEntries(entries0) .createMenu(), builder1.setEntries(entries1) @@ -251,7 +258,9 @@ private void refreshEntries() { menus[selection ^ 1].translate(menus[selection].getBounds().getWidth() + padding, 0); } - /** Watching the directory changes. Allowing hot-loading. */ + /** + * Watching the directory changes. Allowing hot-loading. + */ private class WatcherThread extends Thread implements Closeable { private WatchService watcher; private volatile Thread running = this; @@ -281,7 +290,7 @@ public void run() { @SuppressWarnings("unchecked") WatchEvent ev = (WatchEvent) event; - Path filename = ev.context(); + Path filename = ev.context(); try { urls.add(FOLDER_LOCATION.toPath().resolve(filename).toFile().toURI().toURL()); @@ -387,7 +396,8 @@ public void render(Screen screen) { Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.title"), screen, 6, Color.WHITE); // Info text at the bottom. - if (Game.input.anyControllerConnected()) Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.help.keyboard_needed"), screen, Screen.h - 33, Color.DARK_GRAY); + if (Game.input.anyControllerConnected()) + Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.help.keyboard_needed"), screen, Screen.h - 33, Color.DARK_GRAY); Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.help.move", Game.input.getMapping("cursor-down"), Game.input.getMapping("cursor-up")), screen, Screen.h - 25, Color.DARK_GRAY); Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.help.select", Game.input.getMapping("SELECT")), screen, Screen.h - 17, Color.DARK_GRAY); Font.drawCentered(Localization.getLocalized("minicraft.displays.resource_packs.display.help.position"), screen, Screen.h - 9, Color.DARK_GRAY); @@ -410,11 +420,15 @@ public void render(Screen screen) { } } - /** The object representation of resource pack. */ + /** + * The object representation of resource pack. + */ private static class ResourcePack implements Closeable { private URL packRoot; - /** 0 - before 2.2.0; 1 - 2.2.0-latest */ + /** + * 0 - before 2.2.0; 1 - 2.2.0-latest + */ @SuppressWarnings("unused") private final int packFormat; // The pack format of the pack. private final String name; // The name of the pack. @@ -432,7 +446,9 @@ private ResourcePack(URL packRoot, int packFormat, String name, String desc) { refreshPack(); } - /** This does not include metadata refresh. */ + /** + * This does not include metadata refresh. + */ public void refreshPack() { // Refresh pack logo.png. try { @@ -468,6 +484,7 @@ public void refreshPack() { /** * Open the stream of the zip file. + * * @return {@code true} if the stream has successfully been opened. */ private boolean openStream() { @@ -480,7 +497,9 @@ private boolean openStream() { } } - /** Closing the stream of the zip file if opened. */ + /** + * Closing the stream of the zip file if opened. + */ @Override public void close() throws IOException { if (opened) { @@ -492,6 +511,7 @@ public void close() throws IOException { /** * Getting the stream by the path. + * * @param path The path of the entry. * @return The input stream of the specified entry. * @throws IOException if an I/O error has occurred. @@ -511,18 +531,19 @@ private static interface FilesFilter { // Literally functioned. /** * Getting the subfiles under the specified entry directrory. - * @param path The directory to be listed. + * + * @param path The directory to be listed. * @param filter The filter to be applied. * @return The filtered (if any) subfile and subfolder list. Empty if not or invalid path. */ @NotNull private ArrayList getFiles(String path, FilesFilter filter) { ArrayList paths = new ArrayList<>(); - for (Enumeration e = zipFile.entries(); e.hasMoreElements();) { + for (Enumeration e = zipFile.entries(); e.hasMoreElements(); ) { ZipEntry entry = e.nextElement(); Path parent; if ((parent = Paths.get(entry.getName()).getParent()) != null && parent.equals(Paths.get(path)) && - (filter == null || filter.check(Paths.get(entry.getName()), entry.isDirectory()))) { + (filter == null || filter.check(Paths.get(entry.getName()), entry.isDirectory()))) { paths.add(entry.getName()); } } @@ -533,6 +554,7 @@ private ArrayList getFiles(String path, FilesFilter filter) { /** * Reading the string from the input stream. + * * @param in The input stream to be read. * @return The returned string. */ @@ -543,6 +565,7 @@ public static String readStringFromInputStream(InputStream in) { /** * Loading pack metadata of the pack. + * * @param file The path of the pack. * @return The loaded pack with metadata. */ @@ -564,7 +587,9 @@ public static ResourcePack loadPackMetadata(URL file) { return null; } - /** Intializing the packs from directory and loaded. */ + /** + * Intializing the packs from directory and loaded. + */ public static void initPacks() { // Generate resource packs folder if (FOLDER_LOCATION.mkdirs()) { @@ -573,7 +598,7 @@ public static void initPacks() { ArrayList urls = new ArrayList<>(); // Read and add the .zip file to the resource pack list. Only accept files ending with .zip or directory. - for (File file : Objects.requireNonNull(FOLDER_LOCATION.listFiles((dur, name) -> name.endsWith(".zip")))) { + for (File file : Objects.requireNonNull(FOLDER_LOCATION.listFiles((dur, name) -> name.endsWith(".zip")))) { try { urls.add(file.toPath().toUri().toURL()); } catch (MalformedURLException e) { @@ -600,6 +625,7 @@ public static void initPacks() { /** * Finding the pack by pack's file URL. + * * @param url The url for query. * @return The found resource pack. {@code null} if not found. */ @@ -621,6 +647,7 @@ private static ResourcePack findPackByURL(URL url) { /** * Refreshing the pack list by the urls. + * * @param urls The packs' url to be refreshed. */ private static void refreshResourcePacks(List urls) { @@ -650,13 +677,16 @@ private static void refreshResourcePacks(List urls) { resourcePacks.sort((p1, p2) -> p1.name.compareTo(p2.name)); } - /** Releasing the unloaded packs. */ + /** + * Releasing the unloaded packs. + */ public static void releaseUnloadedPacks() { resourcePacks.clear(); // Releases unloaded packs. } /** * Loading the resource packs when loading preferences. This should only be called by {@link minicraft.saveload.Load}. + * * @param names The names of the packs. */ public static void loadResourcePacks(String[] names) { @@ -677,6 +707,7 @@ public static void loadResourcePacks(String[] names) { /** * Getting the names of the loaded packs. This should only be called by {@link minicraft.saveload.Save}. + * * @return The names of currently loaded packs. */ public static ArrayList getLoadedPacks() { @@ -694,7 +725,9 @@ public static ArrayList getLoadedPacks() { return packs; } - /** Reloading all the resources with the currently packs to be loaded. */ + /** + * Reloading all the resources with the currently packs to be loaded. + */ @SuppressWarnings("unchecked") public static void reloadResources() { loadQuery.clear(); @@ -732,22 +765,32 @@ public static void reloadResources() { /** * Loading the textures of the pack. + * * @param pack The pack to be loaded. * @throws IOException if I/O exception occurs. */ private static void loadTextures(ResourcePack pack) throws IOException { for (String t : pack.getFiles("assets/textures/", null)) { switch (t) { - case "assets/textures/entity/": loadTextures(pack, SpriteType.Entity); break; - case "assets/textures/gui/": loadTextures(pack, SpriteType.Gui); break; - case "assets/textures/item/": loadTextures(pack, SpriteType.Item); break; - case "assets/textures/tile/": loadTextures(pack, SpriteType.Tile); break; + case "assets/textures/entity/": + loadTextures(pack, SpriteType.Entity); + break; + case "assets/textures/gui/": + loadTextures(pack, SpriteType.Gui); + break; + case "assets/textures/item/": + loadTextures(pack, SpriteType.Item); + break; + case "assets/textures/tile/": + loadTextures(pack, SpriteType.Tile); + break; } } } /** * Loading the categories of textures from the pack. + * * @param pack The pack to be loaded. * @param type The category of textures. * @throws IOException if I/O exception occurs. @@ -755,10 +798,18 @@ private static void loadTextures(ResourcePack pack) throws IOException { private static void loadTextures(ResourcePack pack, SpriteType type) throws IOException { String path = "assets/textures/"; switch (type) { - case Entity: path += "entity/"; break; - case Gui: path += "gui/"; break; - case Item: path += "item/"; break; - case Tile: path += "tile/"; break; + case Entity: + path += "entity/"; + break; + case Gui: + path += "gui/"; + break; + case Item: + path += "item/"; + break; + case Tile: + path += "tile/"; + break; } ArrayList pngs = pack.getFiles(path, (p, isDir) -> p.toString().endsWith(".png") && !isDir); @@ -843,6 +894,7 @@ private static void loadTextures(ResourcePack pack, SpriteType type) throws IOEx /** * Loading localization from the pack. + * * @param pack The pack to be loaded. */ private static void loadLocalization(ResourcePack pack) { @@ -886,18 +938,29 @@ private static void loadLocalization(ResourcePack pack) { /** * Loading the books from the pack. + * * @param pack The pack to be loaded. */ private static void loadBooks(ResourcePack pack) { - for (String path : pack.getFiles("assets/books", (path, isDir) -> path.toString().endsWith(".txt") && !isDir)) { + for (String path : pack.getFiles("assets/books", (path, isDir) -> path.toString().endsWith(".txt") && !isDir)) { try { String book = BookData.loadBook(readStringFromInputStream(pack.getResourceAsStream(path))); switch (path) { - case "assets/books/about.txt": BookData.about = () -> book; break; - case "assets/books/credits.txt": BookData.credits = () -> book; break; - case "assets/books/instructions.txt": BookData.instructions = () -> book; break; - case "assets/books/antidous.txt": BookData.antVenomBook = () -> book; break; - case "assets/books/story_guide.txt": BookData.storylineGuide = () -> book; break; + case "assets/books/about.txt": + BookData.about = () -> book; + break; + case "assets/books/credits.txt": + BookData.credits = () -> book; + break; + case "assets/books/instructions.txt": + BookData.instructions = () -> book; + break; + case "assets/books/antidous.txt": + BookData.antVenomBook = () -> book; + break; + case "assets/books/story_guide.txt": + BookData.storylineGuide = () -> book; + break; } } catch (IOException e) { Logging.RESOURCEHANDLER_LOCALIZATION.debug(e, "Unable to load book: {} in pack : {}", path, pack.name); @@ -907,6 +970,7 @@ private static void loadBooks(ResourcePack pack) { /** * Loading sounds from the pack. + * * @param pack The pack to be loaded. */ private static void loadSounds(ResourcePack pack) { diff --git a/src/client/java/minicraft/screen/SkinDisplay.java b/src/client/java/minicraft/screen/SkinDisplay.java index 40896cd5d..3dbfffab1 100644 --- a/src/client/java/minicraft/screen/SkinDisplay.java +++ b/src/client/java/minicraft/screen/SkinDisplay.java @@ -69,7 +69,7 @@ public SkinDisplay() { new Menu.Builder(false, 2, RelPos.CENTER) .setDisplayLength(8) .setSelectable(true) - .setPositioning(new Point(Screen.w/2, Screen.h*3/5), RelPos.CENTER) + .setPositioning(new Point(Screen.w / 2, Screen.h * 3 / 5), RelPos.CENTER) .createMenu() ); @@ -137,7 +137,9 @@ public static void releaseSkins() { } } - /** Watching the directory changes. Allowing hot-loading. */ + /** + * Watching the directory changes. Allowing hot-loading. + */ private class WatcherThread extends Thread { private WatchService watcher; private volatile Thread running = this; @@ -202,7 +204,8 @@ private synchronized static void refreshSkinFiles(List files) { Logging.RESOURCEHANDLER_SKIN.error("Could not read image at path {}. The file is probably missing or formatted wrong.", skinPath); } catch (SecurityException e) { Logging.RESOURCEHANDLER_SKIN.error("Access to file located at {} was denied. Check if game is given permission.", skinPath); - } else { + } + else { Renderer.spriteLinker.setSkin("skin." + name, null); if (skins.containsKey(name)) for (LinkedSprite[] a : skins.remove(name)) { for (LinkedSprite b : a) { diff --git a/src/client/java/minicraft/screen/TempDisplay.java b/src/client/java/minicraft/screen/TempDisplay.java index 544177f82..acbc82517 100644 --- a/src/client/java/minicraft/screen/TempDisplay.java +++ b/src/client/java/minicraft/screen/TempDisplay.java @@ -4,45 +4,45 @@ import minicraft.util.MyUtils; public class TempDisplay extends Display { - + private int milliDelay; - + public TempDisplay(int milliDelay) { this.milliDelay = milliDelay; } - + public TempDisplay(int milliDelay, Menu... menus) { super(menus); this.milliDelay = milliDelay; } - + public TempDisplay(int milliDelay, boolean clearScreen) { super(clearScreen); this.milliDelay = milliDelay; } - + public TempDisplay(int milliDelay, boolean clearScreen, Menu... menus) { super(clearScreen, menus); this.milliDelay = milliDelay; } - + public TempDisplay(int milliDelay, boolean clearScreen, boolean canExit) { super(clearScreen, canExit); this.milliDelay = milliDelay; } - + public TempDisplay(int milliDelay, boolean clearScreen, boolean canExit, Menu... menus) { super(clearScreen, canExit, menus); this.milliDelay = milliDelay; } - + @Override public void init(Display parent) { super.init(parent); - + new Thread(() -> { MyUtils.sleep(milliDelay); - if(Game.getDisplay() == TempDisplay.this) + if (Game.getDisplay() == TempDisplay.this) Game.exitDisplay(); }).start(); } diff --git a/src/client/java/minicraft/screen/TitleDisplay.java b/src/client/java/minicraft/screen/TitleDisplay.java index 6459e3a91..de083b95f 100644 --- a/src/client/java/minicraft/screen/TitleDisplay.java +++ b/src/client/java/minicraft/screen/TitleDisplay.java @@ -34,32 +34,32 @@ public class TitleDisplay extends Display { public TitleDisplay() { super(true, false, new Menu.Builder(false, 2, RelPos.CENTER, - new StringEntry("minicraft.displays.title.display.checking", Color.BLUE), - new BlankEntry(), - new SelectEntry("minicraft.displays.title.play", () -> { - if (WorldSelectDisplay.getWorldNames().size() > 0) - Game.setDisplay(new Display(true, new Menu.Builder(false, 2, RelPos.CENTER, - new SelectEntry("minicraft.displays.title.play.load_world", () -> Game.setDisplay(new WorldSelectDisplay())), - new SelectEntry("minicraft.displays.title.play.new_world", () -> Game.setDisplay(new WorldGenDisplay())) - ).createMenu())); - else Game.setDisplay(new WorldGenDisplay()); - }), - new SelectEntry("minicraft.display.options_display", () -> Game.setDisplay(new OptionsMainMenuDisplay())), - new SelectEntry("minicraft.displays.skin", () -> Game.setDisplay(new SkinDisplay())), - new SelectEntry("minicraft.displays.achievements", () -> Game.setDisplay(new AchievementsDisplay())), - new SelectEntry("minicraft.displays.title.help", () -> - Game.setDisplay(new Display(true, new Menu.Builder(false, 1, RelPos.CENTER, - new BlankEntry(), - new SelectEntry("minicraft.displays.title.help.instructions", () -> Game.setDisplay(new BookDisplay(BookData.instructions.collect()))), - new SelectEntry("minicraft.displays.title.help.storyline_guide", () -> Game.setDisplay(new BookDisplay(BookData.storylineGuide.collect()))), - new SelectEntry("minicraft.displays.title.help.about", () -> Game.setDisplay(new BookDisplay(BookData.about.collect()))), - new SelectEntry("minicraft.displays.title.help.credits", () -> Game.setDisplay(new BookDisplay(BookData.credits.collect()))) - ).setTitle("minicraft.displays.title.help").createMenu())) - ), - new SelectEntry("minicraft.displays.title.quit", Game::quit) + new StringEntry("minicraft.displays.title.display.checking", Color.BLUE), + new BlankEntry(), + new SelectEntry("minicraft.displays.title.play", () -> { + if (WorldSelectDisplay.getWorldNames().size() > 0) + Game.setDisplay(new Display(true, new Menu.Builder(false, 2, RelPos.CENTER, + new SelectEntry("minicraft.displays.title.play.load_world", () -> Game.setDisplay(new WorldSelectDisplay())), + new SelectEntry("minicraft.displays.title.play.new_world", () -> Game.setDisplay(new WorldGenDisplay())) + ).createMenu())); + else Game.setDisplay(new WorldGenDisplay()); + }), + new SelectEntry("minicraft.display.options_display", () -> Game.setDisplay(new OptionsMainMenuDisplay())), + new SelectEntry("minicraft.displays.skin", () -> Game.setDisplay(new SkinDisplay())), + new SelectEntry("minicraft.displays.achievements", () -> Game.setDisplay(new AchievementsDisplay())), + new SelectEntry("minicraft.displays.title.help", () -> + Game.setDisplay(new Display(true, new Menu.Builder(false, 1, RelPos.CENTER, + new BlankEntry(), + new SelectEntry("minicraft.displays.title.help.instructions", () -> Game.setDisplay(new BookDisplay(BookData.instructions.collect()))), + new SelectEntry("minicraft.displays.title.help.storyline_guide", () -> Game.setDisplay(new BookDisplay(BookData.storylineGuide.collect()))), + new SelectEntry("minicraft.displays.title.help.about", () -> Game.setDisplay(new BookDisplay(BookData.about.collect()))), + new SelectEntry("minicraft.displays.title.help.credits", () -> Game.setDisplay(new BookDisplay(BookData.credits.collect()))) + ).setTitle("minicraft.displays.title.help").createMenu())) + ), + new SelectEntry("minicraft.displays.title.quit", Game::quit) ) - .setPositioning(new Point(Screen.w/2, Screen.h*3/5), RelPos.CENTER) - .createMenu() + .setPositioning(new Point(Screen.w / 2, Screen.h * 3 / 5), RelPos.CENTER) + .createMenu() ); } @@ -81,17 +81,16 @@ public void init(Display parent) { World.levels = new Level[World.levels.length]; - if(Game.player == null) + if (Game.player == null) // Was online, need to reset player World.resetGame(false); } private void checkVersion() { VersionInfo latestVersion = Network.getLatestVersion(); - if(latestVersion == null) { + if (latestVersion == null) { Network.findLatestVersion(this::checkVersion); - } - else { + } else { if (latestVersion.version.compareTo(Game.VERSION, true) > 0) { menus[0].updateEntry(0, new StringEntry(Localization.getLocalized("minicraft.displays.title.display.new_version", latestVersion.releaseName), Color.GREEN)); menus[0].updateEntry(1, new LinkEntry(Color.CYAN, Localization.getLocalized("minicraft.displays.title.select_to_download"), latestVersion.releaseUrl, Localization.getLocalized("minicraft.displays.title.link_to_version", latestVersion.releaseUrl))); @@ -140,7 +139,7 @@ public void render(Screen screen) { /// This isn't as complicated as it looks. It just gets a color based off of count, which oscilates between 0 and 25. int bcol = 5 - count / 5; // This number ends up being between 1 and 5, inclusive. - int splashColor = isblue ? Color.BLUE : isRed ? Color.RED : isGreen ? Color.GREEN : Color.get(1, bcol*51, bcol*51, bcol*25); + int splashColor = isblue ? Color.BLUE : isRed ? Color.RED : isGreen ? Color.GREEN : Color.get(1, bcol * 51, bcol * 51, bcol * 25); Font.drawCentered(splashes[rand], screen, (Screen.h / 2) - 44, splashColor); diff --git a/src/client/java/minicraft/screen/TutorialDisplayHandler.java b/src/client/java/minicraft/screen/TutorialDisplayHandler.java index 7c7ac5f5b..d629e7104 100644 --- a/src/client/java/minicraft/screen/TutorialDisplayHandler.java +++ b/src/client/java/minicraft/screen/TutorialDisplayHandler.java @@ -99,7 +99,9 @@ private void tick() { } } - /** Updating all data by the newly completed element. */ + /** + * Updating all data by the newly completed element. + */ public static void updateCompletedElement(TutorialElement element) { if (!element.isCompleted()) return; if (!(boolean) Settings.get("tutorials")) return; @@ -195,15 +197,17 @@ public static void tick(InputHandler input) { } } - /** Rendering directly on the GUI/HUD. */ + /** + * Rendering directly on the GUI/HUD. + */ public static void render(Screen screen) { if (currentGuide != null) { // Is ongoing. String[] lines = Font.getLines(Localization.getLocalized(currentGuide.display.get()), Screen.w, Screen.h, 0); if (ControlGuide.animation > 0) { int textWidth = Font.textWidth(lines); - int xPadding = Screen.w/2 - (textWidth + 8)/2; - int yPadding = Screen.h/2 - (lines.length * 8 + 8)/2; - int yPad = Screen.h/2 - (lines.length * 8)/2; + int xPadding = Screen.w / 2 - (textWidth + 8) / 2; + int yPadding = Screen.h / 2 - (lines.length * 8 + 8) / 2; + int yPad = Screen.h / 2 - (lines.length * 8) / 2; for (int i = 0; i < lines.length * 8 + 8; i++) { // Background. for (int j = 0; j < textWidth + 8; j++) { screen.pixels[xPadding + j + (yPadding + i) * Screen.w] = @@ -241,9 +245,9 @@ public static void render(Screen screen) { Rectangle bounds = menu.getBounds(); String text = Localization.getLocalized("minicraft.displays.tutorial_display_handler.display.element_examine_help", Game.input.getMapping("expandQuestDisplay")); - String[] lines = Font.getLines(text, Screen.w*2/3, Screen.h, 0); + String[] lines = Font.getLines(text, Screen.w * 2 / 3, Screen.h, 0); for (int i = 0; i < lines.length; i++) - Font.draw(lines[i], screen, bounds.getRight() - Font.textWidth(lines[i]), bounds.getBottom() + 8 * (1+i), Color.GRAY); + Font.draw(lines[i], screen, bounds.getRight() - Font.textWidth(lines[i]), bounds.getBottom() + 8 * (1 + i), Color.GRAY); } } @@ -272,7 +276,9 @@ public static void load(JSONObject json) { if (currentOngoingElement != null) currentOngoingElement.update(); } - /** Saving and writing all data into the given JSONObject. */ + /** + * Saving and writing all data into the given JSONObject. + */ public static void save(JSONObject json) { if (currentOngoingElement != null) json.put("CurrentOngoingTutorial", currentOngoingElement.key); tutorialElements.forEach(element -> element.save(json)); diff --git a/src/client/java/minicraft/screen/WorldGenDisplay.java b/src/client/java/minicraft/screen/WorldGenDisplay.java index 660bccafb..5f62a2cab 100644 --- a/src/client/java/minicraft/screen/WorldGenDisplay.java +++ b/src/client/java/minicraft/screen/WorldGenDisplay.java @@ -25,25 +25,26 @@ public class WorldGenDisplay extends Display { private static final Pattern detailedFilenamePattern; private static final String worldNameRegex; + static { if (FileHandler.OS.contains("windows")) { // Reference: https://stackoverflow.com/a/6804755 worldNameRegex = "[^<>:\"/\\\\|?*\\x00-\\x1F]+"; detailedFilenamePattern = Pattern.compile( - "# Match a valid Windows filename (unspecified file system). \n" + - "^ # Anchor to start of string. \n" + - "(?! # Assert filename is not: CON, PRN, \n" + - " (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + - " CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" + - " COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" + - " ) # LPT6, LPT7, LPT8, and LPT9... \n" + - " (?:\\.[^.]*)? # followed by optional extension \n" + - " $ # and end of string \n" + - ") # End negative lookahead assertion. \n" + - "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" + - "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" + - "$ # Anchor to end of string. ", - Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); + "# Match a valid Windows filename (unspecified file system). \n" + + "^ # Anchor to start of string. \n" + + "(?! # Assert filename is not: CON, PRN, \n" + + " (?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + + " CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" + + " COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" + + " ) # LPT6, LPT7, LPT8, and LPT9... \n" + + " (?:\\.[^.]*)? # followed by optional extension \n" + + " $ # and end of string \n" + + ") # End negative lookahead assertion. \n" + + "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" + + "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" + + "$ # Anchor to end of string. ", + Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.COMMENTS); } else if (FileHandler.OS.contains("mac")) { worldNameRegex = "[^/:]+"; detailedFilenamePattern = null; @@ -59,7 +60,7 @@ public static OptionalLong getSeed() { String seedStr = worldSeed.getUserInput(); // If there is no input seed, generate random number - if(seedStr.length() == 0) + if (seedStr.length() == 0) return OptionalLong.empty(); // If the seed is only numbers, just use numbers @@ -72,7 +73,7 @@ public static OptionalLong getSeed() { int len = seedStr.length(); for (int i = 0; i < len; i++) { - seed = 31*seed + seedStr.charAt(i); + seed = 31 * seed + seedStr.charAt(i); } return OptionalLong.of(seed); @@ -84,10 +85,10 @@ public static InputEntry makeWorldNameInput(String prompt, List takenNam @Override public boolean isValid() { - if(!super.isValid()) return false; + if (!super.isValid()) return false; String name = getUserInput(); - for(String other: takenNames) - if(other.equalsIgnoreCase(name)) { + for (String other : takenNames) + if (other.equalsIgnoreCase(name)) { if (!name.equals(lastName)) { Logging.WORLD.debug("Duplicated or existed world name \"{}\".", name); lastName = name; @@ -97,7 +98,7 @@ public boolean isValid() { } try { // Checking if the folder name is valid; - Paths.get(Game.gameDir+"/saves/"+name+"/"); + Paths.get(Game.gameDir + "/saves/" + name + "/"); } catch (InvalidPathException e) { if (!name.equals(lastName)) { Logging.WORLD.debug("Invalid world name (InvalidPathException) \"{}\": {}", name, e.getMessage()); @@ -129,8 +130,8 @@ public String getUserInput() { @Override public void render(Screen screen, int x, int y, boolean isSelected) { - super.render(screen, isGen? - (getUserInput().length() > 11? x - (getUserInput().length()-11) * 8: x): + super.render(screen, isGen ? + (getUserInput().length() > 11 ? x - (getUserInput().length() - 11) * 8 : x) : x, y, isSelected); } }; @@ -153,8 +154,8 @@ public int getColor(boolean isSelected) { HashSet controls = new HashSet<>(); controls.addAll(Arrays.asList(Game.input.getMapping("cursor-up").split("/"))); controls.addAll(Arrays.asList(Game.input.getMapping("cursor-down").split("/"))); - for (String key: controls) { - if(key.matches("^\\w$")) { + for (String key : controls) { + if (key.matches("^\\w$")) { nameHelp.setVisible(true); break; } @@ -162,7 +163,9 @@ public int getColor(boolean isSelected) { worldSeed = new InputEntry("minicraft.displays.world_gen.world_seed", "[-!\"#%/()=+,a-zA-Z0-9]+", 20) { @Override - public boolean isValid() { return true; } + public boolean isValid() { + return true; + } }; Menu mainMenu = @@ -173,7 +176,7 @@ public int getColor(boolean isSelected) { Settings.getEntry("scoretime"), new SelectEntry("minicraft.displays.world_gen.create_world", () -> { - if(!nameField.isValid()) return; + if (!nameField.isValid()) return; WorldSelectDisplay.setWorldName(nameField.getUserInput(), false); Game.setDisplay(new LoadingDisplay()); }) { @@ -197,9 +200,9 @@ public void render(Screen screen, int x, int y, boolean isSelected) { onScreenKeyboardMenu = OnScreenKeyboardMenu.checkAndCreateMenu(); if (onScreenKeyboardMenu == null) - menus = new Menu[] { mainMenu }; + menus = new Menu[]{mainMenu}; else - menus = new Menu[] { onScreenKeyboardMenu, mainMenu }; + menus = new Menu[]{onScreenKeyboardMenu, mainMenu}; } OnScreenKeyboardMenu onScreenKeyboardMenu; diff --git a/src/client/java/minicraft/screen/WorldSelectDisplay.java b/src/client/java/minicraft/screen/WorldSelectDisplay.java index 5b0b4255a..320ef1320 100644 --- a/src/client/java/minicraft/screen/WorldSelectDisplay.java +++ b/src/client/java/minicraft/screen/WorldSelectDisplay.java @@ -68,7 +68,7 @@ private void updateEntries() { }, false); } - menus = new Menu[] { + menus = new Menu[]{ new Menu.Builder(false, 0, RelPos.CENTER, entries) .setDisplayLength(5) .setScrollPolicies(1, true) @@ -230,7 +230,7 @@ public void render(Screen screen) { col = Color.RED; Font.drawCentered(Localization.getLocalized("minicraft.displays.world_select.display.world_too_new"), screen, Font.textHeight() * 5, col); } - Font.drawCentered(Localization.getLocalized("minicraft.displays.world_select.display.world_version", (version.compareTo(new Version("1.9.2")) <= 0 ? "~" : "") + version), screen, Font.textHeight() * 7/2, col); + Font.drawCentered(Localization.getLocalized("minicraft.displays.world_select.display.world_version", (version.compareTo(new Version("1.9.2")) <= 0 ? "~" : "") + version), screen, Font.textHeight() * 7 / 2, col); } Font.drawCentered(Localization.getLocalized("minicraft.displays.world_select.display.help.0", Game.input.getMapping("select")), screen, Screen.h - 60, Color.GRAY); @@ -287,13 +287,20 @@ public static void updateWorlds() { } } - public static String getWorldName() { return worldName; } + public static String getWorldName() { + return worldName; + } + public static void setWorldName(String world, boolean loaded) { worldName = world; loadedWorld = loaded; } - public static boolean hasLoadedWorld() { return loadedWorld; } + public static boolean hasLoadedWorld() { + return loadedWorld; + } - public static ArrayList getWorldNames() { return worldNames; } + public static ArrayList getWorldNames() { + return worldNames; + } } diff --git a/src/client/java/minicraft/screen/entry/ArrayEntry.java b/src/client/java/minicraft/screen/entry/ArrayEntry.java index 98431cf5f..1c540869a 100644 --- a/src/client/java/minicraft/screen/entry/ArrayEntry.java +++ b/src/client/java/minicraft/screen/entry/ArrayEntry.java @@ -20,10 +20,14 @@ public class ArrayEntry extends ListEntry { private ChangeListener changeAction; @SafeVarargs - public ArrayEntry(String label, T... options) { this(label, true, true, options); } + public ArrayEntry(String label, T... options) { + this(label, true, true, options); + } @SafeVarargs - public ArrayEntry(String label, boolean wrap, T... options) { this(label, wrap, true, options); } + public ArrayEntry(String label, boolean wrap, T... options) { + this(label, wrap, true, options); + } @SafeVarargs public ArrayEntry(String label, boolean wrap, boolean localize, T... options) { @@ -49,15 +53,25 @@ public void setValue(Object value) { setSelection(getIndex(value)); // if it is -1, setSelection simply won't set the value. } - protected String getLabel() { return label; } - protected String getLocalizationOption(T option) { return option.toString(); } + protected String getLabel() { + return label; + } + + protected String getLocalizationOption(T option) { + return option.toString(); + } + + public int getSelection() { + return selection; + } - public int getSelection() { return selection; } - public T getValue() { return options[selection]; } + public T getValue() { + return options[selection]; + } public boolean valueIs(Object value) { if (value instanceof String && options instanceof String[]) - return ((String)value).equalsIgnoreCase((String)getValue()); + return ((String) value).equalsIgnoreCase((String) getValue()); else return getValue().equals(value); } @@ -65,7 +79,7 @@ public boolean valueIs(Object value) { private int getIndex(Object value) { boolean areStrings = value instanceof String && options instanceof String[]; for (int i = 0; i < options.length; i++) { - if (areStrings && ((String)value).equalsIgnoreCase((String)options[i]) || options[i].equals(value)) { + if (areStrings && ((String) value).equalsIgnoreCase((String) options[i]) || options[i].equals(value)) { return i; } } @@ -85,7 +99,7 @@ public void setValueVisibility(Object value, boolean visible) { public boolean getValueVisibility(Object value) { int idx = getIndex(value); - if(idx < 0) return false; + if (idx < 0) return false; return optionVis[idx]; } @@ -103,7 +117,7 @@ public void tick(InputHandler input) { if (input.inputPressed("cursor-right")) selection++; } - if(prevSel != selection) { + if (prevSel != selection) { Sound.play("select"); moveSelection(selection - prevSel); } @@ -116,14 +130,14 @@ private void moveSelection(int dir) { do { selection += dir; - if(wrap) { + if (wrap) { selection = selection % options.length; - if(selection < 0) selection = options.length - 1; + if (selection < 0) selection = options.length - 1; } else { - selection = Math.min(selection, options.length-1); + selection = Math.min(selection, options.length - 1); selection = Math.max(0, selection); } - } while(!optionVis[selection] && selection != prevSel); + } while (!optionVis[selection] && selection != prevSel); setSelection(selection); } @@ -145,7 +159,7 @@ public String toString() { public void setChangeAction(ChangeListener l) { this.changeAction = l; - if(l != null) + if (l != null) l.onChange(getValue()); } } diff --git a/src/client/java/minicraft/screen/entry/BlankEntry.java b/src/client/java/minicraft/screen/entry/BlankEntry.java index 9f42b58ef..fcad07afc 100644 --- a/src/client/java/minicraft/screen/entry/BlankEntry.java +++ b/src/client/java/minicraft/screen/entry/BlankEntry.java @@ -11,10 +11,12 @@ public BlankEntry() { } @Override - public void tick(InputHandler input) {} + public void tick(InputHandler input) { + } @Override - public void render(Screen screen, int x, int y, boolean isSelected) {} + public void render(Screen screen, int x, int y, boolean isSelected) { + } @Override public int getWidth() { @@ -22,5 +24,7 @@ public int getWidth() { } @Override - public String toString() { return " "; } + public String toString() { + return " "; + } } diff --git a/src/client/java/minicraft/screen/entry/BooleanEntry.java b/src/client/java/minicraft/screen/entry/BooleanEntry.java index 0829bcd4a..a58a9bfe7 100644 --- a/src/client/java/minicraft/screen/entry/BooleanEntry.java +++ b/src/client/java/minicraft/screen/entry/BooleanEntry.java @@ -5,7 +5,7 @@ public class BooleanEntry extends ArrayEntry { public BooleanEntry(String label, boolean initial) { - super(label, true, new Boolean[] {true, false}); + super(label, true, new Boolean[]{true, false}); setSelection(initial ? 0 : 1); } diff --git a/src/client/java/minicraft/screen/entry/InputEntry.java b/src/client/java/minicraft/screen/entry/InputEntry.java index df32e3ba8..5dceb61e4 100644 --- a/src/client/java/minicraft/screen/entry/InputEntry.java +++ b/src/client/java/minicraft/screen/entry/InputEntry.java @@ -22,9 +22,11 @@ public class InputEntry extends ListEntry { public InputEntry(String prompt) { this(prompt, null, 0); } + public InputEntry(String prompt, String regex, int maxLen) { this(prompt, regex, maxLen, ""); } + public InputEntry(String prompt, String regex, int maxLen, String initValue) { this.prompt = prompt; this.regex = regex; @@ -56,7 +58,9 @@ public void tick(InputHandler input) { } } - public String getUserInput() { return userInput; } + public String getUserInput() { + return userInput; + } public String toString() { return Localization.getLocalized(prompt) + (prompt.length() == 0 ? "" : ": ") + userInput; diff --git a/src/client/java/minicraft/screen/entry/ItemEntry.java b/src/client/java/minicraft/screen/entry/ItemEntry.java index 4da6d2a48..cfc17d1c3 100644 --- a/src/client/java/minicraft/screen/entry/ItemEntry.java +++ b/src/client/java/minicraft/screen/entry/ItemEntry.java @@ -17,12 +17,17 @@ public static ItemEntry[] useItems(List items) { private Item item; - public ItemEntry(Item i) { this.item = i; } + public ItemEntry(Item i) { + this.item = i; + } - public Item getItem() { return item; } + public Item getItem() { + return item; + } @Override - public void tick(InputHandler input) {} + public void tick(InputHandler input) { + } @Override public void render(Screen screen, int x, int y, boolean isSelected) { diff --git a/src/client/java/minicraft/screen/entry/ItemListing.java b/src/client/java/minicraft/screen/entry/ItemListing.java index c123f849c..9150366c1 100644 --- a/src/client/java/minicraft/screen/entry/ItemListing.java +++ b/src/client/java/minicraft/screen/entry/ItemListing.java @@ -3,17 +3,19 @@ import minicraft.item.Item; public class ItemListing extends ItemEntry { - + private String info; - + public ItemListing(Item i, String text) { super(i); setSelectable(false); this.info = text; } - - public void setText(String text) { info = text; } - + + public void setText(String text) { + info = text; + } + @Override public String toString() { return " " + info; diff --git a/src/client/java/minicraft/screen/entry/KeyInputEntry.java b/src/client/java/minicraft/screen/entry/KeyInputEntry.java index a21bb8049..2d362fe88 100644 --- a/src/client/java/minicraft/screen/entry/KeyInputEntry.java +++ b/src/client/java/minicraft/screen/entry/KeyInputEntry.java @@ -23,7 +23,7 @@ private void setMapping(String mapping, Set duplicated) { this.mapping = mapping; StringBuilder buffer = new StringBuilder(); - for (int spaces = 0; spaces < Screen.w/Font.textWidth(" ") - action.length() - mapping.length(); spaces++) + for (int spaces = 0; spaces < Screen.w / Font.textWidth(" ") - action.length() - mapping.length(); spaces++) buffer.append(" "); String newMapping = ""; diff --git a/src/client/java/minicraft/screen/entry/LinkEntry.java b/src/client/java/minicraft/screen/entry/LinkEntry.java index 574bc6422..ab994555f 100644 --- a/src/client/java/minicraft/screen/entry/LinkEntry.java +++ b/src/client/java/minicraft/screen/entry/LinkEntry.java @@ -25,11 +25,22 @@ public class LinkEntry extends SelectEntry { // note that if the failMsg should be localized, such must be done before passing them as parameters, for this class will not do it since, by default, the failMsg contains a url. - public LinkEntry(int color, String urlText) { this(color, urlText, urlText, false); } - public LinkEntry(int color, String text, String url) { this(color, text, url, true); } - public LinkEntry(int color, String text, String url, String failMsg) { this(color, text, url, failMsg, true); } + public LinkEntry(int color, String urlText) { + this(color, urlText, urlText, false); + } + + public LinkEntry(int color, String text, String url) { + this(color, text, url, true); + } + + public LinkEntry(int color, String text, String url, String failMsg) { + this(color, text, url, failMsg, true); + } + + public LinkEntry(int color, String text, String url, boolean localize) { + this(color, text, url, Localization.getLocalized("Go to") + ": " + url, localize); + } - public LinkEntry(int color, String text, String url, boolean localize) { this(color, text, url, Localization.getLocalized("Go to") + ": " + url, localize); } public LinkEntry(int color, String text, String url, String failMsg, boolean localize) { super(text, () -> { if (!checkedDesktop) { @@ -40,7 +51,7 @@ public LinkEntry(int color, String text, String url, String failMsg, boolean loc } } - if(canBrowse) { + if (canBrowse) { // try to open the download link directly from the browser. try { URI uri = URI.create(url); @@ -63,5 +74,7 @@ public LinkEntry(int color, String text, String url, String failMsg, boolean loc } @Override - public int getColor(boolean isSelected) { return color; } + public int getColor(boolean isSelected) { + return color; + } } diff --git a/src/client/java/minicraft/screen/entry/ListEntry.java b/src/client/java/minicraft/screen/entry/ListEntry.java index d1b65c4bd..e5913083d 100644 --- a/src/client/java/minicraft/screen/entry/ListEntry.java +++ b/src/client/java/minicraft/screen/entry/ListEntry.java @@ -14,6 +14,7 @@ public abstract class ListEntry { /** * Ticks the entry. Used to handle input from the InputHandler + * * @param input InputHandler used to get player input. */ public abstract void tick(InputHandler input); @@ -36,9 +37,10 @@ public void render(Screen screen, int x, int y, boolean isSelected, String conta /** * Renders the entry to the given screen. * Coordinate origin is in the top left corner of the entry space. - * @param screen Screen to render the entry to - * @param x X coordinate - * @param y Y coordinate + * + * @param screen Screen to render the entry to + * @param x X coordinate + * @param y Y coordinate * @param isSelected true if the entry is selected, false otherwise */ public void render(Screen screen, int x, int y, boolean isSelected) { @@ -53,13 +55,17 @@ public void render(Screen screen, int x, int y, boolean isSelected) { /** * Returns the current color depending on if the entry is selected. + * * @param isSelected true if the entry is selected, false otherwise * @return the current entry color */ - public int getColor(boolean isSelected) { return isSelected ? COL_SLCT : COL_UNSLCT; } + public int getColor(boolean isSelected) { + return isSelected ? COL_SLCT : COL_UNSLCT; + } /** * Calculates the width of the entry. + * * @return the entry's width */ public int getWidth() { @@ -68,6 +74,7 @@ public int getWidth() { /** * Calculates the height of the entry. + * * @return the entry's height */ public static int getHeight() { @@ -76,27 +83,39 @@ public static int getHeight() { /** * Determines if this entry can be selected. + * * @return true if it is visible and can be selected, false otherwise. */ - public final boolean isSelectable() { return selectable && visible; } + public final boolean isSelectable() { + return selectable && visible; + } /** * Returns whether the entry is visible or not. + * * @return true if the entry is visible, false otherwise */ - public final boolean isVisible() { return visible; } + public final boolean isVisible() { + return visible; + } /** * Changes if the entry can be selected or not. + * * @param selectable true if the entry can be selected, false if not */ - public final void setSelectable(boolean selectable) { this.selectable = selectable; } + public final void setSelectable(boolean selectable) { + this.selectable = selectable; + } /** * Changes if the entry is visible or not. + * * @param visible true if the entry should be visible, false if not */ - public final void setVisible(boolean visible) { this.visible = visible; } + public final void setVisible(boolean visible) { + this.visible = visible; + } @Override public abstract String toString(); diff --git a/src/client/java/minicraft/screen/entry/RangeEntry.java b/src/client/java/minicraft/screen/entry/RangeEntry.java index d6356ca9c..a4a8c5311 100644 --- a/src/client/java/minicraft/screen/entry/RangeEntry.java +++ b/src/client/java/minicraft/screen/entry/RangeEntry.java @@ -1,31 +1,31 @@ package minicraft.screen.entry; public class RangeEntry extends ArrayEntry { - + private static Integer[] getIntegerArray(int min, int max) { Integer[] ints = new Integer[max - min + 1]; - + for (int i = 0; i < ints.length; i++) - ints[i] = min+i; - + ints[i] = min + i; + return ints; } - + private int min, max; - + public RangeEntry(String label, int min, int max, int initial) { super(label, false, getIntegerArray(min, max)); - + this.min = min; this.max = max; - + setValue(initial); } - + @Override public void setValue(Object o) { if (!(o instanceof Integer)) return; - - setSelection(((Integer)o)-min); + + setSelection(((Integer) o) - min); } } diff --git a/src/client/java/minicraft/screen/entry/RecipeEntry.java b/src/client/java/minicraft/screen/entry/RecipeEntry.java index 85faa2d46..41fe3fc75 100644 --- a/src/client/java/minicraft/screen/entry/RecipeEntry.java +++ b/src/client/java/minicraft/screen/entry/RecipeEntry.java @@ -24,7 +24,8 @@ public RecipeEntry(Recipe r) { } @Override - public void tick(InputHandler input) {} + public void tick(InputHandler input) { + } @Override public void render(Screen screen, int x, int y, boolean isSelected) { diff --git a/src/client/java/minicraft/screen/entry/SelectEntry.java b/src/client/java/minicraft/screen/entry/SelectEntry.java index c558a0d9e..ede9c2ad2 100644 --- a/src/client/java/minicraft/screen/entry/SelectEntry.java +++ b/src/client/java/minicraft/screen/entry/SelectEntry.java @@ -16,10 +16,14 @@ public class SelectEntry extends ListEntry { * Creates a new entry which acts as a button. * Can do an action when it is selected. * Localizes the provided string. - * @param text Text displayed on this entry + * + * @param text Text displayed on this entry * @param onSelect Action which happens when the entry is selected */ - public SelectEntry(String text, Action onSelect) { this(text, onSelect, true); } + public SelectEntry(String text, Action onSelect) { + this(text, onSelect, true); + } + public SelectEntry(String text, Action onSelect, boolean localize) { this.onSelect = onSelect; this.text = text; @@ -28,11 +32,16 @@ public SelectEntry(String text, Action onSelect, boolean localize) { /** * Changes the text of the entry. + * * @param text new text */ - void setText(String text) { this.text = text; } + void setText(String text) { + this.text = text; + } - public String getText() { return text; } + public String getText() { + return text; + } @Override public void tick(InputHandler input) { @@ -43,8 +52,12 @@ public void tick(InputHandler input) { } @Override - public int getWidth() { return Font.textWidth(toString()); } + public int getWidth() { + return Font.textWidth(toString()); + } @Override - public String toString() { return localize ? Localization.getLocalized(text) : text; } + public String toString() { + return localize ? Localization.getLocalized(text) : text; + } } diff --git a/src/client/java/minicraft/screen/entry/StringEntry.java b/src/client/java/minicraft/screen/entry/StringEntry.java index de22241aa..fd2cf1de5 100644 --- a/src/client/java/minicraft/screen/entry/StringEntry.java +++ b/src/client/java/minicraft/screen/entry/StringEntry.java @@ -23,11 +23,16 @@ public class StringEntry extends ListEntry { public static StringEntry[] useLines(String... lines) { return useLines(DEFAULT_COLOR, lines); } - public static StringEntry[] useLines(int color, String... lines) { return useLines(color, true, lines); } + + public static StringEntry[] useLines(int color, String... lines) { + return useLines(color, true, lines); + } + public static StringEntry[] useLines(int color, boolean localize, String... lines) { ArrayList lns = new ArrayList<>(); for (String l : lines) { - for (String ll : Font.getLines(localize? Localization.getLocalized(l): l, Screen.w-20, Screen.h*2, 0)) lns.add(ll); + for (String ll : Font.getLines(localize ? Localization.getLocalized(l) : l, Screen.w - 20, Screen.h * 2, 0)) + lns.add(ll); } StringEntry[] entries = new StringEntry[lns.size()]; for (int i = 0; i < lns.size(); i++) @@ -39,8 +44,15 @@ public static StringEntry[] useLines(int color, boolean localize, String... line public StringEntry(String text) { this(text, DEFAULT_COLOR); } - public StringEntry(String text, boolean localize) { this(text, DEFAULT_COLOR, localize); } // This might be false as the text might have been localized already. - public StringEntry(String text, int color) { this(text, color, true); } // This should be always true with the new localization IDs. + + public StringEntry(String text, boolean localize) { + this(text, DEFAULT_COLOR, localize); + } // This might be false as the text might have been localized already. + + public StringEntry(String text, int color) { + this(text, color, true); + } // This should be always true with the new localization IDs. + public StringEntry(String text, int color, boolean localize) { setSelectable(false); this.text = text; @@ -53,11 +65,16 @@ public void setText(String text) { } @Override - public void tick(InputHandler input) {} + public void tick(InputHandler input) { + } @Override - public int getColor(boolean isSelected) { return color; } + public int getColor(boolean isSelected) { + return color; + } @Override - public String toString() { return localize? Localization.getLocalized(text): text; } + public String toString() { + return localize ? Localization.getLocalized(text) : text; + } } diff --git a/src/client/java/minicraft/util/AdvancementElement.java b/src/client/java/minicraft/util/AdvancementElement.java index a0c25c5d5..faa784026 100644 --- a/src/client/java/minicraft/util/AdvancementElement.java +++ b/src/client/java/minicraft/util/AdvancementElement.java @@ -32,7 +32,9 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -/** World-wide. */ +/** + * World-wide. + */ public class AdvancementElement { private static final HashSet recipeUnlockingElements; @@ -100,7 +102,7 @@ public static void loadAdvancementElement(Collection element ElementRewards rewards = loadRewards(json.optJSONObject("rewards")); elements.add(new AdvancementElement(criterionName, - displayable ? json.getString("description"): null, criteria, + displayable ? json.getString("description") : null, criteria, rewards, requirements, unlockingCriteria, unlockingRequirements)); } @@ -144,7 +146,9 @@ public static void loadRecipeUnlockingElements(JSONObject json) { } } - /** Saving and writing all data into the given JSONObject. */ + /** + * Saving and writing all data into the given JSONObject. + */ public static void saveRecipeUnlockingElements(JSONObject json) { recipeUnlockingElements.forEach(element -> element.save(json)); } @@ -204,7 +208,8 @@ public boolean isCompleted() { /** * Marking the criterion as completed if it has not already been completed. - * @param inLoad If this is {@code false}, triggers the status updater. + * + * @param inLoad If this is {@code false}, triggers the status updater. * @param completionTime The completion time. Using the current datetime if this is {@code null}. */ public void markAsCompleted(boolean inLoad, @Nullable LocalDateTime completionTime) { @@ -230,8 +235,13 @@ public ElementRewards(ArrayList items, ArrayList recipes) { this.recipes = recipes; } - public ArrayList getItems() { return new ArrayList<>(items); } - public ArrayList getRecipe() { return new ArrayList<>(recipes); } + public ArrayList getItems() { + return new ArrayList<>(items); + } + + public ArrayList getRecipe() { + return new ArrayList<>(recipes); + } } @SuppressWarnings("unused") @@ -266,8 +276,10 @@ protected void registerCriteria() { }); } - /** Warning: This method should be used carefully as this could impact - * the gaming experience deeply on the progress. */ + /** + * Warning: This method should be used carefully as this could impact + * the gaming experience deeply on the progress. + */ public void deregisterCriteria() { criteria.values().forEach(criterion -> { criterion.trigger.registeredCriteria.remove(criterion); @@ -282,7 +294,9 @@ public boolean isUnlocked() { return unlocked; } - /** Is unlocked but not completed. */ + /** + * Is unlocked but not completed. + */ public boolean isDisplayableAtStatus() { return unlocked && !completed; } @@ -290,9 +304,11 @@ public boolean isDisplayableAtStatus() { public int getNumCriteriaCompleted() { return (int) criteria.values().stream().filter(ElementCriterion::isCompleted).count(); } + public int getTotalNumCriteria() { return criteria.size(); } + public boolean shouldAllCriteriaBeCompleted() { return requirements.isEmpty(); } @@ -314,7 +330,9 @@ protected boolean checkIsCompleted() { })); } - /** Updating and refreshing by the data in this element. */ + /** + * Updating and refreshing by the data in this element. + */ public void update() { registerUnlockingCriteria(); @@ -349,7 +367,10 @@ protected void sendRewards() { } } - public void reset() { reset(true); } + public void reset() { + reset(true); + } + protected void reset(boolean update) { completed = false; unlocked = false; @@ -357,7 +378,9 @@ protected void reset(boolean update) { if (update) update(); } - /** Loading from a JSONObject of an element. */ + /** + * Loading from a JSONObject of an element. + */ public void load(JSONObject json) { reset(false); completed = json.optBoolean("done"); @@ -385,7 +408,9 @@ public void load(JSONObject json) { update(); } - /** Saving and writing data to the root JSONObject */ + /** + * Saving and writing data to the root JSONObject + */ public void save(JSONObject json) { JSONObject elementJson = new JSONObject(); JSONObject criteriaJson = new JSONObject(); @@ -417,7 +442,7 @@ public static abstract class AdvancementTrigger { private static final Set pendingCompletedCriteria = ConcurrentHashMap.newKeySet(); public static void tick() { - for (Iterator it = pendingCompletedCriteria.iterator(); it.hasNext();) { + for (Iterator it = pendingCompletedCriteria.iterator(); it.hasNext(); ) { ElementCriterion criterion = it.next(); criterion.markAsCompleted(false, null); it.remove(); // Action done. @@ -453,18 +478,24 @@ public void register(ElementCriterion criterion) { registeredCriteria.add(criterion); } - /** This should be called by another thread if method {@link #singleThreadNeeded()} is not + /** + * This should be called by another thread if method {@link #singleThreadNeeded()} is not * implemented to return true. If false, this should use {@link #pendingCompletedCriteria} * to mark completed criteria instead of calling it directly as this method should be called - * by the global game tick updater to ensure the synchronization. */ + * by the global game tick updater to ensure the synchronization. + */ protected abstract void trigger0(AdvancementTriggerConditionHandler.AdvancementTriggerConditions conditions); - /** @return {@code true} if this trigger implementation requires single thread as the global game tick updater. */ + /** + * @return {@code true} if this trigger implementation requires single thread as the global game tick updater. + */ protected boolean singleThreadNeeded() { return true; } - /** Triggering and checking passes by another thread. */ + /** + * Triggering and checking passes by another thread. + */ public void trigger(AdvancementTriggerConditionHandler.AdvancementTriggerConditions conditions) { if (!singleThreadNeeded()) executorService.submit(() -> trigger0(conditions)); else trigger0(conditions); @@ -477,20 +508,26 @@ public AdvancementElement.AdvancementTrigger.AdvancementTriggerConditionHandler } public abstract static class AdvancementTriggerConditionHandler { - protected AdvancementTriggerConditionHandler() {} + protected AdvancementTriggerConditionHandler() { + } @NotNull public abstract AdvancementCriterionConditions createCriterionConditions(JSONObject json) throws JSONException; - /** A condition carrier for the corresponding trigger. */ - public abstract static class AdvancementTriggerConditions {} + /** + * A condition carrier for the corresponding trigger. + */ + public abstract static class AdvancementTriggerConditions { + } public abstract static class AdvancementCriterionConditions { - protected AdvancementCriterionConditions() {} + protected AdvancementCriterionConditions() { + } public static class Rangeable> { public final @Nullable T min; public final @Nullable T max; + public Rangeable(@Nullable T min, @Nullable T max) { this.min = min; this.max = max; @@ -514,8 +551,8 @@ private boolean inRange(T value) { public String toString() { return isAbsent(this) ? "" : min == null ? "max: " + max : - max == null ? "min: " + min : - String.format("min: %s;max: %s", min, max); + max == null ? "min: " + min : + String.format("min: %s;max: %s", min, max); } } @@ -523,6 +560,7 @@ public static class ItemConditions { private final HashSet items = new HashSet<>(); private final @Nullable Rangeable count; private final @Nullable Rangeable durability; + private ItemConditions(Set items, @Nullable Rangeable count, @Nullable Rangeable durability) { this.items.addAll(items); this.count = count; @@ -576,7 +614,9 @@ private boolean matches(Item item) { } } - /** Tile location. */ + /** + * Tile location. + */ public static class LocationConditions { private final HashSet tiles = new HashSet<>(); private final @Nullable Integer level; @@ -609,12 +649,14 @@ private static LocationConditions getFromJson(JSONObject json) { try { data = tileJson.getInt("data"); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } } try { level = json.getInt("level"); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } JSONObject positionJson = json.optJSONObject("position"); if (json.has("x")) try { @@ -664,16 +706,19 @@ protected ImpossibleTrigger() { } @Override - public void register(ElementCriterion criterion) {} // No action. + public void register(ElementCriterion criterion) { + } // No action. @Override - protected void trigger0(AdvancementTriggerConditionHandler.AdvancementTriggerConditions conditions) {} // No action. + protected void trigger0(AdvancementTriggerConditionHandler.AdvancementTriggerConditions conditions) { + } // No action. public static class ImpossibleTriggerConditionHandler extends AdvancementTriggerConditionHandler { @Override public @NotNull AdvancementElement.AdvancementTrigger.AdvancementTriggerConditionHandler.AdvancementCriterionConditions createCriterionConditions(JSONObject json) { - return new AdvancementCriterionConditions() {}; // Empty. + return new AdvancementCriterionConditions() { + }; // Empty. } } } @@ -718,7 +763,9 @@ protected void trigger0(AdvancementTriggerConditionHandler.AdvancementTriggerCon } } - /** Modified from {@link #test(List, List)}. */ + /** + * Modified from {@link #test(List, List)}. + */ private static boolean isConditionalMatched(ArrayList items, HashSet itemConditions) { Set> combinations = new HashSet<>(); @@ -751,7 +798,9 @@ private static boolean isConditionalMatched(ArrayList items, } } - /** Used by {@link #allMatch(Collection, Collection, HashMap)} for conditional check for each element. */ + /** + * Used by {@link #allMatch(Collection, Collection, HashMap)} for conditional check for each element. + */ private static boolean isMatched(Item item, InventoryChangedTriggerConditionHandler.InventoryChangedCriterionConditions.ItemConditions itemConditions, @Nullable String selectedItem) { if (!itemConditions.matches(item)) @@ -759,7 +808,9 @@ private static boolean isMatched(Item item, InventoryChangedTriggerConditionHand return selectedItem == null || item.getName().equalsIgnoreCase(selectedItem); } - /** Modified from {@link #containsAll(List, List)}. */ + /** + * Modified from {@link #containsAll(List, List)}. + */ private static boolean allMatch(Collection source, Collection target, HashMap selectedItems) { for (Item e : source) { @@ -772,7 +823,9 @@ private static boolean allMatch(Collection source, Collection boolean test(List list, List> matcher) { List> combinations = new ArrayList<>(); @@ -784,7 +837,9 @@ private static boolean test(List list, List> matcher) { return false; } - /** Original archive of array elements matching. */ + /** + * Original archive of array elements matching. + */ private static boolean containsAll(List source, List target) { for (T e : source) { target.remove(e); @@ -884,6 +939,7 @@ public static class InventoryChangedCriterionConditions extends AdvancementCrite private final @Nullable Rangeable slotsEmpty; private final @Nullable Rangeable slotsFull; private final @Nullable Rangeable slotsOccupied; + private InventoryChangedCriterionConditions(Set items, @Nullable Rangeable slotsEmpty, @Nullable Rangeable slotsFull, @Nullable Rangeable slotsOccupied) { this.items.addAll(items); @@ -940,7 +996,8 @@ public static class PlacedTileTriggerConditionHandler extends AdvancementTrigger Integer data = null; try { data = json.getInt("data"); - } catch (JSONException ignored) {} + } catch (JSONException ignored) { + } return new PlacedTileCriterionConditions(tile, item, location, data); } diff --git a/src/client/java/minicraft/util/Logging.java b/src/client/java/minicraft/util/Logging.java index 0296d48ee..903acaaeb 100644 --- a/src/client/java/minicraft/util/Logging.java +++ b/src/client/java/minicraft/util/Logging.java @@ -6,7 +6,9 @@ public final class Logging { public static boolean logTime = false; public static boolean logThread = false; - /** Applied only when debug mode is enabled */ + /** + * Applied only when debug mode is enabled + */ public static boolean logTrace = false; public static boolean logLevel = false; public static boolean fileLogFull = false; @@ -34,6 +36,8 @@ public final class Logging { public static final TaggedLogger CONTROLLER = Logger.tag("Controller"); public static final TaggedLogger PLAYER = Logger.tag("Player"); - /** This is defined dynamically. */ + /** + * This is defined dynamically. + */ public static TaggedLogger WORLDNAMED = Logger.tag(null); } diff --git a/src/client/java/minicraft/util/MyUtils.java b/src/client/java/minicraft/util/MyUtils.java index d6416da27..6a0f78614 100644 --- a/src/client/java/minicraft/util/MyUtils.java +++ b/src/client/java/minicraft/util/MyUtils.java @@ -2,7 +2,8 @@ public final class MyUtils { - private MyUtils() {} + private MyUtils() { + } public static int clamp(int val, int min, int max) { if (val > max) return max; @@ -10,7 +11,10 @@ public static int clamp(int val, int min, int max) { return val; } - public static int randInt(int max) { return randInt(0, max); } + public static int randInt(int max) { + return randInt(0, max); + } + public static int randInt(int min, int max) { return (int) (Math.random() * (max - min + 1)) + min; } @@ -23,7 +27,7 @@ public static String plural(int num, String word) { public static void sleep(int millis) { try { Thread.sleep(millis); - } catch(InterruptedException ignored) { + } catch (InterruptedException ignored) { } } diff --git a/src/client/java/minicraft/util/Quest.java b/src/client/java/minicraft/util/Quest.java index 3ab17214a..fb81d669e 100644 --- a/src/client/java/minicraft/util/Quest.java +++ b/src/client/java/minicraft/util/Quest.java @@ -20,7 +20,10 @@ public Quest(String key, String description, Map crite this.parent = parent; } - public QuestSeries getSeries() { return series; } + public QuestSeries getSeries() { + return series; + } + public @Nullable Quest getParent() { if (parent != null && series != null) { return series.quests.get(parent); @@ -61,7 +64,9 @@ public QuestSeries(String key, String description, Map q.series = this); } - public HashMap getSeriesQuests() { return new HashMap<>(quests); } + public HashMap getSeriesQuests() { + return new HashMap<>(quests); + } @Override protected boolean checkIsCompleted() { diff --git a/src/client/java/minicraft/util/TinylogLoggingConfiguration.java b/src/client/java/minicraft/util/TinylogLoggingConfiguration.java index 2d6af6ea9..174bff62f 100644 --- a/src/client/java/minicraft/util/TinylogLoggingConfiguration.java +++ b/src/client/java/minicraft/util/TinylogLoggingConfiguration.java @@ -40,7 +40,10 @@ public static class TagList { private Set tags = null; private final boolean all; - public TagList(boolean all) { this.all = all; } + public TagList(boolean all) { + this.all = all; + } + public TagList(Set tags) { this.tags = tags; all = false; @@ -119,12 +122,14 @@ public Set computeLevelsFromMinimum(Level minimum) { return levels; } - /** Generate all possible instances of console writer (writer1) with the configuration. */ + /** + * Generate all possible instances of console writer (writer1) with the configuration. + */ public HashMap generateConsoleWriters() { HashMap map = new HashMap<>(); - for (final boolean i : new boolean[] { false, true}) { - for (final boolean j : new boolean[] { false, true}) { - for (final boolean k : new boolean[] { false, true}) { + for (final boolean i : new boolean[]{false, true}) { + for (final boolean j : new boolean[]{false, true}) { + for (final boolean k : new boolean[]{false, true}) { map.putAll(createConsoleWriter(i, j, k)); } } @@ -132,7 +137,10 @@ public HashMap generateConsoleWriters() { return map; } - /** Generate a console writer with the configuration. */ + + /** + * Generate a console writer with the configuration. + */ public Map createConsoleWriter(boolean logTime, boolean logThread, boolean logTrace) { HashMap properties = new HashMap<>(); String ID = String.format("writer1%s%s%s", logTime ? "T" : "F", logThread ? "T" : "F", logTrace ? "T" : "F"); @@ -148,33 +156,24 @@ public Map createConsoleWriter(boolean logTime, boo return Collections.singletonMap(new ConsoleWriter(properties), new WriterConfig(ID, computeLevelsFromMinimum(level), new TagList(true))); } - /** + /** * Creates a new log entry. * - * @param stackTraceElement - * Optional stack trace element of caller - * @param tag - * Tag name if issued from a tagged logger - * @param level - * Severity level - * @param exception - * Caught exception or throwable to log - * @param formatter - * Formatter for text message - * @param obj - * Message to log - * @param arguments - * Arguments for message - * @param required - * The required log entry value array slice of the tag index of the used tag - * @param contextProvider - * The context provider + * @param stackTraceElement Optional stack trace element of caller + * @param tag Tag name if issued from a tagged logger + * @param level Severity level + * @param exception Caught exception or throwable to log + * @param formatter Formatter for text message + * @param obj Message to log + * @param arguments Arguments for message + * @param required The required log entry value array slice of the tag index of the used tag + * @param contextProvider The context provider * @return Filled log entry */ public static LogEntry createLogEntry(final StackTraceElement stackTraceElement, final String tag, - final Level level, final Throwable exception, final MessageFormatter formatter, final Object obj, - final Object[] arguments, final Collection required, - final TinylogContextProvider contextProvider) { + final Level level, final Throwable exception, final MessageFormatter formatter, final Object obj, + final Object[] arguments, final Collection required, + final TinylogContextProvider contextProvider) { Timestamp timestamp = RuntimeProvider.createTimestamp(); Thread thread = required.contains(LogEntryValue.THREAD) ? Thread.currentThread() : null; diff --git a/src/client/java/minicraft/util/TinylogLoggingProvider.java b/src/client/java/minicraft/util/TinylogLoggingProvider.java index cd465be0e..f076f8aab 100644 --- a/src/client/java/minicraft/util/TinylogLoggingProvider.java +++ b/src/client/java/minicraft/util/TinylogLoggingProvider.java @@ -24,7 +24,9 @@ import java.util.HashMap; import java.util.function.Consumer; -/** Originally copied from {@link org.tinylog.core.TinylogLoggingProvider} */ +/** + * Originally copied from {@link org.tinylog.core.TinylogLoggingProvider} + */ public class TinylogLoggingProvider implements LoggingProvider { private final TinylogContextProvider context; @@ -39,7 +41,9 @@ public class TinylogLoggingProvider implements LoggingProvider { private ConsoleWriter currentConsoleWriter; private FileWriter currentFileWriter; - /** */ + /** + * + */ public TinylogLoggingProvider() { TinylogLoggingConfiguration config = new TinylogLoggingConfiguration(); context = new TinylogContextProvider(); @@ -73,7 +77,7 @@ public TinylogLoggingProvider() { ctr.setAccessible(true); writingThread = ctr.newInstance(writers.keySet()); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException | SecurityException | ClassNotFoundException e) { + | NoSuchMethodException | SecurityException | ClassNotFoundException e) { throw new RuntimeException(e); } @@ -90,7 +94,9 @@ public TinylogLoggingProvider() { } } - /** Applying the configuration in {@link Logging} */ + /** + * Applying the configuration in {@link Logging} + */ public void init() { currentConsoleWriter = consoleWriters.get(String.format("writer1%s%s%s", Logging.logTime ? "T" : "F", Logging.logThread ? "T" : "F", Logging.logTrace ? "T" : "F")); currentFileWriter = fileWriters.get("writer2" + (Logging.fileLogFull ? "Full" : "")); @@ -118,7 +124,7 @@ public boolean isEnabled(final int depth, final String tag, final Level level) { @Override public void log(final int depth, final String tag, final Level level, final Throwable exception, final MessageFormatter formatter, - final Object obj, final Object... arguments) { + final Object obj, final Object... arguments) { StackTraceElement stackTraceElement; if (fullStackTraceRequired.get(currentConsoleWriter) || tag.equals("LOC")) { stackTraceElement = RuntimeProvider.getCallerStackTraceElement(depth + 1); @@ -135,7 +141,7 @@ public void log(final int depth, final String tag, final Level level, final Thro @Override public void log(final String loggerClassName, final String tag, final Level level, final Throwable exception, - final MessageFormatter formatter, final Object obj, final Object... arguments) { + final MessageFormatter formatter, final Object obj, final Object... arguments) { StackTraceElement stackTraceElement; if (fullStackTraceRequired.get(currentConsoleWriter) || tag.equals("LOC")) { stackTraceElement = RuntimeProvider.getCallerStackTraceElement(loggerClassName); @@ -170,11 +176,11 @@ public void shutdown() throws InterruptedException { * Outputs a log entry to all passed writers. */ private void output(final StackTraceElement stackTraceElement, final String tag, - final Level level, final Throwable exception, final MessageFormatter formatter, final Object obj, - final Object[] arguments) { + final Level level, final Throwable exception, final MessageFormatter formatter, final Object obj, + final Object[] arguments) { LogEntry logEntry = TinylogLoggingConfiguration.createLogEntry(stackTraceElement, tag, level, exception, formatter, - obj, arguments, requiredLogEntryValues, context); + obj, arguments, requiredLogEntryValues, context); Consumer addToThread = writer -> { WriterConfig cfg = writers.get(writer); diff --git a/src/client/java/minicraft/util/TutorialElement.java b/src/client/java/minicraft/util/TutorialElement.java index 9c60f5790..a21558cff 100644 --- a/src/client/java/minicraft/util/TutorialElement.java +++ b/src/client/java/minicraft/util/TutorialElement.java @@ -11,7 +11,9 @@ public TutorialElement(String key, String description, Map(), new HashMap<>(), new HashSet<>()); } - /** Updating and refreshing by the data in this element. */ + /** + * Updating and refreshing by the data in this element. + */ public void update() { super.update(); TutorialDisplayHandler.updateCompletedElement(this); diff --git a/src/client/java/minicraft/util/Vector2.java b/src/client/java/minicraft/util/Vector2.java index 04598c2d8..703c67352 100644 --- a/src/client/java/minicraft/util/Vector2.java +++ b/src/client/java/minicraft/util/Vector2.java @@ -10,15 +10,15 @@ public Vector2(double x, double y) { public Vector2 normalized() { double max = Math.max(x, y); - return new Vector2(x/max, y/max); + return new Vector2(x / max, y / max); } public static Vector2 normalize(Vector2 vec) { double max = Math.max(vec.x, vec.y); - return new Vector2(vec.x/max, vec.y/max); + return new Vector2(vec.x / max, vec.y / max); } public static double distance(double x, double y) { - return Math.sqrt(x*x + y*y); + return Math.sqrt(x * x + y * y); } } diff --git a/src/client/resources/resources/recipes.json b/src/client/resources/resources/recipes.json index 335f7e8c2..871290c16 100644 --- a/src/client/resources/resources/recipes.json +++ b/src/client/resources/resources/recipes.json @@ -21,7 +21,9 @@ ], "rewards": { "recipes": { - "Workbench_1": ["Wood_10"] + "Workbench_1": [ + "Wood_10" + ] } } }, @@ -60,7 +62,10 @@ ], "rewards": { "recipes": { - "Torch_2": ["Wood_1", "coal_1"] + "Torch_2": [ + "Wood_1", + "coal_1" + ] } } }, @@ -86,7 +91,9 @@ ], "rewards": { "recipes": { - "plank_2": ["Wood_1"] + "plank_2": [ + "Wood_1" + ] } } }, @@ -112,7 +119,9 @@ ], "rewards": { "recipes": { - "Plank Wall_1": ["plank_3"] + "Plank Wall_1": [ + "plank_3" + ] } } }, @@ -138,7 +147,9 @@ ], "rewards": { "recipes": { - "Wood Door_1": ["plank_5"] + "Wood Door_1": [ + "plank_5" + ] } } }, @@ -190,7 +201,11 @@ ], "rewards": { "recipes": { - "Lantern_1": ["Wood_8", "slime_4", "glass_3"] + "Lantern_1": [ + "Wood_8", + "slime_4", + "glass_3" + ] } } }, @@ -216,7 +231,9 @@ ], "rewards": { "recipes": { - "Stone Brick_1": ["Stone_2"] + "Stone Brick_1": [ + "Stone_2" + ] } } }, @@ -242,7 +259,9 @@ ], "rewards": { "recipes": { - "Stone Brick_1": ["Stone_2"] + "Stone Brick_1": [ + "Stone_2" + ] } } }, @@ -268,7 +287,9 @@ ], "rewards": { "recipes": { - "Stone Wall_1": ["Stone Brick_3"] + "Stone Wall_1": [ + "Stone Brick_3" + ] } } }, @@ -294,7 +315,9 @@ ], "rewards": { "recipes": { - "Stone Door_1": ["Stone Brick_5"] + "Stone Door_1": [ + "Stone Brick_5" + ] } } }, @@ -320,7 +343,9 @@ ], "rewards": { "recipes": { - "Obsidian Brick_1": ["Raw Obsidian_2"] + "Obsidian Brick_1": [ + "Raw Obsidian_2" + ] } } }, @@ -346,7 +371,9 @@ ], "rewards": { "recipes": { - "Ornate Obsidian_1": ["Raw Obsidian_2"] + "Ornate Obsidian_1": [ + "Raw Obsidian_2" + ] } } }, @@ -372,7 +399,9 @@ ], "rewards": { "recipes": { - "Obsidian Wall_1": ["Obsidian Brick_3"] + "Obsidian Wall_1": [ + "Obsidian Brick_3" + ] } } }, @@ -398,7 +427,9 @@ ], "rewards": { "recipes": { - "Obsidian Door_1": ["Obsidian Brick_5"] + "Obsidian Door_1": [ + "Obsidian Brick_5" + ] } } }, @@ -424,7 +455,9 @@ ], "rewards": { "recipes": { - "Oven_1": ["Stone_15"] + "Oven_1": [ + "Stone_15" + ] } } }, @@ -450,7 +483,9 @@ ], "rewards": { "recipes": { - "Furnace_1": ["Stone_20"] + "Furnace_1": [ + "Stone_20" + ] } } }, @@ -502,7 +537,11 @@ ], "rewards": { "recipes": { - "Enchanter_1": ["Wood_5", "String_2", "Lapis_10"] + "Enchanter_1": [ + "Wood_5", + "String_2", + "Lapis_10" + ] } } }, @@ -528,7 +567,9 @@ ], "rewards": { "recipes": { - "Chest_1": ["Wood_20"] + "Chest_1": [ + "Wood_20" + ] } } }, @@ -554,7 +595,9 @@ ], "rewards": { "recipes": { - "Anvil_1": ["iron_5"] + "Anvil_1": [ + "iron_5" + ] } } }, @@ -593,7 +636,10 @@ ], "rewards": { "recipes": { - "Tnt_1": ["Gunpowder_10", "Sand_8"] + "Tnt_1": [ + "Gunpowder_10", + "Sand_8" + ] } } }, @@ -632,7 +678,10 @@ ], "rewards": { "recipes": { - "Loom_1": ["Wood_10", "Wool_5"] + "Loom_1": [ + "Wood_10", + "Wool_5" + ] } } }, @@ -671,7 +720,10 @@ ], "rewards": { "recipes": { - "Wood Fishing Rod_1": ["Wood_10", "String_3"] + "Wood Fishing Rod_1": [ + "Wood_10", + "String_3" + ] } } }, @@ -710,7 +762,10 @@ ], "rewards": { "recipes": { - "Iron Fishing Rod_1": ["Iron_10", "String_3"] + "Iron Fishing Rod_1": [ + "Iron_10", + "String_3" + ] } } }, @@ -749,7 +804,10 @@ ], "rewards": { "recipes": { - "Gold Fishing Rod_1": ["Gold_10", "String_3"] + "Gold Fishing Rod_1": [ + "Gold_10", + "String_3" + ] } } }, @@ -788,7 +846,10 @@ ], "rewards": { "recipes": { - "Gem Fishing Rod_1": ["Gem_10", "String_3"] + "Gem Fishing Rod_1": [ + "Gem_10", + "String_3" + ] } } }, @@ -814,7 +875,9 @@ ], "rewards": { "recipes": { - "Wood Sword_1": ["Wood_5"] + "Wood Sword_1": [ + "Wood_5" + ] } } }, @@ -840,7 +903,9 @@ ], "rewards": { "recipes": { - "Wood Axe_1": ["Wood_5"] + "Wood Axe_1": [ + "Wood_5" + ] } } }, @@ -866,7 +931,9 @@ ], "rewards": { "recipes": { - "Wood Hoe_1": ["Wood_5"] + "Wood Hoe_1": [ + "Wood_5" + ] } } }, @@ -892,7 +959,9 @@ ], "rewards": { "recipes": { - "Wood Pickaxe_1": ["Wood_5"] + "Wood Pickaxe_1": [ + "Wood_5" + ] } } }, @@ -918,7 +987,9 @@ ], "rewards": { "recipes": { - "Wood Shovel_1": ["Wood_5"] + "Wood Shovel_1": [ + "Wood_5" + ] } } }, @@ -957,7 +1028,10 @@ ], "rewards": { "recipes": { - "Wood Bow_1": ["Wood_5", "string_2"] + "Wood Bow_1": [ + "Wood_5", + "string_2" + ] } } }, @@ -996,7 +1070,10 @@ ], "rewards": { "recipes": { - "Rock Sword_1": ["Wood_5", "Stone_5"] + "Rock Sword_1": [ + "Wood_5", + "Stone_5" + ] } } }, @@ -1035,7 +1112,10 @@ ], "rewards": { "recipes": { - "Rock Sword_1": ["Wood_5", "Stone_5"] + "Rock Sword_1": [ + "Wood_5", + "Stone_5" + ] } } }, @@ -1074,7 +1154,10 @@ ], "rewards": { "recipes": { - "Rock Axe_1": ["Wood_5", "Stone_5"] + "Rock Axe_1": [ + "Wood_5", + "Stone_5" + ] } } }, @@ -1113,7 +1196,10 @@ ], "rewards": { "recipes": { - "Rock Pickaxe_1": ["Wood_5", "Stone_5"] + "Rock Pickaxe_1": [ + "Wood_5", + "Stone_5" + ] } } }, @@ -1152,7 +1238,10 @@ ], "rewards": { "recipes": { - "Rock Shovel_1": ["Wood_5", "Stone_5"] + "Rock Shovel_1": [ + "Wood_5", + "Stone_5" + ] } } }, @@ -1204,7 +1293,11 @@ ], "rewards": { "recipes": { - "Rock Bow_1": ["Wood_5", "Stone_5", "string_2"] + "Rock Bow_1": [ + "Wood_5", + "Stone_5", + "string_2" + ] } } }, @@ -1243,7 +1336,10 @@ ], "rewards": { "recipes": { - "arrow_3": ["Wood_2", "Stone_2"] + "arrow_3": [ + "Wood_2", + "Stone_2" + ] } } }, @@ -1269,7 +1365,9 @@ ], "rewards": { "recipes": { - "Leather Armor_1": ["leather_10"] + "Leather Armor_1": [ + "leather_10" + ] } } }, @@ -1295,7 +1393,9 @@ ], "rewards": { "recipes": { - "Snake Armor_1": ["scale_15"] + "Snake Armor_1": [ + "scale_15" + ] } } }, @@ -1321,7 +1421,9 @@ ], "rewards": { "recipes": { - "String_2": ["Wool_1"] + "String_2": [ + "Wool_1" + ] } } }, @@ -1360,7 +1462,10 @@ ], "rewards": { "recipes": { - "red wool_1": ["Wool_1", "rose_1"] + "red wool_1": [ + "Wool_1", + "rose_1" + ] } } }, @@ -1399,7 +1504,10 @@ ], "rewards": { "recipes": { - "blue wool_1": ["Wool_1", "Lapis_1"] + "blue wool_1": [ + "Wool_1", + "Lapis_1" + ] } } }, @@ -1438,7 +1546,10 @@ ], "rewards": { "recipes": { - "green wool_1": ["Wool_1", "Cactus_1"] + "green wool_1": [ + "Wool_1", + "Cactus_1" + ] } } }, @@ -1477,7 +1588,10 @@ ], "rewards": { "recipes": { - "yellow wool_1": ["Wool_1", "Flower_1"] + "yellow wool_1": [ + "Wool_1", + "Flower_1" + ] } } }, @@ -1516,7 +1630,10 @@ ], "rewards": { "recipes": { - "black wool_1": ["Wool_1", "coal_1"] + "black wool_1": [ + "Wool_1", + "coal_1" + ] } } }, @@ -1555,7 +1672,10 @@ ], "rewards": { "recipes": { - "Bed_1": ["Wood_5", "Wool_3"] + "Bed_1": [ + "Wood_5", + "Wool_3" + ] } } }, @@ -1594,7 +1714,10 @@ ], "rewards": { "recipes": { - "blue clothes_1": ["cloth_5", "Lapis_1"] + "blue clothes_1": [ + "cloth_5", + "Lapis_1" + ] } } }, @@ -1633,7 +1756,10 @@ ], "rewards": { "recipes": { - "green clothes_1": ["cloth_5", "Cactus_1"] + "green clothes_1": [ + "cloth_5", + "Cactus_1" + ] } } }, @@ -1672,7 +1798,10 @@ ], "rewards": { "recipes": { - "yellow clothes_1": ["cloth_5", "Flower_1"] + "yellow clothes_1": [ + "cloth_5", + "Flower_1" + ] } } }, @@ -1711,7 +1840,10 @@ ], "rewards": { "recipes": { - "black clothes_1": ["cloth_5", "coal_1"] + "black clothes_1": [ + "cloth_5", + "coal_1" + ] } } }, @@ -1763,7 +1895,11 @@ ], "rewards": { "recipes": { - "orange clothes_1": ["cloth_5", "rose_1", "Flower_1"] + "orange clothes_1": [ + "cloth_5", + "rose_1", + "Flower_1" + ] } } }, @@ -1815,7 +1951,11 @@ ], "rewards": { "recipes": { - "purple clothes_1": ["cloth_5", "Lapis_1", "rose_1"] + "purple clothes_1": [ + "cloth_5", + "Lapis_1", + "rose_1" + ] } } }, @@ -1867,7 +2007,11 @@ ], "rewards": { "recipes": { - "cyan clothes_1": ["cloth_5", "Lapis_1", "Cactus_1"] + "cyan clothes_1": [ + "cloth_5", + "Lapis_1", + "Cactus_1" + ] } } }, @@ -1893,7 +2037,9 @@ ], "rewards": { "recipes": { - "reg clothes_1": ["cloth_5"] + "reg clothes_1": [ + "cloth_5" + ] } } }, @@ -1919,7 +2065,9 @@ ], "rewards": { "recipes": { - "Iron Armor_1": ["iron_10"] + "Iron Armor_1": [ + "iron_10" + ] } } }, @@ -1945,7 +2093,9 @@ ], "rewards": { "recipes": { - "Gold Armor_1": ["gold_10"] + "Gold Armor_1": [ + "gold_10" + ] } } }, @@ -1971,7 +2121,9 @@ ], "rewards": { "recipes": { - "Gem Armor_1": ["gem_65"] + "Gem Armor_1": [ + "gem_65" + ] } } }, @@ -1997,7 +2149,9 @@ ], "rewards": { "recipes": { - "Empty Bucket_1": ["iron_5"] + "Empty Bucket_1": [ + "iron_5" + ] } } }, @@ -2049,7 +2203,11 @@ ], "rewards": { "recipes": { - "Iron Lantern_1": ["iron_8", "slime_5", "glass_4"] + "Iron Lantern_1": [ + "iron_8", + "slime_5", + "glass_4" + ] } } }, @@ -2101,7 +2259,11 @@ ], "rewards": { "recipes": { - "Gold Lantern_1": ["gold_10", "slime_5", "glass_4"] + "Gold Lantern_1": [ + "gold_10", + "slime_5", + "glass_4" + ] } } }, @@ -2140,7 +2302,10 @@ ], "rewards": { "recipes": { - "Iron Sword_1": ["Wood_5", "iron_5"] + "Iron Sword_1": [ + "Wood_5", + "iron_5" + ] } } }, @@ -2179,7 +2344,10 @@ ], "rewards": { "recipes": { - "Iron Claymore_1": ["Iron Sword_1", "shard_15"] + "Iron Claymore_1": [ + "Iron Sword_1", + "shard_15" + ] } } }, @@ -2218,7 +2386,10 @@ ], "rewards": { "recipes": { - "Iron Axe_1": ["Wood_5", "iron_5"] + "Iron Axe_1": [ + "Wood_5", + "iron_5" + ] } } }, @@ -2257,7 +2428,10 @@ ], "rewards": { "recipes": { - "Iron Hoe_1": ["Wood_5", "iron_5"] + "Iron Hoe_1": [ + "Wood_5", + "iron_5" + ] } } }, @@ -2296,7 +2470,10 @@ ], "rewards": { "recipes": { - "Iron Pickaxe_1": ["Wood_5", "iron_5"] + "Iron Pickaxe_1": [ + "Wood_5", + "iron_5" + ] } } }, @@ -2335,7 +2512,10 @@ ], "rewards": { "recipes": { - "Iron Shovel_1": ["Wood_5", "iron_5"] + "Iron Shovel_1": [ + "Wood_5", + "iron_5" + ] } } }, @@ -2387,7 +2567,11 @@ ], "rewards": { "recipes": { - "Iron Bow_1": ["Wood_5", "iron_5", "string_2"] + "Iron Bow_1": [ + "Wood_5", + "iron_5", + "string_2" + ] } } }, @@ -2426,7 +2610,10 @@ ], "rewards": { "recipes": { - "Gold Sword_1": ["Wood_5", "gold_5"] + "Gold Sword_1": [ + "Wood_5", + "gold_5" + ] } } }, @@ -2465,7 +2652,10 @@ ], "rewards": { "recipes": { - "Gold Claymore_1": ["Gold Sword_1", "shard_15"] + "Gold Claymore_1": [ + "Gold Sword_1", + "shard_15" + ] } } }, @@ -2504,7 +2694,10 @@ ], "rewards": { "recipes": { - "Gold Axe_1": ["Wood_5", "gold_5"] + "Gold Axe_1": [ + "Wood_5", + "gold_5" + ] } } }, @@ -2543,7 +2736,10 @@ ], "rewards": { "recipes": { - "Gold Hoe_1": ["Wood_5", "gold_5"] + "Gold Hoe_1": [ + "Wood_5", + "gold_5" + ] } } }, @@ -2582,7 +2778,10 @@ ], "rewards": { "recipes": { - "Gold Pickaxe_1": ["Wood_5", "gold_5"] + "Gold Pickaxe_1": [ + "Wood_5", + "gold_5" + ] } } }, @@ -2621,7 +2820,10 @@ ], "rewards": { "recipes": { - "Gold Shovel_1": ["Wood_5", "gold_5"] + "Gold Shovel_1": [ + "Wood_5", + "gold_5" + ] } } }, @@ -2673,7 +2875,11 @@ ], "rewards": { "recipes": { - "Gold Bow_1": ["Wood_5", "gold_5", "string_2"] + "Gold Bow_1": [ + "Wood_5", + "gold_5", + "string_2" + ] } } }, @@ -2712,7 +2918,10 @@ ], "rewards": { "recipes": { - "Gem Sword_1": ["Wood_5", "gem_50"] + "Gem Sword_1": [ + "Wood_5", + "gem_50" + ] } } }, @@ -2751,7 +2960,10 @@ ], "rewards": { "recipes": { - "Gem Claymore_1": ["Gem Sword_1", "shard_15"] + "Gem Claymore_1": [ + "Gem Sword_1", + "shard_15" + ] } } }, @@ -2790,7 +3002,10 @@ ], "rewards": { "recipes": { - "Gem Axe_1": ["Wood_5", "gem_50"] + "Gem Axe_1": [ + "Wood_5", + "gem_50" + ] } } }, @@ -2829,7 +3044,10 @@ ], "rewards": { "recipes": { - "Gem Hoe_1": ["Wood_5", "gem_50"] + "Gem Hoe_1": [ + "Wood_5", + "gem_50" + ] } } }, @@ -2868,7 +3086,10 @@ ], "rewards": { "recipes": { - "Gem Pickaxe_1": ["Wood_5", "gem_50"] + "Gem Pickaxe_1": [ + "Wood_5", + "gem_50" + ] } } }, @@ -2907,7 +3128,10 @@ ], "rewards": { "recipes": { - "Gem Shovel_1": ["Wood_5", "gem_50"] + "Gem Shovel_1": [ + "Wood_5", + "gem_50" + ] } } }, @@ -2959,7 +3183,11 @@ ], "rewards": { "recipes": { - "Gem Bow_1": ["Wood_5", "gem_50", "string_2"] + "Gem Bow_1": [ + "Wood_5", + "gem_50", + "string_2" + ] } } }, @@ -2985,7 +3213,9 @@ ], "rewards": { "recipes": { - "Shears_1": ["Iron_4"] + "Shears_1": [ + "Iron_4" + ] } } }, @@ -3024,7 +3254,10 @@ ], "rewards": { "recipes": { - "iron_1": ["iron Ore_4", "coal_1"] + "iron_1": [ + "iron Ore_4", + "coal_1" + ] } } }, @@ -3063,7 +3296,10 @@ ], "rewards": { "recipes": { - "gold_1": ["gold Ore_4", "coal_1"] + "gold_1": [ + "gold Ore_4", + "coal_1" + ] } } }, @@ -3102,7 +3338,10 @@ ], "rewards": { "recipes": { - "glass_1": ["sand_4", "coal_1"] + "glass_1": [ + "sand_4", + "coal_1" + ] } } }, @@ -3128,7 +3367,9 @@ ], "rewards": { "recipes": { - "glass bottle_1": ["glass_3"] + "glass bottle_1": [ + "glass_3" + ] } } }, @@ -3167,7 +3408,10 @@ ], "rewards": { "recipes": { - "cooked pork_1": ["raw pork_1", "coal_1"] + "cooked pork_1": [ + "raw pork_1", + "coal_1" + ] } } }, @@ -3206,7 +3450,10 @@ ], "rewards": { "recipes": { - "steak_1": ["raw beef_1", "coal_1"] + "steak_1": [ + "raw beef_1", + "coal_1" + ] } } }, @@ -3245,7 +3492,10 @@ ], "rewards": { "recipes": { - "cooked fish_1": ["raw fish_1", "coal_1"] + "cooked fish_1": [ + "raw fish_1", + "coal_1" + ] } } }, @@ -3271,7 +3521,9 @@ ], "rewards": { "recipes": { - "bread_1": ["wheat_4"] + "bread_1": [ + "wheat_4" + ] } } }, @@ -3297,7 +3549,9 @@ ], "rewards": { "recipes": { - "Baked Potato_1": ["Potato_1"] + "Baked Potato_1": [ + "Potato_1" + ] } } }, @@ -3336,7 +3590,10 @@ ], "rewards": { "recipes": { - "Gold Apple_1": ["apple_1", "gold_8"] + "Gold Apple_1": [ + "apple_1", + "gold_8" + ] } } }, @@ -3375,7 +3632,10 @@ ], "rewards": { "recipes": { - "awkward potion_1": ["glass bottle_1", "Lapis_3"] + "awkward potion_1": [ + "glass bottle_1", + "Lapis_3" + ] } } }, @@ -3414,7 +3674,10 @@ ], "rewards": { "recipes": { - "speed potion_1": ["awkward potion_1", "Cactus_5"] + "speed potion_1": [ + "awkward potion_1", + "Cactus_5" + ] } } }, @@ -3453,7 +3716,10 @@ ], "rewards": { "recipes": { - "light potion_1": ["awkward potion_1", "slime_5"] + "light potion_1": [ + "awkward potion_1", + "slime_5" + ] } } }, @@ -3492,7 +3758,10 @@ ], "rewards": { "recipes": { - "swim potion_1": ["awkward potion_1", "raw fish_5"] + "swim potion_1": [ + "awkward potion_1", + "raw fish_5" + ] } } }, @@ -3544,7 +3813,11 @@ ], "rewards": { "recipes": { - "haste potion_1": ["awkward potion_1", "Wood_5", "Stone_5"] + "haste potion_1": [ + "awkward potion_1", + "Wood_5", + "Stone_5" + ] } } }, @@ -3583,7 +3856,10 @@ ], "rewards": { "recipes": { - "lava potion_1": ["awkward potion_1", "Lava Bucket_1"] + "lava potion_1": [ + "awkward potion_1", + "Lava Bucket_1" + ] } } }, @@ -3622,7 +3898,10 @@ ], "rewards": { "recipes": { - "energy potion_1": ["awkward potion_1", "gem_25"] + "energy potion_1": [ + "awkward potion_1", + "gem_25" + ] } } }, @@ -3661,7 +3940,10 @@ ], "rewards": { "recipes": { - "regen potion_1": ["awkward potion_1", "Gold Apple_1"] + "regen potion_1": [ + "awkward potion_1", + "Gold Apple_1" + ] } } }, @@ -3713,7 +3995,11 @@ ], "rewards": { "recipes": { - "Health potion_1": ["awkward potion_1", "GunPowder_2", "Leather Armor_1"] + "Health potion_1": [ + "awkward potion_1", + "GunPowder_2", + "Leather Armor_1" + ] } } }, @@ -3765,7 +4051,11 @@ ], "rewards": { "recipes": { - "Escape potion_1": ["awkward potion_1", "GunPowder_3", "Lapis_7"] + "Escape potion_1": [ + "awkward potion_1", + "GunPowder_3", + "Lapis_7" + ] } } }, @@ -3830,7 +4120,12 @@ ], "rewards": { "recipes": { - "Totem of Air_1": ["gold_10", "gem_10", "Lapis_5","Cloud Ore_5"] + "Totem of Air_1": [ + "gold_10", + "gem_10", + "Lapis_5", + "Cloud Ore_5" + ] } } } diff --git a/src/client/resources/tinylog.properties b/src/client/resources/tinylog.properties index 0db23bc41..f303f6b62 100644 --- a/src/client/resources/tinylog.properties +++ b/src/client/resources/tinylog.properties @@ -1,33 +1,27 @@ # suppress inspection "UnusedProperty" for whole file # If there is any modification in this file, # minicraft.util.TinylogLoggingProvider and/or minicraft.util.TinylogLoggingConfiguration might also need to be modified. - # Note: # "@" in writer.tag is not implemented as an extra parameter here. - -provider = minicraft.util.TinylogLoggingProvider -writingthread = true # This is always true. - +provider=minicraft.util.TinylogLoggingProvider +writingthread=true # This is always true. # Logging to console # All console writers are generated directly by minicraft.util.TinylogLoggingConfiguration. - # Log file -writer2 = file -writer2.level = trace -writer2.file = logs/log.txt -writer2.charset = UTF-8 -writer2.format = {date: HH:mm:ss.SSS} [{tag}] {level}: {message} - -writer2Full = file -writer2Full.level = trace -writer2Full.file = logs/log.txt -writer2Full.charset = UTF-8 -writer2Full.format = {date: yyyy-MM-dd HH:mm:ss.SSSSSSSSS} [{thread-id}/{thread}] [{tag}] {level}: {message} - +writer2=file +writer2.level=trace +writer2.file=logs/log.txt +writer2.charset=UTF-8 +writer2.format={date: HH:mm:ss.SSS} [{tag}] {level}: {message} +writer2Full=file +writer2Full.level=trace +writer2Full.file=logs/log.txt +writer2Full.charset=UTF-8 +writer2Full.format={date: yyyy-MM-dd HH:mm:ss.SSSSSSSSS} [{thread-id}/{thread}] [{tag}] {level}: {message} # Localization message file -writer3 = file -writer3.level = trace -writer3.file = logs/unlocalized.txt -writer3.charset = UTF-8 -writer3.format = [{file}#L{line}] [{class}#{method}]: {message-only} -writer3.tag = LOC +writer3=file +writer3.level=trace +writer3.file=logs/unlocalized.txt +writer3.charset=UTF-8 +writer3.format=[{file}#L{line}] [{class}#{method}]: {message-only} +writer3.tag=LOC