Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

300 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

PyCC2 — Close Combat 2: A Bridge Too Far (Python Remake)

v0.9.0 | Beta Candidate | July 21, 2026

PythonPygameTestsCC2 FidelityStatusTest Quality

A Python recreation of Atomic Games' legendary WWII tactical wargame — Beta Candidate with full SRP refactoring, real-mode E2E, and mature test suite

🟢 Beta Candidate: Core gameplay + cinematic effects + achievement system + dynamic shadows + projectile trails + SRP architecture cleanup + real SDL E2E validation + visual polish (death fade, screen flash, movement smoothing, UI transitions, weather overlay, shell ejection, button feedback). 6291 tests passing, 38-phase E2E user journey validated in real environment. Ghost feature audit complete — all critical rendering pipelines now active. Environmental audio activated, dirty rectangle optimization live, EnhancedRenderer split complete, ResourceCacheManager online. v0.6.11: 4 ghost modules removed (spritesheet_parser/operation_timeline/context_menu + tactical_ai_types type:ignore fix). v0.7.0: 3 half-integrated modules activated (weapon_jam/surrender_system/campaign_persistence) + TD-078 DDD layer fix (deployment_factory migrated presentation→services). v0.7.1: 19 orphan prototype modules classified via TD-077 (4 DELETE + 10 ARCHIVE + 8 ORPHAN pending v0.8.0+ integration). v0.7.2: INTEGRATE prep (ROADMAP doc sync + flaky benchmark threshold fix 100ms→130ms + 3 ORPHAN module smoke tests). v0.7.3: day_night_cycle interface compatibility fix (time_of_day renamed to time_phase returning TimeOfDay enum + new time_of_day returning float 0.0-24.0 per IDayNightCycle protocol + game_loop_updating caller adaptation for audio + shadow sync). v0.7.4: INTEGRATE prep (squad_group_manager test enhancement 5→35 tests covering 6 dimensions + psychology_system/squad_group_manager INTEGRATE design doc). v0.7.5: INTEGRATE complete (psychology_system wired into TacticalOrchestrator.tick() Phase 5 to filter refused orders by morale/suppression/fatigue + squad_group_manager wired into InputRouter for Ctrl+19 create / 19 quick-select + Minimap bounding-box rendering for active groups, 27 integration tests). v0.7.6: TD-077 remaining 6 ORPHAN modules fully integrated (path_preview + range_indicator wired into Minimap for movement path visualization and unit range circles + cover_seek_ai wired into TacticalOrchestrator.tick() Phase 6 for suppression-driven cover seeking + day_night_cycle activated via GameTime injection to leverage v0.7.3 pre-wired audio/shadow/weather adapters + vehicle_variant_generator + faction_variant_generator wired into unit_database build pipeline expanding templates 80→110, 75 integration tests). v0.7.7: P2 tech debt cleanup (4 F-level cyclomatic complexity refactors: generate_road cc=115→6, handle_player_command cc=73→4, generate_orders cc=68→19, draw_units cc=63→14, total E+ violations 22→18; radon baseline migrated from CI hardcoded BASELINE=23 to pyproject.toml [tool.radon] cc_baseline=18 for single-source-of-truth CI maintenance, pure refactoring no behavior change, 6291 tests passing zero regression).


What's New (v0.6.10)

v0.3.35 — Quick Wins (2026-06-11)

  • Deleted AnimationController dead code (430 lines, 90% overlap with existing systems)
  • Save system security hardening: file permissions locked to 0o600, HMAC key minimum length validation, error logging
  • README documentation synchronized across all 3 languages

v0.3.36 — Infrastructure (2026-06-11)

  • ThemeManager runtime activation: default/dark/light themes now live at startup (3 UI files connected)
  • SurfacePool complete unification: all 6 Surface consumers now use shared LRU pool
  • HUD test coverage: 55 new tests covering CC2HUDManager core functionality (12 classes)
  • Fixed e2e save_load tests (path nesting + chmod tolerance)

