Skip to content

samdickson22/clash-simulator

Repository files navigation

Outdated and probably wrong readme

๐Ÿ† Clash Royale Battle Engine

A blazing-fast, feature-complete Clash Royale battle simulation engine built in Python. Designed for reinforcement learning research and game AI development.

โœจ Features

๐Ÿš€ Core Engine

  • Authentic mechanics from official gamedata.json
  • 33ms fixed timestep (30 FPS) for deterministic simulation
  • 732k+ ticks/second performance in turbo mode
  • Bridge pathfinding and proper troop movement
  • Complete spell system (Arrows, Fireball, Zap, Lightning)
  • Win conditions with crown counting and overtime

๐Ÿค– Machine Learning Ready

  • Gymnasium environment compatible with Stable-Baselines3, RLlib
  • 128ร—128ร—3 observation tensor (owner mask, troop type, HP)
  • 2304 discrete actions encoding (card_idx, x_tile, y_tile)
  • Reward system based on crowns, tower damage, victories
  • Batch simulation for distributed training

๐ŸŽฎ Visualization & Analysis

  • Real-time pygame visualizer with health bars and UI
  • Replay recording with msgspec for fast serialization
  • Battle statistics and performance benchmarking
  • Advanced mechanics (knockback, stun, death spawns)

๐Ÿƒ Quick Start

Basic Battle

from src.clasher.engine import BattleEngine
from src.clasher.arena import Position

# Create and run a battle
engine = BattleEngine("gamedata.json")
battle = engine.create_battle()

# Deploy some cards
battle.deploy_card(0, "Knight", Position(16.0, 8.0))
battle.deploy_card(1, "Archers", Position(16.0, 10.0))

# Run simulation
for _ in range(1000):
    battle.step()
    if battle.game_over:
        break

print(f"Winner: Player {battle.winner}")

Visualized Battle

python3 visualized_battle.py

Watch battles unfold in real-time with the pygame visualizer!

RL Training

from src.clasher.gym_env import ClashRoyaleGymEnv

env = ClashRoyaleGymEnv()
obs, info = env.reset()

for _ in range(1000):
    action = env.action_space.sample()  # Your RL agent here
    obs, reward, terminated, truncated, info = env.step(action)
    if terminated or truncated:
        break

Turbo Benchmarking

from src.clasher.replay import TurboEngine

turbo = TurboEngine("gamedata.json")
results = turbo.benchmark(duration_seconds=10)
print(f"Speed: {results['ticks_per_second']:,} ticks/sec")

๐Ÿ“‹ Installation

# Clone and install dependencies
git clone <your-repo>
cd clasher
pip3 install -r requirements.txt

# Run tests
python3 -m pytest tests/ -v

# Try the demos
python3 example.py                 # Basic engine demo
python3 advanced_demo.py          # Advanced features
python3 test_gym_env.py           # RL environment test
python3 visualized_battle.py      # Visual battle
python3 final_showcase.py         # Complete showcase

๐Ÿ—๏ธ Architecture

src/clasher/
โ”œโ”€โ”€ data.py              # Card data loading from gamedata.json
โ”œโ”€โ”€ arena.py            # Arena geometry and positioning  
โ”œโ”€โ”€ entities.py         # Troops, Buildings, Projectiles
โ”œโ”€โ”€ player.py           # Player state and hand management
โ”œโ”€โ”€ battle.py           # Core battle simulation
โ”œโ”€โ”€ engine.py           # High-level battle engine
โ”œโ”€โ”€ spells.py           # Spell system and effects
โ”œโ”€โ”€ gym_env.py          # Gymnasium RL environment
โ”œโ”€โ”€ replay.py           # Replay recording and turbo mode
โ”œโ”€โ”€ visualizer.py       # Pygame real-time visualizer
โ””โ”€โ”€ advanced_mechanics.py # Knockback, stun, death spawns

๐Ÿ“Š Performance

Metric Value
Simulation speed 732k+ ticks/sec
Real-time speedup 24,000x faster
Battles/second 67+ sustained
Cards supported 146 from gamedata.json
Memory usage ~50MB per battle

๐Ÿงช Testing

# Run all tests
python3 -m pytest tests/ -v

# Specific test suites
python3 -m pytest tests/test_basic.py      # Core functionality
python3 -m pytest tests/test_advanced.py  # Advanced features

Test Coverage:

  • โœ… Card deployment and elixir system
  • โœ… Knight vs Knight mid-bridge battles
  • โœ… Win condition detection
  • โœ… Spell casting and effects
  • โœ… Turbo mode performance
  • โœ… RL environment integration

๐Ÿค– ML Integration Examples

Stable-Baselines3

from stable_baselines3 import PPO
from src.clasher.gym_env import ClashRoyaleGymEnv

env = ClashRoyaleGymEnv(speed_factor=10.0)
model = PPO("CnnPolicy", env, verbose=1)
model.learn(total_timesteps=100000)

Custom Training Loop

from src.clasher.replay import TurboEngine

turbo = TurboEngine("gamedata.json")
results = turbo.run_batch(num_battles=1000, record_replays=True)

# Analyze results for training data
for result in results:
    battle_data = result["result"]
    # Extract features, rewards, etc.

๐ŸŽฏ Roadmap

Implemented โœ…

  • All 9 phases from plan.md complete
  • Core battle mechanics and physics
  • Gymnasium RL environment
  • Real-time visualization
  • Advanced mechanics system

Future Enhancements ๐Ÿšง

  • More cards and mechanics from gamedata.json
  • Tournament and ladder systems
  • Distributed training support
  • WebGL/browser visualization
  • Multi-agent training scenarios

๐Ÿ“š References

Built following the comprehensive plan.md roadmap, incorporating insights from:

๐Ÿ“„ License

MIT License - See LICENSE file for details.

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new features
  4. Ensure all tests pass
  5. Submit a pull request

๐Ÿ† Ready for production ML training and game AI research! ๐Ÿค–

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors