Sudagani John goud
📎 1 file 42,200 chars
📄
ZeroSpawnFootball_Master_Prompt.md
md 708 lines
▶
# ZERO SPAWN FOOTBALL — MASTER BUILD PROMPT (v2)

You are a senior Minecraft plugin engineer. Build **ZeroSpawnFootball**, a complete, production-quality football (soccer) minigame plugin for the **ZERO SPAWN** server.

Branding shown to players: **ZERO SPAWN FOOTBALL**

The result must feel like a polished standalone competitive minigame, not a "snowball football" toy. Every win, loss, draw and goal must be impossible to miss **on screen** (see section 10, the most important section of this prompt).

---

## 0. HOW YOU MUST WORK (delivery protocol)

1. **Never invent API.** If you are not 100% sure a Paper/Bukkit/Adventure method, event or enum constant exists in the target version, either use a safer alternative you are sure about, or list it under `NEEDS VERIFICATION` at the end. A plugin that compiles is worth more than a clever one that doesn't.
2. **Work in phases** and finish each one before the next. After each phase, state what is done and what is next:
   - Phase 1: build files, plugin descriptor, main class, config/message loading, arena storage, `/football` command skeleton. Must compile.
   - Phase 2: arenas + setup commands + validation, queue, lobby GUI, player state snapshot/restore.
   - Phase 3: match state machine, teams, scoreboard, boss bar, countdown, timer.
   - Phase 4: ball entity, physics, kicking, charge, curve, collisions, goal detection.
   - Phase 5: announcement system (section 10) wired to every event, win/lose/draw screens, MVP, end sequence.
   - Phase 6: SQLite stats, stats GUI, leaderboards, disconnect/forfeit, cleanup, README, tests.
3. **Print every file in full**, with its path as a header. No `...`, no "same as before", no TODO, no placeholder bodies, no pseudocode. Every class, command, listener, manager, config key and message key that is referenced must exist.
4. If a build tool is available, actually run `./gradlew build` and fix every error until it produces a jar. If not, do a careful compile-in-your-head review of every file (imports, generics, checked exceptions, null handling) before declaring a phase done.
5. End with: a short self-review against the acceptance checklist (section 21), plus the `NEEDS VERIFICATION` list (may be empty).

---

## 1. TARGET PLATFORM & BUILD

* Server: **Paper 26.2** (target build **26.2-121**; if that exact build is not resolvable, use the closest 26.2 build and say so).
* **Java:** use the version Paper 26.2 actually requires. Paper's own docs say 26.1+ needs Java 25, while some hosting pages still list 21. Read the paper-api POM/Paper docs and set the Gradle toolchain / `options.release` accordingly. Do not guess.
* Build tool: **Gradle (Kotlin DSL)** with `build.gradle.kts` and `settings.gradle.kts`. Add the Gradle wrapper if you can. `./gradlew build` must produce `ZeroSpawnFootball-.jar` in `build/libs/`.
* Paper API: `io.papermc.paper:paper-api` from `https://repo.papermc.io/repository/maven-public/` as `compileOnly`. Resolve the exact version string from the repository metadata, do not invent it.
* **No NMS, no reflection hacks, no deprecated API** where a supported Paper API exists. Use Adventure + **MiniMessage** for all text.
* **WorldEdit/FAWE is an optional soft dependency** (schematic pasting and region selection). The plugin must load, run and play fully without it. WorldEdit classes must only be touched from classes that are never loaded when WorldEdit is absent.
* **SQLite:** use the SQLite JDBC driver Paper provides, or declare it through Paper's plugin library loading. Verify which works on 26.2 and say which you used. All database I/O is async.
* Plugin descriptor: `plugin.yml` (or `paper-plugin.yml` if you are sure of its format) with correct `api-version` for 26.2, `softdepend: [WorldEdit, FastAsyncWorldEdit]`, commands, permissions. Declare that the plugin is **not** Folia-compatible.
* Packages under `com.zerospawn.football`.

---

## 2. NON-NEGOTIABLE RULES

* One `Match` object = one fully isolated game (own players, ball, tasks, scoreboard, boss bar, stats). Matches never touch each other's state.
* Reference players by **UUID**, never keep `Player` objects in long-lived collections.
* Every scheduled task a match creates is tracked and cancelled in one idempotent `Match.destroy()`. Finished matches are removed from every map.
* No per-tick world scans, no `getNearbyEntities` in tick loops, no per-tick file/DB work.
* Nothing is hard-coded that a server owner would want to change: values go in `config.yml`, text in `messages.yml`, arenas in `arenas.yml`.
* Every user-visible string comes from `messages.yml`. No raw strings in Java except log messages and command syntax usage.
* Plugin reload (`/football reload`) re-reads config, messages and arenas **without** killing running matches (new settings apply to new matches; messages apply immediately).
* `onDisable()` ends every match safely, restores every player, removes every entity, and flushes stats to disk synchronously.

---

## 3. GAME MODES

Exactly three modes, as an enum `ArenaMode`:

| Mode | Players per team | Total | Arena size |
|------|------------------|-------|-----------|
| 1v1  | 1 | 2 | small |
| 2v2  | 2 | 4 | medium |
| 4v4  | 4 | 8 | large |

Each mode has its own arena configuration. Several arenas per mode must be supported from day one (list of arenas per mode, a free arena is picked per match).

---

## 4. ARENA SYSTEM

### 4.1 Storage (`arenas.yml`)

