diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index e9b3e1b..bbadf77 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -1,43 +1,43 @@ -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. -# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time -# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle - -name: Gradle build - -on: - push: - branches: [ "master", "dev" ] - pull_request: - branches: [ "master", "dev" ] - -jobs: - build: - - runs-on: ubuntu-latest - permissions: - contents: read - - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 21 - uses: actions/setup-java@v4 - with: - java-version: '21' - distribution: 'temurin' - - # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. - # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md - - name: Setup Gradle - uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 - - - name: Build with Gradle Wrapper - run: ./gradlew build -PcommitHash=$(git rev-parse --short "$GITHUB_SHA") - - - name: Upload build artifacts - uses: actions/upload-artifact@v4 - with: - name: '${{ github.event.repository.name }}' - path: build/libs +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle + +name: Gradle build + +on: + push: + branches: [ "master", "dev" ] + pull_request: + branches: [ "master", "dev" ] + +jobs: + build: + + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + # Configure Gradle for optimal use in GitHub Actions, including caching of downloaded dependencies. + # See: https://github.com/gradle/actions/blob/main/setup-gradle/README.md + - name: Setup Gradle + uses: gradle/actions/setup-gradle@af1da67850ed9a4cedd57bfd976089dd991e2582 # v4.0.0 + + - name: Build with Gradle Wrapper + run: ./gradlew build -PcommitHash=$(git rev-parse --short "$GITHUB_SHA") + + - name: Upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: '${{ github.event.repository.name }}' + path: build/libs diff --git a/.gitignore b/.gitignore index c8fb68a..61bb64a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,101 +1,101 @@ -# Covers JetBrains IDEs: IntelliJ, GoLand, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider -# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 - -# User-specific stuff -.idea/**/workspace.xml -.idea/**/tasks.xml -.idea/**/usage.statistics.xml -.idea/**/dictionaries -.idea/**/shelf - -# AWS User-specific -.idea/**/aws.xml - -# Generated files -.idea/**/contentModel.xml - -# Sensitive or high-churn files -.idea/**/dataSources/ -.idea/**/dataSources.ids -.idea/**/dataSources.local.xml -.idea/**/sqlDataSources.xml -.idea/**/dynamic.xml -.idea/**/uiDesigner.xml -.idea/**/dbnavigator.xml - -# Gradle and Maven with auto-import -# When using Gradle or Maven with auto-import, you should exclude module files, -# since they will be recreated, and may cause churn. Uncomment if using -# auto-import. -# .idea/artifacts -# .idea/compiler.xml -# .idea/jarRepositories.xml -# .idea/modules.xml -# .idea/*.iml -# .idea/modules -# *.iml -# *.ipr - -# File-based project format -*.iws - -# IntelliJ -out/ - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties -fabric.properties - -/.idea/ - - -# Java -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* -replay_pid* - -# Gradle -.gradle -**/build/ -!**/src/**/build/ - -# Ignore Gradle GUI config -gradle-app.setting - -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar - -# Avoid ignore Gradle wrappper properties -!gradle-wrapper.properties - -# Cache of project -.gradletasknamecache - -# Eclipse Gradle plugin generated files -# Eclipse Core -.project -# JDT-specific (Eclipse Java Development Tools) +# Covers JetBrains IDEs: IntelliJ, GoLand, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# File-based project format +*.iws + +# IntelliJ +out/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +/.idea/ + + +# Java +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# Gradle +.gradle +**/build/ +!**/src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) .classpath \ No newline at end of file diff --git a/.run/build_snapshot.run.xml b/.run/[Snapshot] Build.run.xml similarity index 79% rename from .run/build_snapshot.run.xml rename to .run/[Snapshot] Build.run.xml index e2cdddf..afcdc2f 100644 --- a/.run/build_snapshot.run.xml +++ b/.run/[Snapshot] Build.run.xml @@ -3,6 +3,7 @@ @@ -22,8 +23,11 @@ true true + false false false + false + false - + \ No newline at end of file diff --git a/.run/build_release.run.xml b/.run/build_release.run.xml index 491d63f..1550db5 100644 --- a/.run/build_release.run.xml +++ b/.run/build_release.run.xml @@ -1,24 +1,24 @@ - - - - - - - true - true - false - false - - - + + + + + + + true + true + false + false + + + diff --git a/README.md b/README.md index 1f30075..b79d362 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,52 @@ -# JouTak Plugin Template (Java Edition) - -Заготовка для плагина на JouTak (ДжоуТек) (joutak.ru) - - -# Перед использованием - -1. Отредактируйте: - - `gradle.properties` — укажите **версию** и **название** плагина, а также **ссылку на репозиторий** с вашим плагином - - `src/main/java/ru/joutak/` — переименуйте **основной класс** под название вашего плагина - - `src/main/resources/plugin.yml` — укажите **правильный путь** до основного класса плагина и укажите себя как **автора** - - `gradle/libs.versions.toml` — измените **версии** **JDK**, **ядра** и **других библиотек** по необходимости - - Укажите **полный путь до тестового сервера** в переменной окружения системы `SERVER_PATH` - -> [!TIP] -> Указав путь до тестового сервера, можно собирать плагин с помощью конфигурации `[Snapshot] Build`, тогда jar-архив с вашим плагином сразу будет создаваться в нужной папке автоматически. - - -# Сборка плагина - -1. Открыть проект в **IntelliJ IDEA** -2. Нажать кнопку `Run` справа сверху для сборки: - - `[Snapshot]` создает архив с плагином в папке `plugins/` тестового сервера (путь до которого нужно указать в переменной окружения `SERVER_PATH`) - - `[Release]` создает архив с плагином в папке `build/` проекта - - -# Перед началом выполнения тестового задания -> [!NOTE] -> Данный параграф предназначен для тех, кто захотел попробовать себя в роли разработчка плагинов для Minecraft серверов в составе команды JouTak. - -Базовое описание, что нужно сделать: -1) Сделать собственный **fork** данного репозитория -2) Склонировать созданный репозиторий себе по **SSH** (`git clone`) -3) Открыть проект в любой удобной для вас **IDE** -> [!TIP] -> Рекомендуем использовать **IntelliJ IDEA**, так как в ней есть полноценная поддержка **Java** со всеми фишками и плюшками, но выбор за вами -4) Разобраться с расположением папочек и синтаксисом **Java**, затем прописать базовую логику, которая была описана в вашем задании в issues (Любая креативность поощряется) -5) Собрать плагин с помощью **Gradle** -> [!TIP] -> Конфиги уже заранее прописаны (один для тестовых целей, второй для полноценного релиза), вам самим ничего прописывать не надо. Для тестов лучше использовать `[Snapshot]` версию, чтобы каждый раз не перекидывать вручную плагин в папку сервера, главное не забудьте создать переменную окружения `SERVER_PATH`! -6) Запустить на своем компьютере локальный [**Purpur**](https://purpurmc.org) сервер -7) Подключиться на свой локальный сервер и проверить, что плагин работает исправно -8) Отправить **pull request** на **GitHub** и дождаться ответа -> [!TIP] -> Если долго никто не отвечает, то можно пингануть кого-нибудь, чтобы реквест отсмотрели и приняли :) - -Если плагин написан без базовых ошибок (синтаксических и т. п.), то на **GitHub**'е автоматически соберется такой же jar-архив, который будет так же работать на твоем локальном сервере. - -Поначалу всё можно писать в основном классе, но потом все вещи по типу команд, listener'ов и различные event'ы нужно выделить в отдельные классы и пакеты. - -> [!IMPORTANT] -> Главное, если есть какие-то вопросы - не стесняйся спрашивать! +# JouTak Plugin Template (Java Edition) + +Заготовка для плагина на JouTak (ДжоуТек) (joutak.ru) + + +# Перед использованием + +1. Отредактируйте: + - `gradle.properties` — укажите **версию** и **название** плагина, а также **ссылку на репозиторий** с вашим плагином + - `src/main/java/ru/joutak/` — переименуйте **основной класс** под название вашего плагина + - `src/main/resources/plugin.yml` — укажите **правильный путь** до основного класса плагина и укажите себя как **автора** + - `gradle/libs.versions.toml` — измените **версии** **JDK**, **ядра** и **других библиотек** по необходимости + - Укажите **полный путь до тестового сервера** в переменной окружения системы `SERVER_PATH` + +> [!TIP] +> Указав путь до тестового сервера, можно собирать плагин с помощью конфигурации `[Snapshot] Build`, тогда jar-архив с вашим плагином сразу будет создаваться в нужной папке автоматически. + + +# Сборка плагина + +1. Открыть проект в **IntelliJ IDEA** +2. Нажать кнопку `Run` справа сверху для сборки: + - `[Snapshot]` создает архив с плагином в папке `plugins/` тестового сервера (путь до которого нужно указать в переменной окружения `SERVER_PATH`) + - `[Release]` создает архив с плагином в папке `build/` проекта + + +# Перед началом выполнения тестового задания +> [!NOTE] +> Данный параграф предназначен для тех, кто захотел попробовать себя в роли разработчка плагинов для Minecraft серверов в составе команды JouTak. + +Базовое описание, что нужно сделать: +1) Сделать собственный **fork** данного репозитория +2) Склонировать созданный репозиторий себе по **SSH** (`git clone`) +3) Открыть проект в любой удобной для вас **IDE** +> [!TIP] +> Рекомендуем использовать **IntelliJ IDEA**, так как в ней есть полноценная поддержка **Java** со всеми фишками и плюшками, но выбор за вами +4) Разобраться с расположением папочек и синтаксисом **Java**, затем прописать базовую логику, которая была описана в вашем задании в issues (Любая креативность поощряется) +5) Собрать плагин с помощью **Gradle** +> [!TIP] +> Конфиги уже заранее прописаны (один для тестовых целей, второй для полноценного релиза), вам самим ничего прописывать не надо. Для тестов лучше использовать `[Snapshot]` версию, чтобы каждый раз не перекидывать вручную плагин в папку сервера, главное не забудьте создать переменную окружения `SERVER_PATH`! +6) Запустить на своем компьютере локальный [**Purpur**](https://purpurmc.org) сервер +7) Подключиться на свой локальный сервер и проверить, что плагин работает исправно +8) Отправить **pull request** на **GitHub** и дождаться ответа +> [!TIP] +> Если долго никто не отвечает, то можно пингануть кого-нибудь, чтобы реквест отсмотрели и приняли :) + +Если плагин написан без базовых ошибок (синтаксических и т. п.), то на **GitHub**'е автоматически соберется такой же jar-архив, который будет так же работать на твоем локальном сервере. + +Поначалу всё можно писать в основном классе, но потом все вещи по типу команд, listener'ов и различные event'ы нужно выделить в отдельные классы и пакеты. + +> [!IMPORTANT] +> Главное, если есть какие-то вопросы - не стесняйся спрашивать! diff --git a/build.gradle.kts b/build.gradle.kts index d18c647..498803d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,81 +1,81 @@ -val group: String by project -val version: String by project -val repo: String by project - -project.group = group -project.version = version - -plugins { - java -} - -repositories { - mavenCentral() - maven("https://repo.papermc.io/repository/maven-public/") { - name = "papermc-repo" - } - maven("https://oss.sonatype.org/content/groups/public/") { - name = "sonatype" - } -} - -dependencies { - compileOnly(libs.paper) - compileOnly(libs.lombok) - - testImplementation(libs.bundles.junit) -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(libs.versions.jdk.get()) - } -} - -tasks.test { - useJUnitPlatform() -} - -tasks.processResources { - val minecraftVersion = - libs.versions.paper - .get() - .substringBefore("-") - - val commitHash = project.findProperty("commitHash") as String? - - val website = - if (repo.isBlank()) { - "https://joutak.ru" - } else { - if (commitHash.isNullOrBlank()) repo else "$repo/tree/$commitHash" - } - - val props = - mapOf( - "NAME" to project.name, - "VERSION" to project.version, - "MINECRAFT_VERSION" to minecraftVersion, - "WEBSITE" to website, - "LOMBOK_VERSION" to libs.versions.lombok.get(), - ) - - inputs.properties(props) - filteringCharset = "UTF-8" - filesMatching("plugin.yml") { - expand(props) - } -} - -tasks.jar { - archiveFileName.set("${project.name}-${project.version}.jar") - - if (System.getenv("TEST_PLUGIN_BUILD") != null) { - val serverPath = System.getenv("SERVER_PATH") - if (serverPath != null) { - destinationDirectory.set(file("$serverPath\\plugins")) - } else { - logger.warn("SERVER_PATH property is not set!") - } - } -} +val group: String by project +val version: String by project +val repo: String by project + +project.group = group +project.version = version + +plugins { + java +} + +repositories { + mavenCentral() + maven("https://repo.papermc.io/repository/maven-public/") { + name = "papermc-repo" + } + maven("https://oss.sonatype.org/content/groups/public/") { + name = "sonatype" + } +} + +dependencies { + compileOnly(libs.paper) + compileOnly(libs.lombok) + + testImplementation(libs.bundles.junit) +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(libs.versions.jdk.get()) + } +} + +tasks.test { + useJUnitPlatform() +} + +tasks.processResources { + val minecraftVersion = + libs.versions.paper + .get() + .substringBefore("-") + + val commitHash = project.findProperty("commitHash") as String? + + val website = + if (repo.isBlank()) { + "https://joutak.ru" + } else { + if (commitHash.isNullOrBlank()) repo else "$repo/tree/$commitHash" + } + + val props = + mapOf( + "NAME" to project.name, + "VERSION" to project.version, + "MINECRAFT_VERSION" to minecraftVersion, + "WEBSITE" to website, + "LOMBOK_VERSION" to libs.versions.lombok.get(), + ) + + inputs.properties(props) + filteringCharset = "UTF-8" + filesMatching("plugin.yml") { + expand(props) + } +} + +tasks.jar { + archiveFileName.set("${project.name}-${project.version}.jar") + + if (System.getenv("TEST_PLUGIN_BUILD") != null) { + val serverPath = System.getenv("SERVER_PATH") + if (serverPath != null) { + destinationDirectory.set(file("$serverPath\\plugins")) + } else { + logger.warn("SERVER_PATH property is not set!") + } + } +} diff --git a/gradle.properties b/gradle.properties index cf51ce0..f39b923 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,8 @@ -# Plugin properties -repo=https://github.com/JouTak/TemplatePlugin-Java -group=ru.joutak -name=Template-Java -version=1.0.0 - -# Gradle properties +# Plugin properties +repo=https://github.com/AstronOmewa/someCoolNameForRepository +group=ru.joutak +name=yetAnotherWave +version=0.1.5 + +# Gradle properties org.gradle.parallel=true \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7b40284..2d78dbf 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,18 +1,18 @@ -[versions] -jdk = "21" -paper = "1.21.5-R0.1-SNAPSHOT" -lombok = "1.18.32" -junit = "5.13.4" - -[libraries] -paper = { module = "io.papermc.paper:paper-api", version.ref = "paper" } -lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } -junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit"} -junit-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit" } -junit-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit" } -junit-launcher = { module = "org.junit.platform:junit-platform-launcher" } - -[plugins] - -[bundles] +[versions] +jdk = "21" +paper = "1.21.5-R0.1-SNAPSHOT" +lombok = "1.18.32" +junit = "5.13.4" + +[libraries] +paper = { module = "io.papermc.paper:paper-api", version.ref = "paper" } +lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit"} +junit-api = { module = "org.junit.jupiter:junit-jupiter-api", version.ref = "junit" } +junit-engine = { module = "org.junit.jupiter:junit-jupiter-engine", version.ref = "junit" } +junit-launcher = { module = "org.junit.platform:junit-platform-launcher" } + +[plugins] + +[bundles] junit = [ "junit-jupiter", "junit-api", "junit-engine", "junit-launcher" ] \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 2a84e18..92d385b 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index ef07e01..a4df73e 100755 --- a/gradlew +++ b/gradlew @@ -1,4 +1,4 @@ -#!/bin/sh +# !/bin/sh # # Copyright © 2015 the original authors. diff --git a/gradlew.bat b/gradlew.bat index db3a6ac..5eed7ee 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,94 +1,94 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH= - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts index b610ec2..8890e43 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,3 +1,3 @@ -val name: String by settings - +val name: String by settings + rootProject.name = name \ No newline at end of file diff --git a/src/main/java/ru/joutak/template/CreakingSpawnListener.java b/src/main/java/ru/joutak/template/CreakingSpawnListener.java new file mode 100644 index 0000000..450cd39 --- /dev/null +++ b/src/main/java/ru/joutak/template/CreakingSpawnListener.java @@ -0,0 +1,48 @@ +package ru.joutak.template; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.*; +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.block.*; +import org.bukkit.event.*; +import org.bukkit.entity.*; +import org.bukkit.event.Listener; + +public class CreakingSpawnListener implements Listener{ + @EventHandler + public void onSpawn(CreatureSpawnEvent event){ + Wave activeWave = Fight.lastWave(); + if (event.getEntityType() != EntityType.CREAKING) return; + + if (activeWave == null) return; + + Location loc = event.getLocation(); + World world = loc.getWorld(); + + + int radius = 20; + boolean hasHeart = false; + + for (int x = -radius; x <= radius; x++) { + for (int y = -radius; y <= radius; y++) { + for (int z = -radius; z <= radius; z++) { + Block b = world.getBlockAt( + loc.getBlockX() + x, + loc.getBlockY() + y, + loc.getBlockZ() + z + ); + if (b.getType() == Material.CREAKING_HEART) { + hasHeart = true; + break; + } + } + } + } + + if (!hasHeart) return; + + activeWave.addMob(event.getEntity()); + } +} diff --git a/src/main/java/ru/joutak/template/EmptyPlugin.java b/src/main/java/ru/joutak/template/EmptyPlugin.java deleted file mode 100644 index d93430e..0000000 --- a/src/main/java/ru/joutak/template/EmptyPlugin.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.joutak.template; - -import lombok.Getter; -import org.bukkit.plugin.java.JavaPlugin; - -public final class EmptyPlugin extends JavaPlugin { - @Getter - private static EmptyPlugin instance; - - @Override - public void onEnable() { - instance = this; - - getLogger().info( - String.format("Плагин %s версии %s включен!", getPluginMeta().getName(), getPluginMeta().getVersion()) - ); - } - - @Override - public void onDisable() { - - } -} diff --git a/src/main/java/ru/joutak/template/Fight.java b/src/main/java/ru/joutak/template/Fight.java new file mode 100644 index 0000000..80d40db --- /dev/null +++ b/src/main/java/ru/joutak/template/Fight.java @@ -0,0 +1,69 @@ +package ru.joutak.template; +import com.google.j2objc.annotations.Property; +import org.bukkit.entity.*; + +import java.util.*; + +public class Fight{ + private ArrayList waves = new ArrayList<>(); + private Wave currentWave; + + public void addWave(Wave w){ + waves.add(w); + } + + public void rmLast(Wave w){ + if(!waves.isEmpty()) waves.remove(waves.getLast()); + } + + public Wave lastWave(){ + if(!(waves.isEmpty())) return waves.getFirst(); + Wave o = null; + return o; + } + + public void removeMobFromCurrentWave(Entity e){ + if(!(waves.isEmpty())) { + currentWave = waves.getFirst(); + currentWave.removeMob(e); + } + } + + public boolean isCurrentWaveMob(Entity e){ + if(!waves.isEmpty()) { + currentWave = waves.getFirst(); + return currentWave.isWaveMob(e); + } + return false; + } + + public boolean isCurrentWaveFinished() { + if (!waves.isEmpty()) { + currentWave = waves.getFirst(); + return currentWave.isWaveFinished(); + } + return false; + } + + public void endWave(){ + if(!waves.isEmpty()) { + currentWave = waves.getFirst(); + currentWave.bossBar.removePlayer(currentWave.linkedTo); + currentWave.endCallback.perform(); + waves.remove(waves.getFirst()); + currentWave = waves.getFirst(); + currentWave.perform(); + } + } + + public boolean isFightActive(){ + return ((!waves.isEmpty())&&(waves.getFirst().isWaveActive())); + } + + public void clear(){ + for(Wave w: waves){ + w.clear(w.linkedTo.getWorld()); + waves.remove(w); + } + } +} diff --git a/src/main/java/ru/joutak/template/MobDeathListener.java b/src/main/java/ru/joutak/template/MobDeathListener.java new file mode 100644 index 0000000..b20c79e --- /dev/null +++ b/src/main/java/ru/joutak/template/MobDeathListener.java @@ -0,0 +1,20 @@ +package ru.joutak.template; + +import org.bukkit.event.*; +import org.bukkit.entity.*; +import org.bukkit.event.entity.EntityDeathEvent; + +public class MobDeathListener implements Listener{ + + @EventHandler + public void onMobDeath(EntityDeathEvent evt){ + Entity e = (Entity) evt.getEntity(); + + if(Fight.isCurrentWaveMob(e)){ + Fight.removeMobFromCurrentWave(e); + } + if(Fight.isCurrentWaveFinished()){ + Fight.endWave(); + } + } +} diff --git a/src/main/java/ru/joutak/template/PlayerDeathListener.java b/src/main/java/ru/joutak/template/PlayerDeathListener.java new file mode 100644 index 0000000..805c409 --- /dev/null +++ b/src/main/java/ru/joutak/template/PlayerDeathListener.java @@ -0,0 +1,19 @@ +package ru.joutak.template; + +import org.bukkit.event.*; +import org.bukkit.entity.*; +import org.bukkit.event.entity.PlayerDeathEvent; + +public class PlayerDeathListener implements Listener{ + + @EventHandler + public void onPlayerDeath(PlayerDeathEvent evt){ + Player player = evt.getPlayer(); + + if(!Fight.isFightActive()){ + Fight.lastWave().bossBar.removePlayer(player); + Fight.lastWave().clear(player.getWorld()); + Fight.clear(); + } + } +} diff --git a/src/main/java/ru/joutak/template/SomeCoolPlugin.java b/src/main/java/ru/joutak/template/SomeCoolPlugin.java new file mode 100644 index 0000000..948e691 --- /dev/null +++ b/src/main/java/ru/joutak/template/SomeCoolPlugin.java @@ -0,0 +1,697 @@ +package ru.joutak.template; + +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; + +import io.papermc.paper.datacomponent.item.Weapon; +import org.bukkit.*; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarStyle; +import org.bukkit.inventory.ItemStack; +import org.bukkit.plugin.java.JavaPlugin; + +import lombok.Getter; + +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.block.*; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +// import Wave; + + +public final class SomeCoolPlugin extends JavaPlugin { + @Getter + private static SomeCoolPlugin instance; + + public static SomeCoolPlugin getInstance() { + return instance; + } + @Override + public void onEnable() { + instance = this; + + getLogger().info( + String.format("Плагин %s версии %s включен!", getPluginMeta().getName(), getPluginMeta().getVersion()) + ); + getServer().getPluginManager().registerEvents( + new MobDeathListener(), + this + ); + getServer().getPluginManager().registerEvents( + new CreakingSpawnListener(), + this + ); + getServer().getPluginManager().registerEvents( + new PlayerDeathListener(), + this + ); + } + + @Override + public void onDisable() { + + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ + if(command.getName().equalsIgnoreCase("coolplugin")){ + if(args.length < 3) { + sender.sendMessage("Использование: /coolplugin start "); + return false; + } + + int radius; + try { + radius = Integer.parseInt(args[1]); + } catch(NumberFormatException e) { + sender.sendMessage("Радиус должен быть числом!"); + return false; + } + if(sender instanceof Player player){ + String toggler = args[0]; + switch (toggler.toLowerCase()) { + case "start" -> this.start(player, command, label, args); + case "stop" -> this.stop(player, command, label, args); + case "help" -> this.help(player, command, label, args); + default -> player.sendMessage("Неверный аргумент! Используйте /coolplugin ."); + } + } + return true; + } + return false; + } + + public void start(Player player, Command command, String label, String[] args){ + int radius = Integer.parseInt(args[1]); + String level = args[2]; + World world = player.getWorld(); + Location center = player.getLocation(); + final int heightBoundary = 10; + final int attempts = 10; + switch(level){ + case "1": { + // 2 волны, 1 волна -- зомби (80%) + пауки (20%), 2 волна -- пауки(33%) + скелеты (33%) + зомби (34%), награда за волну - случайный эффект + // из ['регенерация','огнестойкость','поглощение'] + // + ['instantHealth','HealthBoost'] и случайное оружие + + PotionEffect[] potionEffects = { + new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 20 * 30, 2), + new PotionEffect(PotionEffectType.ABSORPTION, 20*30, 2), + new PotionEffect(PotionEffectType.REGENERATION, 20*10, 2)}; + PotionEffect[] modifiers = {new PotionEffect(PotionEffectType.INSTANT_HEALTH, 40,1), new PotionEffect(PotionEffectType.HEALTH_BOOST, 30, 20*20)}; + Material[] weapons = { + Material.CROSSBOW, + Material.BOW, + Material.STONE_AXE, + Material.IRON_SWORD, + Material.IRON_AXE, + Material.STONE_SWORD + }; + Material weapon = weapons[ThreadLocalRandom.current().nextInt(weapons.length)]; + class FirstWaveCallback implements WaveEnding{ + public void perform(){ + player.addPotionEffect(potionEffects[ThreadLocalRandom.current().nextInt(potionEffects.length)]); + player.addPotionEffect(modifiers[ThreadLocalRandom.current().nextInt(modifiers.length)]); + if(weapon == Material.CROSSBOW|| weapon == Material.BOW){ + player.getInventory().addItem(new ItemStack(Material.ARROW, 8 + ThreadLocalRandom.current().nextInt(24))); + } + player.getInventory().addItem(new ItemStack(weapon, 1)); + } + } + + class SecondWaveCallback implements WaveEnding{ + public void perform(){ + player.giveExpLevels(5); + player.sendMessage("Yet Another Way Completed!"); + player.getWorld().playSound(player.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 1.0f, 1.0f); + } + } + + final int waveMobCount = 10; + Fight fight = new Fight(); + + Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, BarStyle.SEGMENTED_10){ + @Override + public void perform() { + begin(); + long delay = 0L; + for(int i = 0; i < waveMobCount; i++){ + Location loc = findSpawnBlock(center, radius, heightBoundary); + double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); + if(prob<0.8){ + spawnMob(loc, EntityType.ZOMBIE, world, Sound.ENTITY_WITHER_SPAWN, this, delay); + }else{ + spawnMob(loc, EntityType.SPIDER, world, Sound.ENTITY_BLAZE_AMBIENT, this, delay); + } + delay += 5L+ThreadLocalRandom.current().nextInt(1,10); + } + } + }; + fight.addWave(first); + + final int secondWaveCount = waveMobCount*2; + Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, BarStyle.SEGMENTED_20, BarColor.BLUE){ + @Override + public void perform() { + begin(); + long delay = 7*20L; + for (int i = 0; i < secondWaveCount; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); + if (prob < 0.33) { + spawnMob(loc, EntityType.ZOMBIE, world, Sound.ENTITY_WITHER_SPAWN, this, delay); + } else if (prob < 0.66) { + spawnMob(loc, EntityType.SPIDER, world, Sound.ENTITY_BLAZE_AMBIENT, this, delay); + } else { + spawnMob(loc, EntityType.SKELETON, world, Sound.ENTITY_BLAZE_AMBIENT, this, delay); + } + delay += 5L + ThreadLocalRandom.current().nextInt(1, 10); + } + } + }; + + fight.addWave(second); + + first.perform(); + + } + break; + case "2":{ + // 3 волны, 1 волна -- скелеты (80%) + бризы (20%), 2 волна -- блейзы (50%) + скрипуны (50%), награда за волну - случайный эффект + // из ['регенерация','огнестойкость','поглощение'] + // + ['instantHealth','HealthBoost'] и случайное оружие + + PotionEffect[] potionEffects = { + new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 20 * 60, 2), + new PotionEffect(PotionEffectType.ABSORPTION, 20*60, 2), + new PotionEffect(PotionEffectType.REGENERATION, 20*20, 2)}; + PotionEffect[] modifiers = {new PotionEffect(PotionEffectType.INSTANT_HEALTH, 40,1), new PotionEffect(PotionEffectType.HEALTH_BOOST, 60, 20*20)}; + Material[] weapons = { + Material.CROSSBOW, + Material.BOW, + Material.IRON_SWORD, + Material.IRON_AXE, + Material.DIAMOND_SWORD, + Material.DIAMOND_AXE + }; + Material weapon = weapons[ThreadLocalRandom.current().nextInt(weapons.length)]; + class FirstWaveCallback implements WaveEnding{ + public void perform(){ + player.addPotionEffect(potionEffects[ThreadLocalRandom.current().nextInt(potionEffects.length)]); + player.addPotionEffect(modifiers[ThreadLocalRandom.current().nextInt(modifiers.length)]); + if(weapon == Material.CROSSBOW|| weapon == Material.BOW){ + player.getInventory().addItem(new ItemStack(Material.ARROW, 16 + ThreadLocalRandom.current().nextInt(48))); + } + player.getInventory().addItem(new ItemStack(weapon, 1)); + } + } + + class SecondWaveCallback implements WaveEnding{ + public void perform(){ + player.addPotionEffect(potionEffects[ThreadLocalRandom.current().nextInt(potionEffects.length)]); + player.addPotionEffect(modifiers[ThreadLocalRandom.current().nextInt(modifiers.length)]); + if(weapon == Material.CROSSBOW|| weapon == Material.BOW){ + player.getInventory().addItem(new ItemStack(Material.ARROW, 16 + ThreadLocalRandom.current().nextInt(48))); + } + player.getInventory().addItem(new ItemStack(weapon, 1)); + player.getInventory().addItem(new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 4+ThreadLocalRandom.current().nextInt(4))); + + } + } + class ThirdWaweCallback implements WaveEnding{ + public void perform(){ + player.giveExpLevels(15); + player.sendMessage("Yet Another Way Completed!"); + player.getWorld().playSound(player.getLocation(), Sound.UI_TOAST_CHALLENGE_COMPLETE, 1.0f, 1.0f); + } + } + + final int waveMobCount = 2*radius; + Fight fight = new Fight(); + + Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, BarStyle.SEGMENTED_10){ + @Override + public void perform() { + begin(); + long delay = 0L; + for(int i = 0; i < waveMobCount; i++){ + Location loc = findSpawnBlock(center, radius, heightBoundary); + double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); + if(prob<0.8){ + spawnMob(loc, EntityType.SKELETON, world, Sound.ENTITY_ARROW_SHOOT, this, delay); + }else{ + spawnMob(loc, EntityType.BREEZE, world, Sound.ENTITY_BREEZE_CHARGE, this, delay); + } + delay += 5L+ThreadLocalRandom.current().nextInt(1,10); + } + } + }; + fight.addWave(first); + + final int secondWaveCount = (int) (waveMobCount*1.2); + Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, BarStyle.SEGMENTED_12, BarColor.BLUE){ + @Override + public void perform() { + begin(); + long delay = 10*20L; + world.setTime(13000); + for (int i = 0; i < secondWaveCount; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); + if (prob < 0.5) { + spawnMob(loc, EntityType.BLAZE, world, Sound.ENTITY_BLAZE_HURT, this, delay); + } else{ + spawnRandomCreakingColumn(player, 1, (int)(radius*2.5)); + } + delay += 5L + ThreadLocalRandom.current().nextInt(1, 10); + } + } + }; + + Wave third = new Wave(player, new ThirdWaweCallback(), secondWaveCount, BarStyle.SEGMENTED_10, BarColor.YELLOW){ + @Override + public void perform(){ + begin(); + long delay = 15*20L; + Location loc = findSpawnBlock(center, radius, heightBoundary); + for (int i = 0; i < secondWaveCount; i++) { + spawnMob(loc, EntityType.PHANTOM, world, Sound.ENTITY_WITHER_SPAWN, this, delay); + } + } + }; + + fight.addWave(second); + fight.addWave(third); + + first.perform(); + } + break; + case "3": { + + final int wave1Count = 12 + radius; + final int wave2Count = 16 + radius; + final int wave3Count = 8 + radius / 2; + final int wave4Count = 18 + radius; + final int wave5Support = 4 + radius / 2; + + Fight fight = new Fight(); + + // + class FirstWaveCallback implements WaveEnding { + @Override + public void perform() { + + ThreadLocalRandom r = ThreadLocalRandom.current(); + double roll = r.nextDouble(); + + if (roll < 0.4) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.REGENERATION, + 20 * 30, + 1 + )); + } else if (roll < 0.7) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.RESISTANCE, + 20 * 35, + 1 + )); + } else if (roll < 0.9) { + player.getInventory().addItem( + new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 1) + ); + } else { + player.getInventory().addItem( + new ItemStack(Material.NETHERITE_SCRAP, 1) + ); + } + } + } + + Wave first = new Wave(player, new FirstWaveCallback(), wave1Count, BarStyle.SEGMENTED_20, BarColor.GREEN) { + @Override + public void perform() { + begin(); + long delay = 0L; + + for (int i = 0; i < wave1Count; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + + if (ThreadLocalRandom.current().nextDouble() < 0.7) { + spawnMob(loc, EntityType.ZOMBIE, + world, Sound.ENTITY_ZOMBIE_AMBIENT, this, delay); + } else { + spawnMob(loc, EntityType.CAVE_SPIDER, + world, Sound.ENTITY_SPIDER_AMBIENT, this, delay); + } + + delay += 5L; + } + } + }; + fight.addWave(first); + + // + class SecondWaveCallback implements WaveEnding { + @Override + public void perform() { + + ThreadLocalRandom r = ThreadLocalRandom.current(); + double roll = r.nextDouble(); + + if (roll < 0.35) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.FIRE_RESISTANCE, + 20 * 60, + 2 + )); + } else if (roll < 0.7) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.STRENGTH, + 20 * 30, + 1 + )); + } else if (roll < 0.9) { + player.getInventory().addItem( + new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 2) + ); + } else { + player.getInventory().addItem( + new ItemStack(Material.TOTEM_OF_UNDYING, 1) + ); + } + } + } + + Wave second = new Wave(player, new SecondWaveCallback(), wave2Count, BarStyle.SEGMENTED_10, BarColor.RED) { + @Override + public void perform() { + begin(); + long delay = 5 * 20L; + + for (int i = 0; i < wave2Count; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + + spawnMob(loc, EntityType.BLAZE, + world, Sound.ENTITY_BLAZE_AMBIENT, this, delay); + + if (ThreadLocalRandom.current().nextDouble() < 0.15) { + spawnMob(loc, EntityType.GHAST, + world, Sound.ENTITY_GHAST_SCREAM, this, delay + 5L); + } + + delay += 7L; + } + } + }; + fight.addWave(second); + + // + class ThirdWaveCallback implements WaveEnding { + @Override + public void perform() { + + ThreadLocalRandom r = ThreadLocalRandom.current(); + double roll = r.nextDouble(); + + if (roll < 0.4) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.RESISTANCE, + 20 * 45, + 1 + )); + } else if (roll < 0.7) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.REGENERATION, + 20 * 35, + 2 + )); + } else if (roll < 0.9) { + player.getInventory().addItem( + new ItemStack(Material.DIAMOND_AXE, 1) + ); + } else { + player.getInventory().addItem( + new ItemStack(Material.TOTEM_OF_UNDYING, 1) + ); + } + } + } + + Wave third = new Wave(player, new ThirdWaveCallback(), wave3Count, BarStyle.SEGMENTED_20, BarColor.YELLOW) { + @Override + public void perform() { + begin(); + long delay = 10 * 20L; + + for (int i = 0; i < wave3Count; i++) { + + spawnRandomCreakingColumn(player, 1, radius); + + if (ThreadLocalRandom.current().nextDouble() < 0.1) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + spawnMob(loc, EntityType.PHANTOM, + world, Sound.ENTITY_PHANTOM_AMBIENT, this, delay); + } + + delay += 20L; + } + } + }; + fight.addWave(third); + + // + class FourthWaveCallback implements WaveEnding { + @Override + public void perform() { + + ThreadLocalRandom r = ThreadLocalRandom.current(); + double roll = r.nextDouble(); + + if (roll < 0.3) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.REGENERATION, + 20 * 40, + 2 + )); + } else if (roll < 0.6) { + player.addPotionEffect(new PotionEffect( + PotionEffectType.STRENGTH, + 20 * 35, + 2 + )); + } else if (roll < 0.85) { + player.getInventory().addItem( + new ItemStack(Material.ENCHANTED_GOLDEN_APPLE, 2) + ); + } else { + player.getInventory().addItem( + new ItemStack(Material.TOTEM_OF_UNDYING, 1) + ); + } + } + } + + Wave fourth = new Wave(player, new FourthWaveCallback(), wave4Count, BarStyle.SEGMENTED_20, BarColor.PURPLE) { + @Override + public void perform() { + begin(); + long delay = 15 * 20L; + + for (int i = 0; i < wave4Count; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + + if (ThreadLocalRandom.current().nextDouble() < 0.6) { + spawnMob(loc, EntityType.PIGLIN_BRUTE, + world, Sound.ENTITY_PIGLIN_BRUTE_ANGRY, this, delay); + } else { + spawnMob(loc, EntityType.WITHER_SKELETON, + world, Sound.ENTITY_WITHER_SPAWN, this, delay); + } + + delay += 8L; + } + } + }; + fight.addWave(fourth); + + // + class FifthWaveCallback implements WaveEnding { + @Override + public void perform() { + player.giveExpLevels(30); + player.getWorld().playSound( + player.getLocation(), + Sound.UI_TOAST_CHALLENGE_COMPLETE, + 1.0f, + 1.0f + ); + } + } + + Wave fifth = new Wave(player, new FifthWaveCallback(), 1, BarStyle.SEGMENTED_20, BarColor.BLUE) { + @Override + public void perform() { + begin(); + long delay = 20 * 20L; + + Location bossLoc = findSpawnBlock(center, radius, heightBoundary); + spawnMob(bossLoc, EntityType.WARDEN, + world, Sound.ENTITY_WARDEN_EMERGE, this, delay); + + for (int i = 0; i < wave5Support; i++) { + Location loc = findSpawnBlock(center, radius, heightBoundary); + spawnMob(loc, EntityType.PHANTOM, + world, Sound.ENTITY_PHANTOM_AMBIENT, this, delay + i * 15L); + } + } + }; + fight.addWave(fifth); + first.perform(); + + } + break; + + default: player.sendMessage("Такого уровня сложности нет:( Есть только 1-3 уровни."); + } + + + + } + + public void stop(Player player, Command command, String label, String[] args){ + Fight.clear(); + player.sendMessage("Yet Another Wave Cancelled."); + } + + public void help(Player player, Command command, String label, String[] args){ + + } + + private Location findSpawnBlock( + Location center, + int radius, + int heightBoundary + ){ + Location loc = null; + World world = center.getWorld(); + int dy = 0; + while(loc == null){ + int x = center.getBlockX()+ThreadLocalRandom.current().nextInt(-radius,radius + 1); + int z = center.getBlockZ()+ThreadLocalRandom.current().nextInt(-radius,radius + 1); + int y = center.getBlockY()+Math.clamp( + ThreadLocalRandom.current().nextInt(-radius,radius + 1), + -heightBoundary, + heightBoundary) + +dy; + + Block ground = world.getBlockAt(x,y,z); + Block feet = world.getBlockAt(x,y+1,z); + Block head = world.getBlockAt(x,y+2,z); + +// if(!ground.getType().isSolid()){ dy -=1; continue;} + if(!head.isPassable()){dy+=2;continue;} + if(!feet.isPassable()){dy+=1;continue;} + + loc = new Location(world, x, y+1+0.7, z); + } + return loc; + } + + public void spawnMob(Location loc, EntityType e, World world, Sound s, Wave w, long spawnDelay){ + SomeCoolPlugin.getInstance().getServer().getScheduler().runTaskLater(SomeCoolPlugin.getInstance(),new Runnable(){ + public void run(){ + Entity ent = world.spawnEntity(loc, e); + world.spawnParticle( + Particle.FLAME, + loc.getX(), + loc.getY() + 1, + loc.getZ(), + 30, + 0.3, 0.5, 0.3, + 0.1 + ); + world.playSound(loc, s, 1.0f, ThreadLocalRandom.current().nextFloat(0.5f,1.0f)); + w.addMob(ent); + } + }, spawnDelay); + } + + public void spawnRandomCreakingColumn(Player p, int amount, int radius) { + World world = p.getWorld(); + world.playSound( + p.getLocation(), + Sound.ENTITY_WARDEN_HEARTBEAT, + 1.0f, + 1.0f + ); + for (int i = 0; i < amount; i++) { + + Location base = findSpawnBlock(p.getLocation(), radius, 10); + if (base == null) continue; + + + Location ground = base.clone(); + while (ground.getY() > world.getMinHeight() + && !ground.getBlock().getType().isSolid()) { + ground.subtract(0, 1, 0); + } + + if (!ground.getBlock().getType().isSolid()) continue; + + int height = ThreadLocalRandom.current().nextInt(1, 7); + long delay = i * 20L; + + for (int y = 1; y <= height; y++) { + Location place = ground.clone().add(0, y, 0); + long blockDelay = delay + y * 3L; + + Bukkit.getScheduler().runTaskLater( + SomeCoolPlugin.getInstance(), + () -> { + place.getBlock().setType(Material.PALE_OAK_LOG); + world.playSound( + place, + Sound.BLOCK_WOOD_PLACE, + 1.0f, + ThreadLocalRandom.current().nextFloat(0.6f, 1.0f) + ); + }, + blockDelay + ); + } + Location heart = ground.clone().add(0, height + 1, 0); + Location hat = ground.clone().add(0, height + 2, 0); + Bukkit.getScheduler().runTaskLater( + SomeCoolPlugin.getInstance(), + () -> { + heart.getBlock().setType(Material.CREAKING_HEART); + world.playSound( + heart, + Sound.BLOCK_CREAKING_HEART_PLACE, + 1.0f, + 1.0f + ); + + }, + delay + (height + 1) * 3L + ); + Bukkit.getScheduler().runTaskLater( + SomeCoolPlugin.getInstance(), + () -> { + hat.getBlock().setType(Material.PALE_OAK_LOG); + world.playSound( + hat, + Sound.BLOCK_WOOD_PLACE, + 1.0f, + 1.0f + ); + }, + delay + (height + 2) * 3L + ); + } + } + +} diff --git a/src/main/java/ru/joutak/template/Wave.java b/src/main/java/ru/joutak/template/Wave.java new file mode 100644 index 0000000..63f86b2 --- /dev/null +++ b/src/main/java/ru/joutak/template/Wave.java @@ -0,0 +1,79 @@ +package ru.joutak.template; +import org.bukkit.Sound; +import org.bukkit.entity.*; + +import org.bukkit.Bukkit; +import org.bukkit.World; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BossBar; +import org.bukkit.boss.BarStyle; + +public class Wave{ + protected final Set aliveMobs = new HashSet<>(); + protected int mobCap; + protected Player linkedTo; + protected WaveEnding endCallback; + protected BossBar bossBar; + + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, BarStyle seg){ + this.linkedTo = linkedTo; + this.endCallback = endCallback; + this.mobCap = mobCap; + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, seg); + } + + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, BarStyle seg, BarColor barColor){ + this.linkedTo = linkedTo; + this.endCallback = endCallback; + this.mobCap = mobCap; + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), barColor, seg); + } + + public void addMob(Entity e){ + aliveMobs.add(e.getUniqueId()); + this.bossBar.setProgress(aliveMobs.size() / (float) this.mobCap); + } + + public void removeMob(Entity e){ + aliveMobs.remove(e.getUniqueId()); + this.bossBar.setProgress(aliveMobs.size() / (float) this.mobCap); + } + + public int getAliveNumber(Entity e){ + return aliveMobs.size(); + } + + public boolean isWaveFinished(){ + return aliveMobs.isEmpty(); + } + + public boolean isWaveActive(){ + return !aliveMobs.isEmpty(); + } + + public boolean isWaveMob(Entity e){ + return aliveMobs.contains(e.getUniqueId()); + } + + public void perform(){} + + public void clear(World world){ + for(UUID uuid: aliveMobs){ + Entity e = world.getEntity(uuid); + if (e != null && !e.isDead()) { + world.playSound(e.getLocation(), Sound.BLOCK_AMETHYST_BLOCK_BREAK,1.0f, ThreadLocalRandom.current().nextFloat(0.0f,1.0f)); + e.remove(); + } + } + this.bossBar.removePlayer(linkedTo); + } + + public void begin(){ + this.bossBar.addPlayer(linkedTo); + } + +} diff --git a/src/main/java/ru/joutak/template/WaveEnding.java b/src/main/java/ru/joutak/template/WaveEnding.java new file mode 100644 index 0000000..dcde4ec --- /dev/null +++ b/src/main/java/ru/joutak/template/WaveEnding.java @@ -0,0 +1,5 @@ +package ru.joutak.template; + +public interface WaveEnding { + public void perform(); +} diff --git a/src/main/java/ru/joutak/template/commands/Command.java b/src/main/java/ru/joutak/template/commands/Command.java new file mode 100644 index 0000000..1723ae8 --- /dev/null +++ b/src/main/java/ru/joutak/template/commands/Command.java @@ -0,0 +1,38 @@ +package ru.joutak.template.commands; + +/** + * Базовый интерфейс для всех команд приложения. + *

+ * Определяет контракт, который должна реализовать каждая команда. + * Все команды поддерживают выполнение, вывод описания и указание + * количества требуемых аргументов. + *

+ */ +public interface Command { + /** + * Выполняет команду. + *

+ * Метод содержит основную логику работы команды. + * Реализация зависит от конкретной команды. + *

+ */ + public void execute(); + + /** + * Возвращает описание команды в консоль. + *

+ * Описание включает синтаксис вызова команды + * и краткое пояснение её назначения. + *

+ * + * @return description + */ + public String describe(); + + /** + * Возвращает количество аргументов, требуемых команде. + * + * @return количество аргументов командной строки + */ + public int numberArgsRequired(); +} diff --git a/src/main/java/ru/joutak/template/commands/CommandInvoker.java b/src/main/java/ru/joutak/template/commands/CommandInvoker.java new file mode 100644 index 0000000..2c40a41 --- /dev/null +++ b/src/main/java/ru/joutak/template/commands/CommandInvoker.java @@ -0,0 +1,119 @@ +package ru.joutak.template.commands; + +import org.bukkit.command.defaults.HelpCommand; +import org.bukkit.entity.Player; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Scanner; + +/** + * Класс для управления и выполнения команд приложения. + *

+ * Служит центральным диспетчером команд, предоставляя возможность + * их регистрации, вызова и выполнения. Поддерживает интерактивный режим + * работы с консолью и выполнение команд из скриптов. + *

+ *

+ * При запуске автоматически регистрирует все доступные команды + * и предоставляет интерактивный интерфейс для их вызова. + *

+ */ +public class CommandInvoker { + /** Сканер для чтения пользовательского ввода из консоли */ + private static Scanner sc = new Scanner(System.in); + private static HashMap commands = new HashMap(); + + /** + * Создаёт новый invoking и регистрирует все доступные команды. + *

+ * В конструкторе выполняется регистрация следующих команд: + *

    + *
  • help — вывод справки по командам
  • + *
  • clear — очистка коллекции
  • + *
  • info — информация о коллекции
  • + *
  • show — отображение всех элементов
  • + *
  • exit — завершение работы
  • + *
  • execute_file — выполнение команд из файла
  • + *
  • insert — добавление элемента
  • + *
  • update — обновление элемента по id
  • + *
  • print_unique_author — вывод уникальных авторов
  • + *
  • save — сохранение коллекции в файл
  • + *
  • remove_key — удаление элемента по ключу
  • + *
  • print_field_descending_difficulty — вывод сложности по убыванию
  • + *
  • group_counting_by_maximum_point — группировка по максимальному баллу
  • + *
  • remove_lower_key — удаление элементов с меньшими ключами
  • + *
  • replace_if_greater — замена при большем значении
  • + *
  • replace_if_lower — замена при меньшем значении
  • + *
+ */ + public CommandInvoker(Player p) { + commands.put("help", new HelpCommand()); + + } + + /** + * Запускает интерактивный режим работы приложения. + *

+ * Читает команды из стандартного ввода построчно и передаёт их + * на выполнение до завершения работы программы. + *

+ */ + public void run() { + while (sc.hasNext()) { + String line = sc.nextLine(); + runParticularCommand(line); + } + } + + /** + * Выполняет конкретную команду с заданными аргументами. + *

+ * Парсит строку команды, разделяя её на имя и аргументы. + * Проверяет существование команды и корректность количества аргументов. + * Для команд, реализующих {@link Modable}, устанавливает аргументы перед выполнением. + *

+ * + * @param line строка с именем команды и её аргументами + */ + private static void runParticularCommand(String line){ + String[] tokens = line.trim().replace("\n", "").split(" "); + + String commandName = tokens[0]; + ArrayList args = new ArrayList<>(); + if (tokens.length > 1) { + for (int i = 1; i < tokens.length; i++) { + args.add(tokens[i]); + } + } + + Command command = commands.get(commandName); + if (command == null) { + System.out.println("Неизвестная команда: " + commandName); + return; + } + + + + if (command instanceof Modable) { + if(args.size()==command.numberArgsRequired()) + ((Modable) command).setArguments(args); + else { + System.out.println("Слишком мало/много аргументов. Нужно " + command.numberArgsRequired() + " аргументов."); + return; + } + } + + if(tokens[0] == ""){ + return; + } + + command.execute(); + } +} diff --git a/src/main/java/ru/joutak/template/commands/HelpCommand.java b/src/main/java/ru/joutak/template/commands/HelpCommand.java new file mode 100644 index 0000000..57fdc65 --- /dev/null +++ b/src/main/java/ru/joutak/template/commands/HelpCommand.java @@ -0,0 +1,22 @@ +package ru.joutak.template.commands; + +import java.util.Hashtable; + +public class HelpCommand implements Command{ + @Override + public void execute() { + Hashtable commands = new Hashtable<>(); + commands.put("help", new HelpCommand()); + + } + + @Override + public String describe() { + return "/help - помощь (вывести все команды)"; + } + + @Override + public int numberArgsRequired() { + return 0; + } +} diff --git a/src/main/java/ru/joutak/template/commands/Modable.java b/src/main/java/ru/joutak/template/commands/Modable.java new file mode 100644 index 0000000..bd125ff --- /dev/null +++ b/src/main/java/ru/joutak/template/commands/Modable.java @@ -0,0 +1,20 @@ +package ru.joutak.template.commands; + +import java.util.ArrayList; + +/** + * Интерфейс для команд, требующих аргументы. + *

+ * Расширяет базовый интерфейс {@link Command}, добавляя возможность + * передачи аргументов командной строки. Команды, реализующие этот интерфейс, + * могут принимать дополнительные параметры при вызове. + *

+ */ +public interface Modable extends Command { + /** + * Устанавливает аргументы командной строки для выполнения команды. + * + * @param args список строковых аргументов, переданных команде + */ + public void setArguments(ArrayList args); +} diff --git a/src/main/java/ru/joutak/template/commands/StopCommand.java b/src/main/java/ru/joutak/template/commands/StopCommand.java new file mode 100644 index 0000000..a17b1c0 --- /dev/null +++ b/src/main/java/ru/joutak/template/commands/StopCommand.java @@ -0,0 +1,17 @@ +package ru.joutak.template.commands; + +public class StopCommand implements Command{ + @Override + public void execute() { + + } + @Override + public String describe(){ + + } + + @Override + public int numberArgsRequired() { + return 0; + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 4428874..d3c3917 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,12 +1,18 @@ -name: ${NAME} -version: ${VERSION} -api-version: ${MINECRAFT_VERSION} -main: ru.joutak.template.EmptyPlugin -description: 'A template plugin' -authors: ['EnderDissa', 'Stunnerer', 's4dnex'] -contributors: ['technosimp'] -website: ${WEBSITE} - -depend: [] -libraries: - - 'org.projectlombok:lombok:${LOMBOK_VERSION}' \ No newline at end of file +name: ${NAME} +version: ${VERSION} +api-version: ${MINECRAFT_VERSION} +main: ru.joutak.template.SomeCoolPlugin +description: 'A cool plugin' +authors: ['V7Zeee'] +contributors: [] +website: ${WEBSITE} + +depend: [] +libraries: + - 'org.projectlombok:lombok:${LOMBOK_VERSION}' + +commands: + coolplugin: + description: General command of the coolest plugin ever + usage: /coolplugin + diff --git a/src/test/java/ru/joutak/test/ExampleTest.java b/src/test/java/ru/joutak/test/ExampleTest.java index 3d24ac1..3a85916 100644 --- a/src/test/java/ru/joutak/test/ExampleTest.java +++ b/src/test/java/ru/joutak/test/ExampleTest.java @@ -1,36 +1,36 @@ -package ru.joutak.test; - -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -public class ExampleTest { - @BeforeAll - static void setup() { - System.out.println("@BeforeAll executed"); - } - - @BeforeEach - void setupThis() { - System.out.println("@BeforeEach executed"); - } - - @AfterEach - void tearThis() { - System.out.println("@AfterEach executed"); - } - - @Test - void test() { - Assertions.assertTrue(true); - System.out.println("@Test executed"); - } - - @AfterAll - static void tear() { - System.out.println("@AfterAll executed"); - } -} +package ru.joutak.test; + +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ExampleTest { + @BeforeAll + static void setup() { + System.out.println("@BeforeAll executed"); + } + + @BeforeEach + void setupThis() { + System.out.println("@BeforeEach executed"); + } + + @AfterEach + void tearThis() { + System.out.println("@AfterEach executed"); + } + + @Test + void test() { + Assertions.assertTrue(true); + System.out.println("@Test executed"); + } + + @AfterAll + static void tear() { + System.out.println("@AfterAll executed"); + } +}