<!DOCTYPE html>
<html>
<head>
    <title>2D Top-Down Game with Age System and Reproduction</title>
    <style>
        body { margin: 0; overflow: hidden; }
        canvas { display: block; background: #000; cursor: grab; }
    </style>
</head>
<body>
    <canvas id="gameCanvas"></canvas>
    <script>
        // Setup canvas
        const canvas = document.getElementById("gameCanvas");
        const ctx = canvas.getContext("2d");
        let canvasWidth = window.innerWidth;
        let canvasHeight = window.innerHeight;
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;

        // Tile and world dimensions
        const tileSize = 16; // Adjusted tile size
        const worldWidth = 200; // Increased world size
        const worldHeight = 200;

        // Camera (viewport) position
        let cameraX = 0;
        let cameraY = 0;

        // Variables for panning the camera
        let isPanning = false;
        let startMouseX, startMouseY;
        let startCameraX, startCameraY;

        // World array
        const world = [];
        for(let y = 0; y < worldHeight; y++) {
            world[y] = [];
            for(let x = 0; x < worldWidth; x++) {
                world[y][x] = {};
            }
        }

        // Generate terrain resembling Earth's landscape
        const centerX = worldWidth / 2;
        const centerY = worldHeight / 2;
        const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY);

        for(let y = 0; y < worldHeight; y++) {
            for(let x = 0; x < worldWidth; x++) {
                const dx = x - centerX;
                const dy = y - centerY;
                const distance = Math.sqrt(dx * dx + dy * dy);
                let height = 1 - (distance / maxDistance); // Height decreases from center
                height += (Math.random() - 0.5) * 0.5; // Add noise
                world[y][x].height = height;
                world[y][x].type = 'water'; // Initialize as water
                world[y][x].country = null; // Track ownership for borders
                world[y][x].captureProgress = {}; // Track capture progress for each country
            }
        }

        // Assign land tiles based on height
        for(let y = 0; y < worldHeight; y++) {
            for(let x = 0; x < worldWidth; x++) {
                const tile = world[y][x];
                if(tile.height > 0.3) {
                    tile.type = 'land';
                }
            }
        }

        // Generate woods, food, and iron on land tiles
        for(let y = 0; y < worldHeight; y++) {
            for(let x = 0; x < worldWidth; x++) {
                const tile = world[y][x];
                if(tile.type === 'land') {
                    const rnd = Math.random();
                    if(rnd < 0.15) { // 15% chance to be woods
                        tile.type = 'woods';
                    } else if(rnd < 0.25) { // 10% chance to be food
                        tile.type = 'food';
                    } else if(rnd < 0.28) { // Additional 3% chance to be iron
                        tile.type = 'iron';
                    }
                }
            }
        }

        // Generate rivers
        function generateRivers(numRivers) {
            for(let i = 0; i < numRivers; i++) {
                // Start river at random x position at the top
                let x = Math.floor(Math.random() * worldWidth);
                let y = 0;
                while(y < worldHeight && x >= 0 && x < worldWidth) {
                    if(world[y][x].type !== 'water') {
                        world[y][x].type = 'river';
                    }
                    // Randomly move left, right, or straight down
                    const direction = Math.floor(Math.random() * 3) - 1; // -1, 0, or 1
                    x += direction;
                    y += 1;
                }
            }
        }

        generateRivers(5); // Generate 5 rivers

        // Function to draw the world
        function drawWorld() {
            const startX = Math.floor(cameraX / tileSize);
            const startY = Math.floor(cameraY / tileSize);
            const endX = startX + Math.ceil(canvasWidth / tileSize) + 1;
            const endY = startY + Math.ceil(canvasHeight / tileSize) + 1;

            for(let y = startY; y < endY; y++) {
                for(let x = startX; x < endX; x++) {
                    if(x >= 0 && x < worldWidth && y >= 0 && y < worldHeight) {
                        const tile = world[y][x];
                        switch(tile.type) {
                            case 'land':
                                ctx.fillStyle = '#228B22'; // Forest green
                                break;
                            case 'woods':
                                ctx.fillStyle = '#006400'; // Dark green for woods
                                break;
                            case 'food':
                                ctx.fillStyle = '#FFD700'; // Gold for food sources
                                break;
                            case 'iron':
                                ctx.fillStyle = '#A9A9A9'; // Dark gray for iron
                                break;
                            case 'river':
                                ctx.fillStyle = '#1E90FF'; // Blue for rivers
                                break;
                            case 'water':
                                ctx.fillStyle = '#87CEEB'; // Light blue for water
                                break;
                            case 'house':
                                ctx.fillStyle = '#8B4513'; // Brown for houses
                                break;
                            default:
                                ctx.fillStyle = '#000';
                                break;
                        }
                        ctx.fillRect((x * tileSize) - cameraX, (y * tileSize) - cameraY, tileSize, tileSize);

                        // Optionally, draw tiles claimed by a country in lighter shade
                        if(tile.country && tile.type !== 'water' && tile.type !== 'river') {
                            ctx.fillStyle = tile.country.color + '55'; // Semi-transparent
                            ctx.fillRect((x * tileSize) - cameraX, (y * tileSize) - cameraY, tileSize, tileSize);
                        }
                    }
                }
            }

            // Draw country borders
            countries.forEach(country => {
                ctx.strokeStyle = country.borderColor;
                country.borders.forEach(tile => {
                    ctx.strokeRect((tile.x * tileSize) - cameraX, (tile.y * tileSize) - cameraY, tileSize, tileSize);
                });
            });
        }

        // Character array
        const characters = [];
        // Death effects array
        const deathEffects = [];

        // Country array
        const countries = [];

        // Names for countries and kings
        const countryNames = ["Avalon", "Eldoria", "Valoria", "Draconia", "Zephyria", "Arcadia", "Elysium", "Calradia", "Mythland", "Serentia"];
        let usedCountryNames = [];

        const kingNames = ["Arthur", "Leon", "Maximilian", "Victor", "Robert", "Richard", "William", "Henry", "Edward", "Alexander"];

        // Game time variables
        let inGameYear = 0; // Start from year 0
        let lastYearUpdate = Date.now();
        const yearDuration = 7000; // 7 seconds in milliseconds

        // Character class
        class Character {
            constructor(x, y, age = null) {
                this.x = x;
                this.y = y;
                this.woodCollected = 0;
                this.ironCollected = 0;
                this.moveDelay = Math.floor(Math.random() * 10) + 5; // Random delay between moves
                this.moveCounter = 0;
                this.country = null; // Reference to the country they belong to
                this.hungerCounter = Math.floor(Math.random() * 200) + 100; // Time until next meal
                // Age
                if (age === null) {
                    this.age = Math.floor(Math.random() * 30) + 15; // Random age between 15 and 45
                } else {
                    this.age = age;
                }
                // Gender
                this.gender = Math.random() < 0.5 ? 'male' : 'female';
            }
            move() {
                this.moveCounter++;
                if(this.moveCounter >= this.moveDelay) {
                    this.moveCounter = 0;

                    // Check hunger
                    this.hungerCounter--;
                    if(this.hungerCounter <= 0) {
                        this.eat();
                        this.hungerCounter = Math.floor(Math.random() * 200) + 100; // Reset hunger counter
                    }

                    // Age-related death
                    if(this.age >= 60) {
                        const deathChance = (this.age - 59) / 10; // At age 60, 1% chance, at 70, 100% chance
                        if(Math.random() < deathChance) {
                            this.die('old age');
                            return;
                        }
                    }

                    // Build house if enough wood collected
                    if(this.woodCollected >= 5) {
                        this.buildHouse();
                        this.woodCollected = 0;
                    }

                    // Random direction: up, down, left, right
                    const directions = [
                        {dx: -1, dy: 0}, // left
                        {dx: 1, dy: 0},  // right
                        {dx: 0, dy: -1}, // up
                        {dx: 0, dy: 1},  // down
                    ];
                    const dir = directions[Math.floor(Math.random() * directions.length)];
                    const newX = this.x + dir.dx;
                    const newY = this.y + dir.dy;
                    // Check bounds
                    if(newX >= 0 && newX < worldWidth && newY >= 0 && newY < worldHeight) {
                        const tile = world[newY][newX];

                        // Check if tile is passable (not water or river)
                        if(tile.type === 'land' || tile.type === 'woods' || tile.type === 'food' || tile.type === 'iron' || tile.type === 'house') {
                            // Check for country borders
                            if(this.canEnterTile(tile)) {
                                this.x = newX;
                                this.y = newY;

                                // Collect wood if on woods tile
                                if(tile.type === 'woods') {
                                    this.woodCollected++;
                                    tile.type = 'land'; // Remove woods after chopping
                                    // If part of a country, add wood to country's resources
                                    if(this.country) {
                                        this.country.wood++;
                                    }
                                }

                                // Collect iron if on iron tile
                                if(tile.type === 'iron') {
                                    this.ironCollected++;
                                    tile.type = 'land'; // Remove iron after mining
                                    // If part of a country, add iron to country's resources
                                    if(this.country) {
                                        this.country.iron++;
                                    }
                                }

                                // If part of a country, claim tile
                                if(this.country) {
                                    tile.country = this.country;
                                    this.country.updateBorders();
                                }
                            }
                        }
                    }

                    // Check for proximity to form a country
                    if(!this.country) {
                        checkForCountryFormation(this);
                    }

                    // Check for reproduction
                    this.checkForReproduction();
                }
            }
            eat() {
                if(this.country) {
                    if(this.country.food > 0) {
                        this.country.food--;
                    } else {
                        // No food available, character dies
                        this.die('starvation');
                    }
                } else {
                    // Character without country dies of starvation
                    this.die('starvation');
                }
            }
            die(reason) {
                // Add death effect
                deathEffects.push(new DeathEffect(this.x, this.y, reason));

                // Remove character from the game
                const index = characters.indexOf(this);
                if(index !== -1) {
                    characters.splice(index, 1);
                }
                // Remove from country members if applicable
                if(this.country) {
                    const idx = this.country.members.indexOf(this);
                    if(idx !== -1) {
                        this.country.members.splice(idx, 1);
                    }
                    // Check if country has no members left
                    if(this.country.members.length === 0) {
                        this.country.destroy();
                    }
                }
            }
            buildHouse() {
                const tile = world[this.y][this.x];
                // Can only build on land or woods within own country or unclaimed territory
                if((tile.type === 'land' || tile.type === 'woods') && this.canEnterTile(tile)) {
                    tile.type = 'house';
                    // If part of a country, claim the tile
                    if(this.country) {
                        tile.country = this.country;
                        this.country.updateBorders();
                    }
                }
            }
            canEnterTile(tile) {
                // If the tile is not claimed by any country, it's free to enter
                if(!tile.country) return true;
                // If the tile belongs to the character's own country, they can enter
                if(tile.country === this.country) return true;
                // If the tile is claimed by an enemy country and there's war, can enter
                if(this.country && tile.country && this.country.isAtWarWith(tile.country)) return true;
                // Otherwise, they cannot enter
                return false;
            }
            checkForReproduction() {
                // Only characters of reproductive age can reproduce
                if(this.age < 18 || this.age > 50) return;
                // Find nearby characters of opposite gender in same country
                const reproductionRadius = 1; // Adjacent tiles
                for(let dx = -reproductionRadius; dx <= reproductionRadius; dx++) {
                    for(let dy = -reproductionRadius; dy <= reproductionRadius; dy++) {
                        if(dx === 0 && dy === 0) continue; // Skip self
                        const nx = this.x + dx;
                        const ny = this.y + dy;
                        // Check bounds
                        if(nx >= 0 && nx < worldWidth && ny >=0 && ny < worldHeight) {
                            // Check for character at this position
                            const otherChar = characters.find(other => other.x === nx && other.y === ny && other !== this);
                            if(otherChar && otherChar.gender !== this.gender && otherChar.age >= 18 && otherChar.age <= 50) {
                                // Check if they are in the same country
                                if(this.country && otherChar.country === this.country) {
                                    // Chance to reproduce
                                    const reproductionChance = 0.12; // 5% chance
                                    if(Math.random() < reproductionChance) {
                                        // Create a new character (child)
                                        const child = new Character(this.x, this.y, 0); // Age zero
                                        child.country = this.country;
                                        // Assign country to child and add to country's members
                                        child.country.members.push(child);
                                        characters.push(child);
                                        // Optionally, can log the birth
                                        console.log(`A child is born in ${this.country.name}`);
                                        return; // Only one reproduction per time
                                    }
                                }
                            }
                        }
                    }
                }
            }
            draw() {
                // Calculate position on canvas
                const drawX = (this.x * tileSize) - cameraX;
                const drawY = (this.y * tileSize) - cameraY;

                // Only draw if within the visible area
                if(drawX >= -tileSize && drawX <= canvasWidth && drawY >= -tileSize && drawY <= canvasHeight) {
                    // Draw character sprite
                    ctx.fillStyle = this.country ? this.country.color : '#FFD700'; // Color based on country
                    ctx.fillRect(drawX + 4, drawY + 2, 8, 12); // Body
                    ctx.fillStyle = '#FFFFFF'; // White for face
                    ctx.fillRect(drawX + 5, drawY + 4, 6, 6); // Face
                    ctx.fillStyle = '#000000'; // Black for eyes
                    ctx.fillRect(drawX + 6, drawY + 5, 1, 1); // Left eye
                    ctx.fillRect(drawX + 9, drawY + 5, 1, 1); // Right eye
                    ctx.fillRect(drawX + 7, drawY + 7, 2, 1); // Mouth
                }
            }
        }

        // Army class
        class Army {
            constructor(x, y, country) {
                this.x = x;
                this.y = y;
                this.country = country;
                this.moveDelay = 5;
                this.moveCounter = 0;
                this.target = null; // Target tile or enemy army
                this.isMoving = false;
                this.strength = 100; // Army strength (number of soldiers)
                this.captureDelay = 5; // Time required to capture a tile
                this.captureProgress = 0;
                this.isCapturing = false;
            }
            update() {
                this.moveCounter++;
                if (this.moveCounter >= this.moveDelay) {
                    this.moveCounter = 0;

                    if (this.country.atWar.length > 0) {
                        if (!this.isMoving && !this.isCapturing) {
                            this.findTarget();
                        }
                        if (this.isMoving && this.target) {
                            this.moveTowardsTarget();
                        }
                        if (this.isCapturing) {
                            this.captureTile();
                        }
                    } else {
                        // Patrol or guard borders
                        this.patrol();
                    }
                }
            }
            findTarget() {
                // Find nearest enemy army or border tile
                let nearestTarget = null;
                let minDistance = Infinity;

                // Look for enemy armies first
                this.country.atWar.forEach(enemyCountry => {
                    enemyCountry.army.forEach(enemyArmy => {
                        const dx = enemyArmy.x - this.x;
                        const dy = enemyArmy.y - this.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);
                        if (distance < minDistance) {
                            minDistance = distance;
                            nearestTarget = { x: enemyArmy.x, y: enemyArmy.y, type: 'army', army: enemyArmy };
                        }
                    });
                });

                // If no enemy armies nearby, look for enemy border tiles
                if (!nearestTarget) {
                    this.country.atWar.forEach(enemyCountry => {
                        enemyCountry.borders.forEach(tile => {
                            const dx = tile.x - this.x;
                            const dy = tile.y - this.y;
                            const distance = Math.sqrt(dx * dx + dy * dy);
                            if(distance < minDistance) {
                                minDistance = distance;
                                nearestTarget = { x: tile.x, y: tile.y, type: 'tile' };
                            }
                        });
                    });
                }

                if(nearestTarget) {
                    this.target = nearestTarget;
                    this.isMoving = true;
                }
            }
            moveTowardsTarget() {
                if (this.target) {
                    let dx = this.target.x - this.x;
                    let dy = this.target.y - this.y;

                    if (dx === 0 && dy === 0) {
                        // Arrived at target
                        if (this.target.type === 'army') {
                            this.battle(this.target.army);
                        } else if (this.target.type === 'tile') {
                            this.isMoving = false;
                            this.isCapturing = true;
                            this.captureProgress = 0;
                        }
                        return;
                    }

                    // Normalize direction
                    dx = dx > 0 ? 1 : dx < 0 ? -1 : 0;
                    dy = dy > 0 ? 1 : dy < 0 ? -1 : 0;

                    const newX = this.x + dx;
                    const newY = this.y + dy;

                    if (newX >= 0 && newX < worldWidth && newY >= 0 && newY < worldHeight) {
                        const tile = world[newY][newX];
                        if (this.canEnterTile(tile)) {
                            // Move army
                            this.x = newX;
                            this.y = newY;

                            // Check for enemy army
                            const enemyArmy = findArmyAtPosition(newX, newY, army => army.country !== this.country);
                            if (enemyArmy) {
                                this.battle(enemyArmy);
                                this.target = null;
                                this.isMoving = false;
                            }
                        } else {
                            // Cannot move into tile, find a new path or target
                            this.isMoving = false;
                            this.target = null;
                        }
                    }
                }
            }
            patrol() {
                // Move randomly near borders
                if (!this.isMoving) {
                    const directions = [
                        {dx: -1, dy: 0}, // left
                        {dx: 1, dy: 0},  // right
                        {dx: 0, dy: -1}, // up
                        {dx: 0, dy: 1},  // down
                    ];
                    const dir = directions[Math.floor(Math.random() * directions.length)];
                    const newX = this.x + dir.dx;
                    const newY = this.y + dir.dy;
                    if (newX >= 0 && newX < worldWidth && newY >= 0 && newY < worldHeight) {
                        const tile = world[newY][newX];
                        if (this.canEnterTile(tile)) {
                            this.x = newX;
                            this.y = newY;
                        }
                    }
                }
            }
            battle(enemyArmy) {
                // Both armies lose strength proportional to the enemy's strength
                const damageToEnemy = Math.floor(Math.random() * this.strength * 0.5);
                const damageToSelf = Math.floor(Math.random() * enemyArmy.strength * 0.5);

                enemyArmy.strength -= damageToEnemy;
                this.strength -= damageToSelf;

                // Check if any army is destroyed
                if (enemyArmy.strength <= 0) {
                    enemyArmy.die();
                    // If enemy army is destroyed, remove target
                    this.target = null;
                    this.isMoving = false;
                }
                if (this.strength <= 0) {
                    this.die();
                }
            }
            captureTile() {
                const tile = world[this.y][this.x];
                if (tile.country && tile.country !== this.country) {
                    // Increase capture progress
                    this.captureProgress++;
                    // Optionally, display capture progress visually
                    if(this.captureProgress >= this.captureDelay) {
                        // Capture complete
                        tile.country = this.country;
                        this.country.updateBorders();
                        this.isCapturing = false;
                        this.captureProgress = 0;
                    }
                } else {
                    // Tile is already ours or unclaimed
                    this.isCapturing = false;
                    this.captureProgress = 0;
                }
            }
            canEnterTile(tile) {
                // Armies can enter any tile except water
                if (tile.type === 'water' || tile.type === 'river') return false;
                return true;
            }
            die() {
                // Remove army from the country's army list
                const index = this.country.army.indexOf(this);
                if (index !== -1) {
                    this.country.army.splice(index, 1);
                }
            }
            draw() {
                // Calculate position on canvas
                const drawX = (this.x * tileSize) - cameraX;
                const drawY = (this.y * tileSize) - cameraY;

                // Only draw if within the visible area
                if(drawX >= -tileSize && drawX <= canvasWidth && drawY >= -tileSize && drawY <= canvasHeight) {
                    // Draw army sprite (simple sword icon)
                    ctx.fillStyle = this.country.color;
                    ctx.font = '14px Arial';
                    ctx.fillText('⚔️', drawX + 2, drawY + 14);

                    // Optional: draw strength
                    ctx.fillStyle = '#FFFFFF';
                    ctx.font = '10px Arial';
                    ctx.fillText(this.strength, drawX, drawY + 8);

                    // If capturing, draw progress bar
                    if(this.isCapturing) {
                        ctx.fillStyle = '#FFFFFF';
                        ctx.fillRect(drawX, drawY - 5, tileSize, 3);
                        ctx.fillStyle = '#FF0000';
                        const progressWidth = (this.captureProgress / this.captureDelay) * tileSize;
                        ctx.fillRect(drawX, drawY - 5, progressWidth, 3);
                    }
                }
            }
        }

        function findArmyAtPosition(x, y, filterFn) {
            for (let c of countries) {
                for (let army of c.army) {
                    if (army.x === x && army.y === y) {
                        if (!filterFn || filterFn(army)) {
                            return army;
                        }
                    }
                }
            }
            return null;
        }

        // Death effect class
        class DeathEffect {
            constructor(x, y, reason) {
                this.x = x;
                this.y = y;
                this.duration = 50; // Duration of the effect
                this.reason = reason;
            }
            update() {
                this.duration--;
            }
            draw() {
                // Calculate position on canvas
                const drawX = (this.x * tileSize) - cameraX;
                const drawY = (this.y * tileSize) - cameraY;

                // Only draw if within the visible area
                if(drawX >= -tileSize && drawX <= canvasWidth && drawY >= -tileSize && drawY <= canvasHeight) {
                    // Draw skull icon
                    ctx.fillStyle = `rgba(255, 255, 255, ${this.duration / 50})`; // Fade out effect
                    ctx.font = '14px Arial';
                    if (this.reason === 'old age') {
                        ctx.fillText('☠️', drawX + 2, drawY + 14);
                    } else {
                        ctx.fillText('💀', drawX + 2, drawY + 14);
                    }
                }
            }
        }

        // Country class
        class Country {
            constructor(name, king, members) {
                this.name = name;
                this.king = king;
                this.kingTrait = getRandomKingTrait();
                this.members = members; // Array of characters in the country
                this.wood = 0; // Wood resources
                this.food = 0; // Food resources
                this.iron = 0; // Iron resources

                // Assign a color to the country for visualization
                this.color = this.getUniqueCountryColor();

                // Assign a border color for visualization
                this.borderColor = getRandomBorderColor();

                // Borders are tiles claimed by the country
                this.borders = []; // Array of tiles that form the country's territory
                this.updateBorders();

                this.army = []; // Army units
                this.updateArmy();

                this.atWar = []; // Array of countries this country is at war with
                this.warCooldown = 0; // Cooldown before declaring next war

                // Set war likelihood based on king trait
                this.warLikelihood = this.kingTrait === 'aggressive' ? 0.005 : 0.001; // Adjusted probabilities
            }
            getUniqueCountryColor() {
                let color;
                do {
                    color = getRandomColor();
                } while (countries.some(c => c.color === color)); // Check if any existing country has this color
                return color;
            }

            drawName() {
                // Find the center of the country's territory
                let centerX = 0, centerY = 0;
                this.borders.forEach(tile => {
                    centerX += tile.x;
                    centerY += tile.y;
                });
                centerX /= this.borders.length;
                centerY /= this.borders.length;

                // Adjust font size based on country size (number of tiles)
                const fontSize = Math.max(15, Math.min(50, Math.floor(Math.sqrt(this.borders.length)))); // Adjust min/max as needed

                // Calculate position on canvas
                const drawX = (centerX * tileSize) - cameraX;
                const drawY = (centerY * tileSize) - cameraY;

                // Draw country name
                ctx.fillStyle = this.getContrastingColor(this.color); // Ensure name is visible against background
                ctx.font = `${fontSize}px Arial`;
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                ctx.fillText(this.name, drawX, drawY);
            }

            // Helper function to get a contrasting color for text visibility
            getContrastingColor(hexColor) {
                const rgb = this.hexToRgb(hexColor);
                const luminance = (0.299 * rgb.r + 0.587 * rgb.g + 0.114 * rgb.b) / 255;
                return luminance > 0.5 ? '#000000' : '#FFFFFF'; // Black or white based on luminance
            }

            // Helper function to convert hex color to RGB
            hexToRgb(hex) {
                const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
                return result ? {
                    r: parseInt(result[1], 16),
                    g: parseInt(result[2], 16),
                    b: parseInt(result[3], 16)
                } : null;
            }

            update() {
                this.warCooldown--;
                if (this.warCooldown <= 0 && Math.random() < this.warLikelihood) {
                    // Try to declare war
                    this.declareWar();
                    this.warCooldown = 1000; // Cooldown before next possible declaration
                }

                // Update armies
                this.army.forEach(armyUnit => armyUnit.update());

                // Update army size
                this.updateArmy();

                // Defending armies respond to invasions
                this.respondToInvasions();
            }

            updateBorders() {
                // Clear previous borders
                this.borders = [];
                // Reset food resources
                this.food = 0;
                // Iterate over the world tiles to find those claimed by this country
                for(let y = 0; y < worldHeight; y++) {
                    for(let x = 0; x < worldWidth; x++) {
                        const tile = world[y][x];
                        if(tile.country === this) {
                            this.borders.push({x, y});
                            // Collect food if tile has food
                            if(tile.type === 'food') {
                                this.food++; // Each food tile counts as one food unit
                            }
                        }
                    }
                }
            }

            updateArmy() {
                // Calculate desired army size (2% of population)
                const desiredArmySize = Math.max(1, Math.floor(this.members.length * 0.02));

                // Create or disband army units to match desired size
                while(this.army.length < desiredArmySize && this.iron >= 10) { // Assume each army unit costs 10 iron
                    // Create new army unit at random member's location
                    const member = this.members[Math.floor(Math.random() * this.members.length)];
                    const newArmy = new Army(member.x, member.y, this);
                    this.army.push(newArmy);
                    this.iron -= 10; // Consume iron to create army unit
                }
                while(this.army.length > desiredArmySize) {
                    // Disband army unit
                    this.army.pop();
                }
            }

            declareWar() {
                // Find neighboring countries
                const neighboringCountries = new Set();
                this.borders.forEach(tile => {
                    const neighbors = getNeighborTiles(tile.x, tile.y);
                    neighbors.forEach(nTile => {
                        if(nTile.country && nTile.country !== this) {
                            neighboringCountries.add(nTile.country);
                        }
                    });
                });

                if (neighboringCountries.size > 0) {
                    // Choose a random neighboring country to declare war on
                    const enemies = Array.from(neighboringCountries);
                    const targetCountry = enemies[Math.floor(Math.random() * enemies.length)];

                    // Declare war
                    if (!this.atWar.includes(targetCountry)) {
                        this.atWar.push(targetCountry);
                        console.log(`${this.name} declared war on ${targetCountry.name}`);
                        // Enemy also adds this country to their atWar list
                        if (!targetCountry.atWar.includes(this)) {
                            targetCountry.atWar.push(this);
                        }
                    }
                }
            }
            isAtWarWith(country) {
                return this.atWar.includes(country);
            }
            endWarWith(country) {
                const index = this.atWar.indexOf(country);
                if (index !== -1) {
                    this.atWar.splice(index, 1);
                }
            }
            drawArmy() {
                this.army.forEach(armyUnit => armyUnit.draw());
            }
            respondToInvasions() {
                // Check for enemy armies within our territory
                for (let enemyCountry of this.atWar) {
                    for (let enemyArmy of enemyCountry.army) {
                        const tile = world[enemyArmy.y][enemyArmy.x];
                        if (tile.country === this) {
                            // Enemy army is inside our territory
                            // Move our closest army to engage
                            let nearestArmy = null;
                            let minDistance = Infinity;
                            this.army.forEach(ourArmy => {
                                const dx = ourArmy.x - enemyArmy.x;
                                const dy = ourArmy.y - enemyArmy.y;
                                const distance = Math.sqrt(dx * dx + dy * dy);
                                if (distance < minDistance) {
                                    minDistance = distance;
                                    nearestArmy = ourArmy;
                                }
                            });
                            if (nearestArmy) {
                                nearestArmy.target = { x: enemyArmy.x, y: enemyArmy.y, type: 'army', army: enemyArmy };
                                nearestArmy.isMoving = true;
                            }
                        }
                    }
                }
            }
            destroy() {
                // Remove country from the game
                const cIndex = countries.indexOf(this);
                if(cIndex !== -1) {
                    countries.splice(cIndex, 1);
                }
                // Remove country ownership from tiles
                for(let y = 0; y < worldHeight; y++) {
                    for(let x = 0; x < worldWidth; x++) {
                        const tile = world[y][x];
                        if(tile.country === this) {
                            tile.country = null;
                            tile.captureProgress = {};
                        }
                    }
                }
            }
        }

        function getNeighborTiles(x, y) {
            const neighbors = [];
            const directions = [
                {dx: -1, dy: 0}, // left
                {dx: 1, dy: 0},  // right
                {dx: 0, dy: -1}, // up
                {dx: 0, dy: 1},  // down
            ];
            directions.forEach(dir => {
                const nx = x + dir.dx;
                const ny = y + dir.dy;
                if (nx >= 0 && nx < worldWidth && ny >= 0 && ny < worldHeight) {
                    neighbors.push(world[ny][nx]);
                }
            });
            return neighbors;
        }

        // Helper function to generate a random color
        function getRandomColor() {
            const letters = '0123456789ABCDEF';
            let color = '#';
            for(let i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        }

        // Helper function to generate a random border color
        function getRandomBorderColor() {
            const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#FFFFFF'];
            return colors[Math.floor(Math.random() * colors.length)];
        }

        // Helper function to get a random king trait
        function getRandomKingTrait() {
            const traits = ['aggressive', 'peaceful'];
            return traits[Math.floor(Math.random() * traits.length)];
        }

        // Function to check for country formation
        function checkForCountryFormation(character) {
            // Find nearby characters within a certain radius
            const radius = 3;
            const nearbyCharacters = characters.filter(other => {
                if(other !== character && !other.country) {
                    const dx = other.x - character.x;
                    const dy = other.y - character.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    return distance <= radius;
                }
                return false;
            });

            // Include the character themselves
            nearbyCharacters.push(character);

            // If 5 or more characters are nearby, form a country
            if(nearbyCharacters.length >= 5) {
                // Create a new country
                const countryName = getUniqueCountryName();
                const king = nearbyCharacters[Math.floor(Math.random() * nearbyCharacters.length)];

                // Assign king a name
                king.name = kingNames[Math.floor(Math.random() * kingNames.length)];

                const newCountry = new Country(countryName, king, nearbyCharacters);

                // Assign country to members and claim their current tiles
                nearbyCharacters.forEach(member => {
                    member.country = newCountry;
                    const tile = world[member.y][member.x];
                    tile.country = newCountry;
                });

                // Add country to the list
                countries.push(newCountry);
            }
        }

        // Helper function to get a unique country name
        function getUniqueCountryName() {
            let name = countryNames[Math.floor(Math.random() * countryNames.length)];
            while(usedCountryNames.includes(name) && usedCountryNames.length < countryNames.length) {
                name = countryNames[Math.floor(Math.random() * countryNames.length)];
            }
            usedCountryNames.push(name);
            return name;
        }

        // Function to sort countries by population
        function sortCountriesByPopulation() {
            return countries.slice().sort((a, b) => b.members.length - a.members.length); // Descending order
        }

        // Function to draw the leaderboard table
        function drawLeaderboard() {
            const topCountries = sortCountriesByPopulation().slice(0, 5); // Show top 5 countries

            // Table position and dimensions
            const tableX = 10;
            const tableY = 10;
            const rowHeight = 20;
            const columnWidth = 150;

            // Draw table header
            ctx.fillStyle = '#FFFFFF';
            ctx.font = '14px Arial';
            ctx.fillText('Leaderboard', tableX, tableY);

            // Draw table rows
            topCountries.forEach((country, index) => {
                const rowIndex = tableY + (index + 1) * rowHeight;
                ctx.fillText(`${index + 1}. ${country.name}`, tableX, rowIndex);
                ctx.fillText(`Population: ${country.members.length}`, tableX + columnWidth, rowIndex);
            });
        }

        // Handle mouse clicks to spawn characters
        canvas.addEventListener('click', function(e) {
            const rect = canvas.getBoundingClientRect();
            const mouseX = e.clientX - rect.left;
            const mouseY = e.clientY - rect.top;
            const x = Math.floor((mouseX + cameraX) / tileSize);
            const y = Math.floor((mouseY + cameraY) / tileSize);

            // Spawn character if tile is land or woods and not within another country's borders
            if(x >= 0 && x < worldWidth && y >= 0 && y < worldHeight) {
                const tile = world[y][x];
                const tileType = tile.type;
                if((tileType === 'land' || tileType === 'woods' || tileType === 'food' || tileType === 'iron')) {
                    const character = new Character(x, y);

                    // Assign country if spawned within a country's territory
                    if (tile.country) { 
                        character.country = tile.country;
                        tile.country.members.push(character); // Add to country's members
                    }

                    characters.push(character);
                }
            }
        });

        // Handle mouse down for panning
        canvas.addEventListener('mousedown', function(e) {
            isPanning = true;
            canvas.style.cursor = 'grabbing';
            startMouseX = e.clientX;
            startMouseY = e.clientY;
            startCameraX = cameraX;
            startCameraY = cameraY;
        });

        // Handle mouse move for panning
        canvas.addEventListener('mousemove', function(e) {
            if(isPanning) {
                const dx = e.clientX - startMouseX;
                const dy = e.clientY - startMouseY;
                cameraX = startCameraX - dx;
                cameraY = startCameraY - dy;

                // Clamp camera within world bounds
                cameraX = Math.max(0, Math.min(cameraX, worldWidth * tileSize - canvasWidth));
                cameraY = Math.max(0, Math.min(cameraY, worldHeight * tileSize - canvasHeight));
            }
        });

        // Handle mouse up for panning
        canvas.addEventListener('mouseup', function(e) {
            isPanning = false;
            canvas.style.cursor = 'grab';
        });

        // Handle mouse out
        canvas.addEventListener('mouseleave', function(e) {
            isPanning = false;
            canvas.style.cursor = 'grab';
        });

        // Function to draw everything
        function draw() {
            ctx.clearRect(0, 0, canvasWidth, canvasHeight);
            drawWorld();
            drawLeaderboard();
            characters.forEach(character => character.draw());
            countries.forEach(country => {
                country.drawArmy();
                country.drawName();
                // Optionally, display country names and king traits
                if (country.members.length > 0) {
                    const member = country.members[0];
                    const drawX = (member.x * tileSize) - cameraX;
                    const drawY = (member.y * tileSize) - cameraY;
                    ctx.fillStyle = country.color;
                    ctx.font = '12px Arial';
                    //ctx.fillText('${country.name} (${country.kingTrait}'), drawX, drawY - 5;
                }
            });
            deathEffects.forEach(effect => effect.draw());
        }

        // Game loop
        function gameLoop() {
            // Update in-game year every 7 seconds
            const now = Date.now();
            if (now - lastYearUpdate >= yearDuration) {
                lastYearUpdate = now;
                inGameYear++;
                console.log(`Year ${inGameYear}`);
                // Increase age of all characters
                for (let i = characters.length - 1; i >= 0; i--) {
                    const character = characters[i];
                    character.age++;
                    // Check for age-related death
                    if (character.age >= 60) {
                        const deathChance = (character.age - 59) / 10; // At age 60, 1% chance, at 70, 100% chance
                        if (Math.random() < deathChance) {
                            character.die('old age');
                        }
                    }
                }
            }

            // Update characters
            characters.forEach(character => character.move());
            // Update countries
            for(let i = countries.length - 1; i >= 0; i--) {
                let country = countries[i];
                country.update();
                country.updateBorders();
                // Check for country elimination
                if(country.members.length === 0) {
                    country.destroy();
                }
            }
            // Update death effects
            for(let i = deathEffects.length -1; i >= 0; i--) {
                const effect = deathEffects[i];
                effect.update();
                if(effect.duration <= 0) {
                    deathEffects.splice(i,1); // Remove expired effects
                }
            }
            // Redraw everything
            draw();
            requestAnimationFrame(gameLoop);
        }

        // Initial draw and start game loop
        draw();
        requestAnimationFrame(gameLoop);

        // Adjust canvas size on window resize
        window.addEventListener('resize', function() {
            canvasWidth = window.innerWidth;
            canvasHeight = window.innerHeight;
            canvas.width = canvasWidth;
            canvas.height = canvasHeight;
        });

    </script>
</body>
</html>

Add citizenships so each character would belong to country that he lived in, now some characters drafted to army instead of simple strenght of army, like, every characters now have health and they can fight against other army and lost characters, provide full updated code without missing parts