```yaml
arenas:
  arena1:
    mode: 1v1
    enabled: false          # becomes true only after validation passes
    world: football
    schematic: football_1v1.schem   # optional
    paste-origin: {x: 0, y: 64, z: 0}  # optional
    bounds: {min: {x: 0, y: 0, z: 0}, max: {x: 0, y: 0, z: 0}}
    center: {x: 0.5, y: 65, z: 0.5, yaw: 0, pitch: 0}
    ball: {x: 0.5, y: 65.3, z: 0.5}
    red:
      spawns: []            # list of x,y,z,yaw,pitch
      goal: {min: {x: 0, y: 0, z: 0}, max: {x: 0, y: 0, z: 0}}
    blue:
      spawns: []
      goal: {min: {x: 0, y: 0, z: 0}, max: {x: 0, y: 0, z: 0}}
```

Schematic names: `football_1v1.schem`, `football_2v2.schem`, `football_4v4.schem` in `plugins/ZeroSpawnFootball/schematics/`.

### 4.2 Rules

* Arena is **occupied by at most one match**. `ArenaManager` tracks free/occupied.
* If WorldEdit is present and the arena has a schematic, `/football arena paste ` pastes it (async-safe, main-thread-safe). Pasting is never done automatically during a match.
* **Collision snapshot:** when an arena is loaded or reloaded, build a compact solid-block map (`ArenaCollisionMap`, bitset or byte array over the bounds) on the main thread. Ball physics use this map, so the physics loop never calls `World#getBlockAt`. Rebuild on `/football reload` and `/football arena paste`.
* Players cannot break, place, interact with blocks, use buckets, trample farmland, ignite, or change anything inside an active arena. Explosions and fluid flow do not modify the arena.
* The arena `bounds` also defines the **ball cage**: the ball can never leave it.

### 4.3 Setup commands

```text
/football createarena <1v1|2v2|4v4> 
/football setlobby
/football pos1            (fallback selection if WorldEdit is missing)
/football pos2
/football setbounds              (uses WorldEdit selection or pos1/pos2)
/football setspawn   
/football setcenter 
/football setball 
/football setgoal      (uses WorldEdit selection or pos1/pos2)
/football validate 
/football enable  | disable 
/football deletearena 
/football arena paste 
/football list
```

* Everything saves automatically to `arenas.yml`.
* `validate` prints a checklist, for example: bounds set, world loaded, spawn count equals team size for both teams, ball set, center set, both goals set, goals inside bounds, goals do not overlap. An arena can only be enabled if validation passes.
* `setspawn` index must be between 1 and team size for the arena's mode.

---

## 5. QUEUE & LOBBY

### Entry points

```text
/football                  opens the mode GUI
/football join <1v1|2v2|4v4>
/football leave
/football stats [player]
/football top [goals|wins|assists|saves|matches|mvps]
```

### GUI (`ModeMenu`)

A 3-row menu with three mode buttons (1v1, 2v2, 4v4). Each button shows live: players queued, active matches, free arenas. Clicking joins that queue; clicking again (or the leave item) leaves it. Plus a Stats button and a Leaderboard button. All clicks cancelled, shift-click / number-key / drag exploits blocked. Use a custom `InventoryHolder`. GUI text comes from `messages.yml`.

### Queue rules

* A player can be in **one queue or one match** at a time.
* 1v1: match is created as soon as 2 players are queued. 2v2 at 4, 4v4 at 8.
* A match is created only if a free valid arena of that mode exists. If none exists: players stay queued and see the **Arena unavailable** announcement, and are matched as soon as one frees up.
* Teams are balanced automatically: red/blue split alternating by join order (queue stays FIFO). Make the balancing a pure, unit-testable function.
* Queue HUD (action bar, refreshed every 20 ticks, only while someone is queued):

```text
FOOTBALL 2v2 | Waiting for players... 3/4
```

* Queue join/leave and "queue ready" are announced on screen (section 10).

---

## 6. TEAMS

* Red and Blue. Friendly fire is disabled for football damage entirely: **no player-vs-player damage at all** inside a match.
* Team identity everywhere: coloured leather armour (full set, unbreakable, not droppable, not removable), team-coloured name tags via a scoreboard team (`color`, `allowFriendlyFire(false)`, collision rule `NEVER`/configurable), optional glow (config), team-coloured action bar/titles.
* The scoreboard shows the player's own team.

---

## 7. BALL ENTITY

* **Visual:** one `ItemDisplay` entity (no gravity, no AI, no pickup, never an item entity). Item = `PLAYER_HEAD` with a configurable base64 texture, or a configurable `item-model` key (resource pack), or a fallback material. **Do NOT invent a texture string**: leave `head-texture` empty by default and document in the README how to paste a football texture value. Smooth movement via the display entity's teleport/interpolation duration. Visual rolling rotation proportional to horizontal speed.
* **Hitbox/touch:** one small `Interaction` entity (configurable size) kept at the ball position, used as a hit target and to block unwanted interactions. Both entities are tagged with the plugin's PDC key so they can be found and removed on startup, shutdown, and match end, including after a crash.
* **Per-match visibility:** spawn both entities with `setVisibleByDefault(false)` and `Player#showEntity` only to the match's players. Entities are persistent=false.
* Nobody can pick it up, push it with vanilla mechanics, ride it, leash it, damage it with vanilla damage, or interact with it outside the plugin's rules.
* **Optional (only after everything else works and only if the 26.2 API exposes it):** `ball.visual-mode: SULFUR_CUBE` that uses a Sulfur Cube mob (AI off, silent, invulnerable, moved by the plugin) for a sulfur-themed ball. If unsure the API exists, skip it and list it under `NEEDS VERIFICATION`.

---

## 8. BALL PHYSICS (controlled, cheap, deterministic)

One repeating task **per match** (1 tick), running only while the ball is active. State per ball: position, velocity, spin, last touch (UUID + team + timestamp), grounded flag.

Per tick (use `substeps`, default 2, to prevent tunnelling at high speed):

