mirror of
https://github.com/darksaid98/AlathranWars.git
synced 2026-12-01 14:38:55 +00:00
134 files changed
+6169
-2370
No files matched your search
+1
-1
@@ -432,4 +432,4 @@ ij_yaml_keep_line_breaks = true
|
||||
ij_yaml_sequence_on_new_line = false
|
||||
ij_yaml_space_before_colon = false
|
||||
ij_yaml_spaces_within_braces = true
|
||||
ij_yaml_spaces_within_brackets = true
|
||||
ij_yaml_spaces_within_brackets = true
|
||||
@@ -0,0 +1,2 @@
|
||||
# Set the default behavior, in case people don't have core.autocrlf set.
|
||||
* text=auto
|
||||
@@ -0,0 +1 @@
|
||||
* @darksaid98
|
||||
@@ -0,0 +1,2 @@
|
||||
github: darksaid98
|
||||
patreon: alathramc
|
||||
@@ -0,0 +1,34 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Version information:**
|
||||
- Vanilla version: [e.g. 1.20.2]
|
||||
- Server version: [e.g. paper-123]
|
||||
- Plugin version [e.g. 0.1.0]
|
||||
|
||||
**Additional context**
|
||||
```
|
||||
Add any other context about the problem here including console errors.
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
@@ -0,0 +1,15 @@
|
||||
name: 'Setup Gradle'
|
||||
description: 'Grant execute permissions and validate Gradle wrapper'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Grant execute permissions for Gradle wrapper
|
||||
run: chmod +x gradlew
|
||||
shell: bash
|
||||
|
||||
- name: Validate Gradle Wrapper Authenticity
|
||||
uses: gradle/wrapper-validation-action@v1
|
||||
|
||||
- name: Setup Gradle and Caching
|
||||
uses: gradle/gradle-build-action@v2
|
||||
@@ -0,0 +1,17 @@
|
||||
name: 'Setup JDK'
|
||||
description: 'Set up JDK'
|
||||
|
||||
inputs:
|
||||
java-version:
|
||||
description: 'Java version'
|
||||
required: true
|
||||
default: '17'
|
||||
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
- name: Setup JDK
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
java-version: ${{ inputs.java-version }}
|
||||
distribution: 'temurin'
|
||||
@@ -0,0 +1,26 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
commit-message:
|
||||
prefix: "ci:"
|
||||
target-branch: "main"
|
||||
- package-ecosystem: "gradle"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
commit-message:
|
||||
prefix: "build:"
|
||||
target-branch: "main"
|
||||
groups:
|
||||
"org.flywaydb":
|
||||
patterns:
|
||||
- "org.flywaydb*"
|
||||
"org.jooq":
|
||||
patterns:
|
||||
- "org.jooq*"
|
||||
"net.kyori":
|
||||
patterns:
|
||||
- "net.kyori*"
|
||||
@@ -1,36 +0,0 @@
|
||||
name: Upload release assets
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [ published ]
|
||||
|
||||
jobs:
|
||||
upload_asset:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
packages: write
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Validate Gradle Wrapper
|
||||
uses: gradle/wrapper-validation-action@v1
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v3
|
||||
with:
|
||||
distribution: temurin
|
||||
cache: gradle
|
||||
java-version: 17
|
||||
|
||||
- name: Clean Build
|
||||
run: ./gradlew clean build --no-daemon
|
||||
|
||||
- name: Upload Release Assets
|
||||
uses: AButler/[email protected]
|
||||
with:
|
||||
files: 'build/libs/AlathranWars-*.jar'
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
release-tag: ${{ github.event.release.tag_name }}
|
||||
@@ -0,0 +1,86 @@
|
||||
name: Build & Upload Release jar with Gradle
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
tags:
|
||||
- '*'
|
||||
pull_request:
|
||||
branches:
|
||||
- 'main'
|
||||
- 'master'
|
||||
schedule:
|
||||
- cron: '0 0 * * 6'
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ${{ format('{0}-{1}', github.job, github.ref) }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
java: [ 17 ]
|
||||
if: github.ref_type != 'tag'
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: ./.github/actions/gradle
|
||||
|
||||
- name: Setup JDK
|
||||
uses: ./.github/actions/jdk
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew clean build --info
|
||||
|
||||
- name: Upload build results
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: ${{ matrix.os }} Java ${{ matrix.java }} Snapshot
|
||||
path: ${{ github.workspace }}/build/libs/
|
||||
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
java: [ 17 ]
|
||||
if: github.ref_type == 'tag'
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Gradle
|
||||
uses: ./.github/actions/gradle
|
||||
|
||||
- name: Setup JDK
|
||||
uses: ./.github/actions/jdk
|
||||
with:
|
||||
java-version: ${{ matrix.java }}
|
||||
|
||||
- name: Set Release Environment Variable
|
||||
if: github.ref_type == 'tag'
|
||||
run: |
|
||||
echo "CUSTOM_VERSION=${{ github.ref_name }}" >> $GITHUB_ENV
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew clean build -PcustomVersion=${{ env.CUSTOM_VERSION }}
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
id: release
|
||||
with:
|
||||
name: ${{ format('Release {0}', github.ref_name) }}
|
||||
files: ${{ github.workspace }}/build/libs/*
|
||||
prerelease: ${{ contains(github.ref_name, '-RC-') }}
|
||||
generate_release_notes: true
|
||||
fail_on_unmatched_files: true
|
||||
draft: false
|
||||
@@ -0,0 +1,26 @@
|
||||
name: 'Close Stale Issues & PRs'
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 1 * * *'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v9
|
||||
with:
|
||||
stale-issue-message: 'This issue has been automatically marked as stale because it has been open for 60 days with no activity.'
|
||||
stale-pr-message: 'This PR has been automatically marked as stale because it has been open for 60 days with no activity.'
|
||||
close-issue-message: 'This issue was closed because it has been stalled for -1 days with no activity.'
|
||||
close-pr-message: 'This PR was closed because it has been stalled for -1 days with no activity.'
|
||||
days-before-issue-stale: 60
|
||||
days-before-pr-stale: 60
|
||||
days-before-issue-close: -1
|
||||
days-before-pr-close: -1
|
||||
stale-issue-label: 'stale'
|
||||
stale-pr-label: 'stale'
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
.mtj.tmp/
|
||||
*.class
|
||||
*.jar
|
||||
*.oldWar
|
||||
*.war
|
||||
*.ear
|
||||
*.nar
|
||||
hs_err_pid*
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, caste, color, religion, or sexual
|
||||
identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall
|
||||
community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of
|
||||
any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address,
|
||||
without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
darksaid9889@gmail.com.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of
|
||||
actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or permanent
|
||||
ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the
|
||||
community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by
|
||||
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
||||
[https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
@@ -0,0 +1,44 @@
|
||||
## Pull Requests
|
||||
|
||||
We use the [GitHub flow](https://guides.github.com/introduction/flow/) for contributions.
|
||||
|
||||
1. Fork the repository.
|
||||
2. Create a new branch for each feature, fix or improvement.
|
||||
3. Send a pull request from each feature branch to the **main** branch.
|
||||
|
||||
It is very important to separate new features or improvements into separate feature branches, and to send a pull request for each branch. This allow us to review and pull in new features or improvements individually.
|
||||
|
||||
## Specifications
|
||||
|
||||
### Commit Messages
|
||||
|
||||
All commit messages should adhere to the [Conventional Commits specification](https://conventionalcommits.org/).
|
||||
|
||||
#### Commit Types
|
||||
|
||||
- API relevant changes
|
||||
* `feat` Commits, that adds a new feature
|
||||
* `fix` Commits, that fixes a bug/issue
|
||||
- `refactor` Commits, that rewrite/restructure your code, however does not change any API behaviour
|
||||
* `perf` Commits are special `refactor` commits, that improve performance
|
||||
- `style` Commits, that do not affect the meaning (white-space, formatting, missing semi-colons, etc)
|
||||
- `test` Commits, that add or correct existing tests
|
||||
- `docs` Commits, that affect documentation only
|
||||
- Tooling relevant changes
|
||||
* `build` Commits, that affect build components like build tool, dependencies, project version, ...
|
||||
* `ci` Commits, that affect CI configuration files and scripts
|
||||
- `revert` Commits, that revert previous commits
|
||||
- `chore` Miscellaneous commits without production code change, e.g. modifying `.gitignore`
|
||||
|
||||
### Versioning
|
||||
|
||||
Our project adheres to the [Semantic Versioning 2.0.0 specification](https://semver.org/) for versioning.
|
||||
|
||||
### Style Guide
|
||||
|
||||
Large refactors breaking the style defined in the `.editorconfig` file are frowned upon.
|
||||
When contributing ensure your code follows existing conventions and styling. (*Any issues that arise will be noted in your pull request.*)
|
||||
|
||||
## Licensing
|
||||
|
||||
You must agree that your patch will be licensed under the main license found in this repository, and if we change the license, we will assume that you agreed with the change unless you object to the changes in time.
|
||||
+156
-44
@@ -1,18 +1,28 @@
|
||||
import org.jooq.meta.jaxb.Logging
|
||||
import java.time.Instant
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
|
||||
id("com.github.johnrengelman.shadow") version "8.1.1" // Shades and relocates dependencies, See https://imperceptiblethoughts.com/shadow/introduction/
|
||||
id("xyz.jpenilla.run-paper") version "2.1.0" // Adds runServer and runMojangMappedServer tasks for testing
|
||||
id("xyz.jpenilla.run-paper") version "2.2.2" // Adds runServer and runMojangMappedServer tasks for testing
|
||||
id("net.minecrell.plugin-yml.bukkit") version "0.6.0" // Automatic plugin.yml generation
|
||||
id("io.papermc.paperweight.userdev") version "1.5.5" // Used to develop internal plugins using Mojang mappings
|
||||
id("io.papermc.paperweight.userdev") version "1.5.9" // Used to develop internal plugins using Mojang mappings, See https://github.com/PaperMC/paperweight
|
||||
id("org.flywaydb.flyway") version "10.8.1" // Database migrations
|
||||
id("org.jooq.jooq-codegen-gradle") version "3.19.3"
|
||||
|
||||
eclipse
|
||||
idea
|
||||
}
|
||||
|
||||
group = "com.github.alathra.AlathranWars"
|
||||
version = "3.0.0-SNAPSHOT-3"
|
||||
group = "com.github.alathra"
|
||||
version = "3.0.0"
|
||||
description = ""
|
||||
val mainPackage = "${project.group}.${rootProject.name.lowercase()}"
|
||||
|
||||
java {
|
||||
toolchain.languageVersion.set(JavaLanguageVersion.of(17)) // Configure the java toolchain. This allows gradle to auto-provision JDK 17 on systems that only have JDK 8 installed for example.
|
||||
// withJavadocJar() // Enable Javadoc generation
|
||||
}
|
||||
|
||||
repositories {
|
||||
@@ -34,7 +44,7 @@ repositories {
|
||||
}
|
||||
}
|
||||
|
||||
maven("https://repo.kryptonmc.org/releases/") {
|
||||
maven("https://repo.kryptonmc.org/releases") {
|
||||
content { includeGroup("me.neznamy") }
|
||||
}
|
||||
|
||||
@@ -48,55 +58,79 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly("org.jetbrains:annotations:24.0.1")
|
||||
compileOnly("org.jetbrains:annotations:24.1.0")
|
||||
annotationProcessor("org.jetbrains:annotations:24.1.0")
|
||||
|
||||
paperweight.paperDevBundle("1.19.4-R0.1-SNAPSHOT")
|
||||
implementation("space.arim.morepaperlib:morepaperlib:0.4.3")
|
||||
paperweight.paperDevBundle("1.20.1-R0.1-SNAPSHOT")
|
||||
implementation("space.arim.morepaperlib:morepaperlib:latest.release")
|
||||
|
||||
implementation("com.github.milkdrinkers:simplixstorage:3.2.7")
|
||||
implementation("com.github.milkdrinkers:crate:1.1.0")
|
||||
implementation("com.github.milkdrinkers:colorparser:2.0.0") {
|
||||
exclude(group = "net.kyori", module = "adventure-api")
|
||||
exclude("net.kyori")
|
||||
}
|
||||
|
||||
implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
|
||||
|
||||
compileOnly("me.clip:placeholderapi:2.11.5") {
|
||||
exclude("me.clip.placeholderapi.libs", "kyori")
|
||||
}
|
||||
compileOnly("com.github.MilkBowl:VaultAPI:1.7")
|
||||
|
||||
compileOnly("com.palmergames.bukkit.towny:towny:0.99.5.7") {
|
||||
exclude(group = "com.palmergames.adventure")
|
||||
}
|
||||
|
||||
compileOnly("me.neznamy:tab-api:4.0.0")
|
||||
|
||||
implementation("dev.jorel:commandapi-bukkit-shade:9.0.3") {
|
||||
exclude(group = "net.kyori", module = "adventure-api")
|
||||
}
|
||||
compileOnly("dev.jorel:commandapi-annotations:9.0.3")
|
||||
annotationProcessor("dev.jorel:commandapi-annotations:9.0.3")
|
||||
|
||||
implementation("com.zaxxer:HikariCP:5.0.1")
|
||||
implementation("org.mariadb.jdbc:mariadb-java-client:3.1.4") {
|
||||
isTransitive = false
|
||||
}
|
||||
|
||||
compileOnly("me.clip:placeholderapi:2.11.3") {
|
||||
exclude(group = "me.clip.placeholderapi.libs", module = "kyori")
|
||||
compileOnly("com.palmergames.bukkit.towny:towny:0.100.0.8") {
|
||||
exclude("com.palmergames.adventure")
|
||||
}
|
||||
compileOnly("me.neznamy:tab-api:4.0.2")
|
||||
compileOnly(files("lib/Graves-4.9.jar"))
|
||||
compileOnly("com.github.Gecolay.GSit:core:1.4.9")
|
||||
compileOnly("com.github.Gecolay.GSit:core:1.5.0")
|
||||
compileOnly(files("lib/HeadsPlus-7.0.14.jar"))
|
||||
compileOnly(files("lib/Skulls.jar"))
|
||||
|
||||
// Database Dependencies
|
||||
implementation("com.zaxxer:HikariCP:5.1.0")
|
||||
library("org.flywaydb:flyway-core:10.8.1")
|
||||
library("org.flywaydb:flyway-mysql:10.8.1")
|
||||
library("org.flywaydb:flyway-database-hsqldb:10.8.1")
|
||||
library("org.jooq:jooq:3.19.3")
|
||||
jooqCodegen("com.h2database:h2:2.2.224")
|
||||
|
||||
// JDBC Drivers
|
||||
library("org.hsqldb:hsqldb:2.7.2")
|
||||
library("com.h2database:h2:2.2.224")
|
||||
library("com.mysql:mysql-connector-j:8.3.0")
|
||||
library("org.mariadb.jdbc:mariadb-java-client:3.3.2")
|
||||
}
|
||||
|
||||
tasks {
|
||||
assemble {
|
||||
dependsOn(reobfJar)
|
||||
}
|
||||
|
||||
build {
|
||||
dependsOn(shadowJar)
|
||||
}
|
||||
|
||||
jooqCodegen {
|
||||
dependsOn(flywayMigrate)
|
||||
}
|
||||
|
||||
compileJava {
|
||||
options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
|
||||
|
||||
// Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable.
|
||||
// See https://openjdk.java.net/jeps/247 for more information.
|
||||
options.release.set(17)
|
||||
options.compilerArgs.add("-Xlint:-deprecation")
|
||||
options.compilerArgs.addAll(arrayListOf("-Xlint:all", "-Xlint:-processing", "-Xdiags:verbose"))
|
||||
|
||||
dependsOn(jooqCodegen) // Generate jOOQ sources before compilation
|
||||
}
|
||||
|
||||
javadoc {
|
||||
isFailOnError = false
|
||||
exclude("${mainPackage.replace(".", "/")}/db/schema/**") // Exclude generated jOOQ sources from javadocs
|
||||
val options = options as StandardJavadocDocletOptions
|
||||
options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything
|
||||
options.overview = "src/main/javadoc/overview.html"
|
||||
options.tags("apiNote:a:API Note:", "implNote:a:Implementation Note:", "implSpec:a:Implementation Requirements:")
|
||||
options.use()
|
||||
}
|
||||
|
||||
processResources {
|
||||
@@ -108,40 +142,118 @@ tasks {
|
||||
archiveClassifier.set("")
|
||||
|
||||
// Shadow classes
|
||||
// helper function to relocate a package into our package
|
||||
fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${project.group}.${targetPkg}")
|
||||
fun reloc(originPkg: String, targetPkg: String) = relocate(originPkg, "${mainPackage}.lib.${targetPkg}")
|
||||
|
||||
reloc("space.arim.morepaperlib", "morepaperlib")
|
||||
reloc("de.leonhard.storage", "storageapi")
|
||||
reloc("com.github.milkdrinkers.Crate", "crate")
|
||||
reloc("com.github.milkdrinkers.colorparser", "colorparser")
|
||||
reloc("dev.jorel.commandapi", "commandapi")
|
||||
reloc("com.zaxxer.hikari", "hikaricp")
|
||||
reloc("org.mariadb.jdbc", "mariadb")
|
||||
|
||||
mergeServiceFiles {
|
||||
setPath("META-INF/services/org.flywaydb.core.extensibility.Plugin") // Fix Flyway overriding its own files
|
||||
}
|
||||
|
||||
minimize()
|
||||
}
|
||||
|
||||
runServer {
|
||||
// Configure the Minecraft version for our task.
|
||||
minecraftVersion("1.19.4")
|
||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005")
|
||||
minecraftVersion("1.20.1")
|
||||
|
||||
// IntelliJ IDEA debugger setup: https://docs.papermc.io/paper/dev/debugging#using-a-remote-debugger
|
||||
jvmArgs("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005", "-DPaper.IgnoreJavaVersion=true", "-Dcom.mojang.eula.agree=true", "-DIReallyKnowWhatIAmDoingISwear")
|
||||
systemProperty("terminal.jline", false)
|
||||
systemProperty("terminal.ansi", true)
|
||||
|
||||
// Automatically install dependencies
|
||||
downloadPlugins {
|
||||
url("https://ci.dmulloy2.net/job/ProtocolLib/lastStableBuild/artifact/build/libs/ProtocolLib.jar")
|
||||
github("MilkBowl", "Vault", "1.7.3", "Vault.jar")
|
||||
url("https://download.luckperms.net/1521/bukkit/loader/LuckPerms-Bukkit-5.4.108.jar")
|
||||
modrinth("tab-was-taken", "4.1.2")
|
||||
github("PlaceholderAPI", "PlaceholderAPI", "2.11.4", "PlaceholderAPI-2.11.4.jar")
|
||||
// url("https://www.spigotmc.org/resources/skulls-the-ultimate-head-database.90098/download?version=520217/Skulls.jar")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bukkit {
|
||||
bukkit { // Options: https://github.com/Minecrell/plugin-yml#bukkit
|
||||
// Plugin main class (required)
|
||||
main = "${project.group}.Main"
|
||||
main = "${mainPackage}.${rootProject.name}"
|
||||
|
||||
// Plugin Information
|
||||
name = project.name
|
||||
prefix = "AlathranWars"
|
||||
prefix = project.name
|
||||
version = "${project.version}"
|
||||
description = "${project.description}"
|
||||
authors = listOf("darksaid98", "ShermansWorld", "NinjaMandalorian", "AubriTheHuman")
|
||||
contributors = listOf()
|
||||
apiVersion = "1.19"
|
||||
apiVersion = "1.20"
|
||||
|
||||
// Misc properties
|
||||
load = net.minecrell.pluginyml.bukkit.BukkitPluginDescription.PluginLoadOrder.POSTWORLD // STARTUP or POSTWORLD
|
||||
depend = listOf("Vault", "Towny")
|
||||
softDepend = listOf("TAB")
|
||||
}
|
||||
softDepend = listOf("PlaceholderAPI", "TAB", "Skulls", "HeadsPlus")
|
||||
}
|
||||
|
||||
flyway {
|
||||
url = "jdbc:h2:${project.layout.buildDirectory.get()}/generated/flyway/db;AUTO_SERVER=TRUE;MODE=MySQL;CASE_INSENSITIVE_IDENTIFIERS=TRUE;IGNORECASE=TRUE"
|
||||
user = "sa"
|
||||
password = ""
|
||||
schemas = listOf("PUBLIC").toTypedArray()
|
||||
placeholders = mapOf( // Substitute placeholders for flyway
|
||||
"tablePrefix" to "",
|
||||
"columnSuffix" to " VIRTUAL",
|
||||
"tableDefaults" to "",
|
||||
"uuidType" to "BINARY(16)",
|
||||
"inetType" to "VARBINARY(16)",
|
||||
"binaryType" to "BLOB",
|
||||
"alterViewStatement" to "ALTER VIEW",
|
||||
)
|
||||
validateMigrationNaming = true
|
||||
baselineOnMigrate = true
|
||||
cleanDisabled = false
|
||||
locations = arrayOf(
|
||||
"filesystem:src/main/resources/db/migration",
|
||||
"classpath:db/migration"
|
||||
)
|
||||
}
|
||||
|
||||
jooq {
|
||||
configuration {
|
||||
logging = Logging.ERROR
|
||||
jdbc {
|
||||
driver = "org.h2.Driver"
|
||||
url = flyway.url
|
||||
user = flyway.user
|
||||
password = flyway.password
|
||||
}
|
||||
generator {
|
||||
database {
|
||||
name = "org.jooq.meta.h2.H2Database"
|
||||
includes = ".*"
|
||||
excludes = "(flyway_schema_history)|(?i:information_schema\\..*)|(?i:system_lobs\\..*)" // Exclude db specific files
|
||||
inputSchema = "PUBLIC"
|
||||
schemaVersionProvider = "SELECT :schema_name || '_' || MAX(\"version\") FROM \"flyway_schema_history\"" // Grab version from Flyway
|
||||
}
|
||||
target {
|
||||
packageName = "${mainPackage}.db.schema"
|
||||
directory = layout.buildDirectory.dir("generated-src/jooq").get().toString()
|
||||
withClean(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply custom version arg
|
||||
val versionArg = if (hasProperty("customVersion"))
|
||||
(properties["customVersion"] as String).uppercase() // Uppercase version string
|
||||
else
|
||||
"${project.version}-SNAPSHOT-${Instant.now().epochSecond}" // Append snapshot to version
|
||||
|
||||
// Strip prefixed "v" from version tag
|
||||
project.version = if (versionArg.first().equals('v', true))
|
||||
versionArg.substring(1)
|
||||
else
|
||||
versionArg.uppercase()
|
||||
@@ -0,0 +1,4 @@
|
||||
org.gradle.caching=true
|
||||
org.gradle.parallel=true
|
||||
org.gradle.daemon=true
|
||||
org.gradle.jvmargs=-Xmx2048M
|
||||
Vendored
BIN
Binary file not shown.
+2
-1
@@ -1,6 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
@@ -69,33 +69,31 @@ app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$(ls -ld "$app_path")
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
APP_HOME=$(cd "${APP_HOME:-./}" && pwd -P) || exit
|
||||
|
||||
# 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"'
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn() {
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die() {
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
@@ -107,24 +105,25 @@ cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$(uname)" in #(
|
||||
CYGWIN*) cygwin=true ;; #(
|
||||
Darwin*) darwin=true ;; #(
|
||||
MSYS* | MINGW*) msys=true ;; #(
|
||||
NONSTOP*) nonstop=true ;;
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ]; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
|
||||
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
|
||||
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
|
||||
@@ -132,30 +131,31 @@ location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
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
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC3045
|
||||
MAX_FD=$(ulimit -H -n) ||
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
;;
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) : ;; #(
|
||||
*)
|
||||
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=SC3045
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
@@ -168,25 +168,23 @@ fi
|
||||
# * 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")
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$(cygpath --unix "$JAVACMD")
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg; do
|
||||
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 ;;
|
||||
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")
|
||||
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
|
||||
@@ -195,25 +193,30 @@ if "$cygwin" || "$msys"; then
|
||||
# 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
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
# 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, 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" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1; then
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
@@ -237,10 +240,10 @@ fi
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
File mode changed.
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,12 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0")
|
||||
}
|
||||
|
||||
rootProject.name = "AlathranWars"
|
||||
@@ -1,7 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
import com.github.alathra.AlathranWars.enums.ConflictType;
|
||||
|
||||
public class Conflict {
|
||||
private ConflictType conflictType;
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Singleton
|
||||
public class WarManager {
|
||||
private static WarManager instance;
|
||||
private @NotNull Set<War> wars = new HashSet<>();
|
||||
|
||||
private WarManager() {
|
||||
if (instance != null)
|
||||
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static WarManager getInstance() {
|
||||
if (instance == null)
|
||||
instance = new WarManager();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void loadAll() {
|
||||
wars = SQLQueries.loadAll();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<War> getWars() {
|
||||
return wars;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public War getWar(String warName) {
|
||||
for (@NotNull War war : wars)
|
||||
if (war.equals(warName)) return war;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public War getWar(UUID uuid) {
|
||||
for (@NotNull War war : wars)
|
||||
if (war.equals(uuid)) return war;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
for (@NotNull War war : wars)
|
||||
if (war.getSide(uuid) != null) return war.getSide(uuid);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
for (@NotNull War war : wars)
|
||||
if (war.getSiege(uuid) != null) return war.getSiege(uuid);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public void addWar(War war) {
|
||||
wars.add(war);
|
||||
}
|
||||
|
||||
public void removeWar(War war) {
|
||||
wars.remove(war);
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnyWars(UUID uuid) {
|
||||
for (@NotNull War war : wars) {
|
||||
if (war.isPlayerInWar(uuid)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnyWars(@NotNull Player p) {
|
||||
return isPlayerInAnyWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
public @NotNull Set<War> getPlayerWars(@NotNull Player p) {
|
||||
return getPlayerWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
public @NotNull Set<War> getPlayerWars(UUID uuid) {
|
||||
return wars.stream()
|
||||
.filter(war -> war.isPlayerInWar(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public boolean isTownInAnyWars(Town town) {
|
||||
for (@NotNull War war : wars) {
|
||||
if (war.isTownInWar(town)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public @NotNull Set<War> getTownWars(Town town) {
|
||||
return wars.stream()
|
||||
.filter(war -> war.isTownInWar(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public boolean isNationInAnyWars(Nation nation) {
|
||||
for (@NotNull War war : wars) {
|
||||
if (war.isNationInWar(nation)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public @NotNull Set<War> getNationWars(Nation nation) {
|
||||
return wars.stream()
|
||||
.filter(war -> war.isNationInWar(nation))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWarNames() {
|
||||
return wars.stream()
|
||||
.map(War::getName)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public List<String> getWarLabels() {
|
||||
return wars.stream()
|
||||
.map(War::getLabel)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
return getWars().stream()
|
||||
.map(War::getSieges)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
return getWars().stream()
|
||||
.map(War::getRaids)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnySiege(@NotNull Player p) {
|
||||
return isPlayerInAnySiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
public boolean isPlayerInAnySiege(UUID uuid) {
|
||||
for (@NotNull Siege siege : getSieges()) {
|
||||
if (siege.isPlayerInSiege(uuid)) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public @NotNull Set<Siege> getPlayerSieges(@NotNull Player p) {
|
||||
return getPlayerSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
public @NotNull Set<Siege> getPlayerSieges(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.isPlayerInSiege(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public @NotNull Set<Nation> getNationsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getNations)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public @NotNull Set<Town> getTownsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getTowns)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle;
|
||||
|
||||
public class Battle {
|
||||
/*private int attackerPoints;
|
||||
private int defenderPoints;
|
||||
|
||||
public int getAttackerPoints() {
|
||||
return this.attackerPoints;
|
||||
}
|
||||
|
||||
public void setAttackerPoints(int points) {
|
||||
this.attackerPoints = points;
|
||||
}
|
||||
|
||||
public int getDefenderPoints() {
|
||||
return this.defenderPoints;
|
||||
}
|
||||
|
||||
public void setDefenderPoints(int points) {
|
||||
this.defenderPoints = points;
|
||||
}
|
||||
|
||||
public void addPointsToAttackers(final int points) {
|
||||
this.attackerPoints += points;
|
||||
}
|
||||
|
||||
public void addPointsToDefenders(final int points) {
|
||||
this.defenderPoints += points;
|
||||
}*/
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.Battle;
|
||||
|
||||
public class Raid extends Battle {
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import de.leonhard.storage.Config;
|
||||
|
||||
public class ConfigManager {
|
||||
private final Main instance;
|
||||
private Config cfg;
|
||||
|
||||
public ConfigManager(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
cfg = new Config("config", instance.getDataFolder().getPath(), instance.getResource("config.yml"));
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
|
||||
public Config getConfig() {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.utility.Config;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class DataManager {
|
||||
private final Main instance;
|
||||
private HikariDataSource hikariDataSource;
|
||||
|
||||
public DataManager(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
openConnection();
|
||||
SQLQueries.initDB();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
closeDatabaseConnection();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (hikariDataSource == null)
|
||||
throw new SQLException("Unable to get a connection from the pool. (hikariDataSource is null)");
|
||||
|
||||
Connection connection = hikariDataSource.getConnection();
|
||||
if (connection == null)
|
||||
throw new SQLException("Unable to get a connection from the pool. (HikariDataSource#getConnection returned null)");
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public HikariDataSource getDataSource() {
|
||||
return hikariDataSource;
|
||||
}
|
||||
|
||||
private void openConnection() {
|
||||
if (hikariDataSource != null)
|
||||
return;
|
||||
|
||||
HikariConfig hikariConfig = new HikariConfig();
|
||||
|
||||
final boolean mysqlEnabled = Config.get().getBoolean("mysql.enabled");
|
||||
|
||||
if (mysqlEnabled) {
|
||||
hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource");
|
||||
hikariConfig.addDataSourceProperty("url", "jdbc:mariadb://%s/%s".formatted(
|
||||
Config.get().get("mysql.host", "127.0.0.1:3306"),
|
||||
Config.get().get("mysql.database", "database")
|
||||
));
|
||||
hikariConfig.setUsername(Config.get().get("mysql.user", "username"));
|
||||
hikariConfig.setPassword(Config.get().get("mysql.pass", "123"));
|
||||
hikariConfig.setConnectionTimeout(5000);
|
||||
hikariConfig.setKeepaliveTime(0);
|
||||
} else {
|
||||
@NotNull File dataFolder = new File(instance.getDataFolder(), "database.db");
|
||||
|
||||
if (!dataFolder.exists()) {
|
||||
try {
|
||||
if (!dataFolder.createNewFile())
|
||||
instance.getLogger().severe("File write error: database.db (1)");
|
||||
} catch (IOException e) {
|
||||
instance.getLogger().severe("File write error: database.db (2) - %s".formatted(e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
hikariConfig.setJdbcUrl("jdbc:sqlite:" + dataFolder);
|
||||
hikariConfig.setConnectionInitSql("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=30000");
|
||||
hikariConfig.setConnectionTimeout(30000);
|
||||
}
|
||||
|
||||
hikariConfig.setPoolName("althranwars-hikari");
|
||||
hikariConfig.setMaximumPoolSize(10);
|
||||
hikariConfig.setMinimumIdle(10);
|
||||
hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
|
||||
|
||||
hikariDataSource = new HikariDataSource(hikariConfig);
|
||||
}
|
||||
|
||||
private void closeDatabaseConnection() {
|
||||
instance.getLogger().info("Closing database connection...");
|
||||
|
||||
if (hikariDataSource == null) {
|
||||
instance.getLogger().severe("Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (hikariDataSource.isClosed()) {
|
||||
instance.getLogger().info("Skipped closing database connection: connection is already closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
hikariDataSource.close();
|
||||
} catch (Exception e) {
|
||||
instance.getLogger().severe("Error closing database connections:");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum BattleTeam {
|
||||
SIDE_1,
|
||||
SIDE_2,
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
|
||||
public enum ConflictType {
|
||||
WAR
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarCreateEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class PreSiegeEndEvent {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class PreSiegeStartEvent {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class SiegeEndEvent {
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.events.battle;
|
||||
|
||||
public class SiegeStartEvent {
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.hooks;
|
||||
|
||||
public class HookManager {
|
||||
public HookManager() {
|
||||
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
TABHook.init();
|
||||
TownyHook.init();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,177 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.hooks;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import me.neznamy.tab.api.TabAPI;
|
||||
import me.neznamy.tab.api.TabPlayer;
|
||||
import me.neznamy.tab.api.event.EventBus;
|
||||
import me.neznamy.tab.api.event.player.PlayerLoadEvent;
|
||||
import me.neznamy.tab.api.nametag.UnlimitedNameTagManager;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
public class TABHook {
|
||||
private static boolean enabled = false;
|
||||
private static TabAPI tabAPI;
|
||||
|
||||
public static void init() {
|
||||
if (enabled) return;
|
||||
|
||||
try {
|
||||
tabAPI = TabAPI.getInstance();
|
||||
enabled = true;
|
||||
|
||||
registerPlayerLoadListener();
|
||||
} catch (NoClassDefFoundError ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerPlayerLoadListener() {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable EventBus eventBus = tabAPI.getEventBus();
|
||||
if (eventBus == null) return;
|
||||
|
||||
eventBus.register(PlayerLoadEvent.class, e -> {
|
||||
@NotNull TabPlayer tabPlayer = e.getPlayer();
|
||||
if (tabPlayer.getPlayer() instanceof Player p)
|
||||
PlayerJoinListener.checkPlayer(p);
|
||||
});
|
||||
}
|
||||
|
||||
public static void assignSide1WarSuffix(@NotNull Player p, @NotNull War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" &c[" + war.getSide1().getName() + "]&r")
|
||||
);
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, "&c");
|
||||
}
|
||||
}
|
||||
|
||||
public static void assignSide2WarSuffix(@NotNull Player p, @NotNull War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, UtilsChat.color(" &9[") + war.getSide2().getName() + "]&r");
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, "&9");
|
||||
}
|
||||
}
|
||||
|
||||
public static void assignSide1WarSuffixMerc(@NotNull Player p, @NotNull War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" &a[M]&c[") + war.getSide1() + "]&r");
|
||||
}
|
||||
|
||||
public static void assignSide2WarSuffixMerc(@NotNull Player p, @NotNull War war) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer,
|
||||
UtilsChat.color(" &a[M]&9[") + war.getSide2() + "]&r");
|
||||
}
|
||||
|
||||
public static void resetSuffix(@NotNull Player p) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
|
||||
public static void resetSuffix(@NotNull String username) {
|
||||
if (!enabled) return;
|
||||
|
||||
@NotNull
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(username);
|
||||
|
||||
try {
|
||||
if (offlinePlayer.isOnline()) {
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(username);
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
} catch (NullPointerException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void resetPrefix(@NotNull Player p) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
|
||||
if (TabAPI.getInstance().getNameTagManager() instanceof UnlimitedNameTagManager unm) {
|
||||
unm.setPrefix(tabPlayer, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static void resetPrefix(@NotNull String playername) {
|
||||
if (!enabled) return;
|
||||
|
||||
@NotNull
|
||||
OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playername);
|
||||
try {
|
||||
if (offlinePlayer.isOnline()) {
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(playername);
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setSuffix(tabPlayer, null);
|
||||
}
|
||||
} catch (NullPointerException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public static void removeColorPrefix(@NotNull Player p, @NotNull String prefix) {
|
||||
if (!enabled) return;
|
||||
|
||||
@Nullable TabPlayer tabPlayer = tabAPI.getPlayer(p.getUniqueId());
|
||||
|
||||
if (prefix.length() > 2) {
|
||||
prefix = prefix.substring(0, prefix.length() - 2);
|
||||
} else {
|
||||
Bukkit.getLogger().info("There is an error when removing a color prefix, prefix not long enough:");
|
||||
Bukkit.getLogger().info("Player: " + p.displayName());
|
||||
Bukkit.getLogger().info("Prefix: " + prefix);
|
||||
Bukkit.getLogger().info("------");
|
||||
}
|
||||
|
||||
|
||||
if (tabAPI.getTabListFormatManager() == null) return;
|
||||
|
||||
tabAPI.getTabListFormatManager().setPrefix(tabPlayer, UtilsChat.color(prefix));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.listeners;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.listeners.items.PlayerInteractListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.BlockBreakPlaceListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.PlayerDeathListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.PlayerQuitListener;
|
||||
import com.github.alathra.AlathranWars.listeners.siege.PlayerSitListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.NationListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.listeners.war.TownListener;
|
||||
|
||||
/**
|
||||
* A class to handle registration of event listeners.
|
||||
*/
|
||||
public class ListenerHandler {
|
||||
private final Main instance;
|
||||
|
||||
public ListenerHandler(Main instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
public void onLoad() {
|
||||
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
// Sieges
|
||||
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.siege.PlayerJoinListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerQuitListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new BlockBreakPlaceListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerDeathListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerSitListener(), instance);
|
||||
|
||||
// Wars
|
||||
instance.getServer().getPluginManager().registerEvents(new NationListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new TownListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerJoinListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new com.github.alathra.AlathranWars.listeners.war.PlayerQuitListener(), instance);
|
||||
|
||||
instance.getServer().getPluginManager().registerEvents(new CommandsListener(), instance);
|
||||
instance.getServer().getPluginManager().registerEvents(new PlayerInteractListener(), instance);
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.listeners.war;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.hooks.TABHook;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class PlayerJoinListener implements Listener {
|
||||
public static void checkPlayer(@NotNull Player p) {
|
||||
final @NotNull UUID uuid = p.getUniqueId();
|
||||
|
||||
if (WarManager.getInstance().isPlayerInAnyWars(uuid)) {
|
||||
for (final @NotNull War war : WarManager.getInstance().getWars()) {
|
||||
if (war.getSide1().isPlayerOnSide(uuid) && !war.getSide1().isPlayerSurrendered(uuid)) {
|
||||
TABHook.assignSide1WarSuffix(p, war);
|
||||
} else if (war.getSide2().isPlayerOnSide(uuid) && !war.getSide2().isPlayerSurrendered(uuid)) {
|
||||
TABHook.assignSide2WarSuffix(p, war);
|
||||
} else if (war.getSide1().isPlayerSurrendered(uuid) || war.getSide2().isPlayerSurrendered(uuid)) {
|
||||
TABHook.resetPrefix(p);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
TABHook.resetPrefix(p);
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
private void onPlayerJoin(@NotNull PlayerJoinEvent e) {
|
||||
final @NotNull Player p = e.getPlayer();
|
||||
if (WarManager.getInstance().isPlayerInAnyWars(p)) {
|
||||
for (@NotNull War war : WarManager.getInstance().getWars()) {
|
||||
if (war.isPlayerInWar(p)) {
|
||||
@Nullable Side side = war.getPlayerSide(p);
|
||||
if (side != null) {
|
||||
side.addOnlinePlayer(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* Convenience class for accessing {@link com.github.alathra.AlathranWars.data.ConfigManager}
|
||||
*/
|
||||
public abstract class Config {
|
||||
public static @NotNull de.leonhard.storage.Config get() {
|
||||
return Main.getInstance().getConfigManager().getConfig();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/**
|
||||
* Convenience class for accessing {@link com.github.alathra.AlathranWars.data.DataManager }
|
||||
*/
|
||||
public abstract class DB {
|
||||
public static @NotNull Connection get() throws SQLException {
|
||||
return Main.getInstance().getDataManager().getConnection();
|
||||
}
|
||||
|
||||
public static @NotNull HikariDataSource getDataSource() {
|
||||
return Main.getInstance().getDataManager().getDataSource();
|
||||
}
|
||||
}
|
||||
@@ -1,629 +0,0 @@
|
||||
package com.github.alathra.AlathranWars.utility;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Convenience class for defining and executing SQL queries
|
||||
*/
|
||||
public abstract class SQLQueries {
|
||||
public static void initDB() {
|
||||
try (final Statement statement = DB.get().createStatement()) {
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_list` (
|
||||
`uuid` uuid NOT NULL DEFAULT uuid(),
|
||||
`name` tinytext NOT NULL,
|
||||
`label` tinytext NOT NULL,
|
||||
`side1` uuid NOT NULL DEFAULT uuid(),
|
||||
`side2` uuid NOT NULL DEFAULT uuid(),
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `side2` (`side2`),
|
||||
KEY `side1` (`side1`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides` (
|
||||
`war` uuid NOT NULL,
|
||||
`uuid` uuid NOT NULL,
|
||||
`side` tinytext NOT NULL,
|
||||
`team` tinytext NOT NULL,
|
||||
`name` tinytext NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
`siegeGrace` timestamp NOT NULL,
|
||||
`raidGrace` timestamp NOT NULL,
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `town` (`town`),
|
||||
KEY `war` (`war`),
|
||||
CONSTRAINT `war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_nations` (
|
||||
`side` uuid NOT NULL,
|
||||
`nation` uuid NOT NULL,
|
||||
KEY `side_nations` (`side`),
|
||||
CONSTRAINT `side_nations` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_nations_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`nation` uuid NOT NULL,
|
||||
KEY `side_nations_surrendered` (`side`),
|
||||
CONSTRAINT `side_nations_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_players` (
|
||||
`side` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `side_players` (`side`),
|
||||
CONSTRAINT `side_players` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_players_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `side_players_surrendered` (`side`),
|
||||
CONSTRAINT `side_players_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_towns` (
|
||||
`side` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
KEY `side_towns` (`side`),
|
||||
CONSTRAINT `side_towns` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sides_towns_surrendered` (
|
||||
`side` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
KEY `side_towns_surrendered` (`side`),
|
||||
CONSTRAINT `side_towns_surrendered` FOREIGN KEY (`side`) REFERENCES `wars_sides` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges` (
|
||||
`war` uuid NOT NULL,
|
||||
`uuid` uuid NOT NULL,
|
||||
`town` uuid NOT NULL,
|
||||
`siegeLeader` uuid NOT NULL,
|
||||
`endTime` timestamp NOT NULL,
|
||||
`lastTouched` timestamp NOT NULL,
|
||||
`siegeProgress` int(11) NOT NULL,
|
||||
PRIMARY KEY (`uuid`),
|
||||
KEY `siege_war` (`war`),
|
||||
CONSTRAINT `siege_war` FOREIGN KEY (`war`) REFERENCES `wars_list` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges_players_attackers` (
|
||||
`siege` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `siege_players_attackers` (`siege`),
|
||||
CONSTRAINT `siege_players_attackers` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.addBatch("""
|
||||
CREATE TABLE IF NOT EXISTS `wars_sieges_players_defenders` (
|
||||
`siege` uuid NOT NULL,
|
||||
`player` uuid NOT NULL,
|
||||
KEY `siege_players_defenders` (`siege`),
|
||||
CONSTRAINT `siege_players_defenders` FOREIGN KEY (`siege`) REFERENCES `wars_sieges` (`uuid`) ON DELETE CASCADE ON UPDATE CASCADE
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci;
|
||||
""");
|
||||
|
||||
statement.executeLargeBatch();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveAll() {
|
||||
try (
|
||||
@NotNull Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("INSERT INTO `wars_list` (`uuid`, `name`, `label`, `side1`, `side2`) VALUES (?, ?, ?, ?, ?) "
|
||||
+ "ON DUPLICATE KEY UPDATE `name` = ?, `label` = ?, `side1` = ?, `side2` = ?")
|
||||
) {
|
||||
// Save wars
|
||||
for (@NotNull War war : WarManager.getInstance().getWars()) {
|
||||
// Insert
|
||||
warStatement.setString(1, war.getUUID().toString());
|
||||
warStatement.setString(2, war.getName());
|
||||
warStatement.setString(3, war.getLabel());
|
||||
warStatement.setString(4, war.getSide1().getUUID().toString());
|
||||
warStatement.setString(5, war.getSide2().getUUID().toString());
|
||||
|
||||
// Update
|
||||
warStatement.setString(6, war.getName());
|
||||
warStatement.setString(7, war.getLabel());
|
||||
warStatement.setString(8, war.getSide1().getUUID().toString());
|
||||
warStatement.setString(9, war.getSide2().getUUID().toString());
|
||||
|
||||
warStatement.executeUpdate();
|
||||
|
||||
// Save sides
|
||||
for (@NotNull Side side : war.getSides()) {
|
||||
saveSide(con, side);
|
||||
}
|
||||
|
||||
// Save sieges
|
||||
for (@NotNull Siege siege : war.getSieges()) {
|
||||
saveSiege(con, siege);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSide(@NotNull Connection con, @NotNull Side side) {
|
||||
try (
|
||||
PreparedStatement sideStatement = con.prepareStatement("INSERT INTO `wars_sides` (`war`, `uuid`, `side`, `team`, `name`, `town`, `siegeGrace`, `raidGrace`) VALUES (?, ?, ?, ?, ?, ?, ?, ?) "
|
||||
+ "ON DUPLICATE KEY UPDATE `side` = ?, `team` = ?, `name` = ?, `town` = ?, `siegeGrace` = ?, `raidGrace` = ?")
|
||||
) {
|
||||
// Insert
|
||||
sideStatement.setString(1, side.getWar().getUUID().toString());
|
||||
sideStatement.setString(2, side.getUUID().toString());
|
||||
sideStatement.setString(3, side.getSide().toString());
|
||||
sideStatement.setString(4, side.getTeam().toString());
|
||||
sideStatement.setString(5, side.getName());
|
||||
sideStatement.setString(6, side.getTown().getUUID().toString());
|
||||
sideStatement.setTimestamp(7, Timestamp.from(side.getSiegeGrace()));
|
||||
sideStatement.setTimestamp(8, Timestamp.from(side.getRaidGrace()));
|
||||
|
||||
// Update
|
||||
sideStatement.setString(9, side.getSide().toString());
|
||||
sideStatement.setString(10, side.getTeam().toString());
|
||||
sideStatement.setString(11, side.getName());
|
||||
sideStatement.setString(12, side.getTown().getUUID().toString());
|
||||
sideStatement.setTimestamp(13, Timestamp.from(side.getSiegeGrace()));
|
||||
sideStatement.setTimestamp(14, Timestamp.from(side.getRaidGrace()));
|
||||
|
||||
sideStatement.executeUpdate();
|
||||
|
||||
saveSideNations(con, side, false);
|
||||
saveSideNations(con, side, true);
|
||||
saveSideTowns(con, side, false);
|
||||
saveSideTowns(con, side, true);
|
||||
saveSidePlayers(con, side, false);
|
||||
saveSidePlayers(con, side, true);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSideNations(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `nation`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (@NotNull Nation nation : (surrendered ? side.getSurrenderedNations() : side.getNations())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, nation.getUUID().toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch (Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSideTowns(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `town`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (@NotNull Town town : (surrendered ? side.getSurrenderedTowns() : side.getTowns())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, town.getUUID().toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch (Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSidePlayers(@NotNull Connection con, @NotNull Side side, boolean surrendered) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`side`, `player`) VALUES (?, ?)".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, side.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (@NotNull UUID uuid : (surrendered ? side.getSurrenderedPlayersIncludingOffline() : side.getPlayersIncludingOffline())) {
|
||||
insertStatement.setString(1, side.getUUID().toString());
|
||||
insertStatement.setString(2, uuid.toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch (Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static @NotNull Set<War> loadAll() {
|
||||
@NotNull Set<War> wars = new HashSet<>();
|
||||
|
||||
try (
|
||||
@NotNull Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_list`")
|
||||
) {
|
||||
// Load all wars
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get wars from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
// War data
|
||||
@NotNull UUID uuid = UUID.fromString(warsResult.getString("uuid"));
|
||||
String name = warsResult.getString("name");
|
||||
String label = warsResult.getString("label");
|
||||
@NotNull UUID side1UUID = UUID.fromString(warsResult.getString("side1"));
|
||||
@NotNull UUID side2UUID = UUID.fromString(warsResult.getString("side2"));
|
||||
@NotNull Side side1 = loadSide(con, uuid, side1UUID);
|
||||
@NotNull Side side2 = loadSide(con, uuid, side2UUID);
|
||||
|
||||
wars.add(new War(
|
||||
uuid,
|
||||
name,
|
||||
label,
|
||||
side1,
|
||||
side2,
|
||||
new HashSet<>(),
|
||||
new HashSet<>()
|
||||
));
|
||||
}
|
||||
|
||||
for (War war : wars) {
|
||||
@NotNull Set<Siege> sieges = loadSieges(con, war);
|
||||
war.setSieges(sieges);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return wars;
|
||||
}
|
||||
|
||||
@Contract("_, _, _ -> new")
|
||||
public static @NotNull Side loadSide(@NotNull Connection con, @NotNull UUID warUUID, @NotNull UUID uuid) {
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `wars_sides` WHERE `war` = ? AND `uuid` = ?")) {
|
||||
// Load side
|
||||
warStatement.setString(1, warUUID.toString());
|
||||
warStatement.setString(2, uuid.toString());
|
||||
ResultSet sideResult = warStatement.executeQuery();
|
||||
|
||||
if (sideResult == null)
|
||||
throw new SQLException("Failed to get side from DB");
|
||||
|
||||
sideResult.next();
|
||||
|
||||
// Side data
|
||||
@NotNull BattleSide side = BattleSide.valueOf(sideResult.getString("side"));
|
||||
@NotNull BattleTeam team = BattleTeam.valueOf(sideResult.getString("team"));
|
||||
String name = sideResult.getString("name");
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(sideResult.getString("town")));
|
||||
Instant siegeGrace = sideResult.getTimestamp("siegeGrace").toInstant();
|
||||
Instant raidGrace = sideResult.getTimestamp("raidGrace").toInstant();
|
||||
|
||||
@NotNull Set<UUID> players = loadSidePlayers(con, uuid, false);
|
||||
@NotNull Set<UUID> playersSurrendered = loadSidePlayers(con, uuid, true);
|
||||
@NotNull Set<Nation> nations = loadSideNations(con, uuid, false);
|
||||
@NotNull Set<Nation> nationsSurrendered = loadSideNations(con, uuid, true);
|
||||
@NotNull Set<Town> towns = loadSideTowns(con, uuid, false);
|
||||
@NotNull Set<Town> townsSurrendered = loadSideTowns(con, uuid, true);
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
town,
|
||||
side,
|
||||
team,
|
||||
name,
|
||||
towns,
|
||||
nations,
|
||||
players,
|
||||
townsSurrendered,
|
||||
nationsSurrendered,
|
||||
playersSurrendered,
|
||||
siegeGrace,
|
||||
raidGrace
|
||||
);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static @NotNull Set<UUID> loadSidePlayers(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
|
||||
@NotNull Set<UUID> players = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_players_surrendered" : "wars_sides_players"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get players from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
players.add(UUID.fromString(warsResult.getString("player")));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
public static @NotNull Set<Nation> loadSideNations(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
|
||||
@NotNull Set<Nation> nations = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_nations_surrendered" : "wars_sides_nations"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get nations from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
final @NotNull UUID uuid = UUID.fromString(warsResult.getString("nation"));
|
||||
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(uuid);
|
||||
if (nation == null) continue;
|
||||
|
||||
nations.add(nation);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return nations;
|
||||
}
|
||||
|
||||
public static @NotNull Set<Town> loadSideTowns(@NotNull Connection con, @NotNull UUID sideUUID, boolean surrendered) {
|
||||
@NotNull Set<Town> towns = new HashSet<>();
|
||||
|
||||
try (PreparedStatement warStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `side` = ?".formatted(surrendered ? "wars_sides_towns_surrendered" : "wars_sides_towns"))) {
|
||||
warStatement.setString(1, sideUUID.toString());
|
||||
ResultSet warsResult = warStatement.executeQuery();
|
||||
|
||||
if (warsResult == null)
|
||||
throw new SQLException("Failed to get towns from DB");
|
||||
|
||||
while (warsResult.next()) {
|
||||
final @NotNull UUID uuid = UUID.fromString(warsResult.getString("town"));
|
||||
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(uuid);
|
||||
if (town == null) continue;
|
||||
|
||||
towns.add(town);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return towns;
|
||||
}
|
||||
|
||||
public static @NotNull Set<Siege> loadSieges(@NotNull Connection con, @NotNull War war) {
|
||||
@NotNull Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
try (PreparedStatement siegesStatement = con.prepareStatement("SELECT * FROM `wars_sieges` WHERE `war` = ?")) {
|
||||
siegesStatement.setString(1, war.getUUID().toString());
|
||||
ResultSet siegesResults = siegesStatement.executeQuery();
|
||||
|
||||
if (siegesResults == null)
|
||||
throw new SQLException("Failed to get sieges from DB");
|
||||
|
||||
while (siegesResults.next()) {
|
||||
final UUID uuid = UUID.fromString(siegesResults.getString("uuid"));
|
||||
final @Nullable Town town = TownyAPI.getInstance().getTown(UUID.fromString(siegesResults.getString("town")));
|
||||
final OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(UUID.fromString(siegesResults.getString("siegeLeader")));
|
||||
final Instant endTime = siegesResults.getTimestamp("endTime").toInstant();
|
||||
final Instant lastTouched = siegesResults.getTimestamp("lastTouched").toInstant();
|
||||
final int siegeProgress = siegesResults.getInt("siegeProgress");
|
||||
final Set<UUID> attackersIncludingOffline = loadSiegePlayers(con, uuid, true);
|
||||
final Set<UUID> defendersIncludingOffline = loadSiegePlayers(con, uuid, false);
|
||||
|
||||
if (town == null) continue;
|
||||
|
||||
sieges.add(new Siege(
|
||||
war,
|
||||
uuid,
|
||||
town,
|
||||
siegeLeader,
|
||||
endTime,
|
||||
lastTouched,
|
||||
siegeProgress,
|
||||
attackersIncludingOffline,
|
||||
defendersIncludingOffline
|
||||
));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return sieges;
|
||||
}
|
||||
|
||||
public static @NotNull Set<UUID> loadSiegePlayers(@NotNull Connection con, @NotNull UUID siegeUUID, boolean getAttackers) {
|
||||
@NotNull Set<UUID> players = new HashSet<>();
|
||||
|
||||
try (PreparedStatement siegeStatement = con.prepareStatement("SELECT * FROM `%s` WHERE `siege` = ?".formatted(getAttackers ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"))) {
|
||||
siegeStatement.setString(1, siegeUUID.toString());
|
||||
ResultSet playersResult = siegeStatement.executeQuery();
|
||||
|
||||
if (playersResult == null)
|
||||
throw new SQLException("Failed to get players from DB");
|
||||
|
||||
while (playersResult.next()) {
|
||||
players.add(UUID.fromString(playersResult.getString("player")));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
public static void deleteWar(@NotNull War war) {
|
||||
try (
|
||||
@NotNull Connection con = DB.get();
|
||||
PreparedStatement warStatement = con.prepareStatement("DELETE FROM `wars_list` WHERE `uuid` = ?")
|
||||
) {
|
||||
// Delete war data
|
||||
warStatement.setString(1, war.getUUID().toString());
|
||||
warStatement.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteSiege(@NotNull Siege siege) {
|
||||
try (
|
||||
@NotNull Connection con = DB.get();
|
||||
PreparedStatement siegesStatement = con.prepareStatement("DELETE FROM `wars_sieges` WHERE `uuid` = ?")
|
||||
) {
|
||||
// Delete siege data
|
||||
siegesStatement.setString(1, siege.getUUID().toString());
|
||||
siegesStatement.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSiege(@NotNull Connection con, @NotNull Siege siege) {
|
||||
try (
|
||||
PreparedStatement siegeStatement = con.prepareStatement("INSERT INTO `wars_sieges` (`war`, `uuid`, `town`, `siegeLeader`, `endTime`, `lastTouched`, `siegeProgress`) VALUES (?, ?, ?, ?, ?, ?, ?) "
|
||||
+ "ON DUPLICATE KEY UPDATE `war` = ?, `town` = ?, `siegeLeader` = ?, `endTime` = ?, `lastTouched` = ?, `siegeProgress` = ?")
|
||||
) {
|
||||
// Insert
|
||||
siegeStatement.setString(1, siege.getWar().getUUID().toString());
|
||||
siegeStatement.setString(2, siege.getUUID().toString());
|
||||
siegeStatement.setString(3, siege.getTown().getUUID().toString());
|
||||
siegeStatement.setString(4, siege.getSiegeLeader().getUniqueId().toString());
|
||||
siegeStatement.setTimestamp(5, Timestamp.from(siege.getEndTime()));
|
||||
siegeStatement.setTimestamp(6, Timestamp.from(siege.getLastTouched()));
|
||||
siegeStatement.setInt(7, siege.getSiegeProgress());
|
||||
|
||||
// Update
|
||||
siegeStatement.setString(8, siege.getWar().getUUID().toString());
|
||||
siegeStatement.setString(9, siege.getTown().getUUID().toString());
|
||||
siegeStatement.setString(10, siege.getSiegeLeader().getUniqueId().toString());
|
||||
siegeStatement.setTimestamp(11, Timestamp.from(siege.getEndTime()));
|
||||
siegeStatement.setTimestamp(12, Timestamp.from(siege.getLastTouched()));
|
||||
siegeStatement.setInt(13, siege.getSiegeProgress());
|
||||
|
||||
siegeStatement.executeUpdate();
|
||||
|
||||
saveSiegePlayers(con, siege, false);
|
||||
saveSiegePlayers(con, siege, true);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSiegePlayers(@NotNull Connection con, @NotNull Siege siege, boolean isAttacker) throws SQLException {
|
||||
try (
|
||||
PreparedStatement deleteStatement = con.prepareStatement("DELETE FROM `%s` WHERE `siege` = ?".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"));
|
||||
PreparedStatement insertStatement = con.prepareStatement("INSERT INTO `%s` (`siege`, `player`) VALUES (?, ?)".formatted(isAttacker ? "wars_sieges_players_attackers" : "wars_sieges_players_defenders"))
|
||||
) {
|
||||
try {
|
||||
// Transaction start
|
||||
con.setAutoCommit(false);
|
||||
|
||||
// Delete old
|
||||
deleteStatement.setString(1, siege.getUUID().toString());
|
||||
deleteStatement.executeUpdate();
|
||||
|
||||
// Insert new
|
||||
for (@NotNull UUID uuid : (isAttacker ? siege.getAttackerPlayersIncludingOffline() : siege.getDefenderPlayersIncludingOffline())) {
|
||||
insertStatement.setString(1, siege.getUUID().toString());
|
||||
insertStatement.setString(2, uuid.toString());
|
||||
insertStatement.executeUpdate();
|
||||
}
|
||||
|
||||
// Transaction end
|
||||
con.commit();
|
||||
} catch (Exception e) {
|
||||
con.rollback();
|
||||
} finally {
|
||||
con.setAutoCommit(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+44
-44
@@ -1,13 +1,13 @@
|
||||
package com.github.alathra.AlathranWars;
|
||||
package com.github.alathra.alathranwars;
|
||||
|
||||
import com.github.alathra.AlathranWars.commands.CommandManager;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.data.ConfigManager;
|
||||
import com.github.alathra.AlathranWars.data.DataManager;
|
||||
import com.github.alathra.AlathranWars.hooks.HookManager;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.listeners.ListenerHandler;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.github.alathra.alathranwars.commands.CommandManager;
|
||||
import com.github.alathra.alathranwars.config.ConfigHandler;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.db.DatabaseHandler;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.hooks.HookManager;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.listeners.ListenerHandler;
|
||||
import net.milkbowl.vault.economy.Economy;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
@@ -15,26 +15,18 @@ import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import space.arim.morepaperlib.MorePaperLib;
|
||||
|
||||
public class Main extends JavaPlugin {
|
||||
public class AlathranWars extends JavaPlugin {
|
||||
public static @Nullable Economy econ = null;
|
||||
private static Main instance = null;
|
||||
private static MorePaperLib paperLib;
|
||||
|
||||
private ConfigManager configManager;
|
||||
private DataManager dataManager;
|
||||
private CommandManager commandManager;
|
||||
private static AlathranWars instance;
|
||||
private ConfigHandler configHandler;
|
||||
private DatabaseHandler databaseHandler;
|
||||
private ListenerHandler listenerHandler;
|
||||
|
||||
private CommandManager commandManager;
|
||||
private HookManager hookManager;
|
||||
|
||||
@NotNull
|
||||
public static Main getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public static MorePaperLib getPaperLib() {
|
||||
return paperLib;
|
||||
}
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private boolean setupEconomy() {
|
||||
if (this.getServer().getPluginManager().getPlugin("Vault") == null) {
|
||||
@@ -49,54 +41,62 @@ public class Main extends JavaPlugin {
|
||||
return econ != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
instance = this;
|
||||
paperLib = new MorePaperLib(getInstance());
|
||||
WarManager.getInstance();
|
||||
configManager = new ConfigManager(getInstance());
|
||||
dataManager = new DataManager(getInstance());
|
||||
commandManager = new CommandManager(getInstance());
|
||||
listenerHandler = new ListenerHandler(getInstance());
|
||||
paperLib = new MorePaperLib(instance);
|
||||
WarController.getInstance();
|
||||
configHandler = new ConfigHandler(instance);
|
||||
databaseHandler = new DatabaseHandler(instance);
|
||||
commandManager = new CommandManager(instance);
|
||||
listenerHandler = new ListenerHandler(instance);
|
||||
hookManager = new HookManager();
|
||||
|
||||
configManager.onLoad();
|
||||
dataManager.onLoad();
|
||||
configHandler.onLoad();
|
||||
databaseHandler.onLoad();
|
||||
commandManager.onLoad();
|
||||
listenerHandler.onLoad();
|
||||
hookManager.onLoad();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
this.saveDefaultConfig();
|
||||
new WarItemRegistry();
|
||||
setupEconomy();
|
||||
|
||||
configManager.onEnable();
|
||||
dataManager.onEnable();
|
||||
configHandler.onEnable();
|
||||
databaseHandler.onEnable();
|
||||
commandManager.onEnable();
|
||||
listenerHandler.onEnable();
|
||||
hookManager.onEnable();
|
||||
WarManager.getInstance().loadAll();
|
||||
WarController.getInstance().loadAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
getPaperLib().scheduling().cancelGlobalTasks();
|
||||
SQLQueries.saveAll();
|
||||
configManager.onDisable();
|
||||
DatabaseQueries.saveAll();
|
||||
commandManager.onDisable();
|
||||
listenerHandler.onDisable();
|
||||
hookManager.onDisable();
|
||||
dataManager.onDisable();
|
||||
databaseHandler.onDisable();
|
||||
configHandler.onDisable();
|
||||
}
|
||||
|
||||
public ConfigManager getConfigManager() {
|
||||
return configManager;
|
||||
@NotNull
|
||||
public static AlathranWars getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
public DataManager getDataManager() {
|
||||
return dataManager;
|
||||
public static MorePaperLib getPaperLib() {
|
||||
return paperLib;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public DatabaseHandler getDataHandler() {
|
||||
return databaseHandler;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public ConfigHandler getConfigHandler() {
|
||||
return configHandler;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.github.alathra.alathranwars;
|
||||
|
||||
/**
|
||||
* Implemented in classes that should support being reloaded IE executing the methods during runtime after startup.
|
||||
*/
|
||||
public interface Reloadable {
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
void onLoad();
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
void onEnable();
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
void onDisable();
|
||||
}
|
||||
+19
-7
@@ -1,8 +1,9 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
@@ -12,6 +13,7 @@ import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import dev.jorel.commandapi.executors.CommandArguments;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -24,7 +26,8 @@ public class AdminCommands {
|
||||
.withSubcommands(
|
||||
commandItem(),
|
||||
commandWar(),
|
||||
commandSiege()
|
||||
commandSiege(),
|
||||
commandNames()
|
||||
)
|
||||
.executes((sender, args) -> {
|
||||
if (args.count() == 0)
|
||||
@@ -51,7 +54,7 @@ public class AdminCommands {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Invalid item argument.").build());
|
||||
|
||||
@Nullable ItemStack stack;
|
||||
if (argItem.contains(Main.getInstance().getName().toLowerCase())) {
|
||||
if (argItem.contains(AlathranWars.getInstance().getName().toLowerCase())) {
|
||||
stack = WarItemRegistry.getInstance().getOrNullNamespace(argItem);
|
||||
} else {
|
||||
stack = WarItemRegistry.getInstance().getOrNull(argItem);
|
||||
@@ -96,9 +99,11 @@ public class AdminCommands {
|
||||
WarCommands.commandCreate(true),
|
||||
WarCommands.commandDelete(true),
|
||||
WarCommands.commandJoin(true),
|
||||
WarCommands.commandJoinNear(),
|
||||
WarCommands.commandSurrender(true),
|
||||
WarCommands.commandList(),
|
||||
WarCommands.commandInfo()
|
||||
WarCommands.commandInfo(),
|
||||
WarCommands.commandKick()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -112,4 +117,11 @@ public class AdminCommands {
|
||||
SiegeCommands.commandList()
|
||||
);
|
||||
}
|
||||
|
||||
private CommandAPICommand commandNames() {
|
||||
return new CommandAPICommand("updatenames")
|
||||
.executesPlayer((player, commandArguments) -> {
|
||||
Bukkit.getOnlinePlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
});
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import dev.jorel.commandapi.CommandAPI;
|
||||
import dev.jorel.commandapi.CommandAPIBukkitConfig;
|
||||
|
||||
public class CommandManager {
|
||||
private final Main instance;
|
||||
private final AlathranWars instance;
|
||||
|
||||
public CommandManager(Main instance) {
|
||||
public CommandManager(AlathranWars instance) {
|
||||
this.instance = instance;
|
||||
}
|
||||
|
||||
+91
-30
@@ -1,15 +1,15 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.CommandArgsSiege;
|
||||
import com.github.alathra.AlathranWars.enums.CommandArgsWar;
|
||||
import com.github.alathra.AlathranWars.hooks.TownyHook;
|
||||
import com.github.alathra.AlathranWars.items.WarItemRegistry;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsSiege;
|
||||
import com.github.alathra.alathranwars.enums.CommandArgsWar;
|
||||
import com.github.alathra.alathranwars.hooks.TownyHook;
|
||||
import com.github.alathra.alathranwars.items.WarItemRegistry;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
@@ -22,12 +22,15 @@ import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.CustomArgument;
|
||||
import dev.jorel.commandapi.arguments.StringArgument;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -225,7 +228,6 @@ public class CommandUtil {
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Accepts all towns and nations as argument. Returns a string.
|
||||
*
|
||||
@@ -288,6 +290,64 @@ public class CommandUtil {
|
||||
}));
|
||||
}
|
||||
|
||||
static public Argument<UUID> playerOrTownOrNationInWar(String nodeName, String warNodeName) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argPlayerOrTownOrNationName = info.input();
|
||||
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war)) {
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
|
||||
ColorParser.of(UtilsChat.getPrefix() + "<red>The war does not exist!")
|
||||
.build()
|
||||
);
|
||||
}
|
||||
|
||||
final List<String> townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersIncludingOffline().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.filter(p -> p.getName() != null)
|
||||
.map(OfflinePlayer::getName)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
|
||||
if (townNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName) != null)
|
||||
return TownyAPI.getInstance().getTown(argPlayerOrTownOrNationName).getUUID();
|
||||
|
||||
if (nationNames.contains(argPlayerOrTownOrNationName) && TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName) != null)
|
||||
return TownyAPI.getInstance().getNation(argPlayerOrTownOrNationName).getUUID();
|
||||
|
||||
if (playerNames.contains(argPlayerOrTownOrNationName))
|
||||
return Bukkit.getOfflinePlayer(argPlayerOrTownOrNationName).getUniqueId();
|
||||
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(
|
||||
ColorParser.of(UtilsChat.getPrefix() + "<red>The player, town or nation <name> is not in the war!")
|
||||
.parseMinimessagePlaceholder("name", argPlayerOrTownOrNationName)
|
||||
.build()
|
||||
);
|
||||
}).replaceSuggestions(ArgumentSuggestions.stringCollection(info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
final List<String> nationNames = war.getNations().stream().map(Nation::getName).sorted().toList();
|
||||
final List<String> townNames = war.getTowns().stream().map(Town::getName).sorted().toList();
|
||||
final List<String> playerNames = war.getPlayersIncludingOffline().stream()
|
||||
.filter(offlinePlayer -> Instant.ofEpochMilli(offlinePlayer.getLastSeen()).isAfter(Instant.now().minus(Duration.ofDays(60)))) // Remove players that haven't been on in 60 days
|
||||
.filter(p -> p.getName() != null)
|
||||
.map(OfflinePlayer::getName)
|
||||
.sorted()
|
||||
.toList();
|
||||
|
||||
final List<String> recommendations = new ArrayList<>();
|
||||
recommendations.addAll(nationNames);
|
||||
recommendations.addAll(townNames);
|
||||
recommendations.addAll(playerNames);
|
||||
|
||||
return recommendations;
|
||||
}));
|
||||
}
|
||||
|
||||
public static Argument<Town> customSiegeAttackableTownArgument(String nodeName, String warNodeName, final boolean checkIfIn, final boolean checkIfSieged) {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
if (!(info.previousArgs().get(warNodeName) instanceof War war))
|
||||
@@ -302,7 +362,7 @@ public class CommandUtil {
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is not in that war!").parseLegacy().build());
|
||||
|
||||
if (checkIfSieged) {
|
||||
for (@NotNull Siege siege : WarManager.getInstance().getSieges()) {
|
||||
for (@NotNull Siege siege : WarController.getInstance().getSieges()) {
|
||||
if (siege.getTown().getUUID() == town.getUUID())
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The town is already under siege!").parseLegacy().build());
|
||||
}
|
||||
@@ -342,13 +402,13 @@ public class CommandUtil {
|
||||
final String argSiegeName = info.input();
|
||||
|
||||
@Nullable UUID siegeUUID = null;
|
||||
for (Siege siege : WarManager.getInstance().getSieges()) {
|
||||
for (Siege siege : WarController.getInstance().getSieges()) {
|
||||
if (siege.getName().equals(argSiegeName)) {
|
||||
siegeUUID = siege.getUUID();
|
||||
}
|
||||
}
|
||||
|
||||
final @Nullable Siege siege = WarManager.getInstance().getSiege(siegeUUID);
|
||||
final @Nullable Siege siege = WarController.getInstance().getSiege(siegeUUID);
|
||||
if (siege == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The siege <siege> does not exist!").parseMinimessagePlaceholder("siege", argSiegeName).build());
|
||||
|
||||
@@ -394,7 +454,7 @@ public class CommandUtil {
|
||||
}
|
||||
|
||||
private static List<String> siegeAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
|
||||
return WarManager.getInstance().getSieges().stream().map(Siege::getName).toList();
|
||||
return WarController.getInstance().getSieges().stream().map(Siege::getName).toList();
|
||||
}
|
||||
|
||||
private static List<String> siegeOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
@@ -402,11 +462,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> !siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -418,11 +478,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
siegeNames = WarManager.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
siegeNames = WarController.getInstance().getSieges().stream().filter(siege -> siege.isPlayerInSiege(player)).map(Siege::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,7 +493,7 @@ public class CommandUtil {
|
||||
return new CustomArgument<>(new StringArgument(nodeName), info -> {
|
||||
final String argWarName = info.input();
|
||||
|
||||
final @Nullable War war = WarManager.getInstance().getWar(argWarName);
|
||||
final @Nullable War war = WarController.getInstance().getWar(argWarName);
|
||||
if (war == null)
|
||||
throw CustomArgument.CustomArgumentException.fromAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>The war <war> does not exist!").parseMinimessagePlaceholder("war", argWarName).build());
|
||||
|
||||
@@ -479,7 +539,7 @@ public class CommandUtil {
|
||||
}
|
||||
|
||||
private static List<String> warsAll(SuggestionInfo<CommandSender> info, final boolean isAdmin) {
|
||||
return WarManager.getInstance().getWarNames();
|
||||
return WarController.getInstance().getWarNames();
|
||||
}
|
||||
|
||||
private static List<String> warsOutside(SuggestionInfo<CommandSender> info, final boolean isAdmin, final String playerNodeName) {
|
||||
@@ -487,11 +547,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarManager.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarManager.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> !war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -503,11 +563,11 @@ public class CommandUtil {
|
||||
|
||||
if (isAdmin) {
|
||||
if (info.previousArgs().get(playerNodeName) instanceof Player player) {
|
||||
warNames = WarManager.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
} else {
|
||||
if (info.sender() instanceof Player player) {
|
||||
warNames = WarManager.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
warNames = WarController.getInstance().getWars().stream().filter(war -> war.isPlayerInWar(player)).map(War::getName).toList();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -641,14 +701,15 @@ public class CommandUtil {
|
||||
long regTime = res.getRegistered();
|
||||
int playTicks = Bukkit.getPlayer(res.getUUID()).getStatistic(Statistic.PLAY_ONE_MINUTE);
|
||||
int out = 0;
|
||||
if (Main.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
|
||||
if (AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge") > 0) {
|
||||
//compare the join date, if they joined less that min age ago it is true
|
||||
if ((System.currentTimeMillis() - regTime) < 86400000L * Main.getInstance().getConfig().getInt("minimumPlayerAge"))
|
||||
if ((System.currentTimeMillis() - regTime) < 86400000L * AlathranWars.getInstance().getConfig().getInt("minimumPlayerAge"))
|
||||
out = 1;
|
||||
}
|
||||
if (Main.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
|
||||
if (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") > 0) {
|
||||
//check playtime, if its less than min its true
|
||||
if (playTicks < (Main.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20))) out = 2;
|
||||
if (playTicks < (AlathranWars.getInstance().getConfig().getInt("minimumPlayTime") * (60 * 60 * 20)))
|
||||
out = 2;
|
||||
}
|
||||
|
||||
return out;
|
||||
+17
-28
@@ -1,11 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
@@ -26,10 +27,10 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
|
||||
import static com.github.alathra.AlathranWars.enums.CommandArgsSiege.ALL_SIEGES;
|
||||
import static com.github.alathra.AlathranWars.enums.CommandArgsSiege.IN_SIEGE;
|
||||
import static com.github.alathra.AlathranWars.enums.CommandArgsWar.ALL_WARS;
|
||||
import static com.github.alathra.AlathranWars.enums.CommandArgsWar.IN_WAR;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.ALL_SIEGES;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsSiege.IN_SIEGE;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.ALL_WARS;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.IN_WAR;
|
||||
|
||||
public class SiegeCommands {
|
||||
public SiegeCommands() {
|
||||
@@ -151,7 +152,7 @@ public class SiegeCommands {
|
||||
if (location.distance(townLocation) <= Siege.BATTLEFIELD_START_MIN_RANGE && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to be further than <range> blocks away from the town to start a siege!").parseMinimessagePlaceholder("range", String.valueOf(Siege.BATTLEFIELD_START_MIN_RANGE)).build());
|
||||
|
||||
if ((Main.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
|
||||
if ((AlathranWars.econ.getBalance(siegeLeader) < Siege.SIEGE_VICTORY_MONEY) && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You need to have $<amount> to start a siege!").parseMinimessagePlaceholder("amount", String.valueOf(Siege.SIEGE_VICTORY_MONEY)).build());
|
||||
|
||||
side.setSiegeGrace();
|
||||
@@ -176,7 +177,7 @@ public class SiegeCommands {
|
||||
if (!(args.get("siege") instanceof final @NotNull Siege siege))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid siege.").build());
|
||||
|
||||
siege.noWinner();
|
||||
siege.equalWin(BattleVictoryReason.ADMIN_COMMAND);
|
||||
}
|
||||
|
||||
private static void siegeAbandon(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
@@ -187,13 +188,7 @@ public class SiegeCommands {
|
||||
if (siegeLeader != p && !asAdmin)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You are not the leader of this siege.").build());
|
||||
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of("<prefix>The siege at <town> has been abandoned.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", siege.getTown().getName())
|
||||
.build()
|
||||
);
|
||||
siege.defendersWin();
|
||||
siege.defendersWin(BattleVictoryReason.OPPONENT_RETREAT);
|
||||
}
|
||||
|
||||
private static void siegeSurrender(Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
@@ -212,17 +207,11 @@ public class SiegeCommands {
|
||||
if (!asAdmin && !canKingSurrender && !canMayorSurrender)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>You cannot surrender this town.").build());
|
||||
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of("<prefix>The town of <town> has surrendered.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", siege.getTown().getName())
|
||||
.build()
|
||||
);
|
||||
siege.attackersWin();
|
||||
siege.attackersWin(BattleVictoryReason.OPPONENT_RETREAT);
|
||||
}
|
||||
|
||||
private static void siegeList(@NotNull Player sender, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<Siege> sieges = WarManager.getInstance().getSieges();
|
||||
Set<Siege> sieges = WarController.getInstance().getSieges();
|
||||
|
||||
if (sieges.isEmpty()) {
|
||||
sender.sendMessage(ColorParser.of("<red>There are no sieges at the moment.").build());
|
||||
+210
-93
@@ -1,10 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.commands;
|
||||
package com.github.alathra.alathranwars.commands;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.WarManager;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
@@ -13,6 +15,7 @@ import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
import dev.jorel.commandapi.CommandAPICommand;
|
||||
import dev.jorel.commandapi.arguments.ArgumentSuggestions;
|
||||
import dev.jorel.commandapi.arguments.BooleanArgument;
|
||||
import dev.jorel.commandapi.arguments.GreedyStringArgument;
|
||||
import dev.jorel.commandapi.arguments.PlayerArgument;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
@@ -21,6 +24,8 @@ import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
@@ -32,7 +37,7 @@ import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.github.alathra.AlathranWars.enums.CommandArgsWar.*;
|
||||
import static com.github.alathra.alathranwars.enums.CommandArgsWar.*;
|
||||
|
||||
public class WarCommands {
|
||||
public WarCommands() {
|
||||
@@ -58,6 +63,7 @@ public class WarCommands {
|
||||
.withArguments(
|
||||
CommandUtil.customTownAndNationArgument("side1", "war", false),
|
||||
CommandUtil.customTownAndNationArgument("side2", "war", false),
|
||||
new BooleanArgument("event"),
|
||||
new GreedyStringArgument("warlabel")
|
||||
.replaceSuggestions(
|
||||
ArgumentSuggestions.stringCollection(info -> List.of(
|
||||
@@ -81,6 +87,7 @@ public class WarCommands {
|
||||
|
||||
public static CommandAPICommand commandJoin(boolean asAdmin) {
|
||||
return new CommandAPICommand("join")
|
||||
.withPermission("AlathranWars.war.join")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", asAdmin, asAdmin ? ALL_WARS : OUT_WAR, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", asAdmin, !asAdmin, ""),
|
||||
@@ -89,7 +96,17 @@ public class WarCommands {
|
||||
// new PlayerArgument("nation").setOptional(true).withPermission("AlathranWars.admin.join"),
|
||||
// new PlayerArgument("town").setOptional(true).withPermission("AlathranWars.admin.join")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, false));
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoin(p, args, asAdmin));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandJoinNear() {
|
||||
return new CommandAPICommand("joinnear")
|
||||
.withPermission("AlathranWars.admin")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", true, ALL_WARS, ""),
|
||||
CommandUtil.warSideCreateArgument("side", "war", true, false, "")
|
||||
)
|
||||
.executesPlayer((Player p, CommandArguments args) -> warJoinNear(p, args, true));
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandSurrender(boolean asAdmin) {
|
||||
@@ -116,6 +133,16 @@ public class WarCommands {
|
||||
.executesPlayer(WarCommands::warInfo);
|
||||
}
|
||||
|
||||
public static CommandAPICommand commandKick() {
|
||||
return new CommandAPICommand("kick")
|
||||
.withArguments(
|
||||
CommandUtil.warWarArgument("war", true, ALL_WARS, "player"),
|
||||
CommandUtil.playerOrTownOrNationInWar("target", "war")
|
||||
.withPermission("AlathranWars.admin")
|
||||
)
|
||||
.executesPlayer(WarCommands::warKick);
|
||||
}
|
||||
|
||||
protected static void warCreate(CommandSender p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
if (!(args.get("warlabel") instanceof final String argLabel))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a war label.").build());
|
||||
@@ -123,6 +150,8 @@ public class WarCommands {
|
||||
if (Objects.equals(args.get("side1"), args.get("side2")))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>Cannot declare war on oneself.").build());
|
||||
|
||||
final boolean event = (boolean) args.getOrDefault("event", false);
|
||||
|
||||
final UUID uuid1 = (UUID) args.get("side1");
|
||||
final UUID uuid2 = (UUID) args.get("side2");
|
||||
|
||||
@@ -137,33 +166,42 @@ public class WarCommands {
|
||||
// Implement permission checking here if this is ever going to be exposed to players
|
||||
|
||||
// Create war depending on what args have been passed, attempt to create nation wars first
|
||||
WarBuilder builder = new WarBuilder()
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLabel(argLabel)
|
||||
.setEvent(event);
|
||||
if (nation1 != null) {
|
||||
if (nation2 != null) { // Nation vs Nation
|
||||
|
||||
// Allow civil wars
|
||||
if (nation2.getUUID() != nation1.getUUID()) {
|
||||
new War(argLabel, nation1, nation2);
|
||||
builder
|
||||
.setAggressor(nation1)
|
||||
.setVictim(nation2);
|
||||
} else {
|
||||
new War(argLabel, town1, town2);
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(town2);
|
||||
}
|
||||
|
||||
} else if (town2 != null) { // Nation vs Town
|
||||
|
||||
new War(argLabel, nation1, town2);
|
||||
|
||||
builder
|
||||
.setAggressor(nation1)
|
||||
.setVictim(town2);
|
||||
}
|
||||
} else if (town1 != null) {
|
||||
|
||||
if (town2 != null) { // Town vs Town
|
||||
|
||||
new War(argLabel, town1, town2);
|
||||
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(town2);
|
||||
} else if (nation2 != null) { // Nation vs Town
|
||||
|
||||
new War(argLabel, town1, nation2);
|
||||
|
||||
builder
|
||||
.setAggressor(town1)
|
||||
.setVictim(nation2);
|
||||
}
|
||||
|
||||
}
|
||||
try {
|
||||
builder.create(); // TODO Add war to list
|
||||
} catch (SideCreationException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,92 +232,94 @@ public class WarCommands {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Resident invalid.").build());
|
||||
|
||||
// Get nations and towns
|
||||
@Nullable Nation nation = res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString);
|
||||
@Nullable Town town = res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString);
|
||||
@Nullable Nation nation = asAdmin ? TownyAPI.getInstance().getNation(targetString) : res.hasNation() ? res.getNationOrNull() : TownyAPI.getInstance().getNation(targetString);
|
||||
@Nullable Town town = asAdmin ? TownyAPI.getInstance().getTown(targetString) : res.hasTown() ? res.getTownOrNull() : TownyAPI.getInstance().getTown(targetString);
|
||||
|
||||
final boolean isNation = nation != null;
|
||||
final boolean isTown = town != null;
|
||||
final boolean isPlayer = targetPlayer != null;
|
||||
final boolean isArgNation = nation != null;
|
||||
final boolean isArgTown = town != null;
|
||||
final boolean isArgPlayer = targetPlayer != null;
|
||||
|
||||
// If no valid targets
|
||||
if ((!isNation && !isTown && !isPlayer))
|
||||
if ((!isArgNation && !isArgTown && !isArgPlayer))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Invalid target.").build());
|
||||
|
||||
// Check if player can validly join or not
|
||||
final boolean canKingJoin = (res.hasNation() && res.getNationOrNull().equals(nation) && res.isKing() && nation.isKing(res));
|
||||
final boolean canMayorJoin = (res.hasTown() && res.getTownOrNull().equals(town) && res.isMayor() && town.isMayor(res));
|
||||
|
||||
// Join nation into war
|
||||
if (isNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) {
|
||||
side.addNation(nation);
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(PlayerJoinListener::checkPlayer);
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The nation of <nation> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("nation", nation.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
if (!war.isEventWar()) {
|
||||
// Join nation into war
|
||||
if (isArgNation && nation != null && !war.isNationInWar(nation) && (asAdmin || canKingJoin)) {
|
||||
side.addNation(nation);
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().calculatePlayerColors(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The nation of <nation> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("nation", nation.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (town == null && nation != null && (!canKingJoin || !asAdmin)) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Nation is already in that war.").build());
|
||||
}
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (town == null && nation != null && (!canKingJoin || !asAdmin)) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Nation is already in that war.").build());
|
||||
}
|
||||
|
||||
// Join town into war
|
||||
if (isTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) {
|
||||
side.addTown(town);
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(PlayerJoinListener::checkPlayer);
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The town of <town> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
// Join town into war
|
||||
if (isArgTown && town != null && !war.isTownInWar(town) && (asAdmin || canMayorJoin)) {
|
||||
side.addTown(town);
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> NameColorHandler.getInstance().getPlayerNameColor(player));
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of(
|
||||
"<prefix>The town of <town> joined the war of <war> on the side of <side>."
|
||||
)
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.parseMinimessagePlaceholder("side", side.getName())
|
||||
.build()
|
||||
);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (targetPlayer == null && town != null && !canMayorJoin) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Town is already in that war.").build());
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).toList().forEach(player -> {
|
||||
player.showTitle(warTitle);
|
||||
player.playSound(warSound);
|
||||
});
|
||||
return;
|
||||
} else if (targetPlayer == null && town != null && !canMayorJoin) {
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Town is already in that war.").build());
|
||||
}
|
||||
}
|
||||
|
||||
// Join player into war
|
||||
if (isPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) {
|
||||
if (isArgPlayer && targetPlayer != null && !war.isPlayerInWar(targetPlayer) && asAdmin) {
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(targetPlayer);
|
||||
PlayerJoinListener.checkPlayer(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
@@ -313,6 +353,40 @@ public class WarCommands {
|
||||
}*/
|
||||
}
|
||||
|
||||
protected static void warJoinNear(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
if (!(args.get("side") instanceof final Side side))
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>You need to specify a side.").build());
|
||||
|
||||
final Location location = p.getLocation();
|
||||
|
||||
for (Player targetPlayer : Bukkit.getOnlinePlayers()) {
|
||||
if (p.equals(targetPlayer)) continue;
|
||||
final Location targetLocation = targetPlayer.getLocation();
|
||||
if (!location.getWorld().equals(targetLocation.getWorld())) continue;
|
||||
if (location.distance(targetLocation) > 25D) continue;
|
||||
if (war.isPlayerInWar(targetPlayer)) continue;
|
||||
|
||||
targetPlayer.sendMessage(ColorParser.of(UtilsChat.getPrefix() + "You have joined the war.").build());
|
||||
side.addPlayer(targetPlayer);
|
||||
NameColorHandler.getInstance().calculatePlayerColors(targetPlayer);
|
||||
final Title warTitle = Title.title(
|
||||
ColorParser.of("<gradient:#D72A09:#B01F03><u><b>War")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>You entered the war of <war>!")
|
||||
.parseMinimessagePlaceholder("war", war.getLabel())
|
||||
.build(),
|
||||
Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500))
|
||||
);
|
||||
final Sound warSound = Sound.sound(Key.key("entity.wither.spawn"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
targetPlayer.showTitle(warTitle);
|
||||
targetPlayer.playSound(warSound);
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warSurrender(@NotNull Player p, @NotNull CommandArguments args, boolean asAdmin) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
@@ -359,8 +433,51 @@ public class WarCommands {
|
||||
}
|
||||
}
|
||||
|
||||
protected static void warKick(@NotNull Player p, @NotNull CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
War war = (War) args.get("war");
|
||||
if (war == null) return;
|
||||
|
||||
UUID uuid = (UUID) args.get("target");
|
||||
|
||||
boolean isNation = TownyAPI.getInstance().getNation(uuid) != null;
|
||||
boolean isTown = TownyAPI.getInstance().getTown(uuid) != null;
|
||||
boolean isPlayer = Bukkit.getOfflinePlayer(uuid) != null;
|
||||
|
||||
Nation nation = TownyAPI.getInstance().getNation(uuid);
|
||||
Town town = TownyAPI.getInstance().getTown(uuid);
|
||||
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
|
||||
|
||||
Side sideNation = war.getNationSide(nation);
|
||||
Side sideTown = war.getTownSide(town);
|
||||
Side sidePlayer = war.getPlayerSide(uuid);
|
||||
|
||||
if (isNation && sideNation != null) {
|
||||
sideNation.kickNation(nation);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
nation.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isTown && sideTown != null) {
|
||||
sideTown.kickTown(town);
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
town.getResidents().stream().filter(Resident::isOnline).map(Resident::getPlayer).forEach(player1 -> NameColorHandler.getInstance().calculatePlayerColors(player1));
|
||||
return;
|
||||
}
|
||||
|
||||
if (isPlayer && sidePlayer != null) {
|
||||
sidePlayer.kickPlayer(player.getUniqueId());
|
||||
p.sendMessage(ColorParser.of("Target yeeted.").build());
|
||||
if (player.getPlayer() != null)
|
||||
NameColorHandler.getInstance().calculatePlayerColors(player.getPlayer());
|
||||
return;
|
||||
}
|
||||
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of("<red>Failed to yeet from the war because the target is not in it.").build());
|
||||
}
|
||||
|
||||
private static void warList(@NotNull Player p, CommandArguments args) throws WrapperCommandSyntaxException {
|
||||
Set<War> wars = WarManager.getInstance().getWars();
|
||||
Set<War> wars = WarController.getInstance().getWars();
|
||||
|
||||
if (wars.isEmpty()) {
|
||||
p.sendMessage(ColorParser.of("<red>There are no wars at the moment, the world is at peace.").build());
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.github.alathra.alathranwars.config;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.milkdrinkers.Crate.Config;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
|
||||
/**
|
||||
* A class that generates/loads & provides access to a configuration file.
|
||||
*/
|
||||
@Singleton
|
||||
public class ConfigHandler implements Reloadable {
|
||||
private final AlathranWars alathranWars;
|
||||
private Config cfg;
|
||||
|
||||
/**
|
||||
* Instantiates a new Config handler.
|
||||
*
|
||||
* @param alathranWars the plugin instance
|
||||
*/
|
||||
public ConfigHandler(AlathranWars alathranWars) {
|
||||
this.alathranWars = alathranWars;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad() {
|
||||
cfg = new Config("config", alathranWars.getDataFolder().getPath(), alathranWars.getResource("config.yml")); // Create a config file from the template in our resources folder
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets alathranWars config object.
|
||||
*
|
||||
* @return the alathranWars config object
|
||||
*/
|
||||
public Config getConfig() {
|
||||
return cfg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
|
||||
public class Conflict {
|
||||
private ConflictType conflictType;
|
||||
}
|
||||
+19
-19
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
package com.github.alathra.alathranwars.conflict;
|
||||
|
||||
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
@@ -36,27 +36,27 @@ public class Occupation {
|
||||
if (isOccupied(town)) return;
|
||||
|
||||
// Remove from current nation
|
||||
final boolean hasPreviousNation = town.hasNation();
|
||||
final boolean hasNewNation = occupier != null;
|
||||
final Nation previousNation = town.getNationOrNull();
|
||||
if (hasPreviousNation && hasNewNation && previousNation != occupier)
|
||||
town.removeNation();
|
||||
// final boolean hasPreviousNation = town.hasNation();
|
||||
// final boolean hasNewNation = occupier != null;
|
||||
// final Nation previousNation = town.getNationOrNull();
|
||||
// if (hasPreviousNation && hasNewNation && previousNation != occupier)
|
||||
// town.removeNation();
|
||||
|
||||
// Put town into occupiers nation
|
||||
try {
|
||||
if (hasNewNation)
|
||||
town.setNation(occupier);
|
||||
} catch (AlreadyRegisteredException e) {
|
||||
e.printStackTrace();
|
||||
return;
|
||||
}
|
||||
// // Put town into occupiers nation
|
||||
// try {
|
||||
// if (hasNewNation)
|
||||
// town.setNation(occupier);
|
||||
// } catch (AlreadyRegisteredException e) {
|
||||
// e.printStackTrace();
|
||||
// return;
|
||||
// }
|
||||
town.setConquered(true);
|
||||
|
||||
town.save();
|
||||
if (hasNewNation)
|
||||
occupier.save();
|
||||
|
||||
if (hasPreviousNation && previousNation != occupier)
|
||||
previousNation.save();
|
||||
// if (hasNewNation)
|
||||
// occupier.save();
|
||||
//
|
||||
// if (hasPreviousNation && previousNation != occupier)
|
||||
// previousNation.save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public interface Battle {
|
||||
void start(); // Initiates battle
|
||||
|
||||
void stop(); // Ends battle
|
||||
|
||||
void resume(); // Resume battle after server restart or plugin reload
|
||||
|
||||
void attackersWin(BattleVictoryReason reason); // A Attacker victory
|
||||
|
||||
void defendersWin(BattleVictoryReason reason); // A Defender victory
|
||||
|
||||
void equalWin(BattleVictoryReason reason); // A Draw
|
||||
|
||||
|
||||
UUID uuid = null; // Battle UUID
|
||||
|
||||
default @NotNull UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param battle the battle
|
||||
* @return the boolean
|
||||
*/
|
||||
default boolean equals(@NotNull Battle battle) {
|
||||
return getUUID().equals(battle.getUUID());
|
||||
}
|
||||
|
||||
BattleType battleType = null;
|
||||
|
||||
default BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.AlathranWars.conflict.battle.beam;
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
@@ -51,7 +51,7 @@ public class CrystalLaser extends Laser {
|
||||
* @see #executeEnd(Runnable) to add Runnable-s to execute when the laser will stop
|
||||
*/
|
||||
public CrystalLaser(Location start, Location end, int duration, int distance) throws ReflectiveOperationException {
|
||||
super(start, end, duration, distance);
|
||||
super(start, new Location(end.getWorld(), end.getBlockX(), end.getBlockY(), end.getBlockZ()), duration, distance);
|
||||
|
||||
fakeCrystalDataWatcher = Packets.createFakeDataWatcher();
|
||||
Packets.setCrystalWatcher(fakeCrystalDataWatcher, end);
|
||||
+15
-28
@@ -22,9 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.AlathranWars.conflict.battle.beam;
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
@@ -32,7 +34,10 @@ import org.bukkit.scheduler.BukkitRunnable;
|
||||
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
@@ -65,8 +70,8 @@ public abstract class Laser {
|
||||
throw new IllegalStateException("The Laser Beam API is disabled. An error has occured during initialization.");
|
||||
if (start.getWorld() != end.getWorld())
|
||||
throw new IllegalArgumentException("Locations do not belong to the same worlds.");
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.start = start.clone();
|
||||
this.end = end.clone();
|
||||
this.duration = duration;
|
||||
distanceSquared = distance < 0 ? -1 : distance * distance;
|
||||
}
|
||||
@@ -103,7 +108,6 @@ public abstract class Laser {
|
||||
*/
|
||||
public void start(Plugin plugin) {
|
||||
if (task != null) throw new IllegalStateException("Task already started");
|
||||
// if (runnable != null) throw new IllegalStateException("Task already started");
|
||||
this.plugin = plugin;
|
||||
Runnable runnable = new BukkitRunnable() {
|
||||
int time = 0;
|
||||
@@ -128,28 +132,11 @@ public abstract class Laser {
|
||||
}
|
||||
time++;
|
||||
} catch (ReflectiveOperationException e) {
|
||||
e.printStackTrace();
|
||||
Logger.get().error(ColorParser.of("<red>Laser packer exception: ").build(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public synchronized void cancel() throws IllegalStateException {
|
||||
super.cancel();
|
||||
runnable = null;
|
||||
try {
|
||||
for (Player p : show) {
|
||||
sendDestroyPackets(p);
|
||||
}
|
||||
show.clear();
|
||||
executeEnd.forEach(Runnable::run);
|
||||
} catch (ReflectiveOperationException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}*/
|
||||
};
|
||||
// main.runTaskTimerAsynchronously(plugin, 0L, durationInTicks ? 1L : 20L);
|
||||
// Main.getPaperLib().scheduling().asyncScheduler().run(main);
|
||||
task = Main.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
|
||||
task = AlathranWars.getPaperLib().scheduling().asyncScheduler().runAtFixedRate(runnable, Duration.ZERO, Duration.ofMillis(durationInTicks ? 50L : 1000L));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -180,7 +167,7 @@ public abstract class Laser {
|
||||
/**
|
||||
* Gets laser status.
|
||||
*
|
||||
* @return <code>true</code> if the laser is currently running
|
||||
* @return <code>true</code> if the laser is currently running
|
||||
* (i.e. {@link #start} has been called and the duration is not over)
|
||||
*/
|
||||
public boolean isStarted() {
|
||||
@@ -200,7 +187,7 @@ public abstract class Laser {
|
||||
* @return where exactly is the start position of the laser located
|
||||
*/
|
||||
public Location getStart() {
|
||||
return start;
|
||||
return start.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +196,7 @@ public abstract class Laser {
|
||||
* @return where exactly is the end position of the laser located
|
||||
*/
|
||||
public Location getEnd() {
|
||||
return end;
|
||||
return end.clone();
|
||||
}
|
||||
|
||||
protected abstract void sendStartPackets(Player p, boolean hasSeen) throws ReflectiveOperationException;
|
||||
+1
-1
@@ -22,7 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.AlathranWars.conflict.battle.beam;
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
+19
-28
@@ -22,10 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
*/
|
||||
|
||||
package com.github.alathra.AlathranWars.conflict.battle.beam;
|
||||
package com.github.alathra.alathranwars.conflict.battle.beam;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityType;
|
||||
import net.minecraft.world.entity.animal.Squid;
|
||||
import net.minecraft.world.entity.boss.enderdragon.EndCrystal;
|
||||
import org.bukkit.Bukkit;
|
||||
@@ -39,13 +40,9 @@ import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
class Packets {
|
||||
public static boolean enabled = false;
|
||||
private static Logger logger;
|
||||
static int version;
|
||||
private static int versionMinor;
|
||||
private static final String npack = "net.minecraft.server." + Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
|
||||
@@ -84,16 +81,6 @@ class Packets {
|
||||
|
||||
static {
|
||||
try {
|
||||
logger = new Logger("GuardianBeam", null) {
|
||||
@Override
|
||||
public void log(LogRecord logRecord) {
|
||||
logRecord.setMessage("[GuardianBeam] " + logRecord.getMessage());
|
||||
super.log(logRecord);
|
||||
}
|
||||
};
|
||||
logger.setParent(Bukkit.getServer().getLogger());
|
||||
logger.setLevel(Level.ALL);
|
||||
|
||||
// e.g. Bukkit.getServer().getClass().getPackage().getName() -> org.bukkit.craftbukkit.v1_17_R1
|
||||
String[] versions = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3].substring(1).split("_");
|
||||
version = Integer.parseInt(versions[1]); // 1.X
|
||||
@@ -102,16 +89,13 @@ class Packets {
|
||||
versions = Bukkit.getBukkitVersion().split("-R")[0].split("\\.");
|
||||
versionMinor = versions.length <= 2 ? 0 : Integer.parseInt(versions[2]);
|
||||
} else versionMinor = Integer.parseInt(versions[2].substring(1)); // 1.X.Y
|
||||
// logger.info("Found server version 1." + version + "." + versionMinor);
|
||||
|
||||
ProtocolMappings mappings = ProtocolMappings.getMappings(version);
|
||||
if (mappings == null) {
|
||||
mappings = ProtocolMappings.values()[ProtocolMappings.values().length - 1];
|
||||
// logger.warning("Loaded not matching version of the mappings for your server version (1." + version + "." + versionMinor + ")");
|
||||
}
|
||||
// logger.info("Loaded mappings " + mappings.name());
|
||||
|
||||
Class<?> entityTypesClass = EntityType.class;
|
||||
Class<?> entityTypesClass = getNMSClass("world.entity", "EntityTypes");
|
||||
Class<Entity> entityClass = Entity.class;
|
||||
Class<EndCrystal> crystalClass = EndCrystal.class;
|
||||
Class<?> squidClass = Squid.class;
|
||||
@@ -161,7 +145,10 @@ class Packets {
|
||||
getHandle = Class.forName(cpack + "entity.CraftPlayer").getDeclaredMethod("getHandle");
|
||||
playerConnection = getNMSClass("server.level", "EntityPlayer")
|
||||
.getDeclaredField(version < 17 ? "playerConnection" : (version < 20 ? "b" : "c"));
|
||||
sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(version < 18 ? "sendPacket" : "a", getNMSClass("network.protocol", "Packet"));
|
||||
playerConnection.setAccessible(true);
|
||||
sendPacket = getNMSClass("server.network", "PlayerConnection").getMethod(
|
||||
version < 18 ? "sendPacket" : (version >= 20 && versionMinor >= 2 ? "b" : "a"),
|
||||
getNMSClass("network.protocol", "Packet"));
|
||||
|
||||
if (version >= 17) {
|
||||
setUUID = entityClass.getDeclaredMethod("a_", UUID.class);
|
||||
@@ -170,12 +157,11 @@ class Packets {
|
||||
|
||||
enabled = true;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
String errorMsg = "Laser Beam reflection failed to initialize. The util is disabled. Please ensure your version (" + Bukkit.getServer().getClass().getPackage().getName() + ") is supported.";
|
||||
if (logger == null)
|
||||
System.err.println(errorMsg);
|
||||
else
|
||||
logger.severe(errorMsg);
|
||||
Logger.get().error(
|
||||
ColorParser.of("Laser reflection failed to initialize. The utility is disabled. Please ensure your version (<version>) is supported.")
|
||||
.parseMinimessagePlaceholder("version", Bukkit.getServer().getClass().getPackage().getName())
|
||||
.build()
|
||||
, e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -324,7 +310,12 @@ class Packets {
|
||||
}
|
||||
|
||||
},
|
||||
V1_20(20, "an", "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g"),
|
||||
V1_20(20, null, "b", "e", "c", "d", 89, 38, "V", "aT", "B", "a", "g") {
|
||||
@Override
|
||||
public String getWatcherFlags() {
|
||||
return versionMinor < 2 ? "an" : "ao";
|
||||
}
|
||||
},
|
||||
;
|
||||
|
||||
private final int major;
|
||||
@@ -0,0 +1,636 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.*;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import net.kyori.adventure.bossbar.BossBar;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Raid implements Battle {
|
||||
public static final Duration RAID_DURATION = Duration.ofMinutes(60);
|
||||
public static final int MAX_RAID_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
|
||||
public static final int MAX_RAID_PROGRESS = 60 * 10 * MAX_RAID_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_END = Duration.ofMinutes(40); // If point is not touched in this much time, defenders win
|
||||
public static final Duration ATTACKERS_MUST_TOUCH_REVERT = Duration.ofSeconds(60); // If point is not touched in this much time, raid progress begins reverting
|
||||
public static final int BATTLEFIELD_RANGE = 500;
|
||||
public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
|
||||
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
|
||||
public static final double SIEGE_VICTORY_MONEY = 2500.0;
|
||||
|
||||
private final @NotNull UUID uuid;
|
||||
private final Set<Player> attackers = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> defenders = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> attackerPlayers = new HashSet<>();
|
||||
private final Set<Player> defenderPlayers = new HashSet<>();
|
||||
private final Set<UUID> attackerPlayersIncludingOffline = new HashSet<>();
|
||||
private final Set<UUID> defenderPlayersIncludingOffline = new HashSet<>();
|
||||
private @NotNull War war; // War which raid belongs to
|
||||
private Instant endTime;
|
||||
private int raidProgress = 0;
|
||||
private Instant lastTouched;
|
||||
private RaidRunnable raidRunnable;
|
||||
private Town town; // Town of the raid
|
||||
private boolean side1AreAttackers; // bool of if side1 being attacker
|
||||
private OfflinePlayer raidLeader;
|
||||
private @Nullable TownBlock homeBlock = null;
|
||||
private @Nullable Location townSpawn = null;
|
||||
private @Nullable BossBar activeBossBar = null;
|
||||
private boolean stopped = false; // Used to track if the raid has been already deleted
|
||||
|
||||
public Raid(final @NotNull War war, final Town town, Player raidLeader) {
|
||||
uuid = UUID.randomUUID();
|
||||
|
||||
endTime = Instant.now().plus(RAID_DURATION);
|
||||
lastTouched = Instant.now();
|
||||
|
||||
this.war = war;
|
||||
this.town = town;
|
||||
this.raidLeader = raidLeader;
|
||||
|
||||
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
if (getSide1AreAttackers()) {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
} else {
|
||||
attackerPlayersIncludingOffline.addAll(getWar().getSide2().getPlayersIncludingOffline());
|
||||
defenderPlayersIncludingOffline.addAll(getWar().getSide1().getPlayersIncludingOffline());
|
||||
}
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
// Construct when loading from DB
|
||||
public Raid(War war, @NotNull UUID uuid, Town town, OfflinePlayer raidLeader, Instant endTime, Instant lastTouched, int raidProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
|
||||
this.war = war;
|
||||
this.uuid = uuid;
|
||||
this.town = town;
|
||||
this.raidLeader = raidLeader;
|
||||
this.endTime = endTime;
|
||||
this.lastTouched = lastTouched;
|
||||
this.raidProgress = raidProgress;
|
||||
this.attackerPlayersIncludingOffline.addAll(attackerPlayersIncludingOffline);
|
||||
this.defenderPlayersIncludingOffline.addAll(defenderPlayersIncludingOffline);
|
||||
|
||||
side1AreAttackers = war.getTownSide(town).getTeam().equals(BattleTeam.SIDE_2);
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a raid
|
||||
*/
|
||||
public void start() {
|
||||
raidRunnable = new RaidRunnable(this);
|
||||
if (!war.isEventWar())
|
||||
AlathranWars.econ.withdrawPlayer(raidLeader, SIEGE_VICTORY_MONEY);
|
||||
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
|
||||
final Title defTitle = Title.title(
|
||||
ColorParser.of("<red><u><b><town>")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>Is under raid, defend!")
|
||||
.build(),
|
||||
times
|
||||
);
|
||||
final Title attTitle = Title.title(
|
||||
ColorParser.of("<red><u><b><town>")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>Has been put to raid, attack!")
|
||||
.build(),
|
||||
times
|
||||
);
|
||||
|
||||
final List<Sound> soundList = List.of(
|
||||
Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
|
||||
);
|
||||
|
||||
getDefenderPlayers().forEach(player -> {
|
||||
player.showTitle(defTitle);
|
||||
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
});
|
||||
|
||||
getAttackerPlayers().forEach(player -> {
|
||||
player.showTitle(attTitle);
|
||||
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a raid (after a server restart e.t.c.)
|
||||
*/
|
||||
public void resume() {
|
||||
raidRunnable = new RaidRunnable(this, getRaidProgress());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a raid
|
||||
*/
|
||||
public void stop() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
raidRunnable.cancel();
|
||||
// DatabaseQueries.deleteRaid(this); // TODO Delete raid
|
||||
war.removeRaid(this);
|
||||
}
|
||||
|
||||
public void attackersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
AlathranWars.econ.depositPlayer(raidLeader, SIEGE_VICTORY_MONEY);
|
||||
double amt;
|
||||
|
||||
if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
|
||||
town.getAccount().withdraw(amt, "Raid Defeat");
|
||||
} else {
|
||||
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Raid Defeat");
|
||||
amt = SIEGE_VICTORY_MONEY;
|
||||
}
|
||||
|
||||
AlathranWars.econ.depositPlayer(raidLeader, amt);
|
||||
}
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide1().addScore(50);
|
||||
war.getSide2().addScore(5);
|
||||
} else {
|
||||
war.getSide1().addScore(5);
|
||||
war.getSide2().addScore(50);
|
||||
}
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
|
||||
if (!war.isEventWar()) {
|
||||
Side townSide = getWar().getTownSide(town);
|
||||
Side attackerSide = getAttackerSide();
|
||||
|
||||
if (attackerSide.equals(townSide)) {
|
||||
if (townSide.isTownSurrendered(town))
|
||||
war.unsurrenderTown(town);
|
||||
} else {
|
||||
if (!townSide.isTownSurrendered(town))
|
||||
war.surrenderTown(town);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void defendersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
|
||||
|
||||
if (!war.isEventWar())
|
||||
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Raid Victory");
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide2().addScore(10);
|
||||
} else {
|
||||
war.getSide1().addScore(10);
|
||||
}
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* No winner declared
|
||||
*/
|
||||
public void equalWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Instant getLastTouched() {
|
||||
return lastTouched;
|
||||
}
|
||||
|
||||
public void setLastTouched(Instant lastTouched) {
|
||||
this.lastTouched = lastTouched;
|
||||
}
|
||||
|
||||
public int getRaidProgress() {
|
||||
return raidProgress;
|
||||
}
|
||||
|
||||
public void setRaidProgress(int raidProgress) {
|
||||
if (raidProgress < 0) {
|
||||
raidProgress = 0;
|
||||
} else if (raidProgress > MAX_RAID_PROGRESS) {
|
||||
raidProgress = MAX_RAID_PROGRESS;
|
||||
}
|
||||
this.raidProgress = raidProgress;
|
||||
}
|
||||
|
||||
public float getRaidProgressPercentage() {
|
||||
return (getRaidProgress() * 1.0f) / MAX_RAID_PROGRESS;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public void setWar(final War war) {
|
||||
this.war = war;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Town getTown() {
|
||||
return town;
|
||||
}
|
||||
|
||||
public void setTown(final Town town) {
|
||||
this.town = town;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttackerSide() {
|
||||
return side1AreAttackers ? war.getSide1() : war.getSide2();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender name string
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefenderSide() {
|
||||
return side1AreAttackers ? war.getSide2() : war.getSide1();
|
||||
}
|
||||
|
||||
// SECTION Display Bar
|
||||
|
||||
public void updateDisplayBar(@NotNull CaptureProgressDirection progressDirection) {
|
||||
if (activeBossBar == null)
|
||||
createNewDisplayBar();
|
||||
|
||||
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
p.hideBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
for (@Nullable Player p : this.getPlayersOnBattlefield()) {
|
||||
if (p != null)
|
||||
p.showBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
final String color = switch (progressDirection) {
|
||||
case UP -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
yield "<red>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
yield "<blue>";
|
||||
}
|
||||
}
|
||||
case CONTESTED -> {
|
||||
activeBossBar.color(BossBar.Color.YELLOW);
|
||||
yield "<yellow>";
|
||||
}
|
||||
case UNCONTESTED -> {
|
||||
activeBossBar.color(BossBar.Color.WHITE);
|
||||
yield "<white>";
|
||||
}
|
||||
case DOWN -> {
|
||||
if (getAttackerSide().getSide().equals(BattleSide.ATTACKER)) {
|
||||
activeBossBar.color(BossBar.Color.BLUE);
|
||||
yield "<blue>";
|
||||
} else {
|
||||
activeBossBar.color(BossBar.Color.RED);
|
||||
yield "<red>";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Instant.now().isBefore(getEndTime())) {
|
||||
activeBossBar.name(
|
||||
ColorParser.of("<gray>Capture Progress: %s<progress> <gray>Time: %s<time>min".formatted(color, color))
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutes()))
|
||||
.build()
|
||||
);
|
||||
} else {
|
||||
activeBossBar.name(
|
||||
ColorParser.of("%sOVERTIME".formatted(color)).build()
|
||||
);
|
||||
}
|
||||
activeBossBar.progress(getRaidProgressPercentage());
|
||||
}
|
||||
|
||||
public void createNewDisplayBar() {
|
||||
final @NotNull Component text = ColorParser.of("<gray>Capture Progress: <yellow><progress> <gray>Time: <yellow><time>min")
|
||||
.parseMinimessagePlaceholder("progress", "%.0f%%".formatted(getRaidProgressPercentage() * 100))
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), getEndTime()).toMinutesPart()))
|
||||
.build();
|
||||
|
||||
this.activeBossBar = BossBar.bossBar(text, 0, BossBar.Color.YELLOW, BossBar.Overlay.NOTCHED_10);
|
||||
}
|
||||
|
||||
public void deleteDisplayBar() {
|
||||
if (activeBossBar != null) {
|
||||
for (@NotNull Player p : Bukkit.getOnlinePlayers()) {
|
||||
p.hideBossBar(activeBossBar);
|
||||
}
|
||||
|
||||
activeBossBar = null;
|
||||
}
|
||||
}
|
||||
|
||||
// SECTION UUID
|
||||
|
||||
public @NotNull UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(UUID uuid) {
|
||||
return getUUID().equals(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
*
|
||||
* @param raid the raid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(@NotNull Raid raid) {
|
||||
return getUUID().equals(raid.getUUID());
|
||||
}
|
||||
|
||||
// SECTION Accessors & Getters
|
||||
|
||||
@Nullable
|
||||
public TownBlock getHomeBlock() {
|
||||
return homeBlock;
|
||||
}
|
||||
|
||||
public void setHomeBlock(TownBlock homeBlock) {
|
||||
this.homeBlock = homeBlock;
|
||||
}
|
||||
|
||||
@Nullable
|
||||
public Location getTownSpawn() {
|
||||
return townSpawn;
|
||||
}
|
||||
|
||||
public void setTownSpawn(Location townSpawn) {
|
||||
this.townSpawn = townSpawn;
|
||||
}
|
||||
|
||||
public boolean getSide1AreAttackers() {
|
||||
return side1AreAttackers;
|
||||
}
|
||||
|
||||
public void setSide1AreAttackers(final boolean side1AreAttackers) {
|
||||
this.side1AreAttackers = side1AreAttackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getPlayersOnBattlefield() {
|
||||
return Stream.concat(attackers.stream(), defenders.stream()).collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackers() {
|
||||
return attackers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenders() {
|
||||
return defenders;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getAttackerPlayers() {
|
||||
return attackerPlayers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public Set<Player> getDefenderPlayers() {
|
||||
return defenderPlayers;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public OfflinePlayer getRaidLeader() {
|
||||
return raidLeader;
|
||||
}
|
||||
|
||||
public void setRaidLeader(OfflinePlayer raidLeader) {
|
||||
this.raidLeader = raidLeader;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public String getName() { // TODO Make better raidnames
|
||||
return getTown().getName();
|
||||
}
|
||||
|
||||
// SECTION Time management
|
||||
|
||||
@NotNull
|
||||
public Instant getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(Instant time) {
|
||||
endTime = time;
|
||||
}
|
||||
|
||||
// SECTION Player management
|
||||
|
||||
public boolean isPlayerInRaid(UUID uuid) {
|
||||
return attackerPlayersIncludingOffline.contains(uuid) || defenderPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerInRaid(@NotNull Player p) {
|
||||
return isPlayerInRaid(p.getUniqueId());
|
||||
}
|
||||
|
||||
public @NotNull BattleSide getPlayerSideInRaid(UUID uuid) {
|
||||
if (attackerPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.ATTACKER;
|
||||
|
||||
if (defenderPlayersIncludingOffline.contains(uuid))
|
||||
return BattleSide.DEFENDER;
|
||||
|
||||
return BattleSide.SPECTATOR;
|
||||
}
|
||||
|
||||
public @NotNull BattleSide getPlayerSideInRaid(@NotNull Player p) {
|
||||
return getPlayerSideInRaid(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull Player p, @NotNull BattleSide side) {
|
||||
addPlayer(p.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull OfflinePlayer offlinePlayer, @NotNull BattleSide side) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId(), side);
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull UUID uuid, @NotNull BattleSide side) {
|
||||
if (isPlayerInRaid(uuid)) return;
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.add(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.add(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
addOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void addOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.add(p);
|
||||
case DEFENDER -> defenderPlayers.add(p);
|
||||
}
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull UUID uuid) {
|
||||
if (!isPlayerInRaid(uuid)) return;
|
||||
|
||||
final @NotNull BattleSide side = getPlayerSideInRaid(uuid);
|
||||
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayersIncludingOffline.remove(uuid);
|
||||
case DEFENDER -> defenderPlayersIncludingOffline.remove(uuid);
|
||||
}
|
||||
|
||||
if (Bukkit.getOfflinePlayer(uuid).isOnline()) {
|
||||
final @Nullable Player p = Bukkit.getPlayer(uuid);
|
||||
removeOnlinePlayer(p, side);
|
||||
}
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p, @NotNull BattleSide side) {
|
||||
switch (side) {
|
||||
case ATTACKER -> attackerPlayers.remove(p);
|
||||
case DEFENDER -> defenderPlayers.remove(p);
|
||||
}
|
||||
}
|
||||
|
||||
public Set<UUID> getAttackerPlayersIncludingOffline() {
|
||||
return attackerPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
public Set<UUID> getDefenderPlayersIncludingOffline() {
|
||||
return defenderPlayersIncludingOffline;
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final @NotNull Set<Player> onlineAttackers = attackerPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackerPlayers.clear();
|
||||
attackerPlayers.addAll(onlineAttackers);
|
||||
|
||||
final @NotNull Set<Player> onlineDefenders = defenderPlayersIncludingOffline.stream()
|
||||
.filter(uuid1 -> Bukkit.getOfflinePlayer(uuid1).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenderPlayers.clear();
|
||||
defenderPlayers.addAll(onlineDefenders);
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(@NotNull Location location) {
|
||||
final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
|
||||
final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
|
||||
|
||||
final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
attackers.clear();
|
||||
attackers.addAll(attackersOnBattlefield);
|
||||
|
||||
final @NotNull Set<Player> defendersOnBattlefield = defenderPlayers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
.filter(p -> location.distance(p.getLocation()) < BATTLEFIELD_RANGE)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
defenders.clear();
|
||||
defenders.addAll(defendersOnBattlefield);
|
||||
|
||||
// Emit events for players leaving & entering the battlefield
|
||||
for (Player p : previousAttackersOnBattlefield) {
|
||||
if (p.isConnected() && !attackers.contains(p)) {
|
||||
// TODO Player left battlefield
|
||||
}
|
||||
}
|
||||
for (Player p : attackers) {
|
||||
if (p.isConnected() && !previousAttackersOnBattlefield.contains(p)) {
|
||||
// TODO Player entered battlefield
|
||||
}
|
||||
}
|
||||
|
||||
for (Player p : previousDefendersOnBattlefield) {
|
||||
if (p.isConnected() && !defenders.contains(p)) {
|
||||
// TODO Player left battlefield
|
||||
}
|
||||
}
|
||||
|
||||
for (Player p : defenders) {
|
||||
if (p.isConnected() && !previousDefendersOnBattlefield.contains(p)) {
|
||||
// TODO Player entered battlefield
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
package com.github.alathra.alathranwars.conflict.battle.raid;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.alathranwars.conflict.battle.raid.Raid.*;
|
||||
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
|
||||
|
||||
public class RaidRunnable implements Runnable {
|
||||
// Settings
|
||||
private static final Duration ANNOUNCEMENT_COOLDOWN = Duration.ofMinutes(5);
|
||||
private final static int CAPTURE_RANGE = 10;
|
||||
private final @NotNull Raid raid;
|
||||
|
||||
// Variables
|
||||
private @NotNull CaptureProgressDirection oldProgressDirection = UNCONTESTED;
|
||||
private Instant nextAnnouncement;
|
||||
private final ScheduledTask task;
|
||||
private @Nullable Laser beam;
|
||||
|
||||
/**
|
||||
* Start a raid
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
public RaidRunnable(@NotNull Raid raid) {
|
||||
this.raid = raid;
|
||||
|
||||
raid.setRaidProgress(0);
|
||||
|
||||
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
|
||||
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
raid.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a raid at tick
|
||||
*
|
||||
* @param raid the raid
|
||||
* @param raidProgress the raid ticks
|
||||
*/
|
||||
public RaidRunnable(@NotNull Raid raid, int raidProgress) {
|
||||
this.raid = raid;
|
||||
|
||||
raid.setRaidProgress(raidProgress);
|
||||
|
||||
raid.setHomeBlock(raid.getTown().getHomeBlockOrNull());
|
||||
raid.setTownSpawn(raid.getTown().getSpawnOrNull());
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
raid.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
stopBeam();
|
||||
if (task.isCancelled()) return;
|
||||
|
||||
task.cancel();
|
||||
raid.deleteDisplayBar();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
final @NotNull Town town = raid.getTown();
|
||||
final @Nullable TownBlock homeBlock = raid.getHomeBlock();
|
||||
final @Nullable Location townSpawn = raid.getTownSpawn();
|
||||
|
||||
if (homeBlock != null && townSpawn != null) {
|
||||
town.setHomeBlock(homeBlock);
|
||||
town.setSpawn(townSpawn);
|
||||
}
|
||||
|
||||
// Render beam
|
||||
startBeam();
|
||||
|
||||
// Calculate battlefield players
|
||||
raid.calculateBattlefieldPlayers(townSpawn.toCenterLocation());
|
||||
|
||||
// Progress the raid
|
||||
final int attackersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.ATTACKER);
|
||||
final int defendersOnPoint = getPeopleOnPoint(townSpawn, BattleSide.DEFENDER);
|
||||
final @NotNull CaptureProgressDirection progressDirection = getRaidProgressDirection(attackersOnPoint, defendersOnPoint);
|
||||
|
||||
// Raid is past max time or attackers haven't touched in time, defenders won
|
||||
if (
|
||||
(!progressDirection.equals(CONTESTED) && !progressDirection.equals(UP)) &&
|
||||
(Instant.now().isAfter(raid.getEndTime()) ||
|
||||
Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
|
||||
) {
|
||||
cancel();
|
||||
raid.defendersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (raid.getRaidProgress() >= MAX_RAID_PROGRESS) {
|
||||
cancel();
|
||||
raid.attackersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
final int playerOnPointDiff = attackersOnPoint - defendersOnPoint;
|
||||
|
||||
// If you have less than 5 people contesting you get (4 + excessPlayers) points per second
|
||||
if (playerOnPointDiff < 5) {
|
||||
raid.setRaidProgress(raid.getRaidProgress() + (4 + playerOnPointDiff));
|
||||
} else {
|
||||
raid.setRaidProgress(raid.getRaidProgress() + 10);
|
||||
}
|
||||
}
|
||||
case DOWN -> raid.setRaidProgress(raid.getRaidProgress() - 10);
|
||||
}
|
||||
|
||||
if (oldProgressDirection != progressDirection) {
|
||||
switch (progressDirection) {
|
||||
case UP -> {
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Attackers are capturing the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case CONTESTED -> {
|
||||
if (oldProgressDirection.equals(UNCONTESTED))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case UNCONTESTED -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED) || oldProgressDirection.equals(DOWN))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The home block is no longer being contested.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
case DOWN -> {
|
||||
if (oldProgressDirection.equals(UP) || oldProgressDirection.equals(CONTESTED))
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>The Defenders re-secured the home block.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.build()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Instant.now().isAfter(nextAnnouncement)) {
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
raid.getPlayersOnBattlefield().forEach(p -> p.sendMessage(
|
||||
ColorParser.of("<prefix>Raid time remaining: <time> minutes.")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("time", String.valueOf(Duration.between(Instant.now(), raid.getEndTime()).toMinutesPart()))
|
||||
.build()
|
||||
));
|
||||
}
|
||||
|
||||
raid.updateDisplayBar(progressDirection);
|
||||
oldProgressDirection = progressDirection;
|
||||
}
|
||||
|
||||
public int getPeopleOnPoint(@NotNull Location townSpawn, @NotNull BattleSide battleSide) {
|
||||
int onPoint = 0;
|
||||
|
||||
for (final @NotNull Player p : (battleSide.equals(BattleSide.ATTACKER) ? raid.getAttackers() : raid.getDefenders())) {
|
||||
if (p.isDead())
|
||||
continue;
|
||||
|
||||
if (!townSpawn.getWorld().equals(p.getLocation().getWorld()))
|
||||
continue;
|
||||
|
||||
if (townSpawn.distance(p.getLocation()) <= CAPTURE_RANGE) {
|
||||
onPoint += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return onPoint;
|
||||
}
|
||||
|
||||
public @NotNull CaptureProgressDirection getRaidProgressDirection(int attackersOnPoint, int defendersOnPoint) {
|
||||
final boolean attackersAreOnPoint = attackersOnPoint > 0;
|
||||
final boolean defendersAreOnPoint = defendersOnPoint > 0;
|
||||
|
||||
if (attackersAreOnPoint)
|
||||
raid.setLastTouched(Instant.now());
|
||||
|
||||
if (attackersAreOnPoint && defendersAreOnPoint) {
|
||||
|
||||
if (attackersOnPoint > defendersOnPoint)
|
||||
return UP;
|
||||
|
||||
return CONTESTED;
|
||||
} else if (attackersAreOnPoint && !defendersAreOnPoint) {
|
||||
if (raid.getRaidProgress() == MAX_RAID_PROGRESS)
|
||||
return CONTESTED;
|
||||
|
||||
return UP;
|
||||
} else {
|
||||
if (raid.getRaidProgress() == 0)
|
||||
return UNCONTESTED;
|
||||
|
||||
// If the attackers haven't touched in a while, begin reverting progress
|
||||
if (Instant.now().isAfter(raid.getLastTouched().plus(ATTACKERS_MUST_TOUCH_REVERT))) {
|
||||
return DOWN;
|
||||
} else {
|
||||
return UNCONTESTED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void startBeam() {
|
||||
if (beam != null)
|
||||
return;
|
||||
|
||||
try {
|
||||
@Nullable Location loc1 = raid.getTownSpawn();
|
||||
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
|
||||
beam = new CrystalLaser(loc1, loc2, -1, 300);
|
||||
beam.start(AlathranWars.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
private void stopBeam() {
|
||||
if (beam != null) {
|
||||
beam.stop();
|
||||
beam = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+156
-190
@@ -1,23 +1,21 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.siege;
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.Side;
|
||||
import com.github.alathra.AlathranWars.conflict.War;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.Battle;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.github.alathra.AlathranWars.utility.UUIDUtil;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.*;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.BattleStartEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleResultEvent;
|
||||
import com.github.alathra.alathranwars.events.battle.PreBattleStartEvent;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
import net.kyori.adventure.bossbar.BossBar;
|
||||
import net.kyori.adventure.key.Key;
|
||||
import net.kyori.adventure.sound.Sound;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.Location;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
@@ -27,11 +25,16 @@ import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class Siege extends Battle {
|
||||
/**
|
||||
* The type Siege.
|
||||
*/
|
||||
public class Siege implements Battle {
|
||||
public static final Duration SIEGE_DURATION = Duration.ofMinutes(60);
|
||||
public static final int MAX_SIEGE_PROGRESS_MINUTES = 8; // How many minutes attackers will need to be on point uncontested for to reach 100%
|
||||
public static final int MAX_SIEGE_PROGRESS = 60 * 10 * MAX_SIEGE_PROGRESS_MINUTES; // On reaching this, the attackers win. 10 points is added per second
|
||||
@@ -41,10 +44,9 @@ public class Siege extends Battle {
|
||||
public static final int BATTLEFIELD_START_MAX_RANGE = BATTLEFIELD_RANGE * 2;
|
||||
public static final int BATTLEFIELD_START_MIN_RANGE = 75;
|
||||
public static final double SIEGE_VICTORY_MONEY = 2500.0;
|
||||
private final static Title.Times TITLE_TIMES = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
|
||||
private final static Sound SOUND_VICTORY = Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
private final static Sound SOUND_DEFEAT = Sound.sound(Key.key("entity.wither.death"), Sound.Source.VOICE, 0.5f, 1.0F);
|
||||
|
||||
private final @NotNull UUID uuid;
|
||||
private final static BattleType battleType = BattleType.SIEGE;
|
||||
private final Set<Player> attackers = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> defenders = new HashSet<>(); // Players inside battlefield
|
||||
private final Set<Player> attackerPlayers = new HashSet<>();
|
||||
@@ -64,8 +66,15 @@ public class Siege extends Battle {
|
||||
private @Nullable BossBar activeBossBar = null;
|
||||
private boolean stopped = false; // Used to track if the siege has been already deleted
|
||||
|
||||
/**
|
||||
* Instantiates a new Siege. Used when creating a new siege.
|
||||
*
|
||||
* @param war the war
|
||||
* @param town the town
|
||||
* @param siegeLeader the siege leader
|
||||
*/
|
||||
public Siege(final @NotNull War war, final Town town, Player siegeLeader) {
|
||||
uuid = UUIDUtil.generateSiegeUUID();
|
||||
uuid = UUID.randomUUID();
|
||||
|
||||
endTime = Instant.now().plus(SIEGE_DURATION);
|
||||
lastTouched = Instant.now();
|
||||
@@ -86,7 +95,19 @@ public class Siege extends Battle {
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
// Construct when loading from DB
|
||||
/**
|
||||
* Instantiates a new Siege. Used when loading existing Siege from Database.
|
||||
*
|
||||
* @param war the war
|
||||
* @param uuid the uuid
|
||||
* @param town the town
|
||||
* @param siegeLeader the siege leader
|
||||
* @param endTime the end time
|
||||
* @param lastTouched the last touched
|
||||
* @param siegeProgress the siege progress
|
||||
* @param attackerPlayersIncludingOffline the attacker players including offline
|
||||
* @param defenderPlayersIncludingOffline the defender players including offline
|
||||
*/
|
||||
public Siege(War war, @NotNull UUID uuid, Town town, OfflinePlayer siegeLeader, Instant endTime, Instant lastTouched, int siegeProgress, Set<UUID> attackerPlayersIncludingOffline, Set<UUID> defenderPlayersIncludingOffline) {
|
||||
this.war = war;
|
||||
this.uuid = uuid;
|
||||
@@ -104,204 +125,98 @@ public class Siege extends Battle {
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a siege
|
||||
* Starts the battle
|
||||
*/
|
||||
public void start() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
siegeRunnable = new SiegeRunnable(this);
|
||||
Main.econ.withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
stopped = false;
|
||||
|
||||
final Title.Times times = Title.Times.times(Duration.ofMillis(500), Duration.ofMillis(3500), Duration.ofMillis(500));
|
||||
final Title defTitle = Title.title(
|
||||
ColorParser.of("<red><u><b><town>")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>Is under siege, defend!")
|
||||
.build(),
|
||||
times
|
||||
);
|
||||
final Title attTitle = Title.title(
|
||||
ColorParser.of("<red><u><b><town>")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>Has been put to siege, attack!")
|
||||
.build(),
|
||||
times
|
||||
);
|
||||
if (!war.isEventWar())
|
||||
AlathranWars.econ.withdrawPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
|
||||
final List<Sound> soundList = List.of(
|
||||
Sound.sound(Key.key("item.goat_horn.sound.0"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.2"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.3"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F)),
|
||||
Sound.sound(Key.key("item.goat_horn.sound.7"), Sound.Source.VOICE, 0.5f, new Random().nextFloat(0.9F, 1.0F))
|
||||
);
|
||||
|
||||
getDefenderPlayers().forEach(player -> {
|
||||
player.showTitle(defTitle);
|
||||
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
});
|
||||
|
||||
getAttackerPlayers().forEach(player -> {
|
||||
player.showTitle(attTitle);
|
||||
player.playSound(soundList.get(new Random().nextInt(1, soundList.size())));
|
||||
});
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resumes a siege (after a server restart e.t.c.)
|
||||
* Resumes the battle (after a server restart e.t.c.)
|
||||
*/
|
||||
public void resume() {
|
||||
if (!new PreBattleStartEvent(war, this, BattleType.SIEGE).callEvent()) return;
|
||||
|
||||
siegeRunnable = new SiegeRunnable(this, getSiegeProgress());
|
||||
stopped = false;
|
||||
|
||||
new BattleStartEvent(war, this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a siege
|
||||
* Stops the battle
|
||||
* </p>
|
||||
* Internal stop method for battles which triggers cleanup methods
|
||||
*/
|
||||
public void stop() {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
siegeRunnable.cancel();
|
||||
SQLQueries.deleteSiege(this);
|
||||
war.removeSiege(this);
|
||||
DatabaseQueries.deleteSiege(this); // TODO Run as latent event?
|
||||
war.removeSiege(this); // TODO Run as latent event?
|
||||
}
|
||||
|
||||
public void attackersWin() {
|
||||
Main.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
double amt;
|
||||
/**
|
||||
* Stop a battle in favor of the attackers
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void attackersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.ATTACKER, reason).callEvent()) return;
|
||||
|
||||
if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
|
||||
town.getAccount().withdraw(amt, "Siege Defeat");
|
||||
} else {
|
||||
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Siege Defeat");
|
||||
amt = SIEGE_VICTORY_MONEY;
|
||||
if (!war.isEventWar()) {
|
||||
AlathranWars.econ.depositPlayer(siegeLeader, SIEGE_VICTORY_MONEY);
|
||||
double amt;
|
||||
|
||||
if (town.getAccount().getHoldingBalance() > 10000.0) {
|
||||
amt = Math.floor(town.getAccount().getHoldingBalance()) / 4.0;
|
||||
town.getAccount().withdraw(amt, "Siege Defeat");
|
||||
} else {
|
||||
town.getAccount().withdraw(SIEGE_VICTORY_MONEY, "Siege Defeat");
|
||||
amt = SIEGE_VICTORY_MONEY;
|
||||
}
|
||||
|
||||
AlathranWars.econ.depositPlayer(siegeLeader, amt);
|
||||
}
|
||||
|
||||
Main.econ.depositPlayer(siegeLeader, amt);
|
||||
|
||||
Bukkit.broadcast(ColorParser.of("<prefix>The town of <town> has been sacked and placed under occupation by the armies of <attacker>!")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.parseMinimessagePlaceholder("attacker", getAttackerSide().getName())
|
||||
.build());
|
||||
|
||||
final Title vicAttackTitle = Title.title(
|
||||
ColorParser.of("<green><u><b>Victory")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i><town> has been captured!")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
final Title losAttackTitle = Title.title(
|
||||
ColorParser.of("<red><u><b>Defeat")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i><town> has been lost!")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
getAttackers().forEach(player -> {
|
||||
player.showTitle(vicAttackTitle);
|
||||
player.playSound(SOUND_VICTORY);
|
||||
});
|
||||
getDefenders().forEach(player -> {
|
||||
player.showTitle(losAttackTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide1().addScore(50);
|
||||
war.getSide2().addScore(5);
|
||||
} else {
|
||||
war.getSide1().addScore(5);
|
||||
war.getSide2().addScore(50);
|
||||
}
|
||||
|
||||
stop();
|
||||
|
||||
Side townSide = getWar().getTownSide(town);
|
||||
Side attackerSide = getAttackerSide();
|
||||
|
||||
if (attackerSide.equals(townSide)) {
|
||||
if (townSide.isTownSurrendered(town))
|
||||
war.unsurrenderTown(town);
|
||||
} else {
|
||||
if (!townSide.isTownSurrendered(town))
|
||||
war.surrenderTown(town);
|
||||
}
|
||||
}
|
||||
|
||||
public void defendersWin() {
|
||||
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
|
||||
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of("<prefix>The siege of <town> has been lifted by the defenders!")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build()
|
||||
);
|
||||
|
||||
final Title vicDefendTitle = Title.title(
|
||||
ColorParser.of("<red><u><b>Defeat")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>We failed to capture <town>!")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
final Title losDefendTitle = Title.title(
|
||||
ColorParser.of("<green><u><b>Victory")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i><town> has been made safe!")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
getAttackers().forEach(player -> {
|
||||
player.showTitle(vicDefendTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
getDefenders().forEach(player -> {
|
||||
player.showTitle(losDefendTitle);
|
||||
player.playSound(SOUND_VICTORY);
|
||||
});
|
||||
|
||||
if (side1AreAttackers) {
|
||||
war.getSide2().addScore(10);
|
||||
} else {
|
||||
war.getSide1().addScore(10);
|
||||
}
|
||||
new BattleResultEvent(war, this, BattleVictor.ATTACKER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* No winner declared
|
||||
* Stop a battle in favor of the defenders
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void noWinner() {
|
||||
Bukkit.broadcast(
|
||||
ColorParser.of("<prefix>The siege of <town> has ended in a draw!")
|
||||
.parseMinimessagePlaceholder("prefix", UtilsChat.getPrefix())
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build()
|
||||
);
|
||||
public void defendersWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DEFENDER, reason).callEvent()) return;
|
||||
|
||||
final Title drawTitle = Title.title(
|
||||
ColorParser.of("<yellow><u><b>Draw")
|
||||
.build(),
|
||||
ColorParser.of("<gray><i>The siege at <town> has ended!")
|
||||
.parseMinimessagePlaceholder("town", town.getName())
|
||||
.build(),
|
||||
TITLE_TIMES
|
||||
);
|
||||
getAttackers().forEach(player -> {
|
||||
player.showTitle(drawTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
getDefenders().forEach(player -> {
|
||||
player.showTitle(drawTitle);
|
||||
player.playSound(SOUND_DEFEAT);
|
||||
});
|
||||
if (!war.isEventWar())
|
||||
town.getAccount().deposit(SIEGE_VICTORY_MONEY, "Siege Victory");
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DEFENDER, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
|
||||
/**
|
||||
* End a battle in favor of no one
|
||||
*
|
||||
* @param reason what triggered the end
|
||||
*/
|
||||
public void equalWin(BattleVictoryReason reason) {
|
||||
if (!new PreBattleResultEvent(war, this, BattleType.SIEGE, BattleVictor.DRAW, reason).callEvent()) return;
|
||||
|
||||
new BattleResultEvent(war, this, BattleVictor.DRAW, reason).callEvent();
|
||||
|
||||
stop();
|
||||
}
|
||||
@@ -355,7 +270,7 @@ public class Siege extends Battle {
|
||||
*/
|
||||
@NotNull
|
||||
public Side getAttackerSide() {
|
||||
return side1AreAttackers ? war.getSide1() : war.getSide2();
|
||||
return getSide1AreAttackers() ? war.getSide1() : war.getSide2();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -363,7 +278,7 @@ public class Siege extends Battle {
|
||||
*/
|
||||
@NotNull
|
||||
public Side getDefenderSide() {
|
||||
return side1AreAttackers ? war.getSide2() : war.getSide1();
|
||||
return getSide1AreAttackers() ? war.getSide2() : war.getSide1();
|
||||
}
|
||||
|
||||
// SECTION Display Bar
|
||||
@@ -470,6 +385,13 @@ public class Siege extends Battle {
|
||||
return getUUID().equals(siege.getUUID());
|
||||
}
|
||||
|
||||
// SECTION BattleType
|
||||
|
||||
@Override
|
||||
public BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
|
||||
// SECTION Accessors & Getters
|
||||
|
||||
@Nullable
|
||||
@@ -661,6 +583,9 @@ public class Siege extends Battle {
|
||||
}
|
||||
|
||||
public void calculateBattlefieldPlayers(@NotNull Location location) {
|
||||
final Set<Player> previousAttackersOnBattlefield = new HashSet<>(attackers);
|
||||
final Set<Player> previousDefendersOnBattlefield = new HashSet<>(defenders);
|
||||
|
||||
final @NotNull Set<Player> attackersOnBattlefield = attackerPlayers.stream()
|
||||
.filter(OfflinePlayer::isOnline)
|
||||
.filter(p -> location.getWorld().equals(p.getLocation().getWorld()))
|
||||
@@ -678,5 +603,46 @@ public class Siege extends Battle {
|
||||
|
||||
defenders.clear();
|
||||
defenders.addAll(defendersOnBattlefield);
|
||||
|
||||
// TODO Emit events for players leaving & entering the battlefield
|
||||
|
||||
// Leaving attackers
|
||||
previousAttackersOnBattlefield.stream()
|
||||
.filter(p -> p.isConnected() && !attackers.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player left battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Entering attackers
|
||||
attackers.stream()
|
||||
.filter(p -> p.isConnected() && !previousAttackersOnBattlefield.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player entered battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Leaving defenders
|
||||
previousDefendersOnBattlefield.stream()
|
||||
.filter(p -> p.isConnected() && !defenders.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player left battlefield
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
// Entering defenders
|
||||
defenders.stream()
|
||||
.filter(p -> p.isConnected() && !previousDefendersOnBattlefield.contains(p))
|
||||
.collect(Collectors.toSet())
|
||||
.forEach(p -> {
|
||||
// TODO Player entered battlefield
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+22
-18
@@ -1,11 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.conflict.battle.siege;
|
||||
package com.github.alathra.alathranwars.conflict.battle.siege;
|
||||
|
||||
import com.github.alathra.AlathranWars.Main;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.beam.CrystalLaser;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.beam.Laser;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.CrystalLaser;
|
||||
import com.github.alathra.alathranwars.conflict.battle.beam.Laser;
|
||||
import com.github.alathra.alathranwars.enums.CaptureProgressDirection;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.TownBlock;
|
||||
@@ -18,8 +19,8 @@ import space.arim.morepaperlib.scheduling.ScheduledTask;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
import static com.github.alathra.AlathranWars.conflict.battle.siege.Siege.*;
|
||||
import static com.github.alathra.AlathranWars.enums.CaptureProgressDirection.*;
|
||||
import static com.github.alathra.alathranwars.conflict.battle.siege.Siege.*;
|
||||
import static com.github.alathra.alathranwars.enums.CaptureProgressDirection.*;
|
||||
|
||||
public class SiegeRunnable implements Runnable {
|
||||
// Settings
|
||||
@@ -48,7 +49,7 @@ public class SiegeRunnable implements Runnable {
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = Main.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
@@ -69,7 +70,7 @@ public class SiegeRunnable implements Runnable {
|
||||
|
||||
nextAnnouncement = Instant.now().plus(ANNOUNCEMENT_COOLDOWN);
|
||||
|
||||
task = Main.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
task = AlathranWars.getPaperLib().scheduling().globalRegionalScheduler().runAtFixedRate(this, 0L, 20L);
|
||||
|
||||
siege.updateDisplayBar(CONTESTED);
|
||||
}
|
||||
@@ -111,14 +112,14 @@ public class SiegeRunnable implements Runnable {
|
||||
Instant.now().isAfter(siege.getLastTouched().plus(ATTACKERS_MUST_TOUCH_END)))
|
||||
) {
|
||||
cancel();
|
||||
siege.defendersWin();
|
||||
siege.defendersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
// Attackers captured the town
|
||||
if (siege.getSiegeProgress() >= MAX_SIEGE_PROGRESS) {
|
||||
cancel();
|
||||
siege.attackersWin();
|
||||
siege.attackersWin(BattleVictoryReason.OPPONENT_LOST);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -241,12 +242,15 @@ public class SiegeRunnable implements Runnable {
|
||||
return;
|
||||
|
||||
try {
|
||||
@Nullable Location loc1 = siege.getTownSpawn();
|
||||
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
try {
|
||||
@Nullable Location loc1 = siege.getTownSpawn();
|
||||
@NotNull Location loc2 = new Location(loc1.getWorld(), loc1.getX(), loc1.getY() + 350D, loc1.getZ());
|
||||
|
||||
beam = new CrystalLaser(loc1, loc2, -1, 300);
|
||||
beam.start(Main.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
beam = new CrystalLaser(loc1, loc2, -1, 300);
|
||||
beam.start(AlathranWars.getInstance());
|
||||
} catch (ReflectiveOperationException ignored) {
|
||||
}
|
||||
} catch (NoClassDefFoundError ignored1) {
|
||||
}
|
||||
}
|
||||
|
||||
+361
-131
@@ -1,15 +1,26 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.enums.ConflictType;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.AlathranWars.utility.SQLQueries;
|
||||
import com.github.alathra.AlathranWars.utility.UUIDUtil;
|
||||
import com.github.alathra.AlathranWars.utility.UtilsChat;
|
||||
import com.github.alathra.alathranwars.conflict.Conflict;
|
||||
import com.github.alathra.alathranwars.conflict.Occupation;
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
import com.github.alathra.alathranwars.enums.WarDeleteReason;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import com.github.alathra.alathranwars.events.PreWarCreateEvent;
|
||||
import com.github.alathra.alathranwars.events.PreWarDeleteEvent;
|
||||
import com.github.alathra.alathranwars.events.WarCreateEvent;
|
||||
import com.github.alathra.alathranwars.events.WarDeleteEvent;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.github.alathra.alathranwars.utility.UtilsChat;
|
||||
import com.github.milkdrinkers.colorparser.ColorParser;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.CommandAPIBukkit;
|
||||
@@ -20,6 +31,7 @@ import net.kyori.adventure.title.Title;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@@ -38,23 +50,38 @@ public class War extends Conflict {
|
||||
private final String name; // Used in commands and such, like "TidalHaven.vs.Meme"
|
||||
private final String label;
|
||||
private final ConflictType conflictType = ConflictType.WAR;
|
||||
private boolean event;
|
||||
|
||||
private final @NotNull Side side1;
|
||||
private final Side side2;
|
||||
private Side side1;
|
||||
private Side side2;
|
||||
private final Side attacker; // Reference variable to side1 or side2
|
||||
private final Side defender; // Reference variable to side1 or side2
|
||||
|
||||
private Set<Siege> sieges = new HashSet<>();
|
||||
private Set<Raid> raids = new HashSet<>();
|
||||
|
||||
/**
|
||||
* Instantiates a existing War.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @param name the name
|
||||
* @param label the label
|
||||
* @param side1 the side 1
|
||||
* @param side2 the side 2
|
||||
* @param sieges the sieges
|
||||
* @param raids the raids
|
||||
* @param event the event
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public War(
|
||||
UUID uuid,
|
||||
String name,
|
||||
String label,
|
||||
@NotNull Side side1,
|
||||
Side side1,
|
||||
Side side2,
|
||||
Set<Siege> sieges,
|
||||
Set<Raid> raids
|
||||
Set<Raid> raids,
|
||||
boolean event
|
||||
) {
|
||||
this.uuid = uuid;
|
||||
this.name = name;
|
||||
@@ -68,103 +95,69 @@ public class War extends Conflict {
|
||||
|
||||
this.sieges = sieges;
|
||||
this.raids = raids;
|
||||
this.event = event;
|
||||
|
||||
resume();
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new New war.
|
||||
* Instantiates a new War.
|
||||
*
|
||||
* @param label the name
|
||||
* @param aggressor the side 1
|
||||
* @param victim the side 2
|
||||
* @param uuid the uuid
|
||||
* @param label the label
|
||||
* @param aggressor the aggressor
|
||||
* @param victim the victim
|
||||
* @param event the event
|
||||
* @throws SideCreationException the side creation exception
|
||||
* @throws WrapperCommandSyntaxException the wrapper command syntax exception
|
||||
*/
|
||||
public War(final String label, @NotNull Town aggressor, @NotNull Town victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
@ApiStatus.Internal
|
||||
public War(
|
||||
UUID uuid,
|
||||
String label,
|
||||
Government aggressor,
|
||||
Government victim,
|
||||
boolean event
|
||||
) throws SideCreationException, WrapperCommandSyntaxException {
|
||||
this.uuid = uuid;
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
if (WarController.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
this.side1 = new SideBuilder()
|
||||
.setWarUUID(this.uuid)
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(aggressor)
|
||||
.setSide(BattleSide.ATTACKER)
|
||||
.setTeam(BattleTeam.SIDE_1)
|
||||
.build();
|
||||
this.side2 = new SideBuilder()
|
||||
.setWarUUID(this.uuid)
|
||||
.setUuid(UUID.randomUUID())
|
||||
.setLeader(victim)
|
||||
.setSide(BattleSide.DEFENDER)
|
||||
.setTeam(BattleTeam.SIDE_2)
|
||||
.build();
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
this.event = event;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
if (!new PreWarCreateEvent(this).callEvent())
|
||||
return;
|
||||
|
||||
// TODO All logic below this point should be separated out
|
||||
WarController.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, @NotNull Nation aggressor, @NotNull Nation victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, @NotNull Town aggressor, @NotNull Nation victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
}
|
||||
|
||||
public War(final String label, @NotNull Nation aggressor, @NotNull Town victim) throws WrapperCommandSyntaxException {
|
||||
this.uuid = UUIDUtil.generateWarUUID();
|
||||
this.name = "%s.vs.%s".formatted(aggressor.getName(), victim.getName());
|
||||
this.label = label;
|
||||
|
||||
if (WarManager.getInstance().getWar(this.name) != null)
|
||||
throw CommandAPIBukkit.failWithAdventureComponent(ColorParser.of(UtilsChat.getPrefix() + "<red>A war already exists with that name!").build());
|
||||
|
||||
final @NotNull UUID side1UUID = UUIDUtil.generateSideUUID(null);
|
||||
final @NotNull UUID side2UUID = UUIDUtil.generateSideUUID(side1UUID);
|
||||
this.side1 = new Side(this.uuid, side1UUID, aggressor, BattleSide.ATTACKER, BattleTeam.SIDE_1);
|
||||
this.side2 = new Side(this.uuid, side2UUID, victim, BattleSide.DEFENDER, BattleTeam.SIDE_2);
|
||||
|
||||
this.attacker = side1.getSide().equals(BattleSide.ATTACKER) ? this.side1 : this.side2;
|
||||
this.defender = side1.getSide().equals(BattleSide.DEFENDER) ? this.side1 : this.side2;
|
||||
|
||||
WarManager.getInstance().addWar(this);
|
||||
|
||||
start();
|
||||
new WarCreateEvent(this).callEvent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets uuid.
|
||||
* Gets uuid of the war.
|
||||
*
|
||||
* @return the uuid
|
||||
*/
|
||||
@@ -173,7 +166,7 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets name.
|
||||
* Gets name of the war.
|
||||
*
|
||||
* @return the name
|
||||
*/
|
||||
@@ -182,13 +175,18 @@ public class War extends Conflict {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets label of the war.
|
||||
*
|
||||
* @return the label
|
||||
*/
|
||||
@NotNull
|
||||
public String getLabel() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
* Compare war UUID's.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
@@ -198,17 +196,17 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
* Compare war by UUID's.
|
||||
*
|
||||
* @param war the war
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean equals(@NotNull War war) {
|
||||
public boolean equals(War war) {
|
||||
return this.uuid.equals(war.getUUID());
|
||||
}
|
||||
|
||||
/**
|
||||
* Equals boolean.
|
||||
* Compare war by names.
|
||||
*
|
||||
* @param warName the war name
|
||||
* @return the boolean
|
||||
@@ -237,16 +235,21 @@ public class War extends Conflict {
|
||||
return side2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sides in a list.
|
||||
*
|
||||
* @return the sides
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Side> getSides() {
|
||||
final @NotNull Set<Side> sides = new HashSet<>();
|
||||
sides.add(getSide1());
|
||||
sides.add(getSide2());
|
||||
return sides;
|
||||
return Set.of(
|
||||
getSide1(),
|
||||
getSide2()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets attacker.
|
||||
* Gets attacker side.
|
||||
*
|
||||
* @return the attacker
|
||||
*/
|
||||
@@ -256,7 +259,7 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets defender.
|
||||
* Gets defender side.
|
||||
*
|
||||
* @return the defender
|
||||
*/
|
||||
@@ -265,6 +268,12 @@ public class War extends Conflict {
|
||||
return defender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by name.
|
||||
*
|
||||
* @param name the name
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(String name) {
|
||||
if (getSide1().equals(name))
|
||||
@@ -276,6 +285,12 @@ public class War extends Conflict {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by the side UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
if (getSide1().equals(uuid))
|
||||
@@ -288,7 +303,7 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sieges.
|
||||
* Gets sieges in a list.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
@@ -297,30 +312,47 @@ public class War extends Conflict {
|
||||
return sieges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets sieges for the war.
|
||||
*
|
||||
* @param sieges the sieges
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void setSieges(Set<Siege> sieges) {
|
||||
this.sieges = sieges;
|
||||
this.sieges.forEach(Siege::resume);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets siege by the siege UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the siege
|
||||
*/
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
for (@NotNull Siege siege : sieges) {
|
||||
if (siege.equals(uuid))
|
||||
return siege;
|
||||
}
|
||||
|
||||
return null;
|
||||
return sieges.stream()
|
||||
.filter(s -> s.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add siege.
|
||||
* Add siege to war.
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addSiege(Siege siege) {
|
||||
sieges.add(siege);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove siege from war.
|
||||
*
|
||||
* @param siege the siege
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeSiege(Siege siege) {
|
||||
sieges.remove(siege);
|
||||
}
|
||||
@@ -336,14 +368,50 @@ public class War extends Conflict {
|
||||
}
|
||||
|
||||
/**
|
||||
* Add raid.
|
||||
* Add raid to war.
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addRaid(Raid raid) {
|
||||
raids.add(raid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove raid from war.
|
||||
*
|
||||
* @param raid the raid
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeRaid(Raid raid) {
|
||||
raids.remove(raid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town under siege in this war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownUnderSiege(Town town) {
|
||||
return sieges.stream().anyMatch(siege -> siege.getTown().equals(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town under raid in this war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownUnderRaid(Town town) {
|
||||
return raids.stream().anyMatch(raid -> raid.getTown().equals(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all online players in the war.
|
||||
*
|
||||
* @return the players
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Player> getPlayers() {
|
||||
return Stream.concat(
|
||||
@@ -353,6 +421,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all players, including offline ones in the war.
|
||||
*
|
||||
* @return the players including offline
|
||||
*/
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getPlayersIncludingOffline() {
|
||||
return Stream.concat(
|
||||
@@ -362,6 +435,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered players in the war.
|
||||
*
|
||||
* @return the surrendered players
|
||||
*/
|
||||
@NotNull
|
||||
public Set<OfflinePlayer> getSurrenderedPlayers() {
|
||||
return Stream.concat(
|
||||
@@ -371,25 +449,43 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public boolean isPlayerInWar(@NotNull Player p) {
|
||||
/**
|
||||
* Check if player is in war.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInWar(Player p) {
|
||||
return side1.isPlayerOnSide(p) || side2.isPlayerOnSide(p);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if player is in war.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInWar(UUID uuid) {
|
||||
return side1.isPlayerOnSide(uuid) || side2.isPlayerOnSide(uuid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the side of the player or null if they are not in the war.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getPlayerSide(@NotNull Player p) {
|
||||
if (side1.isPlayerOnSide(p))
|
||||
return getSide1();
|
||||
|
||||
if (side2.isPlayerOnSide(p))
|
||||
return getSide2();
|
||||
|
||||
return null;
|
||||
public Side getPlayerSide(Player p) {
|
||||
return getPlayerSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player side by player UUID or null if they are not in the war.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getPlayerSide(UUID uuid) {
|
||||
if (side1.isPlayerOnSide(uuid))
|
||||
@@ -401,10 +497,22 @@ public class War extends Conflict {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInWar(Town town) {
|
||||
return side1.isTownOnSide(town) || side2.isTownOnSide(town);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town side or null if not in war.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the town side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getTownSide(Town town) {
|
||||
if (side1.isTownOnSide(town))
|
||||
@@ -416,10 +524,22 @@ public class War extends Conflict {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in war boolean.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInWar(Nation nation) {
|
||||
return side1.isNationOnSide(nation) || side2.isNationOnSide(nation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation side or null if not in war.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the nation side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getNationSide(Nation nation) {
|
||||
if (side1.isNationOnSide(nation))
|
||||
@@ -431,14 +551,30 @@ public class War extends Conflict {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a side exists with the specified name.
|
||||
*
|
||||
* @param sideName the side name
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isSideValid(String sideName) {
|
||||
return getSide1().equals(sideName) || getSide2().equals(sideName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all active sieges in the war.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void cancelSieges() {
|
||||
getTowns().forEach(this::cancelSieges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel all active sieges in the war. Ends the sieges in a draw.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void cancelSieges(Town town) {
|
||||
if (this != null) {
|
||||
Side townSide = getTownSide(town);
|
||||
@@ -448,15 +584,20 @@ public class War extends Conflict {
|
||||
getSieges().forEach(siege -> { // TODO INFINITE LOOP, runs surrenderTown
|
||||
if (siege.getTown().equals(town)) {
|
||||
if (siege.getAttackerSide().equals(townSide)) {
|
||||
siege.defendersWin();
|
||||
siege.defendersWin(BattleVictoryReason.ADMIN_CANCEL);
|
||||
} else {
|
||||
siege.attackersWin();
|
||||
siege.attackersWin(BattleVictoryReason.ADMIN_CANCEL);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Surrender a nation and all its towns out of the war.
|
||||
*
|
||||
* @param nation the nation
|
||||
*/
|
||||
public void surrenderNation(Nation nation) {
|
||||
Side nationSide = getNationSide(nation);
|
||||
if (nationSide == null) return;
|
||||
@@ -469,6 +610,11 @@ public class War extends Conflict {
|
||||
nationSide.processSurrenders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Surrender town and all its players out of a war.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
public void surrenderTown(Town town) {
|
||||
Side townSide = getTownSide(town);
|
||||
if (townSide == null) return;
|
||||
@@ -488,6 +634,11 @@ public class War extends Conflict {
|
||||
townSide.processSurrenders();
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsurrender a nation and all its towns and players.
|
||||
*
|
||||
* @param nation the nation
|
||||
*/
|
||||
public void unsurrenderNation(Nation nation) {
|
||||
Side nationSide = getNationSide(nation);
|
||||
if (nationSide == null) return;
|
||||
@@ -496,6 +647,11 @@ public class War extends Conflict {
|
||||
nation.getTowns().forEach(this::unsurrenderTown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsurrender town and all its players.
|
||||
*
|
||||
* @param town the town
|
||||
*/
|
||||
public void unsurrenderTown(Town town) {
|
||||
Side townSide = getTownSide(town);
|
||||
if (townSide == null) return;
|
||||
@@ -505,6 +661,11 @@ public class War extends Conflict {
|
||||
townSide.unsurrenderTown(town);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getTowns() {
|
||||
return Stream.concat(
|
||||
@@ -514,6 +675,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all towns in the war including surrendered towns.
|
||||
*
|
||||
* @return the all towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getAllTowns() {
|
||||
return Stream.concat(
|
||||
@@ -526,6 +692,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nations in the war excluding surrendered ones.
|
||||
*
|
||||
* @return the nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getNations() {
|
||||
return Stream.concat(
|
||||
@@ -535,6 +706,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all nations in the war including surrendered.
|
||||
*
|
||||
* @return the all nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getAllNations() {
|
||||
return Stream.concat(
|
||||
@@ -547,6 +723,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered towns in the war.
|
||||
*
|
||||
* @return the surrendered towns
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Town> getSurrenderedTowns() {
|
||||
return Stream.concat(
|
||||
@@ -556,6 +737,11 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all surrendered nations in the war.
|
||||
*
|
||||
* @return the surrendered nations
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Nation> getSurrenderedNations() {
|
||||
return Stream.concat(
|
||||
@@ -565,6 +751,10 @@ public class War extends Conflict {
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a new war after creation.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void start() {
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has started between <attacker> and <defender>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
@@ -596,25 +786,45 @@ public class War extends Conflict {
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume a pre-existing war after loading it from db.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void resume() {
|
||||
side1.applyNameTags();
|
||||
side2.applyNameTags();
|
||||
}
|
||||
|
||||
public void end() {
|
||||
/**
|
||||
* End a war for the specified reason. Triggered internally by {@link War#defeat(Side)} & {@link War#draw()}.
|
||||
*
|
||||
* @param reason the reason
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void end(WarDeleteReason reason) {
|
||||
if (!new PreWarDeleteEvent(this, reason).callEvent())
|
||||
return;
|
||||
|
||||
getSieges().forEach(Siege::stop);
|
||||
getAllTowns().forEach(Occupation::removeOccupied);
|
||||
|
||||
SQLQueries.deleteWar(this);
|
||||
WarManager.getInstance().removeWar(this);
|
||||
DatabaseQueries.deleteWar(this);
|
||||
WarController.getInstance().removeWar(this);
|
||||
|
||||
// Run check after war is removed to cleanup player tags
|
||||
getPlayers().forEach(PlayerJoinListener::checkPlayer);
|
||||
getPlayers().forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
|
||||
new WarDeleteEvent(this, reason).callEvent();
|
||||
}
|
||||
|
||||
public void defeat(@NotNull Side loserSide) {
|
||||
@NotNull Side loser = loserSide.equals(getSide1()) ? getSide1() : getSide2();
|
||||
@NotNull Side winner = loserSide.equals(getSide1()) ? getSide2() : getSide1();
|
||||
/**
|
||||
* End the war in defeat for the specified side. Internally runs {@link War#end(WarDeleteReason)}.
|
||||
*
|
||||
* @param loserSide the loser side
|
||||
*/
|
||||
public void defeat(Side loserSide) {
|
||||
Side loser = loserSide.equals(getSide1()) ? getSide1() : getSide2();
|
||||
Side winner = loserSide.equals(getSide1()) ? getSide2() : getSide1();
|
||||
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has ended. <red><winner> <reset>has triumphed against <red><loser><reset>.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
@@ -623,16 +833,36 @@ public class War extends Conflict {
|
||||
.build()
|
||||
);
|
||||
|
||||
end();
|
||||
end(WarDeleteReason.DEFEAT);
|
||||
}
|
||||
|
||||
// White defeat/force end war
|
||||
/**
|
||||
* End the war in a white peace/draw. Internally runs {@link War#end(WarDeleteReason)}.
|
||||
*/
|
||||
public void draw() {
|
||||
Bukkit.broadcast(ColorParser.of(UtilsChat.getPrefix() + "The war of <war> has ended with a white peace.")
|
||||
.parseMinimessagePlaceholder("war", getLabel())
|
||||
.build()
|
||||
);
|
||||
|
||||
end();
|
||||
end(WarDeleteReason.DRAW);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets if this is an event war.
|
||||
*
|
||||
* @param event the event
|
||||
*/
|
||||
public void setEventWar(boolean event) {
|
||||
this.event = event;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets if this is an event war. Event wars skip or execute certain logic as they are for player events.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isEventWar() {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.enums.ConflictType;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import dev.jorel.commandapi.exceptions.WrapperCommandSyntaxException;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class WarBuilder {
|
||||
private UUID uuid;
|
||||
private String name;
|
||||
private String label;
|
||||
private ConflictType conflictType = ConflictType.WAR;
|
||||
private boolean event = false;
|
||||
private Side side1;
|
||||
private Side side2;
|
||||
private Set<Siege> sieges = new HashSet<>();
|
||||
private Set<Raid> raids = new HashSet<>();
|
||||
|
||||
private Government aggressor;
|
||||
private Government victim;
|
||||
|
||||
public WarBuilder() {
|
||||
}
|
||||
|
||||
public War resume() {
|
||||
if (
|
||||
uuid == null ||
|
||||
name == null ||
|
||||
label == null ||
|
||||
side1 == null ||
|
||||
side2 == null ||
|
||||
sieges == null ||
|
||||
raids == null
|
||||
) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
name,
|
||||
label,
|
||||
side1,
|
||||
side2,
|
||||
sieges,
|
||||
raids,
|
||||
event
|
||||
);
|
||||
}
|
||||
|
||||
public War create() throws WrapperCommandSyntaxException, SideCreationException {
|
||||
this.setUuid(UUID.randomUUID());
|
||||
|
||||
return new War(
|
||||
uuid,
|
||||
label,
|
||||
aggressor,
|
||||
victim,
|
||||
event
|
||||
);
|
||||
}
|
||||
|
||||
public WarBuilder setUuid(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setName(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setLabel(String label) {
|
||||
this.label = label;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setConflictType(ConflictType conflictType) {
|
||||
this.conflictType = conflictType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSide1(Side side1) {
|
||||
this.side1 = side1;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSide2(Side side2) {
|
||||
this.side2 = side2;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setEvent(boolean event) {
|
||||
this.event = event;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setSieges(Set<Siege> sieges) {
|
||||
this.sieges = sieges;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setRaids(Set<Raid> raids) {
|
||||
this.raids = raids;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressorTown(Town target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressorNation(Nation target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictimTown(Town target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictimNation(Nation target) {
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setAggressor(Government aggressor) {
|
||||
this.aggressor = aggressor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public WarBuilder setVictim(Government victim) {
|
||||
this.victim = victim;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.raid.Raid;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.db.DatabaseQueries;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.ApiStatus;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* The singleton War controller.
|
||||
*/
|
||||
@Singleton
|
||||
public class WarController {
|
||||
private static WarController instance;
|
||||
private @NotNull Set<War> wars = new HashSet<>();
|
||||
|
||||
private WarController() {
|
||||
if (instance != null)
|
||||
Bukkit.getServer().getLogger().warning("Tried to re-initialize singleton");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets or creates an instance of the war controller.
|
||||
*
|
||||
* @return the instance
|
||||
*/
|
||||
@NotNull
|
||||
public static WarController getInstance() {
|
||||
if (instance == null)
|
||||
instance = new WarController();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all wars into memory from database.
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void loadAll() {
|
||||
wars = DatabaseQueries.loadAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all wars.
|
||||
*
|
||||
* @return the wars
|
||||
*/
|
||||
@NotNull
|
||||
public Set<War> getWars() {
|
||||
return wars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets war by its name or returns null.
|
||||
*
|
||||
* @param warName the war name
|
||||
* @return the war
|
||||
*/
|
||||
@Nullable
|
||||
public War getWar(String warName) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.equals(warName))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets war by its UUID or returns null.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the war
|
||||
*/
|
||||
@Nullable
|
||||
public War getWar(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.equals(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets side by the side UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the side
|
||||
*/
|
||||
@Nullable
|
||||
public Side getSide(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.getSide(uuid) != null)
|
||||
.map(war -> war.getSide(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets siege by the siege UUID.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the siege
|
||||
*/
|
||||
@Nullable
|
||||
public Siege getSiege(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.getSiege(uuid) != null)
|
||||
.map(war -> war.getSiege(uuid))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a war to the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void addWar(War war) {
|
||||
getWars().add(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a war from the war controller.
|
||||
*
|
||||
* @param war the war
|
||||
*/
|
||||
@ApiStatus.Internal
|
||||
public void removeWar(War war) {
|
||||
getWars().remove(war);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnyWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isPlayerInWar(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnyWars(Player p) {
|
||||
return isPlayerInAnyWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player wars
|
||||
*/
|
||||
public @NotNull Set<War> getPlayerWars(Player p) {
|
||||
return getPlayerWars(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets list of player wars. Includes if surrendered.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player wars
|
||||
*/
|
||||
public @NotNull Set<War> getPlayerWars(UUID uuid) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isPlayerInWar(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any wars. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnyWars(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any sieges. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnySieges(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderSiege(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is town in any raids. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isTownInAnyRaids(Town town) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isTownInWar(town) && war.isTownUnderRaid(town));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any sieges. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInAnySieges(Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isTownInAnySieges);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any raids. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInAnyRaids(Nation nation) {
|
||||
return nation.getTowns().stream()
|
||||
.anyMatch(this::isTownInAnyRaids);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town sieges. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the town sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getTownSieges(Town town) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.getAttackerSide().isTownOnSide(town) || siege.getDefenderSide().isTownOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town raids. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the town raids
|
||||
*/
|
||||
public @NotNull Set<Raid> getTownRaids(Town town) {
|
||||
return getRaids().stream()
|
||||
.filter(raid -> raid.getAttackerSide().isTownOnSide(town) || raid.getDefenderSide().isTownOnSide(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets town wars. Includes surrendered towns.
|
||||
*
|
||||
* @param town the town
|
||||
* @return the town wars
|
||||
*/
|
||||
public @NotNull Set<War> getTownWars(Town town) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isTownInWar(town))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is nation in any wars. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isNationInAnyWars(Nation nation) {
|
||||
return getWars().stream()
|
||||
.anyMatch(war -> war.isNationInWar(nation));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nation wars. Includes surrendered nations.
|
||||
*
|
||||
* @param nation the nation
|
||||
* @return the nation wars
|
||||
*/
|
||||
public @NotNull Set<War> getNationWars(Nation nation) {
|
||||
return getWars().stream()
|
||||
.filter(war -> war.isNationInWar(nation))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of war names.
|
||||
*
|
||||
* @return the war names
|
||||
*/
|
||||
@NotNull
|
||||
public List<String> getWarNames() {
|
||||
return getWars().stream()
|
||||
.map(War::getName)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of war labels.
|
||||
*
|
||||
* @return the war labels
|
||||
*/
|
||||
@NotNull
|
||||
public List<String> getWarLabels() {
|
||||
return getWars().stream()
|
||||
.map(War::getLabel)
|
||||
.sorted(String::compareToIgnoreCase)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active sieges.
|
||||
*
|
||||
* @return the sieges
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Siege> getSieges() {
|
||||
return getWars().stream()
|
||||
.map(War::getSieges)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all active raids.
|
||||
*
|
||||
* @return the raids
|
||||
*/
|
||||
@NotNull
|
||||
public Set<Raid> getRaids() {
|
||||
return getWars().stream()
|
||||
.map(War::getRaids)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any siege.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnySiege(Player p) {
|
||||
return isPlayerInAnySiege(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Is player in any siege. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isPlayerInAnySiege(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.anyMatch(siege -> siege.isPlayerInSiege(uuid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges.
|
||||
*
|
||||
* @param p the p
|
||||
* @return the player sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getPlayerSieges(Player p) {
|
||||
return getPlayerSieges(p.getUniqueId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets player sieges. Returns true for offline players.
|
||||
*
|
||||
* @param uuid the uuid
|
||||
* @return the player sieges
|
||||
*/
|
||||
public @NotNull Set<Siege> getPlayerSieges(UUID uuid) {
|
||||
return getSieges().stream()
|
||||
.filter(siege -> siege.isPlayerInSiege(uuid))
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets nations at war. Does not include surrendered nations.
|
||||
*
|
||||
* @return the nations at war
|
||||
*/
|
||||
public @NotNull Set<Nation> getNationsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getNations)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets towns at war. Does not include surrendered towns.
|
||||
*
|
||||
* @return the towns at war
|
||||
*/
|
||||
public @NotNull Set<Town> getTownsAtWar() {
|
||||
return getWars().stream()
|
||||
.map(War::getTowns)
|
||||
.flatMap(Set::stream)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.github.alathra.alathranwars.conflict.war;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
|
||||
public class WarCreationException extends SideCreationException {
|
||||
public WarCreationException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
}
|
||||
+75
-60
@@ -1,9 +1,12 @@
|
||||
package com.github.alathra.AlathranWars.conflict;
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.github.alathra.AlathranWars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.AlathranWars.enums.BattleSide;
|
||||
import com.github.alathra.AlathranWars.enums.BattleTeam;
|
||||
import com.github.alathra.AlathranWars.listeners.war.PlayerJoinListener;
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.hooks.NameColorHandler;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
@@ -46,7 +49,7 @@ public class Side {
|
||||
public Side(
|
||||
UUID warUUID,
|
||||
UUID uuid,
|
||||
Town town,
|
||||
Government government,
|
||||
BattleSide side,
|
||||
BattleTeam team,
|
||||
String name,
|
||||
@@ -58,12 +61,11 @@ public class Side {
|
||||
Set<UUID> surrenderedPlayersIncludingOffline,
|
||||
Instant siegeGrace,
|
||||
Instant raidGrace
|
||||
) {
|
||||
) throws SideCreationException {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = town;
|
||||
this.name = name;
|
||||
|
||||
this.towns = towns;
|
||||
@@ -78,16 +80,22 @@ public class Side {
|
||||
this.siegeGrace = siegeGrace;
|
||||
this.raidGrace = raidGrace;
|
||||
|
||||
if (government instanceof Nation nation) {
|
||||
this.town = nation.getCapital();
|
||||
} else if (government instanceof Town town2) {
|
||||
this.town = town2;
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public Side(UUID warUUID, UUID uuid, Town town, BattleSide side, BattleTeam team) {
|
||||
public Side(UUID warUUID, UUID uuid, Government government, BattleSide side, BattleTeam team) throws SideCreationException {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = town;
|
||||
this.name = this.town.getName();
|
||||
|
||||
this.towns = new HashSet<>();
|
||||
this.nations = new HashSet<>();
|
||||
@@ -98,30 +106,18 @@ public class Side {
|
||||
this.surrenderedNations = new HashSet<>();
|
||||
this.surrenderedPlayersIncludingOffline = new HashSet<>();
|
||||
|
||||
addTown(this.town);
|
||||
if (government instanceof Nation nation) {
|
||||
this.town = nation.getCapital();
|
||||
addNation(nation);
|
||||
} else if (government instanceof Town town2) {
|
||||
this.town = town2;
|
||||
addTown(town2);
|
||||
} else {
|
||||
throw new SideCreationException("No town or nation specified!");
|
||||
}
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
public Side(UUID warUUID, UUID uuid, @NotNull Nation nation, BattleSide side, BattleTeam team) {
|
||||
this.warUUID = warUUID;
|
||||
this.uuid = uuid;
|
||||
this.side = side;
|
||||
this.team = team;
|
||||
this.town = nation.getCapital();
|
||||
this.name = this.town.getName();
|
||||
|
||||
this.towns = new HashSet<>();
|
||||
this.nations = new HashSet<>();
|
||||
this.playersIncludingOffline = new HashSet<>();
|
||||
this.players = new HashSet<>();
|
||||
|
||||
this.surrenderedTowns = new HashSet<>();
|
||||
this.surrenderedNations = new HashSet<>();
|
||||
this.surrenderedPlayersIncludingOffline = new HashSet<>();
|
||||
|
||||
addNation(nation);
|
||||
|
||||
calculateOnlinePlayers();
|
||||
}
|
||||
|
||||
@@ -183,7 +179,7 @@ public class Side {
|
||||
return surrenderedNations.contains(nation);
|
||||
}
|
||||
|
||||
public void addTown(@NotNull Town town) {
|
||||
public void addTown(Town town) {
|
||||
if (isTownOnSide(town)) return;
|
||||
|
||||
towns.add(town);
|
||||
@@ -191,7 +187,7 @@ public class Side {
|
||||
town.getResidents().forEach((Resident resident) -> addPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void addNation(@NotNull Nation nation) {
|
||||
public void addNation(Nation nation) {
|
||||
if (isNationOnSide(nation)) return;
|
||||
|
||||
nations.add(nation);
|
||||
@@ -199,7 +195,7 @@ public class Side {
|
||||
nation.getTowns().forEach(this::addTown);
|
||||
}
|
||||
|
||||
public void removeTown(@NotNull Town town) {
|
||||
public void removeTown(Town town) {
|
||||
if (!isTownOnSide(town)) return;
|
||||
|
||||
towns.remove(town);
|
||||
@@ -207,7 +203,7 @@ public class Side {
|
||||
town.getResidents().forEach((Resident resident) -> removePlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void removeNation(@NotNull Nation nation) {
|
||||
public void removeNation(Nation nation) {
|
||||
if (!isNationOnSide(nation)) return;
|
||||
|
||||
nations.remove(nation);
|
||||
@@ -215,7 +211,7 @@ public class Side {
|
||||
nation.getTowns().forEach(this::removeTown);
|
||||
}
|
||||
|
||||
public void surrenderTown(@NotNull Town town) {
|
||||
public void surrenderTown(Town town) {
|
||||
if (isTownSurrendered(town)) return;
|
||||
|
||||
removeTown(town);
|
||||
@@ -225,7 +221,7 @@ public class Side {
|
||||
town.getResidents().forEach((Resident resident) -> surrenderPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void surrenderNation(@NotNull Nation nation) {
|
||||
public void surrenderNation(Nation nation) {
|
||||
if (isNationSurrendered(nation)) return;
|
||||
|
||||
removeNation(nation);
|
||||
@@ -235,7 +231,7 @@ public class Side {
|
||||
nation.getTowns().forEach(this::surrenderTown);
|
||||
}
|
||||
|
||||
public void unsurrenderTown(@NotNull Town town) {
|
||||
public void unsurrenderTown(Town town) {
|
||||
if (!isTownSurrendered(town)) return;
|
||||
|
||||
addTown(town);
|
||||
@@ -245,7 +241,7 @@ public class Side {
|
||||
town.getResidents().forEach((Resident resident) -> unsurrenderPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void unsurrenderNation(@NotNull Nation nation) {
|
||||
public void unsurrenderNation(Nation nation) {
|
||||
if (!isNationSurrendered(nation)) return;
|
||||
|
||||
addNation(nation);
|
||||
@@ -255,7 +251,21 @@ public class Side {
|
||||
nation.getTowns().forEach(this::unsurrenderTown);
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(@NotNull Player p) {
|
||||
public void kickTown(Town town) {
|
||||
towns.remove(town);
|
||||
surrenderedTowns.remove(town);
|
||||
|
||||
town.getResidents().forEach(resident -> kickPlayer(resident.getUUID()));
|
||||
}
|
||||
|
||||
public void kickNation(Nation nation) {
|
||||
nations.remove(nation);
|
||||
surrenderedNations.remove(nation);
|
||||
|
||||
nation.getTowns().forEach(this::kickTown);
|
||||
}
|
||||
|
||||
public boolean isPlayerOnSide(Player p) {
|
||||
return isPlayerOnSide(p.getUniqueId());
|
||||
}
|
||||
|
||||
@@ -263,7 +273,7 @@ public class Side {
|
||||
return playersIncludingOffline.contains(uuid) || surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public boolean isPlayerSurrendered(@NotNull Player p) {
|
||||
public boolean isPlayerSurrendered(Player p) {
|
||||
return isPlayerSurrendered(p.getUniqueId());
|
||||
}
|
||||
|
||||
@@ -271,21 +281,21 @@ public class Side {
|
||||
return surrenderedPlayersIncludingOffline.contains(uuid);
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull Player p) {
|
||||
public void addPlayer(Player p) {
|
||||
addPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull OfflinePlayer offlinePlayer) {
|
||||
public void addPlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
addPlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void addPlayer(@NotNull UUID uuid) {
|
||||
public void addPlayer(UUID uuid) {
|
||||
if (isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.add(uuid);
|
||||
if (getWar() != null) { // We need to check this as on side creation War doesn't exist
|
||||
for (@NotNull Siege siege : getWar().getSieges()) {
|
||||
for (Siege siege : getWar().getSieges()) {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.addPlayer(uuid, BattleSide.ATTACKER);
|
||||
} else {
|
||||
@@ -304,21 +314,21 @@ public class Side {
|
||||
players.add(p);
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull Player p) {
|
||||
public void removePlayer(Player p) {
|
||||
removePlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull OfflinePlayer offlinePlayer) {
|
||||
public void removePlayer(OfflinePlayer offlinePlayer) {
|
||||
if (offlinePlayer.hasPlayedBefore())
|
||||
removePlayer(offlinePlayer.getUniqueId());
|
||||
}
|
||||
|
||||
public void removePlayer(@NotNull UUID uuid) {
|
||||
public void removePlayer(UUID uuid) {
|
||||
if (!isPlayerOnSide(uuid)) return;
|
||||
|
||||
playersIncludingOffline.remove(uuid);
|
||||
if (getWar() != null) { // We need to check this as on side creation War doesn't exist
|
||||
for (@NotNull Siege siege : getWar().getSieges()) {
|
||||
for (Siege siege : getWar().getSieges()) {
|
||||
if (siege.getAttackerSide().equals(this)) {
|
||||
siege.removePlayer(uuid);
|
||||
} else {
|
||||
@@ -333,15 +343,20 @@ public class Side {
|
||||
}
|
||||
}
|
||||
|
||||
public void kickPlayer(UUID uuid) {
|
||||
removePlayer(uuid);
|
||||
surrenderedPlayersIncludingOffline.remove(uuid);
|
||||
}
|
||||
|
||||
public void removeOnlinePlayer(Player p) {
|
||||
players.remove(p);
|
||||
}
|
||||
|
||||
public void surrenderPlayer(@NotNull Player p) {
|
||||
public void surrenderPlayer(Player p) {
|
||||
surrenderPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void surrenderPlayer(@NotNull UUID uuid) {
|
||||
public void surrenderPlayer(UUID uuid) {
|
||||
if (isPlayerSurrendered(uuid)) return;
|
||||
|
||||
removePlayer(uuid);
|
||||
@@ -349,11 +364,11 @@ public class Side {
|
||||
applyNameTags();
|
||||
}
|
||||
|
||||
public void unsurrenderPlayer(@NotNull Player p) {
|
||||
public void unsurrenderPlayer(Player p) {
|
||||
unsurrenderPlayer(p.getUniqueId());
|
||||
}
|
||||
|
||||
public void unsurrenderPlayer(@NotNull UUID uuid) {
|
||||
public void unsurrenderPlayer(UUID uuid) {
|
||||
if (!isPlayerSurrendered(uuid)) return;
|
||||
|
||||
addPlayer(uuid);
|
||||
@@ -362,7 +377,7 @@ public class Side {
|
||||
}
|
||||
|
||||
public void calculateOnlinePlayers() {
|
||||
final @NotNull Set<Player> onlinePlayers = getPlayersIncludingOffline().stream()
|
||||
final Set<Player> onlinePlayers = getPlayersIncludingOffline().stream()
|
||||
.filter(uuid -> Bukkit.getOfflinePlayer(uuid).isOnline())
|
||||
.map(Bukkit::getPlayer)
|
||||
.collect(Collectors.toSet());
|
||||
@@ -374,12 +389,12 @@ public class Side {
|
||||
}
|
||||
|
||||
public void applyNameTags() {
|
||||
players.forEach(PlayerJoinListener::checkPlayer);
|
||||
players.forEach(p -> NameColorHandler.getInstance().getPlayerNameColor(p));
|
||||
surrenderedPlayersIncludingOffline.stream()
|
||||
.filter((UUID uuid) -> Bukkit.getPlayer(uuid) != null)
|
||||
.map(Bukkit::getPlayer)
|
||||
.toList()
|
||||
.forEach(PlayerJoinListener::checkPlayer);
|
||||
.forEach(p -> NameColorHandler.getInstance().calculatePlayerColors(p));
|
||||
}
|
||||
|
||||
// Graces
|
||||
@@ -436,11 +451,11 @@ public class Side {
|
||||
return this.uuid.equals(uuid);
|
||||
}
|
||||
|
||||
public boolean equals(@NotNull War war) {
|
||||
public boolean equals(War war) {
|
||||
return this.warUUID.equals(war.getUUID());
|
||||
}
|
||||
|
||||
public boolean equals(@NotNull Side side) {
|
||||
public boolean equals(Side side) {
|
||||
return getUUID().equals(side.getUUID());
|
||||
}
|
||||
|
||||
@@ -454,7 +469,7 @@ public class Side {
|
||||
|
||||
@Nullable
|
||||
public War getWar() {
|
||||
return WarManager.getInstance().getWar(warUUID); // The war must exist, or this object wouldn't
|
||||
return WarController.getInstance().getWar(warUUID); // The war must exist, or this object wouldn't
|
||||
}
|
||||
|
||||
public void processSurrenders() {
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.palmergames.bukkit.towny.object.Government;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public class SideBuilder {
|
||||
private UUID warUUID;
|
||||
private UUID uuid;
|
||||
private BattleSide side;
|
||||
private BattleTeam team;
|
||||
private String name;
|
||||
|
||||
private Government government;
|
||||
|
||||
private Set<Town> towns;
|
||||
private Set<Nation> nations;
|
||||
private Set<UUID> playersIncludingOffline;
|
||||
private Set<Town> surrenderedTowns;
|
||||
private Set<Nation> surrenderedNations;
|
||||
private Set<UUID> surrenderedPlayersIncludingOffline;
|
||||
private Instant siegeGrace;
|
||||
private Instant raidGrace;
|
||||
|
||||
public SideBuilder() {
|
||||
}
|
||||
|
||||
public Side rebuild() throws SideCreationException {
|
||||
// if (warUUID == null || uuid == null || town == null || side == null || team == null || name == null ||
|
||||
// towns == null || nations == null || playersIncludingOffline == null ||
|
||||
// surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
|
||||
// siegeGrace == null || raidGrace == null
|
||||
// ) throw new IllegalStateException("Missing state to create Side 1");
|
||||
// TODO Cleanup this shit
|
||||
if (warUUID == null || uuid == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1.2");
|
||||
|
||||
if (government == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1.3");
|
||||
if (side == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1.1");
|
||||
|
||||
if (team == null || name == null ||
|
||||
towns == null || nations == null
|
||||
) throw new IllegalStateException("Missing state to create Side 1");
|
||||
|
||||
if (playersIncludingOffline == null ||
|
||||
surrenderedTowns == null || surrenderedNations == null || surrenderedPlayersIncludingOffline == null ||
|
||||
siegeGrace == null || raidGrace == null
|
||||
) throw new IllegalStateException("Missing state to create Side 2");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
government,
|
||||
side,
|
||||
team,
|
||||
name,
|
||||
towns,
|
||||
nations,
|
||||
playersIncludingOffline,
|
||||
surrenderedTowns,
|
||||
surrenderedNations,
|
||||
surrenderedPlayersIncludingOffline,
|
||||
siegeGrace,
|
||||
raidGrace
|
||||
);
|
||||
}
|
||||
|
||||
public Side build() throws SideCreationException {
|
||||
if (warUUID == null || uuid == null || government == null || side == null || team == null)
|
||||
throw new IllegalStateException("Missing state to create new Side");
|
||||
|
||||
return new Side(
|
||||
warUUID,
|
||||
uuid,
|
||||
government,
|
||||
side,
|
||||
team
|
||||
);
|
||||
}
|
||||
|
||||
public SideBuilder setWarUUID(UUID warUUID) {
|
||||
this.warUUID = warUUID;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setUuid(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSide(BattleSide side) {
|
||||
this.side = side;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTeam(BattleTeam team) {
|
||||
this.team = team;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setName(String name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setLeader(Government target) {
|
||||
this.government = target;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setTowns(Set<Town> towns) {
|
||||
this.towns = towns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setNations(Set<Nation> nations) {
|
||||
this.nations = nations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setPlayersIncludingOffline(Set<UUID> playersIncludingOffline) {
|
||||
this.playersIncludingOffline = playersIncludingOffline;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedTowns(Set<Town> surrenderedTowns) {
|
||||
this.surrenderedTowns = surrenderedTowns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedNations(Set<Nation> surrenderedNations) {
|
||||
this.surrenderedNations = surrenderedNations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSurrenderedPlayersIncludingOffline(Set<UUID> surrenderedPlayersIncludingOffline) {
|
||||
this.surrenderedPlayersIncludingOffline = surrenderedPlayersIncludingOffline;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setSiegeGrace(Instant siegeGrace) {
|
||||
this.siegeGrace = siegeGrace;
|
||||
return this;
|
||||
}
|
||||
|
||||
public SideBuilder setRaidGrace(Instant raidGrace) {
|
||||
this.raidGrace = raidGrace;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.conflict.war.side;
|
||||
|
||||
public class SideCreationException extends Exception {
|
||||
public SideCreationException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.data;
|
||||
package com.github.alathra.alathranwars.data;
|
||||
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.github.alathra.alathranwars.data;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import com.palmergames.bukkit.towny.object.metadata.LocationDataField;
|
||||
import com.palmergames.bukkit.towny.utils.MetaDataUtil;
|
||||
import org.bukkit.Location;
|
||||
|
||||
public class TownMetaController {
|
||||
private AlathranWars plugin;
|
||||
private static LocationDataField defendersSpawn = new LocationDataField("alathranwars_defendersSpawn");
|
||||
|
||||
TownMetaController(AlathranWars plugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public static boolean hasDefendersSpawn(Town town) {
|
||||
return town.hasMeta(defendersSpawn.getKey());
|
||||
}
|
||||
|
||||
public static Location getDefendersSpawn(Town town) {
|
||||
if (hasDefendersSpawn(town)) {
|
||||
return MetaDataUtil.getLocation(town, defendersSpawn);
|
||||
} else {
|
||||
Location location = town.getSpawnOrNull();
|
||||
|
||||
setDefendersSpawn(town, location);
|
||||
|
||||
return location;
|
||||
}
|
||||
}
|
||||
|
||||
public static void setDefendersSpawn(Town town, Location location) {
|
||||
if (hasDefendersSpawn(town)) {
|
||||
MetaDataUtil.setLocation(town, defendersSpawn, location, true);
|
||||
} else {
|
||||
town.addMetaData(new LocationDataField(defendersSpawn.getKey(), location));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
package com.github.alathra.alathranwars.db;
|
||||
|
||||
import com.github.alathra.alathranwars.AlathranWars;
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
import com.github.alathra.alathranwars.db.flyway.DatabaseMigrationException;
|
||||
import com.github.alathra.alathranwars.db.flyway.DatabaseMigrationHandler;
|
||||
import com.github.alathra.alathranwars.db.jooq.JooqContext;
|
||||
import com.github.alathra.alathranwars.utility.Cfg;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.zaxxer.hikari.HikariConfig;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import javax.inject.Singleton;
|
||||
import java.io.File;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Class that handles HikariCP connection pool, jOOQ and Flyway migrations.
|
||||
*/
|
||||
@Singleton
|
||||
public class DatabaseHandler implements Reloadable {
|
||||
private final AlathranWars alathranWars;
|
||||
private boolean isConnected = false;
|
||||
private HikariDataSource hikariDataSource;
|
||||
private DatabaseType database;
|
||||
private JooqContext jooqContext;
|
||||
|
||||
/**
|
||||
* Instantiates a new Data handler.
|
||||
*
|
||||
* @param alathranWars the plugin instance
|
||||
*/
|
||||
public DatabaseHandler(AlathranWars alathranWars) {
|
||||
this.alathranWars = alathranWars;
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin load.
|
||||
*/
|
||||
@Override
|
||||
public void onLoad() {
|
||||
try {
|
||||
openConnection();
|
||||
isConnected = true;
|
||||
} catch (Exception e) {
|
||||
Logger.get().error("[DB] Database initialization error: ", e);
|
||||
} finally {
|
||||
if (!isConnected()) {
|
||||
Logger.get().warn("[DB] Failed to initialize database connection. Functionality will be limited.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin enable.
|
||||
*/
|
||||
@Override
|
||||
public void onEnable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* On plugin disable.
|
||||
*/
|
||||
@Override
|
||||
public void onDisable() {
|
||||
try {
|
||||
closeDatabaseConnection();
|
||||
isConnected = false;
|
||||
} catch (Exception e) {
|
||||
Logger.get().error("[DB] Error closing database connections:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns if the database is setup and functioning properly.
|
||||
*
|
||||
* @return the boolean
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return isConnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets db.
|
||||
*
|
||||
* @return the db
|
||||
*/
|
||||
public DatabaseType getDB() {
|
||||
return database;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets jooq context.
|
||||
*
|
||||
* @return the jooq context
|
||||
*/
|
||||
public JooqContext getJooqContext() {
|
||||
return jooqContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a connection from the connection pool.
|
||||
*
|
||||
* @return the connection
|
||||
* @throws SQLException the sql exception
|
||||
*/
|
||||
@NotNull
|
||||
public Connection getConnection() throws SQLException {
|
||||
if (hikariDataSource == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource returned null)");
|
||||
|
||||
final Connection connection = hikariDataSource.getConnection();
|
||||
if (connection == null)
|
||||
throw new SQLException("[DB] Unable to getConnection a connection from the pool. (HikariDataSource#getConnection returned null)");
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a connection pool using HikariCP and executes Flyway migrations.
|
||||
*/
|
||||
private void openConnection() {
|
||||
if (hikariDataSource != null) {
|
||||
Logger.get().warn("[DB] Attempted to create a new database pool while running!");
|
||||
return;
|
||||
}
|
||||
|
||||
final HikariConfig hikariConfig = new HikariConfig();
|
||||
final String vendorName = Cfg.get().get("db.type", DatabaseType.HSQLDB.getDriverName());
|
||||
final DatabaseType db = DatabaseType.getDatabaseTypeFromJdbcPrefix(vendorName);
|
||||
|
||||
if (db == null) {
|
||||
Logger.get().warn("[DB] Invalid database type was specified!");
|
||||
return;
|
||||
}
|
||||
|
||||
final String host = Cfg.get().get("db.host", "127.0.0.1");
|
||||
final String port = Cfg.get().get("db.port", "3306");
|
||||
final String database = Cfg.get().get("db.database", "database");
|
||||
final String username = Cfg.get().get("db.user", "root");
|
||||
final String password = Cfg.get().get("db.pass", "");
|
||||
|
||||
final String connectionProperties = switch (db) {
|
||||
case H2 -> DatabaseType.H2.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
"AUTO_SERVER", "TRUE",
|
||||
"MODE", "MySQL", // MySQL support mode
|
||||
"CASE_INSENSITIVE_IDENTIFIERS", "TRUE",
|
||||
"IGNORECASE", "TRUE"
|
||||
)
|
||||
);
|
||||
case HSQLDB -> DatabaseType.HSQLDB.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
"sql.syntax_mys", "true", // MySQL support mode
|
||||
// Prevent execution of multiple queries in one Statement
|
||||
"sql.restrict_exec", true,
|
||||
// Make the names of generated indexes the same as the names of the constraints
|
||||
"sql.sys_index_names", true,
|
||||
/*
|
||||
* Enforce SQL standards on
|
||||
* 1.) table and column names
|
||||
* 2.) ambiguous column references
|
||||
* 3.) illegal type conversions
|
||||
*/
|
||||
"sql.enforce_names", true,
|
||||
"sql.enforce_refs", true,
|
||||
"sql.enforce_types", true,
|
||||
// Respect interrupt status during query execution
|
||||
"hsqldb.tx_interrupt_rollback", true,
|
||||
// Use CACHED tables by default
|
||||
"hsqldb.default_table_type", "cached",
|
||||
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
|
||||
"allowMultiQueries", true,
|
||||
// Help debug in case of exceptions
|
||||
"dumpQueriesOnException", true
|
||||
)
|
||||
);
|
||||
case MARIADB -> DatabaseType.MARIADB.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Performance improvements
|
||||
"autocommit", false,
|
||||
"defaultFetchSize", 1000,
|
||||
|
||||
// Help debug in case of deadlock
|
||||
"includeInnodbStatusInDeadlockExceptions", true,
|
||||
"includeThreadDumpInDeadlockExceptions", true,
|
||||
|
||||
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
|
||||
"socketTimeout", 14000L,
|
||||
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
|
||||
"allowMultiQueries", true,
|
||||
// Help debug in case of exceptions
|
||||
"dumpQueriesOnException", true
|
||||
)
|
||||
);
|
||||
case MYSQL -> DatabaseType.MYSQL.formatJdbcConnectionProperties(
|
||||
Map.of(
|
||||
// Performance improvements
|
||||
"autocommit", false,
|
||||
"defaultFetchSize", 1000,
|
||||
|
||||
// Help debug in case of deadlock
|
||||
"includeInnodbStatusInDeadlockExceptions", true,
|
||||
"includeThreadDumpInDeadlockExceptions", true,
|
||||
|
||||
// https://github.com/brettwooldridge/HikariCP/wiki/Rapid-Recovery#mysql
|
||||
"socketTimeout", 14000L,
|
||||
// Needed for use with connection init-SQL (hikariConf.setConnectionInitSql)
|
||||
"allowMultiQueries", true,
|
||||
// Help debug in case of exceptions
|
||||
"dumpQueriesOnException", true
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
switch (db) {
|
||||
case HSQLDB, H2 -> {
|
||||
final String subfolder = "data";
|
||||
final String fileName = "database";
|
||||
final String fileExtension = switch (db) {
|
||||
case HSQLDB -> ".hsql";
|
||||
case H2 -> ".mv.db";
|
||||
default -> "";
|
||||
};
|
||||
final String fileNameWithExtension = fileName + fileExtension;
|
||||
|
||||
// Set credentials for HSQL and H2
|
||||
hikariConfig.setUsername("SA");
|
||||
hikariConfig.setPassword("");
|
||||
|
||||
hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
|
||||
hikariConfig.addDataSourceProperty("url", "jdbc:%s:%s".formatted(
|
||||
db.getJdbcPrefix(),
|
||||
alathranWars.getDataFolder().getAbsolutePath() + File.separatorChar + subfolder + File.separatorChar + (db.equals(DatabaseType.H2) ? fileName : fileNameWithExtension) + connectionProperties
|
||||
));
|
||||
}
|
||||
case MYSQL, MARIADB -> {
|
||||
hikariConfig.setDataSourceClassName(db.getDataSourceClassName());
|
||||
hikariConfig.addDataSourceProperty("url", "jdbc:%s://%s%s/%s".formatted(
|
||||
db.getJdbcPrefix(),
|
||||
host,
|
||||
":%s".formatted(port),
|
||||
database + connectionProperties
|
||||
));
|
||||
|
||||
hikariConfig.setUsername(username);
|
||||
hikariConfig.setPassword(password);
|
||||
|
||||
hikariConfig.setKeepaliveTime(0);
|
||||
}
|
||||
}
|
||||
|
||||
hikariConfig.setConnectionTimeout(14000);
|
||||
hikariConfig.setMaxLifetime(25000000);
|
||||
hikariConfig.setInitializationFailTimeout(-1); // We try to create tables after this anyways which will error if no connection
|
||||
|
||||
final int poolSize = Cfg.get().getOrDefault("db.poolsize", 10);
|
||||
hikariConfig.setMaximumPoolSize(poolSize);
|
||||
hikariConfig.setMinimumIdle(poolSize);
|
||||
|
||||
hikariConfig.setPoolName("%s-hikari".formatted(AlathranWars.getInstance().getName()));
|
||||
hikariConfig.setAutoCommit(true);
|
||||
hikariConfig.setTransactionIsolation("TRANSACTION_REPEATABLE_READ");
|
||||
hikariConfig.setIsolateInternalQueries(true);
|
||||
hikariConfig.setConnectionInitSql(db.getConnectionInitSql());
|
||||
|
||||
this.hikariDataSource = new HikariDataSource(hikariConfig);
|
||||
this.database = db;
|
||||
this.jooqContext = new JooqContext(db.getSQLDialect());
|
||||
|
||||
try {
|
||||
new DatabaseMigrationHandler(Cfg.get(), hikariDataSource, db)
|
||||
.migrate();
|
||||
} catch (DatabaseMigrationException e) {
|
||||
Logger.get().error("[DB] Failed to migrate database. Please backup your database and report the issue.", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection pool.
|
||||
*/
|
||||
private void closeDatabaseConnection() throws Exception {
|
||||
Logger.get().info("[DB] Closing database connection...");
|
||||
|
||||
if (hikariDataSource == null) {
|
||||
Logger.get().error("[DB] Skipped closing database connection because the data source is null. Was there a previous error which needs to be fixed? Check your console logs!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (hikariDataSource.isClosed()) {
|
||||
Logger.get().info("[DB] Skipped closing database connection: connection is already closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
hikariDataSource.close();
|
||||
hikariDataSource = null;
|
||||
|
||||
Logger.get().info("[DB] Closed database connection.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,556 @@
|
||||
package com.github.alathra.alathranwars.db;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.siege.Siege;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.Side;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideBuilder;
|
||||
import com.github.alathra.alathranwars.conflict.war.side.SideCreationException;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleSide;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleTeam;
|
||||
import com.github.alathra.alathranwars.utility.DB;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import com.palmergames.bukkit.towny.TownyAPI;
|
||||
import com.palmergames.bukkit.towny.object.Nation;
|
||||
import com.palmergames.bukkit.towny.object.Town;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.jetbrains.annotations.Contract;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jooq.DSLContext;
|
||||
import org.jooq.Record;
|
||||
import org.jooq.Result;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Savepoint;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.github.alathra.alathranwars.db.schema.Tables.*;
|
||||
|
||||
/**
|
||||
* A holder class for all SQL queries
|
||||
*/
|
||||
public abstract class DatabaseQueries {
|
||||
private interface LambdaInterface {
|
||||
void execute(Connection connection, DSLContext dslContext) throws SQLException, DataAccessException;
|
||||
}
|
||||
|
||||
private static void transactionWrapper(Connection con, LambdaInterface lambda) throws SQLException, DataAccessException {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
final Savepoint savePoint = con.setSavepoint();
|
||||
final boolean autoCommit = con.getAutoCommit();
|
||||
|
||||
try {
|
||||
con.setAutoCommit(false);
|
||||
|
||||
lambda.execute(con, context);
|
||||
|
||||
con.commit();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
con.rollback(savePoint);
|
||||
} finally {
|
||||
con.setAutoCommit(autoCommit);
|
||||
}
|
||||
}
|
||||
|
||||
public static byte[] convertUUIDToBytes(UUID uuid) {
|
||||
ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
|
||||
buffer.putLong(uuid.getMostSignificantBits());
|
||||
buffer.putLong(uuid.getLeastSignificantBits());
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
public static UUID convertBytesToUUID(byte[] bytes) {
|
||||
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
|
||||
return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
|
||||
}
|
||||
|
||||
// Setters
|
||||
|
||||
public static void saveAll() {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
for (War war : WarController.getInstance().getWars()) {
|
||||
context
|
||||
// .insertInto(LIST)
|
||||
// .set(LIST.UUID, DatabaseQueries.convertUUIDToBytes(war.getUUID()))
|
||||
// .set(LIST.NAME, war.getName())
|
||||
// .set(LIST.LABEL, war.getLabel())
|
||||
// .set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
|
||||
// .set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
|
||||
// .set(LIST.EVENT, war.isEventWar() ? (byte) 1 : (byte) 0)
|
||||
.insertInto(LIST, LIST.UUID, LIST.NAME, LIST.LABEL, LIST.SIDE1, LIST.SIDE2, LIST.EVENT)
|
||||
.values(
|
||||
DatabaseQueries.convertUUIDToBytes(war.getUUID()),
|
||||
war.getName(),
|
||||
war.getLabel(),
|
||||
DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()),
|
||||
DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()),
|
||||
war.isEventWar() ? (byte) 1 : (byte) 0
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(LIST.NAME, war.getName())
|
||||
.set(LIST.LABEL, war.getLabel())
|
||||
.set(LIST.SIDE1, DatabaseQueries.convertUUIDToBytes(war.getSide1().getUUID()))
|
||||
.set(LIST.SIDE2, DatabaseQueries.convertUUIDToBytes(war.getSide2().getUUID()))
|
||||
.execute();
|
||||
|
||||
// Save sides
|
||||
for (Side side : war.getSides()) {
|
||||
saveSide(con, side);
|
||||
}
|
||||
|
||||
// Save sieges
|
||||
for (Siege siege : war.getSieges()) {
|
||||
saveSiege(con, siege);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
Logger.get().error("SQL Query failed to save data!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSide(Connection con, Side side) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.insertInto(SIDES, SIDES.WAR, SIDES.UUID, SIDES.SIDE, SIDES.TEAM, SIDES.NAME, SIDES.TOWN, SIDES.SIEGEGRACE, SIDES.RAIDGRACE)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getWar().getUUID()),
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
side.getSide().toString(),
|
||||
side.getTeam().toString(),
|
||||
side.getName(),
|
||||
convertUUIDToBytes(side.getTown().getUUID()),
|
||||
LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC)
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(SIDES.SIDE, side.getSide().toString())
|
||||
.set(SIDES.TEAM, side.getTeam().toString())
|
||||
.set(SIDES.NAME, side.getName())
|
||||
.set(SIDES.TOWN, convertUUIDToBytes(side.getTown().getUUID()))
|
||||
.set(SIDES.SIEGEGRACE, LocalDateTime.ofInstant(side.getSiegeGrace(), ZoneOffset.UTC))
|
||||
.set(SIDES.RAIDGRACE, LocalDateTime.ofInstant(side.getRaidGrace(), ZoneOffset.UTC))
|
||||
.execute();
|
||||
|
||||
saveSideNations(con, side);
|
||||
saveSideTowns(con, side);
|
||||
saveSidePlayers(con, side);
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSideNations(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (Nation nation : side.getNations()) {
|
||||
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(nation.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Nation nation : side.getSurrenderedNations()) {
|
||||
context.insertInto(SIDES_NATIONS, SIDES_NATIONS.SIDE, SIDES_NATIONS.NATION, SIDES_NATIONS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(nation.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side nations!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSideTowns(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (Town town : side.getTowns()) {
|
||||
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(town.getUUID()),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (Town town : side.getSurrenderedTowns()) {
|
||||
context.insertInto(SIDES_TOWNS, SIDES_TOWNS.SIDE, SIDES_TOWNS.TOWN, SIDES_TOWNS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(town.getUUID()),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side towns!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSidePlayers(Connection con, Side side) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(side.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (UUID uuid : side.getPlayersIncludingOffline()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (UUID uuid : side.getSurrenderedPlayersIncludingOffline()) {
|
||||
context.insertInto(SIDES_PLAYERS, SIDES_PLAYERS.SIDE, SIDES_PLAYERS.PLAYER, SIDES_PLAYERS.SURRENDERED)
|
||||
.values(
|
||||
convertUUIDToBytes(side.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query failed to save side players!", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void saveSiege(Connection con, Siege siege) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context.insertInto(SIEGES, SIEGES.WAR, SIEGES.UUID, SIEGES.TOWN, SIEGES.SIEGELEADER, SIEGES.ENDTIME, SIEGES.LASTTOUCHED, SIEGES.SIEGEPROGRESS)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getWar().getUUID()),
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(siege.getTown().getUUID()),
|
||||
convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()),
|
||||
LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC),
|
||||
LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC),
|
||||
siege.getSiegeProgress()
|
||||
)
|
||||
.onDuplicateKeyUpdate()
|
||||
.set(SIEGES.WAR, convertUUIDToBytes(siege.getWar().getUUID()))
|
||||
.set(SIEGES.TOWN, convertUUIDToBytes(siege.getTown().getUUID()))
|
||||
.set(SIEGES.SIEGELEADER, convertUUIDToBytes(siege.getSiegeLeader().getUniqueId()))
|
||||
.set(SIEGES.ENDTIME, LocalDateTime.ofInstant(siege.getEndTime(), ZoneOffset.UTC))
|
||||
.set(SIEGES.LASTTOUCHED, LocalDateTime.ofInstant(siege.getLastTouched(), ZoneOffset.UTC))
|
||||
.set(SIEGES.SIEGEPROGRESS, siege.getSiegeProgress())
|
||||
.execute();
|
||||
|
||||
saveSiegePlayers(con, siege);
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void saveSiegePlayers(Connection con, Siege siege) {
|
||||
try {
|
||||
transactionWrapper(con, (connection, context) -> {
|
||||
context
|
||||
.deleteFrom(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
|
||||
for (UUID uuid : siege.getAttackerPlayersIncludingOffline()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
(byte) 0
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
for (UUID uuid : siege.getDefenderPlayersIncludingOffline()) {
|
||||
context.insertInto(SIEGE_PLAYERS, SIEGE_PLAYERS.SIEGE, SIEGE_PLAYERS.PLAYER, SIEGE_PLAYERS.TEAM)
|
||||
.values(
|
||||
convertUUIDToBytes(siege.getUUID()),
|
||||
convertUUIDToBytes(uuid),
|
||||
(byte) 1
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
});
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Getters
|
||||
public static @NotNull Set<War> loadAll() {
|
||||
Set<War> wars = new HashSet<>();
|
||||
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Result<Record> result = context.select()
|
||||
.from(LIST)
|
||||
.fetch();
|
||||
|
||||
for (Record r : result) {
|
||||
UUID uuid = convertBytesToUUID(r.get(LIST.UUID));
|
||||
String name = r.get(LIST.NAME);
|
||||
String label = r.get(LIST.LABEL);
|
||||
@Nullable Side side1 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE1)));
|
||||
@Nullable Side side2 = loadSide(con, uuid, convertBytesToUUID(r.get(LIST.SIDE2)));
|
||||
boolean event = r.get(LIST.EVENT, Boolean.class);
|
||||
|
||||
wars.add( // TODO IllegalStateException
|
||||
new WarBuilder()
|
||||
.setUuid(uuid)
|
||||
.setName(name)
|
||||
.setLabel(label)
|
||||
.setSide1(side1)
|
||||
.setSide2(side2)
|
||||
.setSieges(new HashSet<>())
|
||||
.setRaids(new HashSet<>())
|
||||
.setEvent(event)
|
||||
.resume()
|
||||
);
|
||||
}
|
||||
|
||||
for (War war : wars) {
|
||||
@NotNull Set<Siege> sieges = loadSieges(con, war);
|
||||
war.setSieges(sieges);
|
||||
}
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
|
||||
return wars;
|
||||
}
|
||||
|
||||
@Contract("_, _, _ -> new")
|
||||
public static @Nullable Side loadSide(Connection con, UUID warUUID, UUID uuid) {
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Record r = context.select()
|
||||
.from(SIDES)
|
||||
.where(SIDES.WAR.equal(convertUUIDToBytes(warUUID)))
|
||||
.and(SIDES.UUID.equal(convertUUIDToBytes(uuid)))
|
||||
.fetchOne();
|
||||
|
||||
if (r == null) return null;
|
||||
|
||||
// Side data
|
||||
BattleSide side = BattleSide.valueOf(r.get(SIDES.SIDE));
|
||||
BattleTeam team = BattleTeam.valueOf(r.get(SIDES.TEAM));
|
||||
String name = r.get(SIDES.NAME);
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIDES.TOWN)));
|
||||
Instant siegeGrace = r.get(SIDES.SIEGEGRACE).toInstant(ZoneOffset.UTC);
|
||||
Instant raidGrace = r.get(SIDES.RAIDGRACE).toInstant(ZoneOffset.UTC);
|
||||
|
||||
// Load players
|
||||
Set<UUID> players = new HashSet<>();
|
||||
Set<UUID> playersSurrendered = new HashSet<>();
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIDES_PLAYERS)
|
||||
.where(SIDES_PLAYERS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIDES_PLAYERS.SURRENDERED).equals((byte) 0)) {
|
||||
players.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
playersSurrendered.add(convertBytesToUUID(record.get(SIDES_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Load nations
|
||||
Set<Nation> nations = new HashSet<>();
|
||||
Set<Nation> nationsSurrendered = new HashSet<>();
|
||||
Result<Record> resultNations = context.select()
|
||||
.from(SIDES_NATIONS)
|
||||
.where(SIDES_NATIONS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultNations.forEach(
|
||||
record -> {
|
||||
final UUID identifier = convertBytesToUUID(record.get(SIDES_NATIONS.NATION));
|
||||
if (record.get(SIDES_NATIONS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
|
||||
if (nation != null)
|
||||
nations.add(nation);
|
||||
} else {
|
||||
@Nullable Nation nation = TownyAPI.getInstance().getNation(identifier);
|
||||
if (nation != null)
|
||||
nationsSurrendered.add(nation);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Load towns
|
||||
Set<Town> towns = new HashSet<>();
|
||||
Set<Town> townsSurrendered = new HashSet<>();
|
||||
Result<Record> resultTowns = context.select()
|
||||
.from(SIDES_TOWNS)
|
||||
.where(SIDES_TOWNS.SIDE.equal(convertUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultTowns.forEach(
|
||||
record -> {
|
||||
final UUID identifier = convertBytesToUUID(record.get(SIDES_TOWNS.TOWN));
|
||||
if (record.get(SIDES_TOWNS.SURRENDERED).equals((byte) 0)) {
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
|
||||
if (town2 != null)
|
||||
towns.add(town2);
|
||||
} else {
|
||||
@Nullable Town town2 = TownyAPI.getInstance().getTown(identifier);
|
||||
if (town2 != null)
|
||||
townsSurrendered.add(town2);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return new SideBuilder() // TODO IllegalStateException
|
||||
.setWarUUID(warUUID)
|
||||
.setUuid(uuid)
|
||||
.setLeader(town)
|
||||
.setSide(side)
|
||||
.setTeam(team)
|
||||
.setName(name)
|
||||
.setTowns(towns)
|
||||
.setNations(nations)
|
||||
.setPlayersIncludingOffline(players)
|
||||
.setSurrenderedTowns(townsSurrendered)
|
||||
.setSurrenderedNations(nationsSurrendered)
|
||||
.setSurrenderedPlayersIncludingOffline(playersSurrendered)
|
||||
.setSiegeGrace(siegeGrace)
|
||||
.setRaidGrace(raidGrace)
|
||||
.rebuild();
|
||||
} catch (SideCreationException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static @NotNull Set<Siege> loadSieges(Connection con, War war) {
|
||||
Set<Siege> sieges = new HashSet<>();
|
||||
|
||||
try {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
Result<Record> result = context.select()
|
||||
.from(SIEGES)
|
||||
.where(SIEGES.WAR.equal(convertUUIDToBytes(war.getUUID())))
|
||||
.fetch();
|
||||
|
||||
for (Record r : result) {
|
||||
UUID uuid = convertBytesToUUID(r.get(SIEGES.UUID));
|
||||
@Nullable Town town = TownyAPI.getInstance().getTown(convertBytesToUUID(r.get(SIEGES.TOWN)));
|
||||
OfflinePlayer siegeLeader = Bukkit.getOfflinePlayer(convertBytesToUUID(r.get(SIEGES.SIEGELEADER)));
|
||||
Instant endTime = r.get(SIEGES.ENDTIME).toInstant(ZoneOffset.UTC);
|
||||
Instant lastTouched = r.get(SIEGES.LASTTOUCHED).toInstant(ZoneOffset.UTC);
|
||||
int siegeProgress = r.get(SIEGES.SIEGEPROGRESS);
|
||||
Set<UUID> attackersIncludingOffline = new HashSet<>();
|
||||
Set<UUID> defendersIncludingOffline = new HashSet<>();
|
||||
|
||||
Result<Record> resultPlayers = context.select()
|
||||
.from(SIEGE_PLAYERS)
|
||||
.where(SIEGE_PLAYERS.SIEGE.equal(convertUUIDToBytes(uuid)))
|
||||
.fetch();
|
||||
resultPlayers.forEach(
|
||||
record -> {
|
||||
if (record.get(SIEGE_PLAYERS.TEAM).equals((byte) 0)) {
|
||||
attackersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
} else {
|
||||
defendersIncludingOffline.add(convertBytesToUUID(record.get(SIEGE_PLAYERS.PLAYER)));
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
sieges.add(new Siege(
|
||||
war,
|
||||
uuid,
|
||||
town,
|
||||
siegeLeader,
|
||||
endTime,
|
||||
lastTouched,
|
||||
siegeProgress,
|
||||
attackersIncludingOffline,
|
||||
defendersIncludingOffline
|
||||
));
|
||||
}
|
||||
} catch (DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
|
||||
return sieges;
|
||||
}
|
||||
|
||||
// Deleters
|
||||
|
||||
public static void deleteWar(War war) {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.deleteFrom(LIST)
|
||||
.where(LIST.UUID.equal(convertUUIDToBytes(war.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void deleteSiege(Siege siege) {
|
||||
try (
|
||||
Connection con = DB.getConnection();
|
||||
) {
|
||||
DSLContext context = DB.getContext(con);
|
||||
|
||||
context
|
||||
.deleteFrom(SIEGES)
|
||||
.where(SIEGES.UUID.equal(convertUUIDToBytes(siege.getUUID())))
|
||||
.execute();
|
||||
} catch (SQLException | DataAccessException e) {
|
||||
Logger.get().error("SQL Query threw an error!", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package com.github.alathra.alathranwars.db;
|
||||
|
||||
import com.mysql.cj.jdbc.MysqlDataSource;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.hsqldb.jdbc.JDBCDataSource;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.jooq.SQLDialect;
|
||||
import org.mariadb.jdbc.MariaDbDataSource;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Enum containing information for handling different Database types.
|
||||
*/
|
||||
public enum DatabaseType {
|
||||
/**
|
||||
* HSQLDB database type.
|
||||
*/
|
||||
HSQLDB("HSQLDB", org.hsqldb.jdbcDriver.class.getName(), JDBCDataSource.class.getName(), "hsqldb", ';', ';'),
|
||||
/**
|
||||
* H2 Database Engine database type.
|
||||
*/
|
||||
H2("H2", org.h2.Driver.class.getName(), JdbcDataSource.class.getName(), "h2", ';', ';'),
|
||||
/**
|
||||
* MySQL database type.
|
||||
*/
|
||||
MYSQL("MySQL", com.mysql.jdbc.Driver.class.getName(), MysqlDataSource.class.getName(), "mysql", '?', '&'),
|
||||
/**
|
||||
* MariaDB database type.
|
||||
*/
|
||||
MARIADB("MariaDB", org.mariadb.jdbc.Driver.class.getName(), MariaDbDataSource.class.getName(), "mariadb", '?', '&'),
|
||||
;
|
||||
|
||||
private final String driverName;
|
||||
private final String driverClassName;
|
||||
private final String dataSourceClassName;
|
||||
private final String jdbcPrefix;
|
||||
private final char jdbcPropertyPrefix;
|
||||
private final char jdbcPropertySeparator;
|
||||
|
||||
DatabaseType(String driverName, String driverClassName, String dataSourceClassName, String jdbcPrefix, char jdbcPropertyPrefix, char jdbcPropertySeparator) {
|
||||
this.driverName = driverName;
|
||||
this.driverClassName = driverClassName;
|
||||
this.dataSourceClassName = dataSourceClassName;
|
||||
this.jdbcPrefix = jdbcPrefix;
|
||||
this.jdbcPropertyPrefix = jdbcPropertyPrefix;
|
||||
this.jdbcPropertySeparator = jdbcPropertySeparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets driver name.
|
||||
*
|
||||
* @return the driver name
|
||||
*/
|
||||
public String getDriverName() {
|
||||
return driverName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets driver class name.
|
||||
*
|
||||
* @return the driver class name
|
||||
*/
|
||||
public String getDriverClassName() {
|
||||
return driverClassName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets data source class name.
|
||||
*
|
||||
* @return the data source class name
|
||||
*/
|
||||
public String getDataSourceClassName() {
|
||||
return dataSourceClassName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc prefix.
|
||||
*
|
||||
* @return the jdbc prefix like <code>mysql</code> or <code>mariadb</code>
|
||||
*/
|
||||
public String getJdbcPrefix() {
|
||||
return jdbcPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc property prefix.
|
||||
*
|
||||
* @return the jdbc property prefix like <code>{@literal ;}</code> or <code>{@literal ?}</code>
|
||||
*/
|
||||
public char getJdbcPropertyPrefix() {
|
||||
return jdbcPropertyPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the jdbc property separator.
|
||||
*
|
||||
* @return the jdbc property separator like <code>{@literal ;}</code> or <code>{@literal &}</code>
|
||||
*/
|
||||
public char getJdbcPropertySeparator() {
|
||||
return jdbcPropertySeparator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a map of connection properties into a valid jdbc connection properties string.
|
||||
*
|
||||
* @param properties the properties
|
||||
* @return the string
|
||||
*/
|
||||
public String formatJdbcConnectionProperties(Map<String, Object> properties) {
|
||||
if (properties.isEmpty()) return "";
|
||||
|
||||
List<String> connectionProperties = properties.entrySet().stream()
|
||||
.map(map -> "%s=%s".formatted(map.getKey(), map.getValue()))
|
||||
.toList();
|
||||
|
||||
return jdbcPropertyPrefix + String.join(Character.toString(jdbcPropertySeparator), connectionProperties);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets database type from jdbc prefix.
|
||||
*
|
||||
* @param prefix the prefix
|
||||
* @return the database type or null
|
||||
*/
|
||||
@Nullable
|
||||
public static DatabaseType getDatabaseTypeFromJdbcPrefix(String prefix) {
|
||||
for (DatabaseType type : DatabaseType.values()) {
|
||||
if (type.equals(prefix.toLowerCase())) {
|
||||
return type;
|
||||
}
|
||||
;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getDriverName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this DatabaseType is equal to another.
|
||||
*
|
||||
* @param DatabaseType the database type
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(DatabaseType DatabaseType) {
|
||||
return this.equals(DatabaseType.getDriverName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this DatabaseType is equal to another.
|
||||
*
|
||||
* @param databaseTypeName the database type name
|
||||
* @return boolean
|
||||
*/
|
||||
public boolean equals(String databaseTypeName) {
|
||||
return this.getDriverName().equalsIgnoreCase(databaseTypeName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets sql dialect for this DatabaseType.
|
||||
*
|
||||
* @return the sql dialect
|
||||
*/
|
||||
public SQLDialect getSQLDialect() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> SQLDialect.HSQLDB;
|
||||
case H2 -> SQLDialect.H2;
|
||||
case MYSQL -> SQLDialect.MYSQL;
|
||||
case MARIADB -> SQLDialect.MARIADB;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets column suffix for this DatabaseType.
|
||||
*
|
||||
* @return the column suffix
|
||||
*/
|
||||
public String getColumnSuffix() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> "";
|
||||
case H2, MARIADB, MYSQL -> " VIRTUAL";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets table defaults for this DatabaseType.
|
||||
*
|
||||
* @return the table defaults
|
||||
*/
|
||||
public String getTableDefaults() {
|
||||
return switch (this) {
|
||||
case H2, HSQLDB -> "";
|
||||
case MARIADB, MYSQL -> " CHARACTER SET utf8mb4 COLLATE utf8mb4_bin";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets uuid type for this DatabaseType.
|
||||
*
|
||||
* @return the uuid type
|
||||
*/
|
||||
public String getUuidType() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> "UUID";
|
||||
case H2, MARIADB, MYSQL -> "BINARY(16)";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets inet type for this DatabaseType.
|
||||
*
|
||||
* @return the inet type
|
||||
*/
|
||||
public String getInetType() {
|
||||
return "VARBINARY(16)";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets binary type for this DatabaseType.
|
||||
*
|
||||
* @return the binary type
|
||||
*/
|
||||
public String getBinaryType() {
|
||||
return "BLOB";
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets alter view statement for this DatabaseType.
|
||||
*
|
||||
* @return the alter view statement
|
||||
*/
|
||||
public String getAlterViewStatement() {
|
||||
return switch (this) {
|
||||
case H2, HSQLDB, MYSQL, MARIADB -> "ALTER VIEW";
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets connection init sql for this DatabaseType.
|
||||
*
|
||||
* @return the connection init sql
|
||||
*/
|
||||
public String getConnectionInitSql() {
|
||||
return switch (this) {
|
||||
case HSQLDB -> "SET DATABASE TRANSACTION CONTROL MVLOCKS;";
|
||||
case MARIADB -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
|
||||
// MariaDB defaults
|
||||
"STRICT_TRANS_TABLES",
|
||||
"ERROR_FOR_DIVISION_BY_ZERO",
|
||||
"NO_AUTO_CREATE_USER",
|
||||
"NO_ENGINE_SUBSTITUTION",
|
||||
// ANSI SQL Compliance
|
||||
"ANSI",
|
||||
"NO_BACKSLASH_ESCAPES",
|
||||
"SIMULTANEOUS_ASSIGNMENT", // MDEV-13417
|
||||
"NO_ZERO_IN_DATE",
|
||||
"NO_ZERO_DATE");
|
||||
case H2 -> "";
|
||||
case MYSQL -> "SET NAMES utf8mb4 COLLATE utf8mb4_bin; " + setSqlModes(
|
||||
// MySQL defaults
|
||||
"STRICT_TRANS_TABLES",
|
||||
"ERROR_FOR_DIVISION_BY_ZERO",
|
||||
"NO_ENGINE_SUBSTITUTION",
|
||||
// ANSI SQL Compliance
|
||||
"ANSI",
|
||||
"NO_BACKSLASH_ESCAPES",
|
||||
"NO_ZERO_IN_DATE",
|
||||
"NO_ZERO_DATE");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a concatenated SQL query from the specified parameters.
|
||||
*
|
||||
* @param sqlModes database parameters
|
||||
* @return string
|
||||
*/
|
||||
private static String setSqlModes(String... sqlModes) {
|
||||
final String modes = String.join(",", sqlModes);
|
||||
return "SET @@SQL_MODE = CONCAT(@@SQL_MODE, '," + modes + "')";
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
|
||||
public class DatabaseMigrationException extends Exception {
|
||||
public DatabaseMigrationException(Throwable t) {
|
||||
super(t);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
|
||||
import com.github.alathra.alathranwars.db.DatabaseType;
|
||||
import com.github.milkdrinkers.Crate.Config;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.FlywayException;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Handles Flyway migrations.
|
||||
*/
|
||||
public class DatabaseMigrationHandler {
|
||||
// List of Java migrations
|
||||
private final List<Class<? extends JavaMigration>> migrations = List.of(
|
||||
);
|
||||
|
||||
private final Config config;
|
||||
private final DataSource dataSource;
|
||||
private final DatabaseType databaseType;
|
||||
private Flyway flyway;
|
||||
|
||||
/**
|
||||
* Instantiates a new Database migration handler.
|
||||
*
|
||||
* @param config the config
|
||||
* @param dataSource the data source
|
||||
* @param databaseType the database type
|
||||
*/
|
||||
public DatabaseMigrationHandler(Config config, DataSource dataSource, DatabaseType databaseType) {
|
||||
this.config = config;
|
||||
this.dataSource = dataSource;
|
||||
this.databaseType = databaseType;
|
||||
initializeFlywayInstance();
|
||||
}
|
||||
|
||||
private void initializeFlywayInstance() {
|
||||
final ClassProvider<JavaMigration> javaMigrationClassProvider = new FlywayMigrationsProvider(migrations);
|
||||
final String SQL_TABLE_PREFIX = config.getOrDefault("db.prefix", "example_");
|
||||
final Map<String, String> SQL_PLACEHOLDERS = Map.of(
|
||||
"tablePrefix", SQL_TABLE_PREFIX,
|
||||
"columnSuffix", databaseType.getColumnSuffix(),
|
||||
"tableDefaults", databaseType.getTableDefaults(),
|
||||
"uuidType", databaseType.getUuidType(),
|
||||
"inetType", databaseType.getInetType(),
|
||||
"binaryType", databaseType.getBinaryType(),
|
||||
"alterViewStatement", databaseType.getAlterViewStatement()
|
||||
);
|
||||
|
||||
this.flyway = Flyway
|
||||
.configure(getClass().getClassLoader())
|
||||
.baselineOnMigrate(true)
|
||||
.baselineVersion("0.0")
|
||||
.validateMigrationNaming(true)
|
||||
.javaMigrationClassProvider(javaMigrationClassProvider)
|
||||
.dataSource(dataSource)
|
||||
.locations(
|
||||
"classpath:database-migrations",
|
||||
"db/migration"
|
||||
)
|
||||
.table(SQL_TABLE_PREFIX + "schema_history") // Configure tables and migrations
|
||||
.placeholders(SQL_PLACEHOLDERS)
|
||||
.load();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute Flyway migration. All pending migrations will be applied in order.
|
||||
*
|
||||
* @throws DatabaseMigrationException database migration exception
|
||||
*/
|
||||
public void migrate() throws DatabaseMigrationException {
|
||||
try {
|
||||
this.flyway.migrate();
|
||||
} catch (FlywayException e) {
|
||||
throw new DatabaseMigrationException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes Flyway repair. Repairs the Flyway schema history table. This will perform the following actions:
|
||||
*
|
||||
* <ul>
|
||||
* <li>Remove any failed migrations on databases without DDL transactions (User objects left behind must still be cleaned up manually)</li>
|
||||
* <li>Realign the checksums, descriptions and types of the applied migration</li>
|
||||
* </ul>
|
||||
*
|
||||
* @throws DatabaseMigrationException database migration exception
|
||||
*/
|
||||
public void repair() throws DatabaseMigrationException {
|
||||
try {
|
||||
if (config.getOrDefault("db.repair", false))
|
||||
this.flyway.repair();
|
||||
} catch (FlywayException e) {
|
||||
throw new DatabaseMigrationException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.github.alathra.alathranwars.db.flyway;
|
||||
|
||||
import org.flywaydb.core.api.ClassProvider;
|
||||
import org.flywaydb.core.api.migration.JavaMigration;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
public record FlywayMigrationsProvider(
|
||||
List<Class<? extends JavaMigration>> migrations
|
||||
) implements ClassProvider<JavaMigration> {
|
||||
public FlywayMigrationsProvider(List<Class<? extends JavaMigration>> migrations) {
|
||||
this.migrations = List.copyOf(migrations);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Class<? extends JavaMigration>> getClasses() {
|
||||
return migrations;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.github.alathra.alathranwars.db.flyway.migration;
|
||||
|
||||
import org.flywaydb.core.api.migration.BaseJavaMigration;
|
||||
import org.flywaydb.core.api.migration.Context;
|
||||
|
||||
public class V3__Example extends BaseJavaMigration {
|
||||
@Override
|
||||
public void migrate(Context flywayContext) throws Exception {
|
||||
/*try {
|
||||
final DSLContext context = DB.getContext(flywayContext.getConnection());
|
||||
|
||||
context.alterTable(TEST).addColumn(field(name("meme"), VARCHAR)).execute();
|
||||
|
||||
context
|
||||
.alterTableIfExists(TEST)
|
||||
.addColumnIfNotExists(field(name("column_name"), VARCHAR(32).notNull()*//*.defaultValue("default")*//*))
|
||||
.execute();
|
||||
} catch (Exception e) {
|
||||
Logger.get().error(e.getMessage());
|
||||
}*/
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.github.alathra.alathranwars.db.jooq;
|
||||
|
||||
import com.github.alathra.alathranwars.utility.Cfg;
|
||||
import org.jooq.*;
|
||||
import org.jooq.conf.*;
|
||||
import org.jooq.exception.DataAccessException;
|
||||
import org.jooq.impl.DefaultConfiguration;
|
||||
import org.jooq.tools.JooqLogger;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Utility class for getting jOOQ Context to use with HikariCP.
|
||||
*/
|
||||
public final class JooqContext {
|
||||
static {
|
||||
JooqLogger.globalThreshold(Log.Level.ERROR); // Silence JOOQ warnings
|
||||
}
|
||||
|
||||
private static final String TABLE_PREFIX = Cfg.get().getOrDefault("db.prefix", "example_"); // The table prefix as grabbed from config
|
||||
private static final Pattern MATCH_ALL_EXCEPT_INFORMATION_SCHEMA = Pattern.compile("^(?!INFORMATION_SCHEMA)(.*?)$");
|
||||
private static final Pattern MATCH_ALL = Pattern.compile("^(.*?)$");
|
||||
private static final String REPLACEMENT = "%s$0".formatted(TABLE_PREFIX); //
|
||||
private final SQLDialect dialect;
|
||||
|
||||
/**
|
||||
* Instantiates a new Jooq context.
|
||||
*
|
||||
* @param dialect the getSQLDialect
|
||||
*/
|
||||
public JooqContext(SQLDialect dialect) {
|
||||
this.dialect = dialect;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create DSL Context.
|
||||
*
|
||||
* @param connection the connection
|
||||
* @return the dsl context
|
||||
*/
|
||||
public DSLContext createContext(Connection connection) {
|
||||
record SimpleConnectionProvider(Connection connection) implements ConnectionProvider {
|
||||
|
||||
@Override
|
||||
public Connection acquire() throws DataAccessException {
|
||||
return connection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void release(Connection connection) throws DataAccessException {
|
||||
}
|
||||
}
|
||||
return createWith(new SimpleConnectionProvider(connection));
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies default configuration
|
||||
*
|
||||
* @param connectionProvider A connection lifecycle handler API.
|
||||
* @return DSLContext
|
||||
*/
|
||||
private DSLContext createWith(ConnectionProvider connectionProvider) {
|
||||
return new DefaultConfiguration()
|
||||
.set(connectionProvider)
|
||||
.set(dialect)
|
||||
.set(createSettings())
|
||||
.set(new ExecuteListenerProvider[0])
|
||||
.dsl();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns base settings for DSL Contexts.
|
||||
*
|
||||
* @return Settings
|
||||
*/
|
||||
private Settings createSettings() {
|
||||
return new Settings()
|
||||
.withBackslashEscaping(BackslashEscaping.OFF)
|
||||
.withRenderSchema(false)
|
||||
.withRenderMapping(new RenderMapping() // Support the tables having custom prefix
|
||||
.withSchemata(new MappedSchema()
|
||||
.withInputExpression(MATCH_ALL_EXCEPT_INFORMATION_SCHEMA)
|
||||
.withTables(new MappedTable()
|
||||
.withInputExpression(MATCH_ALL)
|
||||
.withOutput(REPLACEMENT)
|
||||
)
|
||||
)
|
||||
)
|
||||
.withRenderQuotedNames(RenderQuotedNames.ALWAYS)
|
||||
.withRenderNameCase(RenderNameCase.LOWER);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CaptureProgressDirection {
|
||||
UP,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CommandArgsSiege {
|
||||
IN_SIEGE,
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum CommandArgsWar {
|
||||
IN_WAR,
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum ConflictType {
|
||||
WAR
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.github.alathra.alathranwars.enums;
|
||||
|
||||
public enum WarDeleteReason {
|
||||
DRAW,
|
||||
DEFEAT,
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.github.alathra.AlathranWars.enums;
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleSide {
|
||||
ATTACKER,
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleTeam {
|
||||
SIDE_1,
|
||||
SIDE_2,
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleType {
|
||||
SIEGE,
|
||||
RAID,
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleVictor {
|
||||
ATTACKER,
|
||||
DEFENDER,
|
||||
DRAW,
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.github.alathra.alathranwars.enums.battle;
|
||||
|
||||
public enum BattleVictoryReason {
|
||||
OPPONENT_LOST,
|
||||
OPPONENT_RETREAT,
|
||||
ADMIN_COMMAND,
|
||||
ADMIN_CANCEL,
|
||||
}
|
||||
+15
-1
@@ -1,5 +1,6 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
package com.github.alathra.alathranwars.events;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
@@ -8,6 +9,11 @@ import org.jetbrains.annotations.NotNull;
|
||||
public class PreWarCreateEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
private War war;
|
||||
|
||||
public PreWarCreateEvent(War war) {
|
||||
this.war = war;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
@@ -35,4 +41,12 @@ public class PreWarCreateEvent extends Event implements Cancellable {
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -1,5 +1,7 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
package com.github.alathra.alathranwars.events;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.WarDeleteReason;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
@@ -8,6 +10,13 @@ import org.jetbrains.annotations.NotNull;
|
||||
public class PreWarDeleteEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
private War war;
|
||||
private WarDeleteReason reason;
|
||||
|
||||
public PreWarDeleteEvent(War war, WarDeleteReason reason) {
|
||||
this.war = war;
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
@@ -35,4 +44,16 @@ public class PreWarDeleteEvent extends Event implements Cancellable {
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public WarDeleteReason getReason() {
|
||||
return reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.github.alathra.alathranwars.events;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarCreateEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private War war;
|
||||
|
||||
public WarCreateEvent(War war) {
|
||||
this.war = war;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.github.alathra.alathranwars.events;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.WarDeleteReason;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarDeleteEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private War war;
|
||||
private WarDeleteReason reason;
|
||||
|
||||
public WarDeleteEvent(War war, WarDeleteReason reason) {
|
||||
this.war = war;
|
||||
this.reason = reason;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public WarDeleteReason getReason() {
|
||||
return reason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictor;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class BattleResultEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private final War war;
|
||||
private final Battle battle;
|
||||
private final BattleVictor battleVictor;
|
||||
private final BattleVictoryReason battleVictoryReason;
|
||||
|
||||
public BattleResultEvent(War war, Battle battle, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
this.battleVictor = battleVictor;
|
||||
this.battleVictoryReason = battleVictoryReason;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
|
||||
public BattleVictor getBattleVictor() {
|
||||
return battleVictor;
|
||||
}
|
||||
|
||||
public BattleVictoryReason getBattleVictoryReason() {
|
||||
return battleVictoryReason;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class BattleStartEvent extends Event {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private final War war;
|
||||
private final Battle battle;
|
||||
|
||||
public BattleStartEvent(War war, Battle battle) {
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictor;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleVictoryReason;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class PreBattleResultEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
private War war;
|
||||
private final Battle battle;
|
||||
private final BattleType battleType;
|
||||
private final BattleVictor battleVictor;
|
||||
private final BattleVictoryReason battleVictoryReason;
|
||||
|
||||
public PreBattleResultEvent(War war, Battle battle, BattleType battleType, BattleVictor battleVictor, BattleVictoryReason battleVictoryReason) {
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
this.battleType = battleType;
|
||||
this.battleVictor = battleVictor;
|
||||
this.battleVictoryReason = battleVictoryReason;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins
|
||||
*
|
||||
* @return true if this event is cancelled
|
||||
*/
|
||||
@Override
|
||||
public boolean isCancelled() {
|
||||
return this.cancelled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the cancellation state of this event. A cancelled event will not
|
||||
* be executed in the server, but will still pass to other plugins.
|
||||
*
|
||||
* @param cancelled true if you wish to cancel this event
|
||||
*/
|
||||
@Override
|
||||
public void setCancelled(boolean cancelled) {
|
||||
this.cancelled = cancelled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
|
||||
public BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
|
||||
public BattleVictor getBattleVictor() {
|
||||
return battleVictor;
|
||||
}
|
||||
|
||||
public BattleVictoryReason getBattleVictoryReason() {
|
||||
return battleVictoryReason;
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -1,13 +1,25 @@
|
||||
package com.github.alathra.AlathranWars.events;
|
||||
package com.github.alathra.alathranwars.events.battle;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.battle.Battle;
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.enums.battle.BattleType;
|
||||
import org.bukkit.event.Cancellable;
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
public class WarDeleteEvent extends Event implements Cancellable {
|
||||
public class PreBattleStartEvent extends Event implements Cancellable {
|
||||
private static final HandlerList HANDLER_LIST = new HandlerList();
|
||||
private boolean cancelled;
|
||||
private War war;
|
||||
private final Battle battle;
|
||||
private final BattleType battleType;
|
||||
|
||||
public PreBattleStartEvent(War war, Battle battle, BattleType battleType) {
|
||||
this.war = war;
|
||||
this.battle = battle;
|
||||
this.battleType = battleType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the cancellation state of this event. A cancelled event will not
|
||||
@@ -35,4 +47,20 @@ public class WarDeleteEvent extends Event implements Cancellable {
|
||||
public @NotNull HandlerList getHandlers() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public static HandlerList getHandlerList() {
|
||||
return HANDLER_LIST;
|
||||
}
|
||||
|
||||
public War getWar() {
|
||||
return war;
|
||||
}
|
||||
|
||||
public Battle getBattle() {
|
||||
return battle;
|
||||
}
|
||||
|
||||
public BattleType getBattleType() {
|
||||
return battleType;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.github.alathra.alathranwars.Reloadable;
|
||||
|
||||
public class HookManager implements Reloadable {
|
||||
private final PAPIHook papi = new PAPIHook();
|
||||
|
||||
public void onLoad() {
|
||||
papi.onLoad();
|
||||
}
|
||||
|
||||
public void onEnable() {
|
||||
TownyHook.init();
|
||||
papi.onEnable();
|
||||
}
|
||||
|
||||
public void onDisable() {
|
||||
papi.onDisable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.github.alathra.alathranwars.hooks;
|
||||
|
||||
import com.github.alathra.alathranwars.conflict.war.War;
|
||||
import com.github.alathra.alathranwars.conflict.war.WarController;
|
||||
import com.github.alathra.alathranwars.utility.Logger;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class NameColorHandler {
|
||||
private static NameColorHandler instance;
|
||||
private Map<Player, String> playerColor = new HashMap<>();
|
||||
private Map<Player, String> playerInitial = new HashMap<>();
|
||||
|
||||
private NameColorHandler() {
|
||||
if (instance != null)
|
||||
Logger.get().warn("Tried to re-initialize singleton");
|
||||
}
|
||||
|
||||
@NotNull
|
||||
public static NameColorHandler getInstance() {
|
||||
if (instance == null)
|
||||
instance = new NameColorHandler();
|
||||
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void calculatePlayerColors(Player p) {
|
||||
if (!WarController.getInstance().isPlayerInAnyWars(p)) {
|
||||
playerColor.remove(p);
|
||||
playerInitial.remove(p);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<War> war = WarController.getInstance().getPlayerWars(p).stream().findFirst();
|
||||
|
||||
if (war.isEmpty())
|
||||
return;
|
||||
|
||||
final boolean isPlayerSurrendered = war.get().getSide1().isPlayerSurrendered(p) || war.get().getSide2().isPlayerSurrendered(p);
|
||||
|
||||
if (isPlayerSurrendered)
|
||||
return;
|
||||
|
||||
final boolean isSideOne = war.get().getSide1().isPlayerOnSide(p);
|
||||
|
||||
if (isSideOne) {
|
||||
playerColor.put(p, "<red>");
|
||||
} else {
|
||||
playerColor.put(p, "<blue>");
|
||||
}
|
||||
playerInitial.put(p, war.get().getPlayerSide(p).getName().substring(0, 1).toUpperCase());
|
||||
}
|
||||
|
||||
public boolean isPlayerUsingModifiedName(Player p) {
|
||||
calculatePlayerColors(p);
|
||||
return WarController.getInstance().isPlayerInAnyWars(p);
|
||||
}
|
||||
|
||||
public String getPlayerTabNameColor(Player p) {
|
||||
return "%s[%s] ".formatted(playerColor.get(p), playerInitial.get(p));
|
||||
}
|
||||
|
||||
public String getPlayerNameColor(Player p) {
|
||||
return "%s".formatted(playerColor.get(p));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user