v0.3.37 — Deep Optimization (2026-06-11)

  • EnvironmentalAudioSystem activated: 11 procedurally-generated ambient sounds synced to game state
  • Dirty Rectangle rendering optimization: _DirtyRectTracker for partial screen updates
  • EnhancedRenderer God Class split: extracted ShellCasingSystem + FlashEffectSystem + WeatherSystem
  • ResourceCacheManager: HTTP download manager with SHA256 verification, LRU cache, offline mode

🏗️ v0.3.34 — Critical Ghost Fix (June 10, 2026)

  • [FIX]PostProcessingEffects instance was never created — entire post-processing pipeline (desaturation, vignette) now instantiated and active
  • [FIX]Weather overlay defaults to "light_fog" — every battle now has subtle atmospheric haze

🏗️ v0.3.33 — Ghost Fixes + P3 Visual Deep-Dive (June 10, 2026)

  • [FIX] Re-enabled desaturation color grading in render() pipeline (was commented out)
  • [FIX] Tank rotation cache: key strategy changed to (width, height, angle) for O(1) hit rate + precache at init
  • [FIX] Movement smoothing now works for PNG sprite path (was bypassed)
  • [FIX] UI fade transitions now animate (FadeTransition.update() wired into game loop)
  • [VISUAL] Weather overlay system: 4 modes (clear/light_fog/dust/smoke) with animated particle drift
  • [VISUAL] Shell casing ejection physics: brass casings with trajectory, gravity, bounce, fade-out
  • [VISUAL] Button hover/click feedback + tooltip system for all command buttons

🎬 v0.3.32 — Deep Visual Polish (June 9, 2026)

  • [VISUAL] Combat particle enrichment: dirt_splash, blood_pool, hit_marker (5 types per hit vs 2)
  • [VISUAL] Unit death fade-out: 500ms alpha decay with CC2 dark-gray ghost rendering
  • [VISUAL] Screen flash effect: warm white on explosion, soft red on kill shot
  • [VISUAL] Unit movement smoothing: position lerp at 12 u/s prevents teleportation
  • [VISUAL] UI panel transition animations: FadeTransition (0.18-0.2s) on BottomPanel/Minimap/HUD

🎨 v0.3.31 — Rendering & Visual Quality Overhaul (June 8, 2026)

  • [VISUAL] Desaturation effect: numpy pixel-level CC2 grayscale war atmosphere (was pass stub)
  • [VISUAL] Infantry 8-direction differentiation enhanced: ~80%+ visual variety (8 params × 8 dirs)
  • [VISUAL] Minimap terrain detail: roads, buildings, water, woods with distinct rendering
  • [VISUAL] HUD minimap: replaced text placeholder with real Minimap component
  • [PERF] Unified SurfacePool: eliminated 3 duplicate LRU pool implementations → single shared class
  • [PERF] Tank sprite rotation pre-caching: 24 angles cached at init, O(1) lookup
  • [PERF] Terrain static layer cache: dirty-flag-based large-surface cache (+15-20 FPS expected)

🏗️ v0.3.30 — Version Sync & Documentation Update (June 7, 2026)

  • [SYNC] All README versions synchronized to v0.3.30
  • [METRICS] Code quality metrics updated: print cleanup 99.3%, module count verified

🏗️ v0.3.29 — Layer Decoupling + God Class Split (June 6, 2026)

  • [ARCH] services→presentation layer violations: 41 → 25 (-39%)
  • [MIGRATE]SoundType + InteractionMode enums → domain/value_objects/audio_enums.py
  • [DI] HUDManager/DeploymentManager accept injected objects (Minimap, CC2BottomPanel, DeploymentUI)
  • [SPLIT] deployment_ui.py: 2374 → 2071 lines — extracted factory(185) + LOS(221) sub-modules
  • [DOC] GameLoopAssembler documented as Composition Root per Clean Architecture
  • [BUGFIX] e2e test: UnboundLocalError in deployment_manager DUI scope bug