1. Apply gravity and air drag.
2. Integrate position; resolve collisions against `ArenaCollisionMap` per axis (floor, ceiling, walls) with restitution (`bounce-restitution` for floor, `wall-restitution` for walls). Ignore tiny bounces below `min-bounce-speed`.
3. When grounded: apply `ground-friction` to horizontal velocity (rolling). Snap tiny velocities to zero below `stop-threshold`.
4. Apply curve (spin) as a small perpendicular acceleration that decays each tick.
5. Clamp to `max-speed`.
6. Resolve **ball vs player** contact for the match's players only (max 8): if a player's body overlaps the ball, push the ball along the contact normal with `player-collision.knockback`, plus a small share of the player's velocity so dribbling feels natural. **Players are never launched or pushed by the ball.**
7. Keep inside arena bounds (bounce off invisible walls, never leave, never fall into the void). Failsafe: if the ball is outside the cage for any reason, reset it to the ball spawn.
8. Goal check (section 11), only when the match state is `LIVE`.
9. Move the display + interaction entities once per tick (single teleport call each).
10. Emit effects (section 18) with strict rate limits.

Failsafes: if the ball is nearly still for `stuck-reset-seconds` and is trapped in a corner/unreachable spot, nudge it toward the centre; never reset silently, show an on-screen "BALL RESET" announcement.

---

## 9. INPUT & KICKING

Kicks are triggered by **arm swing / left click**, whether the player hits the air, a block, or the ball. Use `PlayerAnimationEvent` (and handle `PrePlayerAttackEntityEvent` / attacks on the Interaction entity so a click on the ball never also deals damage). Because the hitbox is small, the kick is validated by **range + view cone** (`kick.range`, `kick.cone-degrees`), not by entity ray-hit alone.

* **Normal kick:** left click. Direction = player's look direction, with a configurable loft (looking slightly up gives a lob; looking down is clamped to a low ground pass).
* **Sprint kick:** if the player is sprinting, multiply power by `sprint-multiplier`.
* **Distance factor:** kicks from far reach are slightly weaker (`distance-falloff`).
* **Charged kick:** Minecraft cannot detect "holding left click", so charging uses **holding SNEAK** (configurable input). While sneaking with the ball within range or approaching, show on the action bar:

```text
POWER: ███████░░░  70%
```

  Releasing sneak fires the charged kick if the ball is in range; if not, the charge is cancelled quietly. Left click while charging fires immediately at the current charge. Max charge, min/max multiplier all configurable.
* **Power shot:** a kick at or above `power-shot-threshold` of full charge becomes a POWER SHOT: stronger velocity, special trail, special sound, big title for the kicker and a smaller action-bar flash for everyone else, and a longer `power-shot-cooldown`.
* **Cooldown:** per-player `kick.cooldown-ticks` to stop spam; visible as a brief action-bar cooldown hint only if the player spams.
* **Curve:** if the player is moving sideways relative to their facing when kicking, add spin so the ball curves slightly (`curve.strength`, default 0.15, decaying). Must stay subtle.
* Kick feedback: swing animation, impact particles, sound (normal vs strong), tiny cooldown tick. Sounds are never played every tick.

Every kick registers a **touch** (last toucher, team, time) used for possession, assists, own goals, saves and shot stats.

---

## 10. SCREEN ANNOUNCEMENT SYSTEM (THE MOST IMPORTANT PART)

**Rule: every important event is shown on the player's screen (title, subtitle, action bar and/or boss bar). Chat is only a record, never the only place an event appears.**

### 10.1 Architecture

Build an `AnnouncementService` driven entirely by `messages.yml`. Each message is an `Announcement` with optional parts:

```yaml
goal.scored-for:        # example shape; every key listed in 10.3 must exist
  title: "{symbol-ball} GOAL!"
  subtitle: "<{team-color}>{scorer} scored! | {red-score}-{blue-score}"
  actionbar: "Your team leads {score}"
  chat:
    - "{symbol-ball} GOAL! <{team-color}>{scorer} ({assist})"
  sound: goal.scored          # key into the sounds section of config.yml
  times: {fade-in: 0, stay: 50, fade-out: 10}   # ticks
  priority: CRITICAL           # CRITICAL | HIGH | NORMAL | LOW
  droppable: false
```

All placeholders go through MiniMessage `TagResolver`s (`{scorer}`, `{team}`, `{red-score}`, `{blue-score}`, `{time}`, `{mode}`, `{mvp}`, `{points}`, `{goals}`, `{assists}`, `{shots}`, `{saves}`, `{streak}`, and so on). Player-supplied names are inserted as plain text (never parsed as MiniMessage).

### 10.2 The title queue (Minecraft shows only ONE title at a time)

A new title overwrites the old one, so the plugin needs a per-player `TitleQueue`:

* Priorities: `CRITICAL` (goals, final result, MVP, forfeit) > `HIGH` (countdown, kickoff, final whistle, power shot) > `NORMAL` (queue events, time warnings) > `LOW` (info).
* A higher priority interrupts a lower one. Equal priority queues in FIFO order, each shown for its full `stay` time.
* `droppable: true` messages (countdown ticks, time warnings, power shot) are **dropped** if blocked longer than their TTL rather than shown late. CRITICAL messages are never dropped.
* A goal in the last seconds must not be hidden by a "3 2 1" countdown; the goal wins, the stale number is dropped.
* Action bar: Minecraft fades it in about 3 seconds, so persistent action-bar content (queue HUD, match HUD, win/lose banner) is re-sent every 20 ticks while active. Only one component owns the action bar at a time using the same priority rules.
* Boss bar: used for the match timer (one per match, per-player visibility). It changes colour at 60 s (yellow) and 10 s (red) and shows the score.
* Queues are cleared on match end and on leave. No title tasks outlive the match.
* Per-audience sending: the service resolves who sees what (see matrix), never broadcasts to the whole server.

