From 57b942e21378b18030717e276896c9c7084c8086 Mon Sep 17 00:00:00 2001 From: AstronOmewa Date: Sat, 7 Feb 2026 06:00:38 +0300 Subject: [PATCH 1/4] modified: .github/workflows/gradle.yml modified: .gitignore modified: .run/build_release.run.xml modified: .run/build_snapshot.run.xml modified: README.md modified: build.gradle.kts modified: gradle.properties modified: gradle/libs.versions.toml modified: gradle/wrapper/gradle-wrapper.properties modified: gradlew modified: gradlew.bat modified: settings.gradle.kts new file: src/main/java/ru/joutak/someCoolPlugin/Fight.java new file: src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java new file: src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java new file: src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java new file: src/main/java/ru/joutak/someCoolPlugin/Wave.java new file: src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java deleted: src/main/java/ru/joutak/template/EmptyPlugin.java modified: src/main/resources/plugin.yml modified: src/test/java/ru/joutak/test/ExampleTest.java --- .github/workflows/gradle.yml | 86 +-- .gitignore | 200 +++---- .run/build_release.run.xml | 48 +- .run/build_snapshot.run.xml | 58 +- README.md | 104 ++-- build.gradle.kts | 162 +++--- gradle.properties | 14 +- gradle/libs.versions.toml | 34 +- gradle/wrapper/gradle-wrapper.properties | 14 +- gradlew | 502 +++++++++--------- gradlew.bat | 188 +++---- settings.gradle.kts | 4 +- .../java/ru/joutak/someCoolPlugin/Fight.java | 53 ++ .../someCoolPlugin/MobDeathListener.java | 20 + .../someCoolPlugin/PlayerDeathListener.java | 20 + .../joutak/someCoolPlugin/SomeCoolPlugin.java | 140 +++++ .../java/ru/joutak/someCoolPlugin/Wave.java | 63 +++ .../ru/joutak/someCoolPlugin/WaveEnding.java | 5 + .../java/ru/joutak/template/EmptyPlugin.java | 23 - src/main/resources/plugin.yml | 30 +- src/test/java/ru/joutak/test/ExampleTest.java | 72 +-- 21 files changed, 1062 insertions(+), 778 deletions(-) create mode 100644 src/main/java/ru/joutak/someCoolPlugin/Fight.java create mode 100644 src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java create mode 100644 src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java create mode 100644 src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java create mode 100644 src/main/java/ru/joutak/someCoolPlugin/Wave.java create mode 100644 src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java delete mode 100644 src/main/java/ru/joutak/template/EmptyPlugin.java 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_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/.run/build_snapshot.run.xml b/.run/build_snapshot.run.xml index e2cdddf..f6315b3 100644 --- a/.run/build_snapshot.run.xml +++ b/.run/build_snapshot.run.xml @@ -1,29 +1,29 @@ - - - - - - - - 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..cf6d1bb 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=someCoolNameForPlugin +version=0.0.1 + +# 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..c026f59 100755 --- a/gradlew +++ b/gradlew @@ -1,251 +1,251 @@ -#!/bin/sh - -# -# Copyright © 2015 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# SPDX-License-Identifier: Apache-2.0 -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH="\\\"\\\"" - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" 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/someCoolPlugin/Fight.java b/src/main/java/ru/joutak/someCoolPlugin/Fight.java new file mode 100644 index 0000000..cb3f6fd --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/Fight.java @@ -0,0 +1,53 @@ +package ru.joutak.someCoolPlugin; +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.block.*; +import org.bukkit.Location; +import org.bukkit.World; +import java.util.*; + +public class Fight{ + private static ArrayList waves = new ArrayList<>(); + private static Wave currentWave; + + + public void addWave(Wave w){ + waves.add(w); + } + + public void rmLast(Wave w){ + waves.remove(waves.getLast()); + } + + public static Wave lastWave(){ + return waves.getLast(); + } + + public static void removeMobFromCurrentWave(Entity e){ + currentWave = waves.getLast(); + currentWave.removeMob(e); + } + + public static boolean isCurrentWaveMob(Entity e){ + currentWave = waves.getLast(); + return currentWave.isWaveMob(e); + } + + public static boolean isCurrentWaveFinished(){ + currentWave = waves.getLast(); + return currentWave.isWaveFinished(); + } + + public static void endWave(){ + currentWave = waves.getLast(); + currentWave.endCallback.perform(); + } + + public static boolean isFightActive(){ + return ((!waves.isEmpty())&&(waves.getLast().isWaveActive())); + } + + public static void clear(){ + waves = new ArrayList<>(); + } +} diff --git a/src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java b/src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java new file mode 100644 index 0000000..f0afe7d --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java @@ -0,0 +1,20 @@ +package ru.joutak.someCoolPlugin; + +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(); + Fight.lastWave().bossBar.setProgress(1.0 - (Fight.lastWave().mobCap - Fight.lastWave().aliveMobs.size()) / Fight.lastWave().mobCap); + if(Fight.isCurrentWaveMob(e)){ + Fight.removeMobFromCurrentWave(e); + } + if(Fight.isCurrentWaveFinished()){ + Fight.endWave(); + } + } +} diff --git a/src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java b/src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java new file mode 100644 index 0000000..25c4a9f --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java @@ -0,0 +1,20 @@ +package ru.joutak.someCoolPlugin; + +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/someCoolPlugin/SomeCoolPlugin.java b/src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java new file mode 100644 index 0000000..d26a470 --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java @@ -0,0 +1,140 @@ +package ru.joutak.someCoolPlugin; + +import java.util.concurrent.ThreadLocalRandom; + +import org.bukkit.plugin.java.JavaPlugin; + +import lombok.Getter; + +import org.bukkit.command.*; +import org.bukkit.entity.*; +import org.bukkit.block.*; +import org.bukkit.Location; +import org.bukkit.World; + +// import Wave; + + +public final class SomeCoolPlugin extends JavaPlugin { + @Getter + private static SomeCoolPlugin instance; + + private boolean running = false; + + @Override + public void onEnable() { + instance = this; + + getLogger().info( + String.format("Плагин %s версии %s включен!", getPluginMeta().getName(), getPluginMeta().getVersion()) + ); + getServer().getPluginManager().registerEvents( + new MobDeathListener(), + this + ); + } + + @Override + public void onDisable() { + + } + + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ + if(command.getName().equalsIgnoreCase("coolplugin")){ + 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.getInteger(args[1]); + String level = args[2]; + World world = player.getWorld(); + Location center = player.getLocation(); + final int heightBoundary = 10; + final int attempts = 10; + if(!running){ + running = !running; + + switch(level){ + case "1": { + // 2 волны, 1 волна -- зомби (80%) + пауки (20%), 2 волна -- пауки(33%) + скелеты (33%) + зомби (34%), награда за волну - случайный эффект + // из ['регенерация','огнестойкость','поглощение'] + // + ['instantHealth','HealthBoost'] и случайное оружие + + class FirstWaveCallback implements WaveEnding{ + public void perform(){ + + } + } + + int waveMobCount = 10; + Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount); + + for(int i = 0; i < waveMobCount; i++){ + Location loc = this.findSpawnBlock(center, radius, heightBoundary, attempts); + double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); + if(prob<0.8){ + Entity e = world.spawnEntity(loc, EntityType.ZOMBIE); + first.addMob(e); + }else{ + Entity e = world.spawnEntity(loc, EntityType.SPIDER); + first.addMob(e); + } + + } + + }; + default: player.sendMessage("Такого уровня сложности нет:( Есть только 1-3 уровни."); + } + + } + + } + + public void stop(Player player, Command command, String label, String[] args){ + + } + + public void help(Player player, Command command, String label, String[] args){ + + } + + private Location findSpawnBlock( + Location center, + int radius, + int heightBoundary, + int attempts + ){ + World world = center.getWorld(); + for(int i =0; i < attempts; i++){ + 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); + + Block ground = world.getBlockAt(x,y,z); + Block head = world.getBlockAt(x,y+1,z); + Block feet = world.getBlockAt(x,y+2,z); + + if(!ground.getType().isSolid()){continue;} + if(!head.isPassable()){continue;} + if(!feet.isPassable()){continue;} + + return new Location(world, x, y+1, z); + } + return null; + } +} diff --git a/src/main/java/ru/joutak/someCoolPlugin/Wave.java b/src/main/java/ru/joutak/someCoolPlugin/Wave.java new file mode 100644 index 0000000..253d4d2 --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/Wave.java @@ -0,0 +1,63 @@ +package ru.joutak.someCoolPlugin; +import org.bukkit.command.*; +import org.bukkit.entity.*; + +import org.bukkit.block.*; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +import java.util.*; + +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){ + this.linkedTo = linkedTo; + this.endCallback = endCallback; + this.mobCap = mobCap; + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, BarStyle.SEGMENTED_10); + } + + public void addMob(Entity e){ + aliveMobs.add(e.getUniqueId()); + } + + public void removeMob(Entity e){ + aliveMobs.remove(e.getUniqueId()); + } + + 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 clear(World world){ + for(UUID uuid: aliveMobs){ + Entity e = world.getEntity(uuid); + if (e != null && !e.isDead()) { + e.remove(); + } + } + } + +} diff --git a/src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java b/src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java new file mode 100644 index 0000000..a30e23a --- /dev/null +++ b/src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java @@ -0,0 +1,5 @@ +package ru.joutak.someCoolPlugin; + +public interface WaveEnding { + public void perform(); +} 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/resources/plugin.yml b/src/main/resources/plugin.yml index 4428874..140cf2c 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: ['V7Zee'] +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"); + } +} From 24542979176d6ec7984ac02b44003bfaac6c990a Mon Sep 17 00:00:00 2001 From: n3sostr3l Date: Mon, 9 Feb 2026 08:38:49 +0300 Subject: [PATCH 2/4] Major changes --- ...pshot.run.xml => [Snapshot] Build.run.xml} | 62 ++- gradle.properties | 4 +- gradlew | 502 +++++++++--------- .../java/ru/joutak/someCoolPlugin/Fight.java | 53 -- .../joutak/someCoolPlugin/SomeCoolPlugin.java | 140 ----- .../java/ru/joutak/someCoolPlugin/Wave.java | 63 --- .../template/CreakingSpawnListener.java | 48 ++ src/main/java/ru/joutak/template/Fight.java | 69 +++ .../MobDeathListener.java | 6 +- .../PlayerDeathListener.java | 5 +- .../ru/joutak/template/SomeCoolPlugin.java | 428 +++++++++++++++ src/main/java/ru/joutak/template/Wave.java | 96 ++++ .../WaveEnding.java | 2 +- src/main/resources/plugin.yml | 2 +- 14 files changed, 934 insertions(+), 546 deletions(-) rename .run/{build_snapshot.run.xml => [Snapshot] Build.run.xml} (79%) delete mode 100644 src/main/java/ru/joutak/someCoolPlugin/Fight.java delete mode 100644 src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java delete mode 100644 src/main/java/ru/joutak/someCoolPlugin/Wave.java create mode 100644 src/main/java/ru/joutak/template/CreakingSpawnListener.java create mode 100644 src/main/java/ru/joutak/template/Fight.java rename src/main/java/ru/joutak/{someCoolPlugin => template}/MobDeathListener.java (63%) rename src/main/java/ru/joutak/{someCoolPlugin => template}/PlayerDeathListener.java (82%) create mode 100644 src/main/java/ru/joutak/template/SomeCoolPlugin.java create mode 100644 src/main/java/ru/joutak/template/Wave.java rename src/main/java/ru/joutak/{someCoolPlugin => template}/WaveEnding.java (60%) 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 f6315b3..afcdc2f 100644 --- a/.run/build_snapshot.run.xml +++ b/.run/[Snapshot] Build.run.xml @@ -1,29 +1,33 @@ - - - - - - - - true - true - false - false - - - + + + + + + + + true + true + false + false + false + false + false + + + \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index cf6d1bb..f39b923 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,8 +1,8 @@ # Plugin properties repo=https://github.com/AstronOmewa/someCoolNameForRepository group=ru.joutak -name=someCoolNameForPlugin -version=0.0.1 +name=yetAnotherWave +version=0.1.5 # Gradle properties org.gradle.parallel=true \ No newline at end of file diff --git a/gradlew b/gradlew index c026f59..a4df73e 100755 --- a/gradlew +++ b/gradlew @@ -1,251 +1,251 @@ -#!/bin/sh - -# -# Copyright © 2015 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# SPDX-License-Identifier: Apache-2.0 -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH="\\\"\\\"" - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" +# !/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/src/main/java/ru/joutak/someCoolPlugin/Fight.java b/src/main/java/ru/joutak/someCoolPlugin/Fight.java deleted file mode 100644 index cb3f6fd..0000000 --- a/src/main/java/ru/joutak/someCoolPlugin/Fight.java +++ /dev/null @@ -1,53 +0,0 @@ -package ru.joutak.someCoolPlugin; -import org.bukkit.command.*; -import org.bukkit.entity.*; -import org.bukkit.block.*; -import org.bukkit.Location; -import org.bukkit.World; -import java.util.*; - -public class Fight{ - private static ArrayList waves = new ArrayList<>(); - private static Wave currentWave; - - - public void addWave(Wave w){ - waves.add(w); - } - - public void rmLast(Wave w){ - waves.remove(waves.getLast()); - } - - public static Wave lastWave(){ - return waves.getLast(); - } - - public static void removeMobFromCurrentWave(Entity e){ - currentWave = waves.getLast(); - currentWave.removeMob(e); - } - - public static boolean isCurrentWaveMob(Entity e){ - currentWave = waves.getLast(); - return currentWave.isWaveMob(e); - } - - public static boolean isCurrentWaveFinished(){ - currentWave = waves.getLast(); - return currentWave.isWaveFinished(); - } - - public static void endWave(){ - currentWave = waves.getLast(); - currentWave.endCallback.perform(); - } - - public static boolean isFightActive(){ - return ((!waves.isEmpty())&&(waves.getLast().isWaveActive())); - } - - public static void clear(){ - waves = new ArrayList<>(); - } -} diff --git a/src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java b/src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java deleted file mode 100644 index d26a470..0000000 --- a/src/main/java/ru/joutak/someCoolPlugin/SomeCoolPlugin.java +++ /dev/null @@ -1,140 +0,0 @@ -package ru.joutak.someCoolPlugin; - -import java.util.concurrent.ThreadLocalRandom; - -import org.bukkit.plugin.java.JavaPlugin; - -import lombok.Getter; - -import org.bukkit.command.*; -import org.bukkit.entity.*; -import org.bukkit.block.*; -import org.bukkit.Location; -import org.bukkit.World; - -// import Wave; - - -public final class SomeCoolPlugin extends JavaPlugin { - @Getter - private static SomeCoolPlugin instance; - - private boolean running = false; - - @Override - public void onEnable() { - instance = this; - - getLogger().info( - String.format("Плагин %s версии %s включен!", getPluginMeta().getName(), getPluginMeta().getVersion()) - ); - getServer().getPluginManager().registerEvents( - new MobDeathListener(), - this - ); - } - - @Override - public void onDisable() { - - } - - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args){ - if(command.getName().equalsIgnoreCase("coolplugin")){ - 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.getInteger(args[1]); - String level = args[2]; - World world = player.getWorld(); - Location center = player.getLocation(); - final int heightBoundary = 10; - final int attempts = 10; - if(!running){ - running = !running; - - switch(level){ - case "1": { - // 2 волны, 1 волна -- зомби (80%) + пауки (20%), 2 волна -- пауки(33%) + скелеты (33%) + зомби (34%), награда за волну - случайный эффект - // из ['регенерация','огнестойкость','поглощение'] - // + ['instantHealth','HealthBoost'] и случайное оружие - - class FirstWaveCallback implements WaveEnding{ - public void perform(){ - - } - } - - int waveMobCount = 10; - Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount); - - for(int i = 0; i < waveMobCount; i++){ - Location loc = this.findSpawnBlock(center, radius, heightBoundary, attempts); - double prob = ThreadLocalRandom.current().nextDouble(0.0, 1.0); - if(prob<0.8){ - Entity e = world.spawnEntity(loc, EntityType.ZOMBIE); - first.addMob(e); - }else{ - Entity e = world.spawnEntity(loc, EntityType.SPIDER); - first.addMob(e); - } - - } - - }; - default: player.sendMessage("Такого уровня сложности нет:( Есть только 1-3 уровни."); - } - - } - - } - - public void stop(Player player, Command command, String label, String[] args){ - - } - - public void help(Player player, Command command, String label, String[] args){ - - } - - private Location findSpawnBlock( - Location center, - int radius, - int heightBoundary, - int attempts - ){ - World world = center.getWorld(); - for(int i =0; i < attempts; i++){ - 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); - - Block ground = world.getBlockAt(x,y,z); - Block head = world.getBlockAt(x,y+1,z); - Block feet = world.getBlockAt(x,y+2,z); - - if(!ground.getType().isSolid()){continue;} - if(!head.isPassable()){continue;} - if(!feet.isPassable()){continue;} - - return new Location(world, x, y+1, z); - } - return null; - } -} diff --git a/src/main/java/ru/joutak/someCoolPlugin/Wave.java b/src/main/java/ru/joutak/someCoolPlugin/Wave.java deleted file mode 100644 index 253d4d2..0000000 --- a/src/main/java/ru/joutak/someCoolPlugin/Wave.java +++ /dev/null @@ -1,63 +0,0 @@ -package ru.joutak.someCoolPlugin; -import org.bukkit.command.*; -import org.bukkit.entity.*; - -import org.bukkit.block.*; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; - -import java.util.*; - -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){ - this.linkedTo = linkedTo; - this.endCallback = endCallback; - this.mobCap = mobCap; - this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, BarStyle.SEGMENTED_10); - } - - public void addMob(Entity e){ - aliveMobs.add(e.getUniqueId()); - } - - public void removeMob(Entity e){ - aliveMobs.remove(e.getUniqueId()); - } - - 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 clear(World world){ - for(UUID uuid: aliveMobs){ - Entity e = world.getEntity(uuid); - if (e != null && !e.isDead()) { - e.remove(); - } - } - } - -} 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/Fight.java b/src/main/java/ru/joutak/template/Fight.java new file mode 100644 index 0000000..36c8034 --- /dev/null +++ b/src/main/java/ru/joutak/template/Fight.java @@ -0,0 +1,69 @@ +package ru.joutak.template; +import org.bukkit.entity.*; + +import java.util.*; + +public class Fight{ + private static ArrayList waves = new ArrayList<>(); + private static Wave currentWave; + + + public void addWave(Wave w){ + waves.add(w); + } + + public void rmLast(Wave w){ + if(!waves.isEmpty()) waves.remove(waves.getLast()); + } + + public static Wave lastWave(){ + if(!waves.isEmpty()) return waves.getFirst(); + Wave o = null; + return o; + } + + public static void removeMobFromCurrentWave(Entity e){ + if(!waves.isEmpty()) { + currentWave = waves.getFirst(); + currentWave.removeMob(e); + } + } + + public static boolean isCurrentWaveMob(Entity e){ + if(!waves.isEmpty()) { + currentWave = waves.getFirst(); + return currentWave.isWaveMob(e); + } + return false; + } + + public static boolean isCurrentWaveFinished() { + if (!waves.isEmpty()) { + currentWave = waves.getFirst(); + return currentWave.isWaveFinished(); + } + return false; + } + + public static 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 static boolean isFightActive(){ + return ((!waves.isEmpty())&&(waves.getFirst().isWaveActive())); + } + + public static void clear(){ + for(Wave w: waves){ + w.clear(w.linkedTo.getWorld()); + waves.remove(w); + } + } +} diff --git a/src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java b/src/main/java/ru/joutak/template/MobDeathListener.java similarity index 63% rename from src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java rename to src/main/java/ru/joutak/template/MobDeathListener.java index f0afe7d..b20c79e 100644 --- a/src/main/java/ru/joutak/someCoolPlugin/MobDeathListener.java +++ b/src/main/java/ru/joutak/template/MobDeathListener.java @@ -1,4 +1,4 @@ -package ru.joutak.someCoolPlugin; +package ru.joutak.template; import org.bukkit.event.*; import org.bukkit.entity.*; @@ -8,8 +8,8 @@ public class MobDeathListener implements Listener{ @EventHandler public void onMobDeath(EntityDeathEvent evt){ - Entity e = (Entity)evt.getEntity(); - Fight.lastWave().bossBar.setProgress(1.0 - (Fight.lastWave().mobCap - Fight.lastWave().aliveMobs.size()) / Fight.lastWave().mobCap); + Entity e = (Entity) evt.getEntity(); + if(Fight.isCurrentWaveMob(e)){ Fight.removeMobFromCurrentWave(e); } diff --git a/src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java b/src/main/java/ru/joutak/template/PlayerDeathListener.java similarity index 82% rename from src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java rename to src/main/java/ru/joutak/template/PlayerDeathListener.java index 25c4a9f..805c409 100644 --- a/src/main/java/ru/joutak/someCoolPlugin/PlayerDeathListener.java +++ b/src/main/java/ru/joutak/template/PlayerDeathListener.java @@ -1,4 +1,4 @@ -package ru.joutak.someCoolPlugin; +package ru.joutak.template; import org.bukkit.event.*; import org.bukkit.entity.*; @@ -10,11 +10,10 @@ public class PlayerDeathListener implements Listener{ public void onPlayerDeath(PlayerDeathEvent evt){ Player player = evt.getPlayer(); - if(Fight.isFightActive()){ + 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..08a3f4a --- /dev/null +++ b/src/main/java/ru/joutak/template/SomeCoolPlugin.java @@ -0,0 +1,428 @@ +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.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, 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, 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, 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, 20, 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, 20, 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":{ + player.sendMessage(""); + } + 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(), // координата X + loc.getY() + 1, // немного выше головы + loc.getZ(), // координата Z + 30, // количество частиц + 0.3, 0.5, 0.3, // смещение по X, Y, Z (для рассеивания) + 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(); + + 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 * 10L; + + 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..0933578 --- /dev/null +++ b/src/main/java/ru/joutak/template/Wave.java @@ -0,0 +1,96 @@ +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; + protected int segments; + + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, int seg){ + this.segments = seg; + this.linkedTo = linkedTo; + this.endCallback = endCallback; + this.mobCap = mobCap; + BarStyle style = switch(segments){ + case 6-> style = BarStyle.SEGMENTED_6; + case 12-> style = BarStyle.SEGMENTED_12; + case 20-> style = BarStyle.SEGMENTED_20; + default-> style = BarStyle.SEGMENTED_10; + }; + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, style); + } + + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, int segments, BarColor barColor){ + this.segments = segments; + this.linkedTo = linkedTo; + this.endCallback = endCallback; + this.mobCap = mobCap; + BarStyle style; + switch(segments){ + case 6: style = BarStyle.SEGMENTED_6; + case 10: style = BarStyle.SEGMENTED_10; + case 12: style = BarStyle.SEGMENTED_12; + case 20: style = BarStyle.SEGMENTED_20; + default: style = BarStyle.SEGMENTED_10; + } + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), barColor, style); + } + + 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/someCoolPlugin/WaveEnding.java b/src/main/java/ru/joutak/template/WaveEnding.java similarity index 60% rename from src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java rename to src/main/java/ru/joutak/template/WaveEnding.java index a30e23a..dcde4ec 100644 --- a/src/main/java/ru/joutak/someCoolPlugin/WaveEnding.java +++ b/src/main/java/ru/joutak/template/WaveEnding.java @@ -1,4 +1,4 @@ -package ru.joutak.someCoolPlugin; +package ru.joutak.template; public interface WaveEnding { public void perform(); diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 140cf2c..d3c3917 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -3,7 +3,7 @@ version: ${VERSION} api-version: ${MINECRAFT_VERSION} main: ru.joutak.template.SomeCoolPlugin description: 'A cool plugin' -authors: ['V7Zee'] +authors: ['V7Zeee'] contributors: [] website: ${WEBSITE} From 3fc18f1b5075fe10cac717df002f8bf509a7e7b4 Mon Sep 17 00:00:00 2001 From: n3sostr3l Date: Tue, 24 Feb 2026 18:41:56 +0300 Subject: [PATCH 3/4] =?UTF-8?q?=D0=B2=D1=81=D0=B5=20=D1=81=D0=B4=D0=B5?= =?UTF-8?q?=D0=BB=D0=B0=D0=BB,=20=D0=B2=D1=81=D0=B5=20=D0=B7=D0=B0=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=BC=D0=B8=D1=82=D0=B8=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ru/joutak/template/SomeCoolPlugin.java | 290 +++++++++++++++++- 1 file changed, 279 insertions(+), 11 deletions(-) diff --git a/src/main/java/ru/joutak/template/SomeCoolPlugin.java b/src/main/java/ru/joutak/template/SomeCoolPlugin.java index 08a3f4a..851a089 100644 --- a/src/main/java/ru/joutak/template/SomeCoolPlugin.java +++ b/src/main/java/ru/joutak/template/SomeCoolPlugin.java @@ -287,10 +287,272 @@ public void perform(){ first.perform(); } break; - case "3":{ - player.sendMessage(""); + 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, 15, 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, 20, 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, 25, 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, 30, 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, 40, 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 уровни."); } @@ -342,13 +604,13 @@ public void spawnMob(Location loc, EntityType e, World world, Sound s, Wave w, l public void run(){ Entity ent = world.spawnEntity(loc, e); world.spawnParticle( - Particle.FLAME, // тип партикла - loc.getX(), // координата X - loc.getY() + 1, // немного выше головы - loc.getZ(), // координата Z - 30, // количество частиц - 0.3, 0.5, 0.3, // смещение по X, Y, Z (для рассеивания) - 0.1 // скорость частиц + 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); @@ -358,7 +620,12 @@ public void run(){ 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); @@ -374,7 +641,7 @@ public void spawnRandomCreakingColumn(Player p, int amount, int radius) { if (!ground.getBlock().getType().isSolid()) continue; int height = ThreadLocalRandom.current().nextInt(1, 7); - long delay = i * 10L; + long delay = i * 20L; for (int y = 1; y <= height; y++) { Location place = ground.clone().add(0, y, 0); @@ -406,6 +673,7 @@ public void spawnRandomCreakingColumn(Player p, int amount, int radius) { 1.0f, 1.0f ); + }, delay + (height + 1) * 3L ); From d97454aa75775faeb051d82b38d8df9d33cec02b Mon Sep 17 00:00:00 2001 From: n3sostr3l Date: Mon, 2 Mar 2026 11:39:10 +0300 Subject: [PATCH 4/4] =?UTF-8?q?=D0=9D=D0=B0=D1=87=D0=B0=D0=BB=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BF=D1=8B=D1=82=D0=BA=D0=B8=20=D0=B2=20SOLID?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/ru/joutak/template/Fight.java | 24 ++-- .../ru/joutak/template/SomeCoolPlugin.java | 21 ++-- src/main/java/ru/joutak/template/Wave.java | 25 +--- .../ru/joutak/template/commands/Command.java | 38 ++++++ .../template/commands/CommandInvoker.java | 119 ++++++++++++++++++ .../joutak/template/commands/HelpCommand.java | 22 ++++ .../ru/joutak/template/commands/Modable.java | 20 +++ .../joutak/template/commands/StopCommand.java | 17 +++ 8 files changed, 243 insertions(+), 43 deletions(-) create mode 100644 src/main/java/ru/joutak/template/commands/Command.java create mode 100644 src/main/java/ru/joutak/template/commands/CommandInvoker.java create mode 100644 src/main/java/ru/joutak/template/commands/HelpCommand.java create mode 100644 src/main/java/ru/joutak/template/commands/Modable.java create mode 100644 src/main/java/ru/joutak/template/commands/StopCommand.java diff --git a/src/main/java/ru/joutak/template/Fight.java b/src/main/java/ru/joutak/template/Fight.java index 36c8034..80d40db 100644 --- a/src/main/java/ru/joutak/template/Fight.java +++ b/src/main/java/ru/joutak/template/Fight.java @@ -1,12 +1,12 @@ package ru.joutak.template; +import com.google.j2objc.annotations.Property; import org.bukkit.entity.*; import java.util.*; public class Fight{ - private static ArrayList waves = new ArrayList<>(); - private static Wave currentWave; - + private ArrayList waves = new ArrayList<>(); + private Wave currentWave; public void addWave(Wave w){ waves.add(w); @@ -16,20 +16,20 @@ public void rmLast(Wave w){ if(!waves.isEmpty()) waves.remove(waves.getLast()); } - public static Wave lastWave(){ - if(!waves.isEmpty()) return waves.getFirst(); + public Wave lastWave(){ + if(!(waves.isEmpty())) return waves.getFirst(); Wave o = null; return o; } - public static void removeMobFromCurrentWave(Entity e){ - if(!waves.isEmpty()) { + public void removeMobFromCurrentWave(Entity e){ + if(!(waves.isEmpty())) { currentWave = waves.getFirst(); currentWave.removeMob(e); } } - public static boolean isCurrentWaveMob(Entity e){ + public boolean isCurrentWaveMob(Entity e){ if(!waves.isEmpty()) { currentWave = waves.getFirst(); return currentWave.isWaveMob(e); @@ -37,7 +37,7 @@ public static boolean isCurrentWaveMob(Entity e){ return false; } - public static boolean isCurrentWaveFinished() { + public boolean isCurrentWaveFinished() { if (!waves.isEmpty()) { currentWave = waves.getFirst(); return currentWave.isWaveFinished(); @@ -45,7 +45,7 @@ public static boolean isCurrentWaveFinished() { return false; } - public static void endWave(){ + public void endWave(){ if(!waves.isEmpty()) { currentWave = waves.getFirst(); currentWave.bossBar.removePlayer(currentWave.linkedTo); @@ -56,11 +56,11 @@ public static void endWave(){ } } - public static boolean isFightActive(){ + public boolean isFightActive(){ return ((!waves.isEmpty())&&(waves.getFirst().isWaveActive())); } - public static void clear(){ + public void clear(){ for(Wave w: waves){ w.clear(w.linkedTo.getWorld()); waves.remove(w); diff --git a/src/main/java/ru/joutak/template/SomeCoolPlugin.java b/src/main/java/ru/joutak/template/SomeCoolPlugin.java index 851a089..948e691 100644 --- a/src/main/java/ru/joutak/template/SomeCoolPlugin.java +++ b/src/main/java/ru/joutak/template/SomeCoolPlugin.java @@ -6,6 +6,7 @@ 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; @@ -131,7 +132,7 @@ public void perform(){ final int waveMobCount = 10; Fight fight = new Fight(); - Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, 10){ + Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, BarStyle.SEGMENTED_10){ @Override public void perform() { begin(); @@ -151,7 +152,7 @@ public void perform() { fight.addWave(first); final int secondWaveCount = waveMobCount*2; - Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, 20, BarColor.BLUE){ + Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, BarStyle.SEGMENTED_20, BarColor.BLUE){ @Override public void perform() { begin(); @@ -230,7 +231,7 @@ public void perform(){ final int waveMobCount = 2*radius; Fight fight = new Fight(); - Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, 10){ + Wave first = new Wave(player, new FirstWaveCallback(), waveMobCount, BarStyle.SEGMENTED_10){ @Override public void perform() { begin(); @@ -250,7 +251,7 @@ public void perform() { fight.addWave(first); final int secondWaveCount = (int) (waveMobCount*1.2); - Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, 20, BarColor.BLUE){ + Wave second = new Wave(player, new SecondWaveCallback(), secondWaveCount, BarStyle.SEGMENTED_12, BarColor.BLUE){ @Override public void perform() { begin(); @@ -269,7 +270,7 @@ public void perform() { } }; - Wave third = new Wave(player, new ThirdWaweCallback(), secondWaveCount, 20, BarColor.YELLOW){ + Wave third = new Wave(player, new ThirdWaweCallback(), secondWaveCount, BarStyle.SEGMENTED_10, BarColor.YELLOW){ @Override public void perform(){ begin(); @@ -329,7 +330,7 @@ public void perform() { } } - Wave first = new Wave(player, new FirstWaveCallback(), wave1Count, 15, BarColor.GREEN) { + Wave first = new Wave(player, new FirstWaveCallback(), wave1Count, BarStyle.SEGMENTED_20, BarColor.GREEN) { @Override public void perform() { begin(); @@ -384,7 +385,7 @@ public void perform() { } } - Wave second = new Wave(player, new SecondWaveCallback(), wave2Count, 20, BarColor.RED) { + Wave second = new Wave(player, new SecondWaveCallback(), wave2Count, BarStyle.SEGMENTED_10, BarColor.RED) { @Override public void perform() { begin(); @@ -439,7 +440,7 @@ public void perform() { } } - Wave third = new Wave(player, new ThirdWaveCallback(), wave3Count, 25, BarColor.YELLOW) { + Wave third = new Wave(player, new ThirdWaveCallback(), wave3Count, BarStyle.SEGMENTED_20, BarColor.YELLOW) { @Override public void perform() { begin(); @@ -493,7 +494,7 @@ public void perform() { } } - Wave fourth = new Wave(player, new FourthWaveCallback(), wave4Count, 30, BarColor.PURPLE) { + Wave fourth = new Wave(player, new FourthWaveCallback(), wave4Count, BarStyle.SEGMENTED_20, BarColor.PURPLE) { @Override public void perform() { begin(); @@ -530,7 +531,7 @@ public void perform() { } } - Wave fifth = new Wave(player, new FifthWaveCallback(), 1, 40, BarColor.BLUE) { + Wave fifth = new Wave(player, new FifthWaveCallback(), 1, BarStyle.SEGMENTED_20, BarColor.BLUE) { @Override public void perform() { begin(); diff --git a/src/main/java/ru/joutak/template/Wave.java b/src/main/java/ru/joutak/template/Wave.java index 0933578..63f86b2 100644 --- a/src/main/java/ru/joutak/template/Wave.java +++ b/src/main/java/ru/joutak/template/Wave.java @@ -18,36 +18,19 @@ public class Wave{ protected Player linkedTo; protected WaveEnding endCallback; protected BossBar bossBar; - protected int segments; - public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, int seg){ - this.segments = seg; + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, BarStyle seg){ this.linkedTo = linkedTo; this.endCallback = endCallback; this.mobCap = mobCap; - BarStyle style = switch(segments){ - case 6-> style = BarStyle.SEGMENTED_6; - case 12-> style = BarStyle.SEGMENTED_12; - case 20-> style = BarStyle.SEGMENTED_20; - default-> style = BarStyle.SEGMENTED_10; - }; - this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, style); + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), BarColor.GREEN, seg); } - public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, int segments, BarColor barColor){ - this.segments = segments; + public Wave(Player linkedTo, WaveEnding endCallback, int mobCap, BarStyle seg, BarColor barColor){ this.linkedTo = linkedTo; this.endCallback = endCallback; this.mobCap = mobCap; - BarStyle style; - switch(segments){ - case 6: style = BarStyle.SEGMENTED_6; - case 10: style = BarStyle.SEGMENTED_10; - case 12: style = BarStyle.SEGMENTED_12; - case 20: style = BarStyle.SEGMENTED_20; - default: style = BarStyle.SEGMENTED_10; - } - this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), barColor, style); + this.bossBar = Bukkit.createBossBar(String.format("Yet Another Wave"), barColor, seg); } public void addMob(Entity e){ 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; + } +}