In this blog post, we'll dive into the technical details of Architects of Chaos, a physics-based building game where two AI agents compete to build the tallest and most stable structure.
The Concept
The core idea was to create a game that blends physics-based simulation with strategic AI decision-making. We wanted to see how different building philosophies (stability vs. height) would fare against each other and against unpredictable environmental challenges.
The Tech Stack
- React 18+: For the UI and state management.
- Matter.js: A 2D physics engine for the web, handling all collisions, gravity, and constraints.
- Tailwind CSS: For modern, responsive styling and layout.
- Motion (Framer Motion): For smooth UI animations and transitions.
- Lucide React: For a consistent and clean icon set.
Architecture: Syncing React and Matter.js
The biggest technical challenge was keeping the React state and the Matter.js physics engine in sync. We used a central game loop within a useEffect hook in GameCanvas.tsx.
The Game Loop
The game loop is responsible for:
- Updating Physics: Stepping the Matter.js engine.
- Calculating Metrics: Determining the height and stability of each agent's structure.
- Managing Phases: Transitioning between agent turns, settling phases, and environmental events.
// Simplified game loop in GameCanvas.tsx
useEffect(() => {
const runner = Matter.Runner.create();
Matter.Runner.run(runner, engineRef.current);
const updateLoop = setInterval(() => {
if (gameState.isPaused) return;
// Calculate metrics
updateAgentMetrics(agentA, setAgentA);
updateAgentMetrics(agentB, setAgentB);
// Phase management
if (gameState.phase === 'SETTLING') {
// Check if all bodies have settled
const allSettled = bodies.every(b => b.speed < 0.1);
if (allSettled) {
// Transition to next phase
}
}
}, 100);
return () => {
Matter.Runner.stop(runner);
clearInterval(updateLoop);
};
}, [gameState.isPaused, gameState.phase]);
Real-Time Stability Metrics
One of the most engaging features of the game is the Real-Time Stability Gauge. Unlike simple height trackers, this gauge calculates structural integrity on the fly.
We factor in several physical properties:
- Center of Mass Offset: How far the structure's mass is from its base center.
- Structural Leaning: The horizontal deviation of the tower.
- Real-Time Velocity: If blocks are still moving or vibrating, stability drops.
- Aspect Ratio: A wide "pile" is naturally more stable than a thin "tower," and the gauge reflects this architectural reality.
When stability drops below 30%, the gauge enters a CRITICAL state, pulsing red to warn the player of an imminent collapse.
AI Agents: Strategy vs. Ambition
The AI agents, Fortress Architect and High-Rise Maverick, have distinct building strategies implemented in src/logic/ai.ts.
- Fortress Architect: Prioritizes a wide base and stability.
- High-Rise Maverick: Focuses on stacking blocks vertically for maximum height.
// Example AI logic for Fortress Architect
export function getAgentAMove(agentBodies: Matter.Body[], plotRange: [number, number], round: number, difficulty: Difficulty): BlockPlacement {
// ... logic to find a stable spot near the center of existing mass ...
const avgX = agentBodies.reduce((acc, b) => acc + b.position.x, 0) / agentBodies.length;
let x = avgX + (Math.random() - 0.5) * jitter;
// Ensure the block stays within the plot boundaries
x = Math.max(plotRange[0] + halfWidth, Math.min(plotRange[1] - halfWidth, x));
return { type, x, rotation };
}
🌪️ Environmental Challenges: Adding Chaos
To make the game more dynamic, we introduced environmental challenges like Slippery Ground, Earthquakes, and The Storm. These effects are triggered randomly and their intensity scales with the selected difficulty.
- Slippery Ground: Temporarily reduces friction on all blocks.
- Earthquake: Applies a brief vertical force to all blocks.
- The Storm: A final, high-intensity phase where gravity and forces are randomized.
Architects of Chaos demonstrates how physics-based simulations can be integrated into a React application to create engaging and unpredictable gameplay. By combining strategic AI with dynamic environmental effects, we've created a game that is both fun to play and technically interesting to build.
Check out the full source code on GitHub.