### 10.3 Announcement matrix (every row must exist in `messages.yml` and be wired in code)

Audience legend: **ALL** = every player in that match, **WIN** = winning team, **LOSE** = losing team, **ME** = the player the event is about, **TEAM** = the player's team.

| Event | Audience | Title / Subtitle | Action bar | Boss bar | Chat | Sound | Particles |
|---|---|---|---|---|---|---|---|
| Joined queue | ME | "QUEUE JOINED" / mode | queue HUD | - | line | pling | - |
| Left queue | ME | "LEFT QUEUE" | - | - | line | soft | - |
| Queue progress | ALL in queue | - | `Waiting for players... 3/4` | - | - | tick (rare) | - |
| Queue ready | ALL in queue | "MATCH FOUND" / mode | "Preparing arena..." | - | line | level-up | - |
| Arena unavailable | ME | "NO ARENA FREE" / "You are still queued" | queue HUD | - | line | bass | - |
| Match starting | ALL | "{mode} STARTING" / team + opponents | your team colour | timer shown | line | horn | - |
| Countdown 3 / 2 / 1 | ALL | big number, own colour per number | "Get ready" | - | - | pling (distinct pitch each) | - |
| KICK OFF | ALL | "KICK OFF!" / "Good luck" | - | - | - | horn | burst at centre |
| Kick-off after goal | ALL | 3-2-1 + "KICK OFF!" | - | - | - | same | - |
| **GOAL (scoring team)** | WIN-side | "GOAL!" gold / "{scorer} scored! 2-1" | "Your team leads / ties / trails" | flash | box | stadium sequence | strong team-colour burst |
| **GOAL CONCEDED (conceding team)** | LOSE-side | "GOAL CONCEDED" red / "{scorer} scored for {team}" | "Keep fighting - 1-2" | flash | box | low horn | small |
| Goal (scorer extra) | ME | action bar "YOU SCORED!" | yes | - | - | extra level-up | firework above head |
| Assist | ME + TEAM | subtitle line "Assist: {name}" | "ASSIST!" for the assister | - | in goal box | chime | - |
| Own goal | ALL | "OWN GOAL!" / "{player} scored against their own team" | yes | - | line | oof + horn | - |
| Save | ME (+ small to TEAM) | - | "SAVE!" | - | - | block | small |
| Power shot | ME big, ALL small | "POWER SHOT!" (ME) | "{player} POWER SHOT" (ALL) | - | - | special | special trail |
| Ball reset | ALL | - | "Ball reset - kick off in 3" | - | - | tick | - |
| 60 s remaining | ALL | - subtitle "60 SECONDS REMAINING" | yes | yellow | - | tick | - |
| 30 s remaining | ALL | - subtitle "30 SECONDS REMAINING" | yes | yellow | - | tick | - |
| 10 s remaining | ALL | "10" / "SECONDS REMAINING" | yes | red | - | tick | - |
| 5 / 4 / 3 / 2 / 1 | ALL | big red number | - | red | - | pling rising pitch | - |
| Final whistle | ALL | "FINAL WHISTLE" / score | - | removed | - | whistle x3 | - |
| **VICTORY (winning team)** | WIN | "VICTORY!" gold / "{team} WINS {red}-{blue}" | "You won! +1 win, streak {streak}" | - | summary | win fanfare | fireworks around them |
| **DEFEAT (losing team)** | LOSE | "DEFEAT" dark red / "{team} won {red}-{blue}" | "Better luck next time - rematch from the menu" | - | summary | sad low notes | none / dim |
| **DRAW** | ALL | "DRAW" yellow / "{red}-{blue}" | "Nobody wins - nobody loses" | - | summary | neutral | small |
| **WIN BY FORFEIT** | WIN | "VICTORY BY FORFEIT" / "{team} left the match" | yes | - | line | fanfare | fireworks |
| **LOSS BY FORFEIT** | the leaver(s) | "FORFEIT" / "You left the match" | yes | - | line | low | - |
| MVP | ALL | "MATCH MVP" / "{mvp} ({points} pts)" | - | - | MVP line | level-up | stars above MVP |
| Match stats table | ALL | - | - | - | table (10.5) | - | - |
| Player left / disconnected | ALL | subtitle "{player} LEFT THE MATCH" | yes | - | line | bass | - |
| Forfeit timer running | ALL | - | "{team} needs players - forfeit in 20s" | countdown | - | tick | - |
| Player reconnected | ALL | subtitle "{player} IS BACK" | yes | - | line | pling | - |
| Match cancelled | ALL | "MATCH CANCELLED" / reason | yes | - | line | bass | - |
| Returning to lobby | ALL | - | "Returning to lobby in 5..." | - | - | tick | - |

### 10.4 Personalised end-of-match screen (win AND lose, exact timeline)

Durations are configurable under `match.end-screen`. Defaults:

```text
T+0.0s  Final whistle: title "FINAL WHISTLE" + score, ball frozen, players frozen (movement locked, not teleported), boss bar removed, whistle x3.
T+2.0s  RESULT SCREEN (held ~5s, action bar re-sent every second):
          winners : "VICTORY!"   gold,     subtitle "RED TEAM WINS 5-3",   fireworks + win fanfare
          losers  : "DEFEAT"     dark red, subtitle "Blue Team won 3-5",   low sad notes, no fireworks
          draw    : "DRAW"       yellow,   subtitle "2-2",                 neutral sound
T+7.0s  MVP screen (~4s): "MATCH MVP" / "PlayerName (14 pts)", star particles above the MVP (modes listed in mvp.enabled-modes).
T+11.0s Chat: match stats table + each player's personal summary (10.5).
T+12.0s Action bar countdown "Returning to lobby in 5..4..3..", then teleport + full state restore + scoreboard removal.
```

Forfeit and cancelled matches use the same screens with their own text.

Personal result line for every player (action bar during result, chat afterwards): result (WIN/LOSS/DRAW), your goals/assists/shots/saves, MVP bonus if any, current win streak, and updated career totals (matches, wins).

### 10.5 Chat summary formats

Goal box (chat, once per goal, never duplicated):

```text
╔══════════════════════╗
        GOAL!
      RED TEAM
  PlayerName  (assist: Name)
╚══════════════════════╝
```

Match stats table (sorted by goals, then assists, then shots):

```text
MATCH STATS
Player        Goals  Assists  Shots  Saves
Player1          2       1       7      0
Player2          1       2       5      1
```

---

## 11. GOALS, ASSISTS, SAVES, SHOTS (exact definitions)

* **Goal region:** two AABBs per arena. The ball scores when its centre is inside a goal region while match state is `LIVE`. Ball in RED goal = BLUE scores; ball in BLUE goal = RED scores.
* **Debounce:** the first valid detection flips state `LIVE -> GOAL`, which makes any further detection a no-op. Exactly one goal per ball entry, exactly one announcement set.
* **Scorer / own goal:** the last toucher. If the last toucher's team is the team that benefits, it is a normal goal. If the last toucher belongs to the defending team, it is an **own goal** (point goes to the other team, own-goal stat to the toucher).
* **Assist:** the previous toucher from the scoring team, different from the scorer, who touched the ball within `assist-window-seconds` (default 6) with no opponent touch in between.
* **Shot:** a kick whose predicted path (simple capped simulation, max 2 s, ignoring players) enters the opponent's goal region, or that ends inside a "danger zone" box in front of it. Count `shots` for any such kick and `shots_on_target` when it would score.
* **Successful shot:** a shot that results in a goal.
* **Save:** a defending player touches the ball within 0.7 s after an on-target shot **and** after that touch the ball no longer would enter the goal. Credit once per shot.
* After a goal: freeze the ball, run the celebration (strong particles, sounds, titles), wait `goal-reset-delay`, reset ball to centre, optionally reset players to spawns (`reset-positions-after-goal`), run the kick-off countdown, then set state back to `LIVE`.
* If the timer hits zero during a goal celebration, the goal still counts and the match ends once the celebration finishes.
* Optional **golden-goal overtime** (`match.overtime`, off by default): if drawn at zero, play an extra period; first goal wins; still drawn at the end = DRAW.

---

## 12. MATCH STATE MACHINE

`PREPARING -> COUNTDOWN -> LIVE <-> GOAL (celebration -> COUNTDOWN) -> ENDING -> CLEANUP -> FINISHED`
plus `CANCELLED` reachable from any state.

* `Match` owns: id, mode, arena, teams, players (UUID -> `MatchPlayer`), scores, timer, ball, stats, task handles, boss bar, state.
* All transitions go through one method that validates the transition, so illegal states cannot occur.
* Timer: one 20-tick task; the match clock only runs in `LIVE` and `COUNTDOWN` after kickoff (not during goal celebrations or end screens).
* Players are frozen (movement locked) during `COUNTDOWN` and `ENDING` by a method that does not teleport them every tick (use walk-speed/jump lock and restore exact values afterwards).

---

## 13. SCOREBOARD

Per-player `Scoreboard` with a sidebar objective, **flicker-free** (team-prefix lines, unique invisible entries, update only lines whose text changed, hide the red score numbers using the number-format API if available). Updated on events and once per second for the clock.

```text
        ZERO SPAWN FOOTBALL
━━━━━━━━━━━━━━━━━━
RED         3
BLUE        2

TIME     02:41
━━━━━━━━━━━━━━━━━━
BALL: RED   (last toucher's team)
Mode: 2v2
You: RED
```

At match end the sidebar keeps the final score during the end screen, then the player's previous scoreboard is restored exactly.

---

## 14. PLAYER PROTECTION & STATE RESTORE

During a match: no block break/place/interact, no item drop/pickup, no inventory access (except plugin GUIs), no commands other than `/football ...` (and permission `football.bypass`), no PvP, no hunger loss, no fall damage, no damage at all, no fire, no vehicle riding, no ender-pearl/projectile abuse, no teleport out (plugin teleports allowed), gamemode forced to `ADVENTURE`, void safety (teleport back to own spawn, no death).

**PlayerStateSnapshot** (inventory contents, armour, offhand, health, food, saturation, XP and level, potion effects, gamemode, flight allowed/flying, walk/fly speed, fire/air ticks, absorption, location, previous scoreboard) is taken when a player enters a match and restored when they leave it, however they leave it.

**Crash safety:** snapshots are also written to `plugins/ZeroSpawnFootball/snapshots/.dat` (use `ItemStack.serializeItemsAsBytes`/`serializeAsBytes`, verify the exact method on 26.2). On join, if a snapshot file exists and the player is not in a match, restore it and delete the file. Delete the file after normal restore. A server crash can therefore never lose a player's inventory.

Restoring state to a player who is offline: store the snapshot and restore on next join.

---

## 15. DISCONNECT / LEAVE / FORFEIT

* In **queue**: `/football leave` or quit removes the player cleanly.
* In **match**: `/football leave` asks for confirmation (`/football leave confirm`) and counts as abandoning (stats: counts as a loss and a match played). Disconnecting does the same, except reconnect is allowed if `disconnect.allow-rejoin: true` and the match is still running (restore their match state and position).
* A team that still has players continues (their teammates are announced via the matrix). If a team has **zero** players present, start the forfeit timer (`disconnect.forfeit-after`, default 30 s) with a visible countdown. If nobody rejoins, the other team wins **by forfeit** (win/lose screens in 10.3). If both teams are empty, cancel the match silently and clean up.
* The leaver never gets a win; forfeit winners get a win but no MVP bonus.