🏗️ v0.3.28 — EnhancedRenderer God Class Split (June 5, 2026)

  • [ARCH] EnhancedRenderer: 1389 → 943 lines (-32%, -446 lines)
  • [NEW]ui_overlay_renderer.py (389 lines) — VL flags, attack lines, queued commands, LOS overlay
  • [MIGRATE] Unit Drawing methods (hexagon/direction/movement-mode) → UnitRenderer (self-contained)
  • [BUGFIX] Duplicate spawn_explosion / spawn_muzzle_flash definitions removed
  • [BUGFIX]_draw_attack_lines repeated imports cleaned up
  • [BUGFIX]direction_indicator closure capture bug fixed (explicit unit param)

🧹 v0.3.27 — Product Maturity Cleanup (June 5, 2026)

  • [CLEANUP] Migrated 20+ bare print()logging across 7 files
  • [BUGFIX] feedback.py: pygame.Fontpygame.font as Font
  • [BUGFIX] pixel_artist_3d.py: /tmp/ → cross-platform tempfile.gettempdir()
  • [TEST] 27 new smoke tests covering previously zero-coverage modules

🚀 v0.3.26 — E2E Readiness + SAVE/LOAD Fix (June 5, 2026)

  • [ARCH] GameStateView Protocol breaks presentation→services circular dependency
  • [ARCH] GameLoopAssembler extracted (140-line post_init → 10 sub-methods)
  • [BUGFIX] Direction.from_angle() N↔S mapping corrected to CC2 convention
  • [BUGFIX] SAVE/LOAD: component field(init=False) pattern fixed
  • [E2E] Upgraded: 20 phases/dummy → 38 phases/real SDL mode

🔧 v0.3.25 — Architecture Cleanup (June 5, 2026)

  • Circular dependency elimination, EventBus type safety, God Class splits, 90+ module tests

🚀 v0.3.23 — Optimization Round 1 (June 2, 2026)

  • [OPT-01] EventBus unification: removed redundant publish_named calls
  • [OPT-02] EnhancedRenderer God Class split: 2243→1377 lines, 3 sub-modules extracted
  • [OPT-03] SpriteRenderer Surface pooling: 17 allocations replaced
  • [OPT-04] ParticlePool activation: dual-mode pool (dataclass + dict)
  • [OPT-05] Orphan module marking: 8 modules marked PLANNED
  • [OPT-06] Duplicate code elimination: shared rendering_utils.py, enum import consolidation
  • [OPT-07] Hardcoded path fix: absolute path → relative

🔧 v0.3.22 — Critical Bug Fixes (June 2, 2026)

  • [P0] EventBus dual-channel bridge: publish() auto-bridges TypedDict events to named handlers
  • [P0] Surface pooling: _get_pooled_surface() with LRU eviction
  • [P1] Achievement persistence: load() on startup, save() on shutdown
  • [P1] Explosion event: published in CombatDirector
  • [P1] pyproject.toml version: 0.3.0 → 0.3.21
  • [Docs] Created CHANGELOG.md, deleted 9 outdated docs

🎬 v0.3.17-v0.3.21 — Cinematic Effects & Deep Integration (June 2, 2026)

  • Camera Effects System: EffectStack with 5 effect types (shake/zoom/slow-motion/push-pull/freeze) + 6 easing functions
  • Achievement System: 11 achievements across 4 categories (combat/campaign/survival/special) with JSON persistence
  • Dynamic Shadow System: Time-of-day aware shadow rendering for buildings, trees, and units
  • Projectile Trail System: 4 trail types (bullet/shell/rocket/mortar) with particle rendering
  • Deep Integration: All 4 modules wired into GameLoop + EnhancedRenderer + EventBus
  • EventBus Named Channel: subscribe_to()/publish_named() for game event routing
  • Surface Pool Optimization: ProjectileTrail and DynamicShadow use cached surfaces (eliminates per-frame allocation)
  • Explosion Events: CombatDirector now publishes Explosion named events for camera effects
  • Achievement Persistence: Auto-load on startup, auto-save on shutdown
  • 17-Phase E2E Validation: Full user journey from faction selection to victory/defeat

