Okay, creating a fully functional, polished, 3D Risk clone entirely within a single response is a monumental task, equivalent to many weeks or months of development. It involves complex game logic, AI (optional but desired), networking (for multiplayer), detailed 3D modeling, UI design, and robust state management.
However, I can provide you with a foundational structure and a significant starting point using Three.js for the 3D rendering and plain JavaScript for the game logic. This will include:
- Basic 3D Setup: Scene, camera, renderer, basic lighting.
- Simplified Map Representation: Using simple 3D shapes for territories.
- Core Game Data: Structures for territories, continents, players.
- Basic Turn Structure: Cycling through players and phases (Reinforce, Attack, Fortify).
- Mouse Interaction: Selecting territories using Raycasting.
- Simplified Mechanics:
- Initial territory assignment.
- Basic reinforcement calculation (territory count).
- Basic attack logic (dice roll comparison).
- Basic fortify logic (moving troops).
- Basic UI: Displaying current player, phase, and simple messages.
This code will NOT include:
- A real Risk map model (uses abstract shapes).
- Continent bonuses.
- Risk cards.
- Sophisticated AI opponents.
- Multiplayer networking.
- Advanced graphics/animations.
- Detailed win/loss conditions (just basic territory control).
- Complex edge cases or rule variations.
- Saving/Loading games.
You will need the Three.js library. You can download it or link to a CDN.
Project Structure:
risk-clone/
├── index.html
├── style.css
├── js/
│ ├── main.js # Main game logic, Three.js setup
│ ├── gameConfig.js # Map data, game settings
│ └── utils.js # Helper functions (dice rolling etc.)
└── (optional) node_modules/three/ # or link to CDN
1. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D Risk Clone</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="game-container">
<canvas id="c"></canvas>
</div>
<div id="ui">
<div id="info">
<p>Player: <span id="currentPlayer"></span></p>
<p>Phase: <span id="currentPhase"></span></p>
<p>Armies to place: <span id="armiesToPlace">0</span></p>
</div>
<div id="message">Welcome to 3D Risk!</div>
<div id="controls">
<button id="endPhaseBtn">End Phase / Attack</button>
<button id="endTurnBtn">End Turn</button> <!-- Primarily for Fortify -->
</div>
<div id="dice-result" style="display: none;">
<p>Attacker Roll: <span id="attackerDice"></span></p>
<p>Defender Roll: <span id="defenderDice"></span></p>
<p>Result: <span id="combatResult"></span></p>
</div>
</div>
<!-- Use CDN or local file -->
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module" src="js/main.js"></script>
</body>
</html>
2. style.css
body {
margin: 0;
font-family: sans-serif;
color: white;
background-color: #222;
display: flex; /* Use flexbox for layout */
height: 100vh; /* Full viewport height */
}
#game-container {
flex-grow: 1; /* Allow canvas container to take up available space */
position: relative; /* Needed for absolute positioning of canvas */
overflow: hidden; /* Hide anything outside the container */
}
#c {
display: block; /* Remove extra space below canvas */
width: 100%; /* Make canvas fill its container */
height: 100%;
}
#ui {
width: 250px; /* Fixed width for the UI panel */
padding: 15px;
background-color: rgba(0, 0, 0, 0.7);
box-sizing: border-box; /* Include padding in width */
display: flex;
flex-direction: column;
gap: 10px; /* Space between UI elements */
}
#info p, #message, #dice-result p {
margin: 5px 0;
}
#controls button {
padding: 8px 12px;
margin-top: 10px;
cursor: pointer;
width: 100%; /* Make buttons fill UI width */
box-sizing: border-box;
}
#dice-result {
margin-top: 15px;
padding: 10px;
border: 1px solid #555;
background-color: #333;
}
.highlighted { /* Style for selected territory (optional) */
/* You might need to handle highlighting via material changes in JS */
}
/* Style territories via JS material changes */
3. js/gameConfig.js
// Simplified Map and Game Configuration
// --- Player Colors ---
export const PLAYER_COLORS = [
0xff0000, // Red
0x0000ff, // Blue
0x00ff00, // Green
0xffff00, // Yellow
// Add more colors if needed
];
// --- Game Phases ---
export const PHASES = {
REINFORCEMENT: 'Reinforcement',
ATTACK: 'Attack',
FORTIFY: 'Fortify',
GAME_OVER: 'Game Over'
};
// --- Territory Definitions ---
// NOTE: This is a highly simplified abstract map.
// A real implementation would use coordinates derived from an actual map SVG/model.
// Adjacency needs to be manually defined.
export const TERRITORIES = {
// ID: { name, adjacent: [neighbor IDs], initialX, initialY }
// Using simple grid-like positions for this example
't1': { name: 'Territory 1', adjacent: ['t2', 't4'], x: -15, y: 10 },
't2': { name: 'Territory 2', adjacent: ['t1', 't3', 't5'], x: 0, y: 10 },
't3': { name: 'Territory 3', adjacent: ['t2', 't6'], x: 15, y: 10 },
't4': { name: 'Territory 4', adjacent: ['t1', 't5', 't7'], x: -15, y: 0 },
't5': { name: 'Territory 5', adjacent: ['t2', 't4', 't6', 't8'], x: 0, y: 0 },
't6': { name: 'Territory 6', adjacent: ['t3', 't5', 't9'], x: 15, y: 0 },
't7': { name: 'Territory 7', adjacent: ['t4', 't8'], x: -15, y: -10 },
't8': { name: 'Territory 8', adjacent: ['t5', 't7', 't9'], x: 0, y: -10 },
't9': { name: 'Territory 9', adjacent: ['t6', 't8'], x: 15, y: -10 },
};
export const TERRITORY_IDS = Object.keys(TERRITORIES);
// --- Basic Game Settings ---
export const MIN_REINFORCEMENTS = 3;
export const STARTING_ARMIES_PER_PLAYER = (numPlayers) => {
// Example: Adjust based on player count (official rules vary)
if (numPlayers === 2) return 40;
if (numPlayers === 3) return 35;
if (numPlayers === 4) return 30;
return 25; // Default for 5+
};
// --- Constants ---
export const TERRITORY_SIZE = 5; // Visual size in 3D space
export const TERRITORY_DEPTH = 1; // Extrusion depth
export const ARMY_INDICATOR_OFFSET_Y = 2; // How high text is above territory
4. js/utils.js
// Utility Functions
/**
* Simulates rolling multiple six-sided dice.
* @param {number} numDice - The number of dice to roll.
* @returns {number[]} An array of dice results, sorted descending.
*/
export function rollDice(numDice) {
const results = [];
for (let i = 0; i < numDice; i++) {
results.push(Math.floor(Math.random() * 6) + 1);
}
return results.sort((a, b) => b - a); // Sort descending
}
/**
* Shuffles an array in place using the Fisher-Yates algorithm.
* @param {Array} array - The array to shuffle.
*/
export function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
/**
* Creates a simple 3D text label.
* Requires THREE.Sprite and THREE.SpriteMaterial, THREE.CanvasTexture
*/
export function createTextSprite(message, parameters = {}) {
const fontface = parameters.fontface || 'Arial';
const fontsize = parameters.fontsize || 18;
const borderThickness = parameters.borderThickness || 4;
const borderColor = parameters.borderColor || { r: 0, g: 0, b: 0, a: 1.0 };
const backgroundColor = parameters.backgroundColor || { r: 255, g: 255, b: 255, a: 1.0 };
const textColor = parameters.textColor || { r: 0, g: 0, b: 0, a: 1.0 };
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = `Bold ${fontsize}px ${fontface}`;
// Measure text width
const metrics = context.measureText(message);
const textWidth = metrics.width;
// Set canvas size based on text
canvas.width = textWidth + borderThickness * 2;
canvas.height = fontsize * 1.4 + borderThickness * 2; // Adjust height factor as needed
// Background
context.fillStyle = `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, ${backgroundColor.a})`;
// Border
context.strokeStyle = `rgba(${borderColor.r}, ${borderColor.g}, ${borderColor.b}, ${borderColor.a})`;
context.lineWidth = borderThickness;
// Draw rounded rect (optional, simple rect here)
context.fillStyle = `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, ${backgroundColor.a})`;
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeRect(borderThickness / 2, borderThickness / 2, canvas.width - borderThickness, canvas.height - borderThickness);
// Text
context.fillStyle = `rgba(${textColor.r}, ${textColor.g}, ${textColor.b}, ${textColor.a})`;
context.font = `Bold ${fontsize}px ${fontface}`; // Reset font after measurement
context.fillText(message, borderThickness, fontsize + borderThickness);
// Canvas contents to texture
const texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
const spriteMaterial = new THREE.SpriteMaterial({ map: texture });
const sprite = new THREE.Sprite(spriteMaterial);
// Scale sprite to appropriate size
sprite.scale.set(canvas.width * 0.1, canvas.height * 0.1, 1.0); // Adjust scale factor
return sprite;
}
5. js/main.js
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { TERRITORIES, TERRITORY_IDS, PLAYER_COLORS, PHASES, MIN_REINFORCEMENTS, STARTING_ARMIES_PER_PLAYER, TERRITORY_SIZE, TERRITORY_DEPTH, ARMY_INDICATOR_OFFSET_Y } from './gameConfig.js';
import { rollDice, shuffleArray, createTextSprite } from './utils.js';
// --- Global Variables ---
let scene, camera, renderer, controls;
let raycaster, mouse;
let gameMeshes = {}; // Map territory ID -> { mesh, label }
let territoryData = {}; // Stores runtime data: owner, armies
let players = [];
let currentPlayerIndex = 0;
let currentPhase = PHASES.REINFORCEMENT;
let armiesToPlace = 0;
// State for Attack Phase
let attackSourceTerritoryId = null;
let attackTargetTerritoryId = null;
// State for Fortify Phase
let fortifySourceTerritoryId = null;
let fortifyTargetTerritoryId = null;
let hasFortifiedThisTurn = false;
// --- Initialization ---
function init() {
setupScene();
setupLighting();
setupEventListeners();
createMapMeshes(); // Create 3D representations first
setupGame(2); // Start a game with 2 players
updateUI();
animate();
}
// --- Three.js Setup ---
function setupScene() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333);
const container = document.getElementById('game-container');
const width = container.clientWidth;
const height = container.clientHeight;
camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.position.set(0, 30, 25); // Adjust camera position
renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('c'), antialias: true });
renderer.setSize(width, height);
renderer.setPixelRatio(window.devicePixelRatio);
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Optional: smooth camera movement
controls.dampingFactor = 0.1;
controls.screenSpacePanning = false; // Keep panning intuitive
controls.maxPolarAngle = Math.PI / 2 - 0.1; // Prevent camera going below ground
controls.minDistance = 10;
controls.maxDistance = 100;
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
}
function setupLighting() {
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(5, 10, 7);
scene.add(directionalLight);
}
// --- Map Creation ---
function createMapMeshes() {
const shape = new THREE.Shape();
// Simple square shape for territories
const halfSize = TERRITORY_SIZE / 2;
shape.moveTo(-halfSize, -halfSize);
shape.lineTo(halfSize, -halfSize);
shape.lineTo(halfSize, halfSize);
shape.lineTo(-halfSize, halfSize);
shape.lineTo(-halfSize, -halfSize);
const extrudeSettings = {
steps: 1,
depth: TERRITORY_DEPTH,
bevelEnabled: false,
};
const geometry = new THREE.ExtrudeGeometry(shape, extrudeSettings);
geometry.center(); // Center the geometry for easier positioning
for (const id in TERRITORIES) {
const territoryInfo = TERRITORIES[id];
const material = new THREE.MeshStandardMaterial({ color: 0x888888 }); // Default neutral color
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(territoryInfo.x, TERRITORY_DEPTH / 2, territoryInfo.y); // Use Z for depth, Y for height
mesh.rotation.x = -Math.PI / 2; // Rotate to lay flat on XZ plane
mesh.userData = { id: id, type: 'territory' }; // Store ID for raycasting
scene.add(mesh);
// Create initial army count label (invisible initially)
const label = createTextSprite('0', { fontsize: 24, backgroundColor: { r: 50, g: 50, b: 50, a: 0.7 } });
label.position.set(territoryInfo.x, TERRITORY_DEPTH + ARMY_INDICATOR_OFFSET_Y, territoryInfo.y);
label.visible = false;
scene.add(label);
gameMeshes[id] = { mesh, label };
}
}
// --- Game Logic Setup ---
function setupGame(numPlayers) {
console.log(`Setting up game with ${numPlayers} players.`);
players = [];
for (let i = 0; i < numPlayers; i++) {
players.push({
id: i,
name: `Player ${i + 1}`,
color: PLAYER_COLORS[i % PLAYER_COLORS.length],
armies: STARTING_ARMIES_PER_PLAYER(numPlayers),
territories: new Set() // Store territory IDs owned by the player
});
}
// --- Initial Territory Distribution ---
const shuffledTerritoryIds = [...TERRITORY_IDS]; // Clone the array
shuffleArray(shuffledTerritoryIds);
let playerIdx = 0;
shuffledTerritoryIds.forEach(territoryId => {
const owner = players[playerIdx];
territoryData[territoryId] = {
owner: owner.id,
armies: 1 // Start with 1 army
};
owner.territories.add(territoryId);
owner.armies--; // Decrement from starting pool
updateTerritoryVisuals(territoryId);
playerIdx = (playerIdx + 1) % numPlayers;
});
// --- Distribute Remaining Armies (Basic Placement) ---
// In real Risk, players place these one by one. Here, we distribute somewhat evenly.
players.forEach(player => {
const territoriesOwned = Array.from(player.territories);
while (player.armies > 0) {
const targetTerritoryId = territoriesOwned[Math.floor(Math.random() * territoriesOwned.length)];
territoryData[targetTerritoryId].armies++;
player.armies--;
updateTerritoryVisuals(targetTerritoryId); // Update label
}
});
currentPlayerIndex = 0;
startTurn();
}
// --- Game Flow ---
function startTurn() {
const currentPlayer = players[currentPlayerIndex];
console.log(`--- ${currentPlayer.name}'s Turn ---`);
currentPhase = PHASES.REINFORCEMENT;
attackSourceTerritoryId = null;
attackTargetTerritoryId = null;
fortifySourceTerritoryId = null;
fortifyTargetTerritoryId = null;
hasFortifiedThisTurn = false;
calculateReinforcements();
updateUI();
setMessage(`${currentPlayer.name}, place your ${armiesToPlace} reinforcements.`);
}
function calculateReinforcements() {
const currentPlayer = players[currentPlayerIndex];
const territoryCount = currentPlayer.territories.size;
// Basic reinforcement: territories / 3 (min MIN_REINFORCEMENTS)
// TODO: Add continent bonuses here
armiesToPlace = Math.max(MIN_REINFORCEMENTS, Math.floor(territoryCount / 3));
}
function advancePhase() {
const currentPlayer = players[currentPlayerIndex];
switch (currentPhase) {
case PHASES.REINFORCEMENT:
if (armiesToPlace > 0) {
setMessage(`You must place all reinforcements (${armiesToPlace} left).`);
return;
}
currentPhase = PHASES.ATTACK;
setMessage(`${currentPlayer.name}, select a territory to attack from.`);
attackSourceTerritoryId = null;
attackTargetTerritoryId = null;
break;
case PHASES.ATTACK:
currentPhase = PHASES.FORTIFY;
setMessage(`${currentPlayer.name}, select a territory to fortify from (optional).`);
fortifySourceTerritoryId = null;
fortifyTargetTerritoryId = null;
break;
case PHASES.FORTIFY:
endTurn();
break;
}
updateUI();
}
function endTurn() {
console.log(`--- ${players[currentPlayerIndex].name}'s Turn Ends ---`);
// Check for win condition (simple: one player owns all)
if (players[currentPlayerIndex].territories.size === TERRITORY_IDS.length) {
gameOver(players[currentPlayerIndex]);
return;
}
currentPlayerIndex = (currentPlayerIndex + 1) % players.length;
startTurn();
}
function gameOver(winner) {
currentPhase = PHASES.GAME_OVER;
setMessage(`Game Over! ${winner.name} wins!`);
updateUI();
// Disable further interaction (optional)
window.removeEventListener('click', onMouseClick);
document.getElementById('endPhaseBtn').disabled = true;
document.getElementById('endTurnBtn').disabled = true;
}
// --- Player Actions ---
function handleTerritoryClick(territoryId) {
if (!territoryId || currentPhase === PHASES.GAME_OVER) return;
const currentPlayer = players[currentPlayerIndex];
const territory = territoryData[territoryId];
console.log(`Clicked ${TERRITORIES[territoryId].name} (Owner: Player ${territory.owner + 1}, Armies: ${territory.armies}) Phase: ${currentPhase}`);
switch (currentPhase) {
case PHASES.REINFORCEMENT:
handleReinforcementPlacement(territoryId, currentPlayer, territory);
break;
case PHASES.ATTACK:
handleAttackSelection(territoryId, currentPlayer, territory);
break;
case PHASES.FORTIFY:
handleFortifySelection(territoryId, currentPlayer, territory);
break;
}
updateUI(); // Refresh UI after action
}
function handleReinforcementPlacement(territoryId, currentPlayer, territory) {
if (territory.owner === currentPlayer.id) {
if (armiesToPlace > 0) {
territory.armies++;
armiesToPlace--;
updateTerritoryVisuals(territoryId);
setMessage(`${currentPlayer.name}, place remaining ${armiesToPlace} reinforcements.`);
if (armiesToPlace === 0) {
setMessage(`${currentPlayer.name}, all reinforcements placed. Click 'End Phase' to attack.`);
}
} else {
setMessage("No more reinforcements to place.");
}
} else {
setMessage("You can only reinforce your own territories.");
}
}
function handleAttackSelection(territoryId, currentPlayer, territory) {
// 1. Select Source Territory
if (!attackSourceTerritoryId) {
if (territory.owner === currentPlayer.id && territory.armies > 1) {
attackSourceTerritoryId = territoryId;
highlightTerritory(territoryId, 0xffff00); // Highlight source
setMessage(`Selected ${TERRITORIES[territoryId].name}. Now select an adjacent enemy territory to attack.`);
} else if (territory.owner === currentPlayer.id && territory.armies <= 1) {
setMessage("Cannot attack from a territory with only 1 army.");
} else {
setMessage("Select one of your territories with >1 army to attack from.");
}
}
// 2. Select Target Territory
else {
const sourceTerritory = territoryData[attackSourceTerritoryId];
const sourceInfo = TERRITORIES[attackSourceTerritoryId];
if (territoryId === attackSourceTerritoryId) {
// Deselect source
unhighlightTerritory(attackSourceTerritoryId);
attackSourceTerritoryId = null;
setMessage(`${currentPlayer.name}, select a territory to attack from.`);
} else if (territory.owner !== currentPlayer.id && sourceInfo.adjacent.includes(territoryId)) {
// Valid target selected
attackTargetTerritoryId = territoryId;
highlightTerritory(territoryId, 0xff8800); // Highlight target
setMessage(`Attacking ${TERRITORIES[territoryId].name} from ${sourceInfo.name}. Click 'Attack' button to roll dice.`);
// In a real game, you'd prompt for # of attacking armies here
} else if (territory.owner === currentPlayer.id) {
setMessage("Cannot target your own territory. Select an adjacent enemy territory or click your source again to deselect.");
} else {
setMessage(`${TERRITORIES[territoryId].name} is not adjacent to ${sourceInfo.name}. Select an adjacent enemy territory.`);
}
}
}
function executeAttack() {
if (!attackSourceTerritoryId || !attackTargetTerritoryId || currentPhase !== PHASES.ATTACK) {
setMessage("Select source and target territories first.");
return;
}
const attacker = players[currentPlayerIndex];
const sourceData = territoryData[attackSourceTerritoryId];
const targetData = territoryData[attackTargetTerritoryId];
const defender = players[targetData.owner];
// Determine number of dice (simplified)
const attackerDiceCount = Math.min(3, sourceData.armies - 1);
const defenderDiceCount = Math.min(2, targetData.armies);
if (attackerDiceCount <= 0) {
setMessage("Not enough armies to attack.");
resetAttackSelection();
return;
}
const attackerRolls = rollDice(attackerDiceCount);
const defenderRolls = rollDice(defenderDiceCount);
console.log(`Attack: ${attacker.name} (${attackerDiceCount} dice) vs ${defender.name} (${defenderDiceCount} dice)`);
console.log(`Attacker rolls: ${attackerRolls}`);
console.log(`Defender rolls: ${defenderRolls}`);
let attackerLosses = 0;
let defenderLosses = 0;
const comparisons = Math.min(attackerRolls.length, defenderRolls.length);
for (let i = 0; i < comparisons; i++) {
if (attackerRolls[i] > defenderRolls[i]) {
defenderLosses++;
} else {
attackerLosses++;
}
}
sourceData.armies -= attackerLosses;
targetData.armies -= defenderLosses;
const resultMsg = `Result: Attacker loses ${attackerLosses}, Defender loses ${defenderLosses}.`;
console.log(resultMsg);
displayDiceResult(attackerRolls, defenderRolls, resultMsg);
// Check for territory conquest
if (targetData.armies <= 0) {
setMessage(`Success! ${TERRITORIES[attackTargetTerritoryId].name} conquered!`);
console.log(`${attacker.name} conquered ${TERRITORIES[attackTargetTerritoryId].name}`);
// Change ownership
defender.territories.delete(attackTargetTerritoryId);
attacker.territories.add(attackTargetTerritoryId);
targetData.owner = attacker.id;
// Move attacking armies (prompt for number in real game)
// Must move at least attackerDiceCount armies. Here, move all possible leaving 1 behind.
const armiesToMove = attackerDiceCount; // Or prompt: Math.min(attackerDiceCount, sourceData.armies - 1);
targetData.armies = armiesToMove; // Territory starts with the moved armies
sourceData.armies -= armiesToMove;
// Check if defender is eliminated
if (defender.territories.size === 0) {
setMessage(`${defender.name} has been eliminated!`);
console.log(`${defender.name} eliminated!`);
// TODO: Handle card transfer if implemented
// TODO: Remove player from turn cycle? (complex state change)
}
// Update visuals for both territories
updateTerritoryVisuals(attackSourceTerritoryId);
updateTerritoryVisuals(attackTargetTerritoryId); // This also changes color
resetAttackSelection(); // Reset for next potential attack
// Check for win condition after conquest
if (attacker.territories.size === TERRITORY_IDS.length) {
gameOver(attacker);
return; // Stop further actions if game over
}
setMessage(`${attacker.name}, attack again or click 'End Phase'.`);
} else {
// Attack failed or territory not conquered yet
updateTerritoryVisuals(attackSourceTerritoryId);
updateTerritoryVisuals(attackTargetTerritoryId);
// Keep selection for potential re-attack if desired? For simplicity, we reset.
resetAttackSelection();
setMessage(`${resultMsg} Attack again or click 'End Phase'.`);
}
}
function resetAttackSelection() {
if (attackSourceTerritoryId) unhighlightTerritory(attackSourceTerritoryId);
if (attackTargetTerritoryId) unhighlightTerritory(attackTargetTerritoryId); // Unhighlight target too
attackSourceTerritoryId = null;
attackTargetTerritoryId = null;
document.getElementById('dice-result').style.display = 'none'; // Hide dice result
}
function handleFortifySelection(territoryId, currentPlayer, territory) {
if (hasFortifiedThisTurn) {
setMessage("You can only fortify once per turn.");
return;
}
// 1. Select Source
if (!fortifySourceTerritoryId) {
if (territory.owner === currentPlayer.id && territory.armies > 1) {
fortifySourceTerritoryId = territoryId;
highlightTerritory(territoryId, 0x00ffff); // Cyan highlight
setMessage(`Selected ${TERRITORIES[territoryId].name} to fortify from. Select an adjacent friendly territory to move troops to.`);
} else if (territory.owner === currentPlayer.id && territory.armies <= 1) {
setMessage("Cannot fortify from a territory with only 1 army.");
} else {
setMessage("Select one of your territories with >1 army.");
}
}
// 2. Select Target
else {
const sourceInfo = TERRITORIES[fortifySourceTerritoryId];
if (territoryId === fortifySourceTerritoryId) {
// Deselect source
unhighlightTerritory(fortifySourceTerritoryId);
fortifySourceTerritoryId = null;
setMessage(`${currentPlayer.name}, select a territory to fortify from (optional).`);
} else if (territory.owner === currentPlayer.id && isConnected(fortifySourceTerritoryId, territoryId, currentPlayer.id)) {
// Valid target selected (must be owned and connected)
fortifyTargetTerritoryId = territoryId;
highlightTerritory(territoryId, 0x00ffff); // Cyan highlight
// --- Prompt for number of armies ---
const maxArmiesToMove = territoryData[fortifySourceTerritoryId].armies - 1;
const numToMove = prompt(`Move how many armies to ${TERRITORIES[territoryId].name}? (1-${maxArmiesToMove})`, '1');
const armiesToMove = parseInt(numToMove, 10);
if (isNaN(armiesToMove) || armiesToMove < 1 || armiesToMove > maxArmiesToMove) {
setMessage(`Invalid number. Please enter a number between 1 and ${maxArmiesToMove}. Fortification cancelled.`);
resetFortifySelection();
} else {
// Execute Fortify
territoryData[fortifySourceTerritoryId].armies -= armiesToMove;
territoryData[fortifyTargetTerritoryId].armies += armiesToMove;
hasFortifiedThisTurn = true;
setMessage(`Moved ${armiesToMove} armies from ${sourceInfo.name} to ${TERRITORIES[territoryId].name}. Click 'End Turn'.`);
updateTerritoryVisuals(fortifySourceTerritoryId);
updateTerritoryVisuals(fortifyTargetTerritoryId);
resetFortifySelection(); // Clear highlights
document.getElementById('endPhaseBtn').disabled = true; // Disable phase advance after fortify
}
} else if (territory.owner !== currentPlayer.id) {
setMessage("Cannot fortify to an enemy territory.");
} else { // Own territory, but not connected
setMessage(`${TERRITORIES[territoryId].name} is not connected to ${sourceInfo.name} through your territories. Fortification cancelled.`);
resetFortifySelection();
}
}
}
function resetFortifySelection() {
if (fortifySourceTerritoryId) unhighlightTerritory(fortifySourceTerritoryId);
if (fortifyTargetTerritoryId) unhighlightTerritory(fortifyTargetTerritoryId);
fortifySourceTerritoryId = null;
fortifyTargetTerritoryId = null;
}
// Basic connectivity check (BFS or DFS) - needed for Fortify
function isConnected(startId, endId, playerId) {
const visited = new Set();
const queue = [startId];
visited.add(startId);
while (queue.length > 0) {
const currentId = queue.shift();
if (currentId === endId) {
return true; // Found a path
}
const neighbors = TERRITORIES[currentId].adjacent;
for (const neighborId of neighbors) {
// Check if neighbor exists in data (safety), is owned by player, and not visited
if (territoryData[neighborId] && territoryData[neighborId].owner === playerId && !visited.has(neighborId)) {
visited.add(neighborId);
queue.push(neighborId);
}
}
}
return false; // No path found
}
// --- Visual Updates ---
function updateTerritoryVisuals(territoryId) {
const data = territoryData[territoryId];
const visual = gameMeshes[territoryId];
if (!data || !visual) return;
const ownerColor = players[data.owner]?.color || 0x888888; // Fallback to gray
// Update color
visual.mesh.material.color.setHex(ownerColor);
// Update army count label
visual.label.material.map.dispose(); // Dispose old texture
const newLabel = createTextSprite(String(data.armies), {
fontsize: 24,
backgroundColor: { r: 50, g: 50, b: 50, a: 0.7 },
textColor: {r: 255, g: 255, b: 255, a: 1.0} // White text
});
visual.label.material = newLabel.material;
visual.label.scale.copy(newLabel.scale); // Adjust scale if text size changes
visual.label.visible = true; // Make sure label is visible
}
function highlightTerritory(territoryId, color) {
const visual = gameMeshes[territoryId];
if (visual && visual.mesh) {
// Store original color if not already highlighted
if (!visual.mesh.userData.originalColor) {
visual.mesh.userData.originalColor = visual.mesh.material.color.getHex();
}
visual.mesh.material.color.setHex(color);
visual.mesh.material.emissive.setHex(color); // Make it glow slightly
visual.mesh.material.emissiveIntensity = 0.4;
}
}
function unhighlightTerritory(territoryId) {
const visual = gameMeshes[territoryId];
if (visual && visual.mesh && visual.mesh.userData.originalColor !== undefined) {
visual.mesh.material.color.setHex(visual.mesh.userData.originalColor);
visual.mesh.material.emissive.setHex(0x000000); // Turn off glow
visual.mesh.material.emissiveIntensity = 0;
delete visual.mesh.userData.originalColor; // Remove stored color
} else if (visual && visual.mesh) {
// If no original color was stored (wasn't highlighted), ensure emissive is off
visual.mesh.material.emissive.setHex(0x000000);
visual.mesh.material.emissiveIntensity = 0;
// Re-apply owner color just in case
const ownerColor = players[territoryData[territoryId]?.owner]?.color || 0x888888;
visual.mesh.material.color.setHex(ownerColor);
}
}
// --- UI Updates ---
function updateUI() {
const currentPlayer = players[currentPlayerIndex];
const infoPlayer = document.getElementById('currentPlayer');
const infoPhase = document.getElementById('currentPhase');
const infoArmies = document.getElementById('armiesToPlace');
const endPhaseButton = document.getElementById('endPhaseBtn');
const endTurnButton = document.getElementById('endTurnBtn');
if (currentPhase !== PHASES.GAME_OVER && currentPlayer) {
infoPlayer.textContent = `${currentPlayer.name} (${currentPlayer.territories.size} territories)`;
infoPlayer.style.color = `#${currentPlayer.color.toString(16).padStart(6, '0')}`;
} else if (currentPhase === PHASES.GAME_OVER) {
infoPlayer.textContent = "Game Over";
infoPlayer.style.color = 'white';
} else {
infoPlayer.textContent = "Loading...";
infoPlayer.style.color = 'white';
}
infoPhase.textContent = currentPhase;
infoArmies.textContent = armiesToPlace;
infoArmies.parentElement.style.display = (currentPhase === PHASES.REINFORCEMENT) ? 'block' : 'none';
// --- Button Logic ---
endPhaseButton.disabled = false; // Default enable
endTurnButton.disabled = true; // Default disable (only enabled after fortify or skipping fortify)
endPhaseButton.textContent = "End Phase / Attack"; // Default text
if (currentPhase === PHASES.REINFORCEMENT) {
endPhaseButton.textContent = "End Reinforcement";
if (armiesToPlace > 0) endPhaseButton.disabled = true; // Cannot end if armies remain
} else if (currentPhase === PHASES.ATTACK) {
endPhaseButton.textContent = "Attack / End Attack Phase";
// Enable attack button ONLY if source and target are selected
endPhaseButton.disabled = (!attackSourceTerritoryId || !attackTargetTerritoryId);
// If attack is not possible (no selection), the button serves to END the attack phase
if (!attackSourceTerritoryId && !attackTargetTerritoryId) {
endPhaseButton.disabled = false; // Allow ending the phase even without selection
endPhaseButton.textContent = "End Attack Phase";
} else {
endPhaseButton.textContent = "Attack!";
}
} else if (currentPhase === PHASES.FORTIFY) {
endPhaseButton.textContent = "Skip Fortify"; // Button now skips fortify
endPhaseButton.disabled = hasFortifiedThisTurn; // Disable skip if already fortified
endTurnButton.disabled = false; // Enable End Turn during fortify phase
} else if (currentPhase === PHASES.GAME_OVER) {
endPhaseButton.disabled = true;
endTurnButton.disabled = true;
}
}
function setMessage(msg) {
document.getElementById('message').textContent = msg;
}
function displayDiceResult(attackerRolls, defenderRolls, resultMsg) {
document.getElementById('attackerDice').textContent = attackerRolls.join(', ');
document.getElementById('defenderDice').textContent = defenderRolls.join(', ');
document.getElementById('combatResult').textContent = resultMsg;
document.getElementById('dice-result').style.display = 'block';
}
// --- Event Listeners ---
function setupEventListeners() {
window.addEventListener('resize', onWindowResize);
window.addEventListener('click', onMouseClick); // Use click instead of mousedown
document.getElementById('endPhaseBtn').addEventListener('click', () => {
if (currentPhase === PHASES.ATTACK) {
if (attackSourceTerritoryId && attackTargetTerritoryId) {
executeAttack(); // If selection is made, button means "Attack!"
} else {
advancePhase(); // Otherwise, it means "End Attack Phase"
}
} else if (currentPhase === PHASES.FORTIFY) {
// If clicked during Fortify, it means "Skip Fortify"
endTurn();
}
else {
advancePhase(); // Handles Reinforcement -> Attack
}
});
document.getElementById('endTurnBtn').addEventListener('click', () => {
if (currentPhase === PHASES.FORTIFY) {
endTurn();
}
});
}
function onWindowResize() {
const container = document.getElementById('game-container');
const width = container.clientWidth;
const height = container.clientHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
}
function onMouseClick(event) {
// Calculate mouse position in normalized device coordinates (-1 to +1)
const canvasBounds = renderer.domElement.getBoundingClientRect();
mouse.x = ((event.clientX - canvasBounds.left) / canvasBounds.width) * 2 - 1;
mouse.y = -((event.clientY - canvasBounds.top) / canvasBounds.height) * 2 + 1;
// Update the picking ray with the camera and mouse position
raycaster.setFromCamera(mouse, camera);
// Calculate objects intersecting the picking ray
const intersects = raycaster.intersectObjects(scene.children);
for (let i = 0; i < intersects.length; i++) {
if (intersects[i].object.userData.type === 'territory') {
handleTerritoryClick(intersects[i].object.userData.id);
return; // Process only the first territory hit
}
}
// If clicked on empty space, potentially deselect
if (currentPhase === PHASES.ATTACK && attackSourceTerritoryId && !attackTargetTerritoryId) {
resetAttackSelection();
setMessage(`${players[currentPlayerIndex].name}, select a territory to attack from.`);
updateUI();
} else if (currentPhase === PHASES.FORTIFY && fortifySourceTerritoryId && !fortifyTargetTerritoryId) {
resetFortifySelection();
setMessage(`${players[currentPlayerIndex].name}, select a territory to fortify from (optional).`);
updateUI();
}
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
controls.update(); // Only required if controls.enableDamping or .autoRotate are set
renderer.render(scene, camera);
}
// --- Start the game ---
init();
How to Run:
- Save: Save the files with the specified names and structure.
- Get Three.js:
- CDN (Easiest): The
index.html provided uses a CDN link via importmap. This should work directly.
- Local: Download Three.js (
npm install three if using Node/npm) and adjust the import paths in index.html and main.js to point to your local three.module.js and the addons folder.
- Web Server: You cannot simply open
index.html directly from your filesystem due to JavaScript module security restrictions (CORS). You need to serve the files using a simple local web server.
- If you have Node.js/npm:
npx serve . in the risk-clone directory.
- If you have Python 3:
python -m http.server in the risk-clone directory.
- Use extensions like "Live Server" in VS Code.
- Access: Open your browser and navigate to the local server address (e.g.,
http://localhost:8080 or http://localhost:8000 or whatever your server uses).
Next Steps & Improvements:
- Real Map: Replace the abstract
TERRITORIES data and the simple square shapes with data and geometries derived from a real Risk map (e.g., loading an SVG, parsing paths, extruding them). This is a significant step.
- Continent Bonuses: Implement logic in
calculateReinforcements to check continent ownership and add bonus armies.
- Risk Cards: Add card deck, dealing cards on conquest, card sets, and turn-in logic during Reinforcement.
- Attack Army Selection: Prompt the user for how many armies (1-3, less than total armies - 1) to use for attack.
- Fortify Army Selection: Improve the prompt for moving armies during Fortify.
- Refined UI: Use a proper UI library or more detailed HTML/CSS for displaying player stats, cards, better prompts, etc.
- Visual Polish: Better territory models, textures, army indicators (maybe simple cylinders or icons instead of just text), attack/move animations.
- AI: Implement AI logic for computer opponents (decision making for placement, attack, fortify). This is very complex.
- Multiplayer: Add networking (WebSockets probably) for multiple human players.
- Sound Effects.
- Robust Error Handling & Edge Cases.
This foundation gives you the core loop, 3D interaction, and basic mechanics to build upon. Good luck!