---

## 16. COMMANDS & PERMISSIONS

```text
/football                       open GUI
/football join 
/football leave [confirm]
/football stats [player]
/football top [category]
/football admin                 admin help/status
/football reload
/football createarena  
/football deletearena 
/football setlobby
/football pos1 | pos2
/football setbounds 
/football setspawn   
/football setcenter 
/football setball 
/football setgoal  
/football validate 
/football enable  | disable 
/football arena paste 
/football forcestart     start a match with whoever is queued, if the minimum is met
/football stop [arena|matchId]       end a match (confirm by default)
/football list                       arenas, status, active matches, queues
/football debug                      (admin) toggle debug HUD: ball speed, tick time, task counts
```

Aliases: `/fb`, `/zsfootball`.

Permissions: `football.use` (default true), `football.admin` (default op), `football.bypass` (default op: allows commands/building outside matches' restrictions).

**Tab completion** for every argument: modes, arena names, `red|blue`, indices based on mode team size, stat categories, online player names.

---

## 17. CONFIGURATION

### 17.1 `config.yml` (create with comments, every value used by the code)

```yaml
settings:
  debug: false
  prefix: "ZERO SPAWN FOOTBALL » "

symbols:                      # Minecraft's default font does not render colour emoji. Keep these BMP-safe.
  ball: "⚽"
  red: "●"
  blue: "●"
  trophy: "★"
  warning: "⚠"
  bar-full: "█"
  bar-empty: "░"

lobby:
  after-match: LOBBY          # LOBBY | PREVIOUS_LOCATION (falls back to PREVIOUS_LOCATION if no lobby set)

queue:
  enabled: true
  start-delay-when-full: 2    # seconds
  hud-interval-ticks: 20

match:
  duration: 300
  countdown: 3
  goal-reset-delay: 5
  kickoff-countdown-after-goal: 3
  reset-positions-after-goal: true
  min-players-per-team-to-continue: 1
  overtime: {enabled: false, golden-goal: true, duration: 60}
  time-warnings: [60, 30, 10, 5, 4, 3, 2, 1]
  end-screen:
    final-whistle-seconds: 2
    result-seconds: 5
    mvp-seconds: 4
    summary-delay-seconds: 1
    return-delay-seconds: 12
  force-adventure-mode: true
  glow-teams: false

ball:
  radius: 0.25
  hitbox-size: 0.7
  visual:
    material: PLAYER_HEAD
    head-texture: ""          # paste a base64 football skin texture value here
    item-model: ""            # optional resource-pack item model key
    fallback-material: SNOWBALL
    scale: 0.6
    rolling-rotation: true
  physics:
    gravity: 0.05
    air-drag: 0.995
    ground-friction: 0.96
    bounce-restitution: 0.55
    wall-restitution: 0.70
    min-bounce-speed: 0.12
    stop-threshold: 0.012
    max-speed: 1.8
    substeps: 2
  stuck-reset-seconds: 12
  curve: {enabled: true, strength: 0.15, decay: 0.96}
  player-collision: {enabled: true, knockback: 0.15}

kick:
  range: 3.0
  cone-degrees: 70
  power: 0.8
  sprint-multiplier: 1.35
  distance-falloff: 0.30
  loft: {min: 0.05, max: 0.55}
  cooldown-ticks: 8
  charge:
    enabled: true
    input: SNEAK              # SNEAK (recommended)
    max-ticks: 30
    min-multiplier: 1.0
    max-multiplier: 2.0
    power-shot-threshold: 0.95
    power-shot-cooldown-ticks: 60

ball-effects:
  enabled: true
  trail: true
  trail-speed-threshold: 0.35
  trail-max-particles-per-tick: 3
  impact-particles: true
  goal-particles: true
  colors: {primary: "#FFF3B0", secondary: "#FFFFFF"}   # sulfur-like yellow/white

announcements:
  titles: true
  actionbar: true
  bossbar: true
  chat: true
  sounds: true

scoring:
  assist-window-seconds: 6
  save-window-seconds: 0.7

mvp:
  enabled-modes: [2v2, 4v4]
  winning-team-only: false
  points: {goal: 5, assist: 3, save: 3, successful-shot: 1, win: 5, own-goal: -3}

disconnect:
  allow-rejoin: true
  forfeit-after: 30

stats:
  enabled: true
  database-file: stats.db
  leaderboard-cache-seconds: 60
  leaderboard-size: 10

sounds:                       # namespaced keys + volume + pitch; verify each key exists in 26.2
  kick: {key: "minecraft:entity.player.attack.knockback", volume: 0.8, pitch: 1.2}
  strong-kick: {key: "minecraft:entity.iron_golem.attack", volume: 1.0, pitch: 1.0}
  goal:                       # multi-cue sequence, delay in ticks
    - {delay: 0,  key: "minecraft:event.raid.horn",                 volume: 1.0, pitch: 1.0}
    - {delay: 4,  key: "minecraft:entity.firework_rocket.blast",    volume: 1.0, pitch: 1.0}
    - {delay: 8,  key: "minecraft:entity.player.levelup",          volume: 1.0, pitch: 1.2}
    - {delay: 14, key: "minecraft:block.note_block.bell",           volume: 1.0, pitch: 1.5}
    - {delay: 20, key: "minecraft:entity.firework_rocket.twinkle",  volume: 1.0, pitch: 1.0}
  countdown: {key: "minecraft:block.note_block.pling", volume: 1.0, pitches: [0.8, 1.0, 1.2]}
  kickoff: {key: "minecraft:event.raid.horn", volume: 1.0, pitch: 1.0}
  whistle: {key: "minecraft:block.note_block.flute", volume: 1.0, pitch: 2.0}
  victory: {key: "minecraft:ui.toast.challenge_complete", volume: 1.0, pitch: 1.0}
  defeat: {key: "minecraft:entity.villager.no", volume: 1.0, pitch: 0.7}
```

(Add the same kind of timed list for `victory` and `defeat` if you want fuller fanfares. No placeholders may remain in the shipped config.)

### 17.2 `messages.yml`

Every row of the matrix in 10.3 has one or more keys here (including separate keys for WIN/LOSE/DRAW audiences). Ship a complete default English file. Unknown/missing keys fall back to the bundled default and log once, never throw.

### 17.3 Sound handling

Sounds are read from config as namespaced keys and played through Adventure `Sound`/`Key`. An invalid key logs one warning, never throws, never spams. Goal and victory sounds are multi-cue sequences scheduled with a few delayed tasks owned by the match.

---

## 18. EFFECTS (strict budgets)

* **Trail:** only while speed >= `trail-speed-threshold`, at most `trail-max-particles-per-tick`, using small yellow/white `DUST` (plus occasional cloud/glow), sent only to the match's players. Power shots use a distinct stronger trail.
* **Impact:** a handful of particles + sound per kick, never per tick.
* **Goal effect (much stronger):** team-colour dust ring around the goal, `FIREWORK` particles, flash around the goal frame, an explosion-style particle burst at the ball (no damage, no block change), spread across several ticks so it never causes a spike. Hard cap per effect.
* **Win effect:** firework-style particles around the winning team for the result screen (optionally real `Firework` entities with `setSilent`, tagged and removed, only if you can guarantee cleanup; particles are the default).
* Never send particles to the whole world. Never use `World#spawnParticle` for match visuals.

---

## 19. DATA STORAGE & STATS (SQLite)

Tables:

```sql
players(uuid TEXT PRIMARY KEY, name TEXT, matches INT, wins INT, losses INT, draws INT,
        goals INT, assists INT, shots INT, shots_on_target INT, saves INT, own_goals INT,
        mvps INT, win_streak INT, best_win_streak INT, updated_at INTEGER);
match_history(id INTEGER PRIMARY KEY AUTOINCREMENT, mode TEXT, arena TEXT, started_at INTEGER,
        ended_at INTEGER, red_score INT, blue_score INT, result TEXT, forfeit INT);
```

* A single-thread async executor does all DB work. Stats are cached on join, mutated in memory during the match, and written **in one transaction at match end**. On a failed write: log, retry once, keep the data queued; flush synchronously in `onDisable`.
* Name is updated on join.
* **Leaderboards:** goals, wins, assists, saves, matches, mvps. Cached for `leaderboard-cache-seconds`, queried async. `/football top` shows rank, name and value (use ordinal numbers or BMP-safe medals). A `TopMenu` GUI optional.
* **Stats GUI:** clean 3-row `StatsMenu` with the player's head and one item per stat, plus win rate and best streak.
* `/football stats ` works for offline players (look up by name in the DB).

### MVP

`MvpCalculator` (pure function, unit tested): score = goals*5 + assists*3 + saves*3 + successful shots*1 + win*5 + own goals*(-3) (all weights from config). Tie-break order: goals, assists, saves, fewer own goals, UUID order (deterministic). MVP is not pay-to-win and uses no ranks/perks. 1v1 is excluded by default via `mvp.enabled-modes`.

---

## 20. PROJECT STRUCTURE (every listed class must exist and be used)

```text
ZeroSpawnFootball/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle/wrapper/...
├── README.md
└── src/
    ├── main/java/com/zerospawn/football/
    │   ├── ZeroSpawnFootballPlugin.java
    │   ├── config/        ConfigManager, MessagesManager, Settings (typed config view)
    │   ├── arena/         ArenaMode, Arena, ArenaManager, ArenaStorage, ArenaRegion, ArenaValidator,
    │   │                  ArenaCollisionMap, SchematicService (+ WorldEditHook loaded only if present),
    │   │                  SelectionService (pos1/pos2 fallback)
    │   ├── queue/         QueueManager, QueueTicket
    │   ├── match/         Match, MatchManager, MatchState, TeamSide, MatchTeam, MatchPlayer,
    │   │                  MatchStats, MatchResult, GoalRecord, TouchRecord, MatchTimer
    │   ├── ball/          Ball, BallPhysics, BallVisual, BallEffects, KickCalculator,
    │   │                  ChargeTracker, TouchTracker, ShotPredictor
    │   ├── announce/      AnnouncementService, Announcement, AnnouncementKey, TitleQueue,
    │   │                  SoundCue, SoundSequence, Audience
    │   ├── ui/            MenuHolder, ModeMenu, StatsMenu, TopMenu, ScoreboardService, BossBarService
    │   ├── stats/         StatsService, StatsRepository, PlayerStats, StatCategory,
    │   │                  LeaderboardService, MvpCalculator
    │   ├── player/        PlayerStateSnapshot, PlayerStateService, SnapshotStorage, FreezeService
    │   ├── command/       FootballCommand, subcommand classes, FootballTabCompleter
    │   ├── listener/      ProtectionListener, ArenaBuildListener, DamageListener, HungerListener,
    │   │                  InventoryListener, CommandBlockListener, ConnectionListener,
    │   │                  KickListener, MenuListener, BallEntityListener
    │   └── util/          Text (MiniMessage helpers), Cuboid, Vec, Ticks
    ├── main/resources/    plugin.yml, config.yml, messages.yml
    └── test/java/...      JUnit 5 tests (see section 21)
```

---

## 21. PERFORMANCE & ACCEPTANCE CHECKLIST

### Performance budget

* Idle server with zero matches: **no repeating tasks** from the plugin except none/at most one cheap housekeeping timer.
* One match = one physics task + one 20-tick HUD/timer task (+ short-lived celebration tasks). The physics task does no world block lookups (uses `ArenaCollisionMap`) and iterates at most 8 players.
* Particle caps as in section 18. No allocation-heavy code in hot loops (reuse vectors where reasonable).
* `/football debug` shows per-match tick cost so the owner can verify.

### Unit tests (JUnit 5, pure logic, no server needed)

Team balancing, queue FIFO + match creation thresholds, `MvpCalculator` incl. tie-breaks, kick power/charge/curve math, goal-attribution (goal, own goal, assist window), title queue priority/drop rules, stats aggregation, leaderboard ordering.

### Acceptance checklist (answer each at the end with PASS and a one-line reason)

1. Plugin loads with and without WorldEdit, no errors on a clean start.
2. `./gradlew build` produces the jar.
3. Arena setup + `validate` + `enable` works for 1v1, 2v2, 4v4.
4. Queue thresholds 2/4/8 create matches; two arenas of one mode run two matches at once without interference.
5. Ball cannot be picked up, cannot leave the arena, cannot clip through floor/walls at max speed.
6. Normal, sprint, charged, power-shot kicks and curve all work and are cooldown-limited.
7. Exactly one goal event per goal; own goals and assists attributed correctly.
8. Every row of the announcement matrix fires, titles never get lost or overwritten wrongly, goal beats countdown.
9. Winners see VICTORY, losers see DEFEAT, draws see DRAW, forfeits show forfeit screens, MVP and stats table appear.
10. Disconnect/rejoin/forfeit work as specified.
11. After every end path (normal end, stop, cancel, forfeit, disconnect, plugin disable, reload, crash then restart) all players are restored exactly, all entities/tasks/boss bars/scoreboards are gone, nothing leaks.
12. Stats persist across restart, leaderboards correct.

---

## 22. FINAL OUTPUT

Provide the **complete project** file by file (full contents), the exact build command, install steps (Paper 26.2 server, optional WorldEdit, folder for schematics), a README with setup walkthrough for all three modes (including the 4v4 setspawn sequence, how to set the ball texture, and how to edit messages), and the final self-review. The project must compile against Paper 26.2 and build to a jar with no manual fixes.

Prioritise in this order:

1. Responsive ball physics and reliable goal detection
2. Complete on-screen win/lose/draw/goal announcements (section 10)
3. Clean 1v1 / 2v2 / 4v4 matchmaking
4. Safe state restore and cleanup
5. Stable multi-arena matches
6. Great visual and audio feedback
7. Stats, MVP, leaderboards
8. Performance
9. Easy arena setup
Kodari AI
KodariOct 3 at 11:00 am 1
ZeroSpawnFootball
A complete football (soccer) minigame plugin for Paper 26.2 servers. Features three match modes (1v1, 2v2, 4v4) with automatic queue-based matchmaking and team balancing. Includes a custom physics-driven ball entity using ItemDisplay and Interaction entities, with support for normal, sprint, charged, and power-shot kicks, plus ball curve. Provides a comprehensive on-screen announcement system with prioritized title queues, action bars, and boss bars for goals, victories, defeats, draws, and MVP awards. Includes arena setup commands with WorldEdit integration, player state snapshot/restore for crash safety, SQLite-based persistent stats with leaderboards, and full player protection during matches.
  1. Phase 1: Gradle build, plugin descriptor, config/messages, startup, and /football command.

  2. Phase 2: Arena definitions, persistence, validation, and setup commands.

  3. Phase 3: FIFO queues, isolated match lifecycle, teams, timer, and player restoration.

  4. Phase 4: Ball entity, kick/physics, collisions, and goals.

  5. Phase 5: On-screen announcements and match results.

  6. Phase 6: Persistent statistics, cleanup, README, and final acceptance review.

Phase 1 created: Gradle build files, plugin descriptor, default configuration/messages/arena storage, startup class, and /football help, reload, and arena-list commands.

Build with gradle build using JDK 25. I haven’t run the build, and the plugin is not yet playable: arena setup, matchmaking, gameplay, announcements, and stats remain for the later phases.

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle.kts
README.md
settings.gradle.kts
Code
13 577
src/main/java/com/zerospawn/football/ZeroSpawnFootballPlugin.java
package com.zerospawn.football;

import com.zerospawn.football.arena.ArenaStorage;
import com.zerospawn.football.command.FootballCommand;
import com.zerospawn.football.config.ConfigManager;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;

public final class ZeroSpawnFootballPlugin extends JavaPlugin {
    private ConfigManager configManager;
    private ArenaStorage arenaStorage;

    @Override
    public void onEnable() {
        saveDefaultConfig();
        saveResource("messages.yml", false);
        saveResource("arenas.yml", false);

        configManager = new ConfigManager(this);
        configManager.reload();
        arenaStorage = new ArenaStorage(this);
        arenaStorage.load();

        PluginCommand command = getCommand("football");
        if (command == null) {
            getLogger().severe("The football command is missing from plugin.yml; disabling plugin.");
            getServer().getPluginManager().disablePlugin(this);
            return;
        }
        FootballCommand footballCommand = new FootballCommand(this);
        command.setExecutor(footballCommand);
        command.setTabCompleter(footballCommand);
        getLogger().info("ZERO SPAWN FOOTBALL enabled.");
    }

    @Override
    public void onDisable() {
        if (arenaStorage != null) {
            arenaStorage.save();
        }
    }

    public ConfigManager configManager() {
        return configManager;
    }

    public ArenaStorage arenaStorage() {
        return arenaStorage;
    }

    public void reloadPluginData() {
        reloadConfig();
        configManager.reload();
        arenaStorage.load();
    }
}