🔍 v0.3.13-v0.3.16 — Critical Audit & Architecture (June 1, 2026)

  • Test Quality Revolution: Fixed 121 weak assertions across 45+ test files
  • God Class Split: Extracted particle_effects_renderer.py + environment_renderer.py from EnhancedRenderer
  • Surface Pool LRU: OrderedDict with LRU eviction (max_size=50)
  • 4 Flaky Tests Fixed: Semantic property verification instead of exact pixel matching
  • Maturity Score: Critically assessed at 7.3/10 (down from self-assessed 8.7, but more honest)

🔒 v0.3.12 — Security & Stability (May 31, 2026)

  • Dynamic Import Removal: Eliminated __import__() anti-pattern (security risk: code injection vector)
  • Data Model Extraction: Extracted deployment_models.py from deployment_ui.py (-100 lines)
  • Test Stabilization: Fixed flaky test_gray_roof with expanded color variant list

🏗️ v0.3.11 — Project Cleanup & Architecture Refactoring (May 31, 2026)

  • Major Refactoring: EnhancedRenderer decomposed from 5975→2175 lines (-63.6%)
  • 9 New Modules: Extracted rendering systems (terrain, shadows, lighting, infantry)
  • Technical Debt: 8/16 items resolved (50% clearance rate)
  • Performance: Surface object pool (PERF-001), viewport culling (PERF-002)
  • Magic Number Elimination: 15 named constants extracted (WARM_OVERLAY_COLOR, VIGNETTE_*, etc.)

✨ v0.3.1 — Visual Fidelity Sprint (V01-V05)

  • V01: CC2 Three-Panel HUD (25%/45%/30% layout) matching original CC2 interface
  • V02: VP Number Display with golden bold font + pulse animation
  • V03: Crater Depth Enhancement with 5-layer gradient rendering + debris particles
  • V04: Irregular Explosion Fireball with flame tongues (not perfect circles)
  • V05: CC2 Dark Color Tone Grading (-15% brightness, warm shift)

🏗️ v0.3.2 — Architecture Refactoring

  • A1: Renderer Split — 5500-line monolith → 8 focused modules (sprite/particle/lighting/terrain/unit/decoration)
  • A2: DDD Dependency Inversion — 9 domain layer violations fixed (IEventPublisher + IRandomNumberGenerator interfaces)
  • A3: Naming Convention Audit — Passed (unit_id/is_alive/can_act patterns consistent)
  • A4: Performance Optimization — Particle system +16.8% FPS (1082→1263), _render_smoke bugfix

📊 v0.3.0 Major Features (Previous Release)

  • CC2-Authentic Victory Conditions: Instant VL capture, 20-minute battle timer, point-based scoring
  • 7 Command Hotkeys: Z (Move) / X (Move Fast) / S (Sneak) / C (Fire) / V (Smoke) / D (Defend) / H (Hide)
  • Command Queue System: Shift+right-click to queue multiple commands
  • Engineer Bridge Demolition: Engineers can destroy bridges, creating impassable water gaps
  • Building Garrison System: Units enter buildings for defense bonuses; window firing arc restrictions
  • Deployment LOS Preview: See line-of-sight before committing unit placement
  • Faction Difficulty Asymmetry: Different experience/supply levels per faction (Green/Veteran/Elite/Crack)
  • Campaign Day Briefing: Strategic map overview at start of each campaign day
  • Battle-to-Battle Unit Carryover: Surviving units persist across campaign battles
  • Campaign End Screen: Summary of campaign results after final battle
  • Enhanced Visuals: Improved terrain textures, tank turret rotation, wounded soldier visuals
  • Death Animation: Directional falling animation for casualties
  • Environment Lighting: Shadow rendering for buildings and terrain features

📊 Statistics

MetricValue
Total Tests6291 passed (0 failed, 2 skipped) ✅
Test QualityA+ (121 weak assertions eliminated) 🎯
E2E Tests28 test files (38-phase real SDL mode, 100% pass rate)
Maps63 historical maps (Operation Market Garden)
Unit Templates277 (infantry, vehicles, weapons)
Weapon Types69 authentic CC2 weapons
Campaign Battles29 battles across 9 days, 3 sectors
AI Behaviors8+ tactical AI types (flanking, suppression, VP, recon, supply-line awareness, etc.)
Code Files388 Python modules (src/pycc2 .py files, verified via find src/pycc2 -name "*.py" | wc -l)
Class Definitions330+ classes
Extracted Modules22 rendering/data systems (new: ShellCasingSystem, FlashEffectSystem, WeatherSystem, ResourceCacheManager + previous 19)
Technical Debt0 God Classes (P2-2 canceled: 4 candidates judged NOT God Class via SRP analysis)
Layer Violations~25 (down from 41 in v0.3.29, -39%)
CC2 Fidelity~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction + v0.6.3v0.6.5 AI complete

📈 Code Quality Metrics (v0.6.10)

DimensionScoreNotes
Architecture7.5/10DDD + DI, EnhancedRenderer split complete (3 subsystems extracted), 0 God Classes (P2-2 canceled), layer violations -39%
Test Quality9.5/10 ✅6536 tests, weak assertions <1%, smoke tests for zero-coverage modules
Test Coverage8.5/10Broad coverage, 27 new smoke tests in v0.3.27, 55 new HUD tests in v0.3.36
Code Quality7.5/10~1 bare print() remaining (99.3% cleaned) (down from 200+), logging migration complete, AnimationController dead code removed
Performance8.5/10Surface pool LRU unified (6/6 consumers), dirty rectangle optimization live, terrain cache, tank rotation cache, viewport culling
Security9.5/10 ✅Zero eval/exec, HMAC saves (permissions 0o600, key validation), no injection vectors
Documentation8.5/10Synchronized to v0.6.10 (this update)
Maintainability8/10Clear patterns, good logging, ghost audit complete, critical pipelines active, environmental audio online
Visual Polish8/10 🆕Death fade, screen flash, movement lerp, UI transitions, weather, shells, tooltips (v0.3.31-v0.3.34)
Overall Health8.2/10Beta Candidate

Current Status: Beta Candidate — Fully Playable

This is an honest assessment based on runtime verification and E2E testing.

What Works ✅

FeatureStatusDetails
Main Menu✅ WorkingFull navigation, campaign/scenario selection
Campaign Structure✅ Working3 Sectors, 7 Operations, 29 Battles, 9 Days
Campaign Day Briefing✅ WorkingStrategic map overview at start of each day
Campaign Carryover✅ WorkingSurviving units persist between battles
Campaign End Screen✅ WorkingSummary of campaign results
Map Loading✅ Working63 map JSON files with accurate terrain
Deployment Phase✅ WorkingCC2-style drag-and-drop with LOS preview
Combat Interface✅ WorkingBottom panel, unit info, command buttons, timer
Unit Selection✅ WorkingClick to select, info panel shows health/morale/ammo
Command System✅ WorkingAll 7 CC2 commands with hotkeys (Z/X/S/C/V/D/H)
Command Queue✅ WorkingShift+right-click to queue (visual feedback pending)
Victory Conditions✅ WorkingInstant VL capture, 20min timer, point scoring
Building Garrison✅ WorkingDefense bonuses + window firing arcs
Bridge Destruction✅ WorkingEngineers can demolish bridges
Faction Difficulty✅ WorkingAsymmetric experience/supply per faction
AI Opponent✅ WorkingFlanking, suppression, VP capture, attack/move behaviors
Sprite Rendering✅ WorkingInfantry 8-direction sprites, vehicle turret rotation
Death Animation✅ WorkingDirectional falling animation
Environment Lighting✅ WorkingShadow rendering
Audio✅ WorkingWeapon sounds, ambient, music playback
Save System✅ WorkingHMAC-SHA256 signed saves with Pydantic validation
Tutorial System✅ WorkingInteractive new player guidance

Needs Polish ⚠️

FeatureStatusNotes
Command Queue UI⚠️ PartialQueue works, visual waypoint display pending
Vehicle Damage Visuals⚠️ PartialDamage states tracked, visual feedback incomplete
Smoke Particle Effects⚠️ PartialMechanics work, particle rendering needs improvement
Save/Load UI Integration⚠️ PartialBackend exists, full UI pending

Game Screenshots

Combat Scenes

