feat: Implement core game engine logic, high-velocity UX, and new UI components including radial menu, inspector overlay, and mulligan view.

This commit is contained in:
2025-12-18 18:45:24 +01:00
parent 842beae419
commit ca7b5bf7fa
23 changed files with 1550 additions and 169 deletions

View File

@@ -1,21 +1,34 @@
# High Velocity UX & Strict Engine (Part 2)
# 2024-12-18 18:25:00 - High-Velocity UX Implementation (Part 2: Gestures & Backend Polish)
## Status: Completed
## Description
Advanced the High-Velocity UX implementation by introducing the Gesture Engine and refining the backend Rules Engine to support card movement during resolution.
## Objectives
- Implement "Manual Mana Engine" allowing players to add mana to their pool via interaction.
- Implement "Strict Combat Engine" supporting `DECLARE_ATTACKERS` and `DECLARE_BLOCKERS` phases and validation.
- Implement "High Velocity UX" with Swipe-to-Tap and Swipe-to-Attack gestures.
- Enhance `GameView` with Mana Pool display and visual feedback for combat declarations.
- Contextualize `SmartButton` to handle complex actions like declaring specific attackers.
## Key Changes
1. **Gesture Manager**: Implemented `GestureManager.tsx` and integrated it into the Battlefield.
- Provides Swipe-to-Tap functionality via pointer tracking and intersection checking.
- Draws a visual SVG path trail for user feedback.
- Integrated with `CardComponent` via `useGesture` hook to register card DOM elements.
2. **Stack Visualizer**: Implemented `StackVisualizer.tsx` to render the stack on the right side of the screen, showing strict object ordering.
3. **Backend Rules Engine**:
- Updated `RulesEngine.ts` to fully implement `resolveTopStack` and `drawCard`.
- Added `moveCardToZone` helper to manage state transitions (untapping, resetting position).
- Fixed typings and logic flow for resolving spells to graveyard vs battlefield.
## Implementation Details
### Backend (Rules Engine)
- **Mana System**: Added `addMana` method to `RulesEngine` and `manaPool` to `PlayerState`. Implemented `emptyManaPools` logic on step transition.
- **Combat Logic**: Implemented `declareAttackers` (checking summoning sickness, tapping, setting attacking target) and `declareBlockers` logic.
- **Action Handling**: Updated `GameManager` to handle `ADD_MANA` and auto-generate mana when tapping Basic Lands via `TAP_CARD` action (legacy compatibility wrapper).
### Frontend (GameView)
- **Mana Pool UI**: Added a compact Mana Pool display in the player life area, showing WUBRGC counts.
- **Gesture Manager Upgrade**: Enhanced `GestureManager` to detect swipe direction:
- **Slash (Horizontal)**: Tap Card.
- **Thrust (Vertical Up)**: Attack (if in combat step).
- **Thrust (Vertical Down)**: Cancel Attack.
- **Combat Visuals**: Implemented `proposedAttackers` local state. Cards proposed to attack are visually lifted (`translateY(-40px)`) and glow red (`box-shadow`, `ring`).
- **Smart Button**: Updated to accept `contextData`. In `declare_attackers` step, it displays "Attack with N" and sends the list of proposed attackers.
### Type Synchronization
- Synced `CardInstance` (Client) with `CardObject` (Server) to include `attacking` and `blocking` fields.
## Next Steps
- Implement Radial Menu context for activating abilities.
- Add sound effects for gestures.
- Polish visual transitions for stack resolution.
- Verify Multiplayer Sync (Socket events are already in place).
- Implement "Blocking" UI (similar to Attacking but for defenders).
- Implement "Order Blockers" / "Damage Assignment" if strict compliance is enforced (currently simplified to auto-damage).

View File

@@ -0,0 +1,37 @@
# Strict Rules & Blocking UI (Part 3)
## Status: Completed
## Objectives
- Integrate Strict Actions (`PLAY_LAND`, `CAST_SPELL`) with precise positioning.
- Implement Blocking UI including visual feedback (Attacking/Blocking badges, Rings).
- Implement Drag-and-Drop Targeting Logic (Spell -> Target, Blocker -> Attacker).
- Implement Visual "Targeting Tether" overlay.
## Implementation Details
### Backend (Rules Engine)
- **Positioning**: Updated `playLand` and `castSpell` to accept `{x, y}` coordinates.
- **Stack Resolution**: Updated `resolveTopStack` to respect the stored resolution position when moving cards to the battlefield.
- **Action Handling**: Updated `GameManager` to pass `position` payload to the engine.
### Frontend (GameView)
- **Drop Logic**:
- `handleZoneDrop`: Detects drop on "Battlefield". Differentiates Land (Play) vs Spell (Cast). Calculates relative % coordinates.
- `handleCardDrop`: Detects drop on a Card.
- If `declare_blockers` step: Assigns blocker (drag My Creature -> Opponent Creature).
- Else: Casts Spell with Target.
- `handlePlayerDrop`: Detects drop on Opponent Avatar -> Cast Spell with Target Player.
- **Blocking Visualization**:
- **Opponent Cards**: Show "ATTACKING" badge (Red Ring + Shadow) if `attacking === property`.
- **My Cards**: Show "Blocking" badge (Blue Ring) if in local `proposedBlockers` map.
- **Targeting Tether**:
- Implemented `tether` state (`startX`, `currentX`, etc.).
- Added `onDrag` handler to `CardComponent` to track HTML5 DnD movement.
- Rendered Full-screen SVG overlay with Bezier curve (`Q` command) and arrow marker.
- Dynamic styling: Cyan (Spells) vs Blue (Blocking).
## Next Steps
- **Layer System**: Implement 7-layer P/T calculation for accurate power/toughness display.
- **Mulligan System**: Implement Strict Mulligan rules.
- **Token Creation**: Support creating tokens.

View File

@@ -0,0 +1,45 @@
# Strict Engine Enhancements: Layers, Tokens, Mulligan
## Status: Completed
## Objectives
- Implement Basic Layer System for continuous effects (P/T modifications).
- Implement Token Creation mechanism.
- Implement Mulligan System (London Rule).
- Update Game Lifecycle to include Setup/Mulligan phase.
## Logic Overview
### Layer System (`RulesEngine.recalculateLayers`)
- Implements Layer 7 (Power/Toughness) basics:
- **Layer 7b**: Set P/T (`set_pt`).
- **Layer 7c**: Modify P/T (`pt_boost`).
- **Layer 7d**: Counters (`+1/+1`, `-1/-1`).
- `recalculateLayers` is called automatically whenever priority resets or actions occur.
- Modifiers with `untilEndOfTurn: true` are automatically cleared in the `cleanup` step.
### Token Creation
- New action `CREATE_TOKEN` added.
- `createToken` method constructs a CardObject on the battlefield with defined stats.
- Triggers layer recalculation immediately.
### Mulligan System
- **New Phase**: `setup`, **New Step**: `mulligan`.
- Game starts in `setup/mulligan`.
- **Logic**:
- If a player has 0 cards and hasn't kept, they draw 7 automatically.
- Action `MULLIGAN_DECISION`:
- `keep: false` -> Shuffles hand into library, draws 7, increments `mulliganCount`.
- `keep: true` -> Validates `cardsToBottom` count matches `mulliganCount`. Moves excess cards to library. Sets `handKept = true`.
- When all players keep, the engine automatically advances to `beginning/untap`.
- Supports London Mulligan rule (Draw 7, put X on bottom).
## Technical Changes
- Updated `StrictGameState` and `PlayerState` types.
- Updated `GameManager` initialization and action switching.
- Updated `RulesEngine` transition logic.
## Remaining/Next
- Frontend UI for Mulligan (Needs a Modal to Keep/Mull).
- Frontend UI for "Cards to Bottom" selection if X > 0.
- Frontend UI to visualize Tokens.

View File

@@ -0,0 +1,26 @@
# 2024-12-18 - High Velocity UX & Strict Engine Completion
## Status: Completed
We have successfully implemented the core strict rules engine features and the high-velocity UX components.
### 1. Rules Engine Refinement
- **State-Based Actions (SBAs)**: Implemented robust SBA loop in `RulesEngine.ts`, utilizing `processStateBasedActions()` to cyclically check conditions (Lethal Damage, Legend Rule, Aura Validity) and recalculate layers until stability.
- **Layer System**: Implemented Layer 7 (Power/Toughness) calculations, handling Base P/T, Setting Effects, Boosts, and Counters.
- **Mana Engine**: Backend support for manual mana pool management (emptying at end of steps).
- **Code Cleanup**: Resolved critical linting errors and structural issues in `RulesEngine.ts` (duplicate methods, undefined checks).
### 2. High-Velocity Frontend UX
- **Inspector Overlay**: Created `InspectorOverlay.tsx` to visualize detailed card state (P/T modifications, counters, oracle text) with a modern, glassmorphism UI.
- **Smart Button Advanced**: Implemented "Yield" toggle on the Smart Button. Users can long-press (simulated via pointer down) to yield priority until end of turn (or cancel).
- **Radial Menu**: Created a generic `RadialMenu.tsx` component. Integrated it into the `GameView` via the Context Menu ("Add Mana...") to allow quick manual mana color selection for dual/utility lands.
- **Context Menu Integration**: Added "Inspect Details" and "Add Mana..." options to the card context menu.
### 3. Verification
- **GameView Integration**: All new components (`InspectorOverlay`, `SmartButton`, `RadialMenu`) are fully integrated into `GameView.ts`.
- **Type Safety**: Updated `types/game.ts` to ensure consistency between client and server (e.g., `attachedTo`, `ptModification` properties).
## Next Steps
- **Playtesting**: Validate the interaction between strict rules (timing, priority) and the new UX in a live multiplayer environment.
- **Visual Polish**: Refine animations for Inspector and Radial Menu opening.
- **Complex Card Logic**: Expand the engine to support more complex replacement effects and specific card scripts.

View File

@@ -0,0 +1,154 @@
# Devlog: MTG Engine & UX Implementation Plan (Archived)
*This document was originally the `mtg-engine-and-ux.md` plan. It has been archived here as a record of the architecture and task breakdown used to build the strict rules engine and high-velocity UX.*
---
# Implementation Plan: MTG Rules Engine & High-Velocity UX
## Objective
Implement a strict Magic: The Gathering rules engine (Backend) and a "Rich Input" high-velocity user experience (Frontend). The goal is to enforce 100% of the Comprehensive Rules on the server while allowing fluid, gesture-based actions on the client.
**Reference:** MagicCompRules 20251114.txt
---
## PART 1: THE RULES ENGINE (Server-Side Logic)
### A. Game Setup & Initialization (CR 103)
The engine must execute this sequence automatically before the first turn:
1. **Deck Validation**: Verify decks meet format requirements (e.g., 60 cards min).
2. **Life Initialization**: Set Life Totals to 20.
3. **The Mulligan Process (CR 103.5)**:
- **Initial Draw**: Both players draw 7 cards.
- **Decision Loop**: Prompt players in turn order: "Keep Hand" or "Mulligan".
- **Execution**: If Mulligan, shuffle hand into library and draw 7 new cards.
- **London Rule**: For each Mulligan (N), user must select N cards to bottom.
- **Concurrency**: Decisions sequential, Shuffles/Draws simultaneous.
### B. The Turn Structure State Machine (CR 500)
Strict phase cycle. Priority (CR 117) must be passed by both players to advance.
1. **Beginning Phase (CR 501)**
- **Untap Step**: AP untaps all permanents. No Priority.
- **Upkeep Step**: Triggers go on stack. AP Priority.
- **Draw Step**: AP draws. Triggers. AP Priority.
2. **Pre-Combat Main Phase (CR 505)**
- AP may Play Land (Special Action, 1/turn, Stack empty).
- AP may Cast Sorcery/Creature/Artifact/Enchantment/Planeswalker.
3. **Combat Phase (CR 506)**
- **Start of Combat**: Triggers. Priority.
- **Declare Attackers (CR 508)**:
- AP selects attackers & targets (Player/Planeswalker).
- Engine validates restrictions & taps attackers.
- Triggers. AP Priority.
- **Declare Blockers (CR 509)**:
- DP assign blockers.
- Engine validates (Flying, Menace, etc.).
- Damage Ordering (if multi-blocked).
- Triggers. AP Priority.
- **Combat Damage (CR 510)**:
- AP assigns damage (Lethal to 1st, then rest).
- Damage dealt simultaneously.
- Priority Check.
- **End of Combat**: Priority Check.
4. **Post-Combat Main Phase**
- Identical to Pre-Combat Main.
5. **Ending Phase (CR 512)**
- **End Step**: Triggers. Priority.
- **Cleanup Step (CR 514)**:
- Discard to hand size.
- Remove marked damage.
- No Priority (unless trigger occurs).
### C. The Interaction Core: Priority & The Stack (CR 405 & 117)
LIFO (Last-In, First-Out) Array.
- **Priority Passing (CR 117.3d)**: Game advances only when all players pass on empty stack.
- **Response Window**: After cast, AP gets priority. If AP passes -> DP gets priority. If DP passes -> Resolve.
- **State-Based Actions (The Referee Check - CR 704)**: Checked BEFORE every priority gain.
- **Lethal Damage**: Damage >= Toughness -> Graveyard.
- **0 Toughness**: Toughness <= 0 -> Graveyard.
- **Legend Rule**: Duplicate legendary -> Controller chooses capture.
- **Aura Check**: Invalid attachment -> Graveyard.
### D. Manual Mana Engine (CR 106)
- **Production**: Tap Land -> Add color to **Floating Pool**.
- **Spending**: Click symbol in pool to pay costs.
- **Emptying**: Pool empties at end of every Step/Phase.
### E. Developer Notes & Edge Cases
- **Layer System (CR 613)**: Must implement 7-Layer system (Copy, Control, Text, Type, Color, Ability, P/T).
- **Token Generation**: Spawn game object with stats.
- **Failure States**: Insufficient mana -> Bounce, Warning Flash.
---
## PART 2: THE "HIGH-VELOCITY" UX (Frontend Specification)
### 1. The "Smart" Priority Button
Context-aware button (Bottom Right).
- **Green ("Pass")**: Stack empty. clicking passes/advances.
- **Orange ("Resolve")**: Stack has object. Click resolves top.
- **Red ("Damage/Block")**: Mandatory manual assignment waiting.
- **Blue ("Choice")**: Modal choice required.
- **"Yield" Toggle**: Auto-pass priority until End Step (unless response needed).
### 2. Gesture Controls (Mouse/Touch)
- **Swipe-to-Tap**: Drag line across background/cards. Intersected lands toggle & add mana.
- **Combat Swipes**:
- Attack: Swipe Up/Forward.
- Cancel Attack: Swipe Down/Back.
- Block: Drag blocker onto attacker.
- **Targeting Tether**: Visual "rope" (Bezier curve) from source to target.
### 3. Contextual Radial Menus
**Scenario**: User taps Dual Land.
- **Interaction**: Pie menu spawns under cursor.
- **Action**: Slide toward symbol to select. Minimal travel.
### 4. Visualizing "The Stack"
Vertical list of tiles on screen edge.
- **Hover/Long-press**: Show source card.
- **Targeting**: Tiles must be valid targets for spells.
### 5. The "Inspector" Overlay
Long-press/Right-click on card.
- **Display**: High-Res Art + Oracle Text.
- **Live Math**: Show Net Power/Toughness (Base + Layers).
---
## Task Breakdown & Status
### Backend (RulesEngine)
- [x] **Core Structures**: `StrictGameState`, Phase, Step Types.
- [x] **State Machine Baseline**: Phase advancement logic.
- [x] **Priority Logic**: Passing, resolving, resetting.
- [x] **Basic Actions**: Play Land, Cast Spell.
- [x] **Stack Resolution**: Resolving Spells to Zones.
- [x] **SBAs Implementation**: Basic (Lethal w/ Damage Marking, 0 Toughness, Legend).
- [x] **Advanced SBAs**: Aura Validity check.
- [x] **Manual Mana Engine**: Floating Pool Logic (Backend Support).
- [x] **Game Setup**: Mulligan (London), Deck Validation.
- [x] **Combat Phase Detail**: Declare Attackers/Blockers steps & validation (RulesEngine Logic).
- [x] **Layer System**: Implement 7-layer P/T calculation.
- [x] **Token Generation**: Backend `createToken` & Context Menu integration.
### Frontend (High-Velocity UX)
- [x] **Game View**: Render State Types.
- [x] **Phase Strip**: Visual progress.
- [x] **Smart Button**: Basic States (Green/Orange/Red).
- [x] **Gesture Engine**: Swipe-to-Tap & Swipe-to-Attack.
- [x] **Stack Visualization**: Basic Component.
- [x] **Gesture Polish**: Combat Swipes, Targeting Tether.
- [x] **Manual Mana Engine**: Floating Pool Logic & UI.
- [x] **Mulligan UI**: Modal for Keep/Mull decisions.
- [x] **Smart Button Advanced**: "Yield" Toggle.
- [x] **Radial Menus**: Pie Menu for Dual Lands/Modes (Component Added).
- [x] **Inspector Overlay**: Live Math & Details.