botWebWars/AGENTS.md

18 KiB
Raw Permalink Blame History

AGENTS.md - botWebWars AI Agent Guide

Welcome to botWebWars! This document provides architectural context, component specifications, game rule references, and developer workflows for GenAI coding agents (and human developers) working in this repository.


1. System Overview

botWebWars is an autonomous tactical bot arena built on a 64 × 64 discrete grid (coordinates (0, 0) to (64, 64)). Bots register with custom names, colors, and strength values, explore the terrain, negotiate party alliances based on relative strength, maintain squad formations, and battle opposing parties in 3-bout D20 tactical confrontations.

Tech Stack

  • Backend: Python 3.12, FastAPI, Uvicorn, Pydantic v2, WebSockets, Pytest.
  • Frontend: React 19, TypeScript, Vite, Tailwind CSS v4, Lucide React icons.
  • Deployment: Multi-stage Dockerfile (Node 22 build -> Python 3.12-slim runtime), Docker Compose.
  • Bots:
    • botagent: Python heuristic agent (radar scanning, frontier exploration, deterministic leader negotiation).
    • botagent_ai: LLM-assisted Python agent (Ollama / LLM-driven strategic negotiation and pathing).
    • botagent_gear: Vertex AI (Gemini) LLM-assisted agent (Google Cloud Vertex AI / Gemini 2.5 & 1.5 strategic reasoning).

2. Repository Layout

botWebWars/
├── AGENTS.md                  # This file: AI agent orientation and system manual
├── GAME_RULES.md              # Canonical rules of engagement, movement, and scoring
├── README.md                  # Human-facing overview and quickstart
├── Dockerfile                 # Multi-stage production container build (frontend + backend)
├── docker-compose.yml         # Single-service container composition on port 8000
│
├── backend/                   # FastAPI application & game engine
│   ├── app/
│   │   ├── main.py            # FastAPI entry point, CORS, static SPA serving, WebSockets
│   │   ├── game.py            # Core game logic, grid state, movement, battle resolution
│   │   ├── models.py          # Pydantic schemas (Player, Party, Battle, Move, etc.)
│   │   ├── config.py          # App settings & environment configurations
│   │   └── api/
│   │       ├── routes.py      # REST endpoints (/api/players, /api/board, /api/parties, etc.)
│   │       └── websocket.py   # Connection manager for real-time WebSocket clients
│   ├── tests/
│   │   └── test_api.py        # Pytest test suite for game mechanics & API routes
│   └── requirements.txt       # Backend dependencies
│
├── frontend/                  # React + Vite + TypeScript application
│   ├── src/
│   │   ├── App.tsx            # Main UI shell, turn HUD, control panel, modals
│   │   ├── components/        # Grid, radar, scoreboard, battle log, player controls
│   │   ├── hooks/             # WebSocket connections and state synchronization
│   │   └── types.ts           # Frontend TypeScript interfaces mirroring backend models
│   ├── package.json           # Frontend dependencies and build scripts
│   └── vite.config.ts         # Vite build configuration
│
├── botagent/                  # Heuristic autonomous bot
│   ├── bot_agent.py           # Autonomous client using radar, memory, and game API
│   └── README.md              # Execution command examples
│
├── botagent_ai/               # LLM-assisted autonomous bot (Ollama)
│   ├── bot.py                 # Bot delegating strategic pathing/alliances to an LLM
│   ├── requirements.txt       # Dependencies (ollama, requests)
│   └── INSTALL.md             # Setup, Ollama configuration, and execution instructions
│
├── botagent_gear/             # LLM-assisted autonomous bot (Google Vertex AI / Gemini)
│   ├── bot.py                 # Bot delegating decisions to Vertex AI Gemini
│   ├── requirements.txt       # Dependencies (google-auth, requests)
│   ├── SETUP.md               # Google Cloud authentication & Vertex AI setup guide
│   ├── INSTALL.md             # Installation, virtual environment, and dependency instructions
│   └── README.md              # Feature overview and invocation examples
│
└── examples/                  # Reference screenshots and board style designs

3. Game Rules & Mechanics (GAME_RULES.md Reference)

When writing bots, backend engine logic, or game simulations, adhere strictly to GAME_RULES.md:

1. Alliances (Solo vs. Solo)

  • When two solo bots encounter each other (adjacent or on same tile), they may form an alliance.
  • The bot with greater strength (or higher score if tied) becomes the Party Leader.
  • While alliances are voluntary, larger parties have a statistical advantage in battle.

2. Solo vs. Party Encounters

  • A solo bot joins an existing party if the party leader's strength is >= the solo bot's strength.
  • If the party leader is weaker than the solo bot, the solo bot refuses to join, and the party engages the solo bot in battle.

3. Party vs. Party Battles (3-Bout D20)

  • Two opposing parties that encounter each other must battle.
  • Bout Resolution:
    • Exactly 3 bouts are conducted.
    • In each bout, each party rolls a 20-sided die (D20 between 1 and 20).
    • Bout Score = Squad Total Strength * D20 Roll.
    • Highest score wins the bout. Best 2-out-of-3 bouts wins the overall battle.
  • Scoring & Penalties:
    • Winning Leader: +2 score points.
    • Winning Party Members: +1 score point each.
    • Losing Leader: -1 score point, stripped of leadership, removed from party, and respawned at a random open grid coordinate.
    • Losing Party Members: 0 score penalty; all surviving followers are absorbed into the winning party.
    • Health Damage: All defeated party members (including the leader) lose 1 to 3 health points (randomized). Default health is 10 HP for all bots upon registration.

4. Party Squad Movement

  • The party leader chooses movement direction.
  • Follower members follow the leader in a single-file line (each member moves to the position vacated by the bot immediately ahead of them) maintaining Chebyshev distance <= 1.

5. Terrain Obstacles & Diagonal Squeeze

  • Mountains and forests are impassable.
  • Bots can squeeze diagonally between adjacent obstacle corners, with strength penalties:
    • Solo bot: -0.1 strength.
    • Party: Leader loses -0.2 strength; followers each lose -0.1 strength.
    • Moving along outer obstacle edges has no penalty. Minimum bot strength floor is 0.1.

6. Gary the Wizard (NPC Encounter & Challenge)

  • Gary the Wizard is a wandering NPC who roams the map at a random passable coordinate.
  • Players (or party leaders) who locate Gary the Wizard (adjacent or on same tile, distance <= 1) may voluntarily choose to challenge him.
  • Challenge Resolution (3-Bout D20):
    • Exactly 3 bouts are conducted.
    • In each bout, each side rolls a D20 die, multiplied by their strength (Gary the Wizard has 3.0 strength; parties use squad total strength).
    • Highest bout score wins the bout. Best 2-out-of-3 bouts wins the challenge.
  • Victory Rewards & Defeat Penalties:
    • Victory: The player (or party leader) decides and chooses which reward to claim:
      • +2 Score Points: Adds +2 score points.
      • +2 Strength: Adds +2.0 strength to the bot (recalculating squad total strength if in a party).
      • +2 Health: Adds +2 health points (expanding max health if current health exceeds initial maximum).
    • Defeat: Player/party leader loses 2 health (or 2 score points if they do not have health to lose).
  • Post-Challenge:
    • Following the challenge, Gary the Wizard teleports to a new random open coordinate on the map.

7. Player Health, Damage & Death

  • All bots register with default 10 HP (configurable).
  • Health damage is sustained by losing battles (-1 to -3 HP) or losing Gary the Wizard challenges (-2 HP).
  • When a bot's health drops to 0 HP, they are dead.
  • Death Consequences:
    • Party Disconnection: The dead bot is immediately detached from any party. If the dead bot was the leader, squad leadership transfers to the strongest surviving squad member (or the party dissolves if empty). Defeated dead followers are not absorbed.
    • Gravestone Marker: A gravestone replaces their icon on the board at their final coordinate. Deceased leaders do not respawn elsewhere.
    • No Turns or Actions: Dead bots are omitted from turn order rotation and can no longer move, duel, or take any actions.
    • Scoreboard Preservation: Dead bots remain listed on the scores and scoreboard rankings with their final achieved score, strength, and visited locations.

8. Game Conclusion

  • The game concludes when all surviving bots on the board are united into a single remaining party (or if only 1 survivor remains).
  • Final rankings and trophies (1st, 2nd, 3rd) are awarded based on Score (with Strength as the tiebreaker), with all bots (surviving and deceased) included on the scoreboard.

4. Backend & API Specifications

The backend serves both REST endpoints under /api and a live WebSocket stream at /ws.

Key REST Endpoints

Method Path Description
GET /api/health Container healthcheck endpoint
POST /api/players Register bot: {"name": str, "color": str, "strength": int, "health": int}
GET /api/players List all active players, scores, health, and positions
GET /api/board Full board state (grid, obstacles, players, parties, wizard, current turn)
POST /api/board/reset Clear board, reset parties, reset players, and respawn wizard
GET /api/wizard Get current Gary the Wizard NPC coordinates and attributes
POST /api/wizard/challenge Challenge Gary the Wizard NPC: `{"player_id": str, "reward_choice": "score"
GET /api/players/{id}/radar Scans surroundings, finds closest bots and Gary the Wizard NPC
GET /api/players/{id}/memory Coordinate history and visited locations
GET /api/players/{id}/available-moves Valid movements in all 8 directions (evaluates terrain & obstacles)
POST /api/players/{id}/move Execute a move (`{"direction": "N"
POST /api/players/{id}/ai-step Perform one autonomous decision step via internal game engine
POST /api/players/{id}/pass Pass turn to next queued entity
GET /api/turn Current turn owner, round number, and turn order
GET /api/parties List all parties, leaders, and member IDs
POST /api/parties Manually construct an alliance party
POST /api/battles/fight Initiate a 3-bout D20 battle between adjacent parties

Real-Time WebSocket (/ws)

  • Automatically broadcasts state changes (init, move, battle, wizard_challenge_resolved, party_formed, turn_change, game_over).
  • Client can send ping messages {"action": "ping"} and receives {"event": "pong"}.

5. Frontend Architecture

  • Path: frontend/
  • Framework: React 19 + TypeScript bundled with Vite.
  • Styling: Tailwind CSS v4.
  • Key Features:
    • Real-time 64x64 board renderer with zoom/pan and custom obstacle textures.
    • Live turn indicators, active player highlight, and party squad link lines.
    • Radar visualization panel showing target distances and alignment.
    • Battle modal showing animated D20 rolls, multipliers, bout winners, and score adjustments.
    • Autonomous loop toggle to run rounds continuously from the browser.

6. Docker & Container Deployment

The application is containerized into a single unified image via Dockerfile and docker-compose.yml:

  1. Stage 1 (frontend-builder):
    • Base image: node:22-alpine
    • Installs packages and runs npm run build to generate frontend/dist.
  2. Stage 2 (production):
    • Base image: python:3.12-slim
    • Installs backend requirements from backend/requirements.txt.
    • Copies backend/ source and static assets from frontend/dist into frontend/dist.
    • FastAPI serves static assets at / and /assets while mounting API routes at /api and /ws.
    • Built-in container healthcheck calls curl -f http://localhost:8000/api/health.

7. Bot Implementations

A. Heuristic Bot: botagent/

  • Entry File: botagent/bot_agent.py
  • Technique: Deterministic rule-based autonomous agent.
  • Workflow:
    1. Registers bot via POST /api/players.
    2. Polls GET /api/turn to wait for its turn.
    3. Uses GET /api/players/{id}/radar to find nearest target and detect Gary the Wizard NPC proximity.
    4. Avoids looping using internal coordinate history.
    5. Computes vector direction, evaluates diagonal obstacles, and moves.
    6. Evaluates alliances vs. fights strictly according to strength hierarchy.
    7. Decides whether to challenge Gary the Wizard NPC based on relative strength and health advantage.
  • Run Command:
    python3 botagent/bot_agent.py --name CyberBot --color "#10b981" -s 4 -H 10 --url http://localhost:8000/api
    

B. LLM-Assisted Bot: botagent_ai/

  • Entry File: botagent_ai/bot.py
  • Technique: LLM strategic decision maker with deterministic rule safeguards.
  • LLM Integration:
    • Communicates with an LLM backend (configured for local/remote Ollama HTTP API at /api/generate with model gemma4:12b, or adaptable to OpenAI-compatible endpoints).
    • Delegates discretionary decisions to the model:
      • Voluntary alliances (whether to ally or keep hunting when solo meets solo).
      • Voluntary Wizard challenges (whether to challenge Gary the Wizard NPC when adjacent for +2 score vs. -2 health risk).
      • Navigation direction toward radar targets while balancing obstacle squeeze trade-offs.
    • Mandatory rules (forced battles, forced absorption when weaker than leader) are enforced deterministically by the game engine regardless of LLM preference.
  • Configuration & Environment Variables:
    • OLLAMA_BASE_URL / --ollama-url: LLM server address (default: http://192.168.1.220:11434).
    • OLLAMA_MODEL / --ollama-model: Model identifier (default: gemma4:12b).
    • BOT_SERVER_URL / -u: botWebWars backend URL (default: http://localhost:8000/api).
    • BOT_NAME / -n: Bot name.
    • BOT_COLOR / -c: Bot hex color.
    • BOT_STRENGTH / -s: Starting strength (1-10).
    • BOT_HEALTH / -H / --health: Starting health points (default: 10).
  • Run Command:
    export OLLAMA_BASE_URL="http://localhost:11434"
    export OLLAMA_MODEL="gemma4:12b"
    python3 botagent_ai/bot.py -n MyAIBot -s 4 -H 10 -c "#8b5cf6"
    

C. Vertex AI (Gemini) Bot: botagent_gear/

  • Entry File: botagent_gear/bot.py
  • Technique: Google Cloud Vertex AI (Gemini) model reasoning for spatial navigation, minimap analysis, and strategic voluntary alliances/wizard duels.
  • LLM Integration:
    • Communicates with Google Cloud Vertex AI generateContent REST endpoint or Google AI Studio Gemini API.
    • Features structured JSON generation (responseMimeType: application/json) and system instruction enforcement.
    • Delegates discretionary choices to Gemini: voluntary alliances, choosing whether to challenge Gary the Wizard NPC, and spatial pathing.
    • Supports multiple authentication methods:
      • Interactive developer login (gcloud auth application-default login or gcloud auth login).
      • Automated service account keys (GOOGLE_APPLICATION_CREDENTIALS).
      • Direct API keys (GEMINI_API_KEY or VERTEX_API_KEY).
    • Configurable via --health / -H (or BOT_HEALTH, default: 10).
  • Documentation:
    • SETUP.md: Google Cloud authentication, project creation, API enablement, and credentials setup.
    • INSTALL.md: Virtual environment and dependency installation instructions.
    • README.md: Bot overview, CLI reference, and execution examples.
  • Run Command:
    python3 botagent_gear/bot.py --name GeminiGear --color "#4285f4" -s 5 -H 10
    

8. Common Developer Workflows

docker compose up --build

Access UI at http://localhost:8000.

Local Development (Manual Setup)

1. Backend:

cd backend
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
uvicorn app.main:app --reload --port 8000

2. Frontend:

cd frontend
npm install
npm run dev

3. Run Backend Test Suite:

# Run locally with pytest
PYTHONPATH=backend pytest backend/tests

# Or run via docker container
docker run --rm botwebwars:test pytest backend/tests

9. Guidelines for GenAI Agents Modifying this Codebase

  1. Preserve Rules Fidelity:

    • Any updates to alliance logic, battles, diagonal squeezes, or victory states must match GAME_RULES.md.
    • Update GAME_RULES.md and tests in backend/tests/test_api.py whenever game mechanics are modified.
  2. Frontend-Backend Sync:

    • When modifying schemas in backend/app/models.py, update matching TypeScript interfaces in frontend/src/types.ts.
    • Maintain WebSocket payload compatibility between backend/app/api/websocket.py and frontend hooks (frontend/src/hooks/).
  3. Bot Compatibility:

    • Ensure REST endpoint signature modifications are reflected in botagent/bot_agent.py, botagent_ai/bot.py, and botagent_gear/bot.py.
    • Preserve CLI flag compatibility across all bot scripts.
  4. Multi-Stage Build Integrity:

    • If adding frontend build dependencies, verify Dockerfile compiles cleanly in stage 1 (npm run build) and correctly mounts to frontend/dist in stage 2.