Combat Scene 1
Allied infantry advancing through Arnhem streets
Combat Scene 2
Tank engagement near bridge objective
Combat Scene 3
Defensive position in Dutch countryside
Combat Scene 4
Urban warfare in city streets

Strategic Map

Strategic Map
Operation Market Garden — Three-sector strategic overview

More Screenshots

战斗5战斗6战斗7战斗8战斗9

View all 13 screenshots in assets/CC2-snapshot/


Quick Start

Prerequisites

  • Python 3.11+ (3.12+ recommended)
  • Pygame 2.2+
  • macOS / Linux / Windows

Installation

# Clone the repository
git clone https://github.com/lulin70/PyCC2.git
cd PyCC2
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # macOS/Linux# .venv\Scripts\activate # Windows# Install package (editable mode for development)
pip install -e .# Or install with dev dependencies
pip install -e ".[dev]"

Running the Game

# Start the game
pycc2
# Or using Python module
python -m pycc2.main

Controls

ActionInput
Select UnitLeft-click
Issue CommandRight-click drag (radial menu) or hotkey (Z/X/S/C/V/D/H)
Multi-selectShift + Left-click
Queue CommandsShift + Right-click
Pan CameraArrow keys / WASD / Edge scroll
ZoomMouse wheel
PauseESC (menu) / Space (time control)
LOS CheckHold Ctrl

Technical Architecture

PyCC2/
├── src/pycc2/
│ ├── domain/ # Core game logic (pure Python, highly testable)
│ │ ├── ai/ # Behavior Tree AI, tactical decision systems
│ │ ├── components/ # ECS: Health, Morale, Weapon, Position, Vision
│ │ ├── entities/ # Squad, Unit, GameMap, Projectile
│ │ ├── systems/ # Campaign, Combat, Ballistics, Pathfinding
│ │ └── value_objects/ # Damage, Direction, TerrainType, Vec2
│ ├── services/ # Game loop, AI service, Event bus, Combat director
│ ├── presentation/ # Rendering, Input handling, UI, Audio
│ │ ├── rendering/ # Camera, HUD, Minimap, Sprites, Isometric engine
│ │ │ ├── surface_pool.py # Unified Surface LRU pool
│ │ │ ├── shell_casing_system.py # Shell ejection physics system (125L)
│ │ │ ├── flash_effect_system.py # Screen flash effect system (101L)
│ │ │ ├── weather_system.py # Weather overlay rendering system (160L)
│ │ │ └── fade_transition.py # UI alpha fade transition
│ │ ├── input/ # Command system, Interaction controller
│ │ ├── ui/ # Menus, Panels, Tooltips, Deployment UI
│ │ └── audio/ # Sound system, Voice commands
│ └── infrastructure/ # Save system, Config, Parsers
├── data/
│ ├── maps/ # 63 historical map JSON files
│ ├── scenarios/ # 11 scenario configurations
│ └── units/ # Unit template definitions
├── tests/ # 6536 tests (unit + integration + E2E + smoke)
├── assets/ # Sprites, sounds, CC2 reference screenshots
└── docs/ # Design documents, PRD, Gap analysis

Design Principles:

  • Domain-Driven Design: Clean separation of business logic from infrastructure
  • Event-Driven Architecture: EventBus for loose coupling between systems
  • Fixed Timestep: Logic @30 UPS, Rendering @60 FPS
  • Component-Based Entities: ECS pattern for flexible unit composition
  • Behavior Tree AI: Modular, extensible AI decision framework

Implemented Systems

Combat Systems

SystemStatusDescription
Swiss Cheese Damage Model✅ CompleteRealistic penetration and damage calculation
Suppression System (6 levels)✅ CompleteFrom light to full suppression with morale effects
Morale & Psychology✅ CompleteDr. Silver's military psychology model
Fatigue System✅ CompletePerformance degradation over time
Weapon Jamming✅ CompleteHistorical weapon reliability (e.g., Sten 1.5%)
Ammo Pickup/Scavenging✅ CompleteSearch bodies for ammo and weapons
Surrender/Capture✅ CompleteUnits surrender when broken
Squad Degradation✅ CompleteCombat effectiveness declines with losses
NCO Rally✅ CompleteSergeants can rally panicked troops
Smoke Tactics AI✅ CompleteAI uses smoke for movement cover
Ballistic System✅ CompletePhysics-based trajectory with range/drop

AI Behaviors

AI TypeStatusDescription
Flanking AI✅ WorkingAttempts to attack from the side/rear
Suppression AI✅ WorkingPins enemies with sustained fire
Victory Point AI✅ WorkingCaptures and holds objectives
Attack Nearest AI✅ WorkingEngages closest threat
Move to Objective AI✅ WorkingAdvances toward mission goals
Commander AI✅ WorkingCoordinates squad-level tactics
Cover Seek AI✅ WorkingTakes cover when under fire
Retreat AI✅ WorkingWithdraws when overwhelmed

Campaign Systems

SystemStatusDescription
Four-Layer Hierarchy✅ CompleteCampaign → Sector → Operation → Battle
Supply Lines✅ CompleteLand/air supply with cutoff mechanics
Unit Carryover✅ CompleteVeterans persist between battles
Reinforcement System✅ CompleteDynamic reinforcements based on supply
Victory Conditions✅ CompleteCC2-authentic VL/timer/scoring
Faction Difficulty✅ CompleteAsymmetric Green/Veteran/Elite/Crack levels

Testing

# Full test suite (6536 tests)
pytest tests/ -q
# By category
pytest tests/unit/ -q # Unit tests (~3680)
pytest tests/integration/ -q # Integration tests
pytest tests/e2e/ -q # End-to-end tests (22 files, 38-phase real SDL mode)
pytest tests/unit/test_smoke_zero_coverage.py # Smoke tests for zero-coverage modules# With coverage report
pytest tests/ --cov=src/pycc2 --cov-report=term-missing
# E2E deep integration tests (real SDL, user journey scenarios)
pytest tests/e2e/ -m e2e -v

Test Coverage Highlights:

  • ✅ Backend domain logic: comprehensively tested
  • ✅ UI integration: key interaction paths covered
  • ✅ E2E gameplay: 38-phase deep integration scenarios (deployment → combat → victory)
  • ✅ AI behaviors: all 6 major AI types verified
  • ✅ Campaign flow: multi-battle carryover validated

CC2 Fidelity Assessment

DimensionTargetCurrentStatus
Map Library25-30 historical maps63 maps with accurate terrain✅ Exceeds
Campaign Structure4-layer hierarchyFull hierarchy with carryover & briefing✅ Complete
Weapon System~50 weapons69 weapons with authentic stats✅ Complete
Unit Diversity130+ unit types277 templates with sprite rendering✅ Complete
AI TacticsMature behavior trees8+ AI types (incl. ReconAI, SupplyAwarenessAI, psychology model)✅ Functional
Visual QualityCC2 pixel art (hand-drawn)Procedural textures + PixVoxel ortho sprites + SVG/programmatic sprites + shadows + 3-panel HUD + VP display⚠️ ~70% (v0.5.0 P0: PixVoxel CC0 sprites wired, 14/18 unit types covered; v0.6.10 palette correction)
Combat MechanicsSuppression + moraleSwiss Cheese model, 6 levels✅ Complete
Command System7 commandsAll 7 commands with hotkeys + queue✅ Complete
Victory ConditionsCC2-authenticInstant VL, 20min timer, points✅ Complete
Building GarrisonCC2 building entryDefense bonuses, window arcs✅ Complete
Bridge DestructionEngineer demosEngineers destroy bridges✅ Complete
AudioFull soundscapeWeapons, ambient, music🟡 ~85%

Overall Fidelity: ~75% (Visual: ~70%, Mechanics: 80%) ⚠️ v0.4.16 honest correction (88%→75%) + v0.5.0 P0: PixVoxel Blank ortho sprites wired into game loop (3968 sprites, 14/18 unit types covered, indexed-palette recoloring) + v0.6.3v0.6.5 AI behaviors complete. See GAP_ANALYSIS.md for remaining gaps and VISUAL_FIDELITY_IMPROVEMENT_PLAN.md for improvement plan.


Roadmap

Completed Milestones

  • M1: Emergency Fixes (May 23-24) — Fixed 5 P0 critical bugs, game became playable
  • M2: Core Features (May 25-27) — CC2 victory conditions, 7 commands, garrison, bridge destruction, campaign carryover, enhanced visuals

Current Phase: M3 — Polish & Visual Fidelity

  • CC2 Three-Panel HUD ✅ v0.3.1-V01
  • VP Number Display (golden bold + pulse) ✅ v0.3.1-V02
  • Crater Depth Enhancement (5-layer gradient) ✅ v0.3.1-V03
  • Irregular Explosion Fireball ✅ v0.3.1-V04
  • CC2 Dark Color Tone Grading ✅ v0.3.1-V05
  • Command queue UI (visual waypoint display)
  • Vehicle damage visual feedback (smoke, fire, immobilized)
  • Save/Load full UI integration
  • Audio mixing balance pass

Future Phases

M4: Architecture Improvements (v0.5) — PARTIALLY COMPLETE (v0.3.2)

  • Split large files (enhanced_renderer 5500→8 modules) ✅ v0.3.2-A1
  • Domain layer dependency inversion (9 violations fixed) ✅ v0.3.2-A2
  • Naming convention unification (audit passed) ✅ v0.3.2-A3
  • Performance profiling (+16.8% FPS) ✅ v0.3.2-A4
  • Domain layer slimdown (75.4% → <50%)
  • Unify unit definition system (4 sets → 1)
  • Clean up technical debt (30 bare except → specific exceptions)

M5: Quality & Sustainability (v0.6)

  • CI/CD enhancement (4-stage pipeline)
  • Documentation consolidation
  • Additional E2E test coverage
  • Performance optimization for large maps

Target: v1.0

  • Full gameplay loop working end-to-end
  • ≥90% CC2 fidelity (currently ~75%, visual ~70% / mechanics 80% — v0.4.16 honest correction; v0.5.0 P0: PixVoxel wired; v0.6.3v0.6.5 AI recon/psychology/supply complete)
  • Complete AI tactical behaviors
  • Sound effects and music
  • CC2-authentic victory conditions
  • Campaign carryover system
  • Save/Load functionality (backend done, UI pending)
  • Full visual polish

Contributing

We welcome contributions! This is an early-stage project with many opportunities for involvement:

  1. Bug Reports — Include logs, screenshots, steps to reproduce
  2. Code — Follow existing patterns, add tests, maintain style guide
  3. Assets — Sprites, sounds, maps always needed (see assets/README.md)
  4. Documentation — Improvements to docs, user guides, tutorials
  5. Playtesting — Feedback on gameplay balance and CC2 authenticity

Development Setup

# Install development dependencies
pip install -e ".[dev]"# Code quality checks
ruff check src/ tests/ # Lint
ruff format src/ tests/ # Format
mypy src/pycc2/domain/ # Type check (domain layer)# Run pre-commit hooks
pre-commit run --all-files

See INSTALL.md for complete setup instructions.


Documentation

DocumentDescription
User GuidePlayer instructions (Chinese)
Installation GuideDetailed setup instructions
Design DocArchitecture decisions
PRDProduct requirements document
Gap AnalysisCC2 fidelity comparison
Technical DebtKnown debt items and cleanup plan
SecuritySecurity design and audit
Test PlanTesting strategy and coverage goals
Improvement Planv0.6.9/v0.6.10 improvement roadmap

License

MIT License — see LICENSE

Close Combat 2 is a trademark of its respective owners. This is an unofficial fan remake for educational purposes.


Acknowledgments

  • Atomic Games — For the original Close Combat series (1997)
  • Dr. Steven Silver — For the military psychology model underlying morale mechanics
  • OpenCombat Community — For CC2 analysis and reverse engineering references
  • All Contributors — For code, feedback, assets, and patience during development

Star History

Star History Chart

Last updated: 2026-07-13 | v0.6.10 (Beta Candidate) | Tests: 6536 collected / 2 skipped | Gap Analysis | Roadmap | Project Status

About

Close Combat 2: A Bridge Too Far Remake - Python recreation (ALPHA v0.0.1)

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages