<!DOCTYPE html>
<html>
<head>
    <title>完整版二战战略模拟</title>
    <style>
        /* 修复显示问题的样式 */
        body { 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #1a1a1a;
            color: #fff;
            margin: 0;
            padding: 20px;
            height: 100vh;
            overflow: hidden;
        }
        .container {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: 20px;
            height: calc(100vh - 40px);
        }
        .sidebar {
            background: #2a2a2a;
            padding: 20px;
            border-radius: 10px;
            overflow-y: auto;
        }
        .main-panel {
            background: #333;
            padding: 20px;
            border-radius: 10px;
            display: flex;
            flex-direction: column;
        }
        .nation-block {
            padding: 15px;
            border: 2px solid #444;
            margin: 5px;
            cursor: pointer;
            transition: all 0.3s;
            border-radius: 5px;
            background: #3a3a3a;
        }
        .nation-block:hover {
            background: #4a4a4a;
        }
        .occupied { background: #d32f2f !important; }
        .ally { border-color: #2196F3; }
        .axis { border-color: #FF9800; }
        .tab-content { 
            display: none;
            height: calc(100% - 120px);
            overflow-y: auto;
        }
        .tab-content.active { display: block; }
        .resource-bar {
            height: 20px;
            background: #4CAF50;
            margin: 5px 0;
            border-radius: 3px;
        }
        #worldMap {
            display: grid;
            grid-template-columns: repeat(8, 1fr);
            gap: 10px;
            margin-bottom: 20px;
            flex: 1;
        }
        .event-log {
            height: 200px;
            overflow-y: auto;
            background: #252525;
            padding: 15px;
            border-radius: 5px;
            border: 1px solid #444;
        }
        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
            transition: background 0.3s;
        }
        button:hover {
            background: #45a049;
        }
        .tech-node {
            padding: 10px;
            background: #2a2a2a;
            margin: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .tech-node.unlocked {
            background: #4CAF50;
        }
        #timeControl {
            margin-bottom: 15px;
            padding: 10px;
            background: #2a2a2a;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2 id="nationName">国家管理</h2>
            <div class="tabs">
                <button onclick="switchTab('overview')" class="active">总览</button>
                <button onclick="switchTab('military')">军事</button>
                <button onclick="switchTab('diplomacy')">外交</button>
                <button onclick="switchTab('tech')">科技</button>
            </div>

            <div id="overview" class="tab-content active">
                <h3>国家状态</h3>
                <p>政治体制: 
                    <select id="ideology" onchange="changeIdeology()">
                        <option value="totalitarianism">极权主义</option>
                        <option value="socialism">社会主义</option>
                        <option value="capitalism">资本主义</option>
                    </select>
                </p>
                <p>年份: <span id="gameYear">1939</span>年<span id="gameMonth">1</span>月</p>
                <p>经济力量: <span id="economyValue">100</span></p>
                <div class="resource-bar" style="width: calc(100% * var(--economy) / 200)"></div>
                
                <h4>资源储备</h4>
                <p>钢铁: <span id="steel">1000</span>吨</p>
                <p>石油: <span id="oil">500</span>桶</p>
                <p>人口: <span id="population">5000</span>万</p>
                <p>幸福度: <span id="happiness">70</span>%</p>
            </div>

            <div id="military" class="tab-content">
                <h3>军事力量</h3>
                <button onclick="recruitTroops()">征召部队 (消耗200钢铁)</button>
                <button onclick="buildTank()">生产坦克 (消耗500钢铁 300石油)</button>
                <button onclick="declareWar()">宣战</button>
                <div id="militaryUnits">
                    <p>步兵师: <span id="infantryCount">0</span></p>
                    <p>坦克师: <span id="tanksCount">0</span></p>
                    <p>航空队: <span id="aircraftCount">0</span></p>
                </div>
            </div>

            <div id="diplomacy" class="tab-content">
                <h3>外交关系</h3>
                <div id="diplomaticRelations"></div>
                <button onclick="proposeAlliance()">提议结盟</button>
                <button onclick="startNegotiation()">开启贸易谈判</button>
            </div>

            <div id="tech" class="tab-content">
                <h3>科技树</h3>
                <div class="tech-tree" id="techTree">
                    <div class="tech-node" id="tech-infantry" onclick="researchTech('infantry')">基础步兵训练</div>
                    <div class="tech-node" id="tech-tanks" onclick="researchTech('tanks')">装甲战术理论</div>
                    <div class="tech-node" id="tech-aviation" onclick="researchTech('aviation')">空军作战学说</div>
                </div>
            </div>
        </div>

        <div class="main-panel">
            <div id="timeControl">
                <button onclick="togglePause()" id="pauseButton">暂停</button>
                <span>速度: </span>
                <select id="gameSpeed" onchange="changeGameSpeed()">
                    <option value="1000">1x</option>
                    <option value="500">2x</option>
                    <option value="250">4x</option>
                </select>
            </div>
            <div id="worldMap"></div>
            <div class="event-log" id="eventLog"></div>
        </div>
    </div>

<script>
// 游戏核心数据模型
const GameState = {
    currentNation: null,
    year: 1939,
    month: 1,
    isPaused: false,
    gameSpeed: 1000,
    nations: {
        '德国': createNation("德国", "axis", "totalitarianism"),
        '苏联': createNation("苏联", "allies", "socialism"),
        '美国': createNation("美国", "allies", "capitalism"),
        '日本': createNation("日本", "axis", "totalitarianism"),
        '英国': createNation("英国", "allies", "capitalism")
    },
    factoryTypes: {
        steel: { cost: 1000, production: 50 },
        oil: { cost: 1500, production: 30 },
        military: { cost: 2000, production: 10 }
    },
    europeanCountries: ['德国', '法国', '英国', '意大利', '波兰', '苏联', '西班牙']
};

function createNation(name, faction, ideology) {
    return {
        name,
        faction,
        ideology,
        economy: 100,
        military: 100,
        population: 5000,
        happiness: 70,
        inflation: 1.0,
        resources: {
            steel: 1000,
            oil: 500,
            food: 2000
        },
        factories: {
            steel: 0,
            oil: 0,
            military: 0
        },
        territories: [name],
        relations: {},
        militaryUnits: {
            infantry: 10,
            tanks: 0,
            aircraft: 0
        },
        technologies: new Set(),
        lastActionMonth: 0
    };
}

const GameEngine = {
    intervalId: null,
    
    init() {
        this.generateWorldMap();
        this.startGameLoop();
        this.initializeDiplomaticRelations();
        this.updateUI();
    },

    initializeDiplomaticRelations() {
        Object.values(GameState.nations).forEach(nation => {
            Object.values(GameState.nations).forEach(other => {
                if (nation !== other) {
                    nation.relations[other.name] = {
                        value: nation.faction === other.faction ? 60 : 30,
                        isAllied: false
                    };
                }
            });
        });
    },

    generateWorldMap() {
        const map = document.getElementById('worldMap');
        map.innerHTML = '';
        GameState.europeanCountries.forEach(country => {
            const div = document.createElement('div');
            div.className = `nation-block ${GameState.nations[country]?.faction || 'neutral'}`;
            div.textContent = country;
            map.appendChild(div);
        });
    },

    startGameLoop() {
        this.intervalId = setInterval(() => {
            if (!GameState.isPaused) {
                this.updateGameState();
                this.updateAI();
                this.checkVictoryConditions();
                GameState.month++;
                if (GameState.month > 12) {
                    GameState.month = 1;
                    GameState.year++;
                }
                this.updateUI();
            }
        }, GameState.gameSpeed);
    },

    updateGameState() {
        Object.values(GameState.nations).forEach(nation => {
            // 经济系统
            nation.economy += this.calculateEconomicGrowth(nation);
            // 工厂生产
            nation.resources.steel += nation.factories.steel * 50;
            nation.resources.oil += nation.factories.oil * 30;
            nation.militaryUnits.infantry += nation.factories.military * 2;
            
            // 通货膨胀
            nation.inflation *= 1 + (nation.economy / 10000);
            
            // 人口系统
            const popGrowth = 0.01 * (nation.happiness - 50);
            nation.population = Math.floor(nation.population * (1 + popGrowth/100));
            
            // 资源消耗
            nation.resources.food -= nation.population * 0.002;
            if (nation.resources.food < 0) {
                nation.happiness -= 10;
                nation.population *= 0.98;
            }
        });
    },

    updateAI() {
        Object.values(GameState.nations).forEach(nation => {
            if (nation !== GameState.currentNation) {
                this.runAI(nation);
            }
        });
    },

    runAI(nation) {
        if (GameState.month - nation.lastActionMonth < 6) return;
        nation.lastActionMonth = GameState.month;
        
        // 军事行动
        if (Math.random() < 0.3) {
            const enemies = Object.values(GameState.nations).filter(n => 
                n !== nation && !nation.relations[n.name].isAllied
            );
            if (enemies.length > 0) {
                const target = enemies[Math.floor(Math.random() * enemies.length)];
                this.aiDeclareWar(nation, target);
            }
        }
        
        // 建造工厂
        if (nation.resources.steel > 2000) {
            nation.factories.steel++;
            nation.resources.steel -= 2000;
            logEvent(`<span class="ai-action">${nation.name} 建造了钢铁厂</span>`);
        }
    },

    aiDeclareWar(attacker, defender) {
        const attackPower = attacker.militaryUnits.infantry * 10 + attacker.militaryUnits.tanks * 50;
        const defensePower = defender.militaryUnits.infantry * 10 + defender.militaryUnits.tanks * 50;
        
        if (attackPower > defensePower * 0.8) {
            attacker.territories.push(defender.name);
            defender.territories = defender.territories.filter(t => t !== defender.name);
            logEvent(`<span class="ai-action">${attacker.name} 占领了 ${defender.name}!</span>`);
            document.querySelectorAll('.nation-block').forEach(block => {
                if (block.textContent === defender.name) block.classList.add('occupied');
            });
        }
    },

    updateUI() {
        const nation = GameState.currentNation;
        if (!nation) return;

        document.getElementById('nationName').textContent = nation.name;
        document.getElementById('economyValue').textContent = Math.floor(nation.economy);
        document.getElementById('steel').textContent = Math.floor(nation.resources.steel);
        document.getElementById('oil').textContent = Math.floor(nation.resources.oil);
        document.getElementById('population').textContent = Math.floor(nation.population);
        document.getElementById('happiness').textContent = Math.floor(nation.happiness);
        document.getElementById('gameYear').textContent = GameState.year;
        document.getElementById('gameMonth').textContent = GameState.month;
        
        document.getElementById('infantryCount').textContent = nation.militaryUnits.infantry;
        document.getElementById('tanksCount').textContent = nation.militaryUnits.tanks;
        document.getElementById('aircraftCount').textContent = nation.militaryUnits.aircraft;
        
        Object.keys(GameState.techTree).forEach(techId => {
            const techNode = document.getElementById(`tech-${techId}`);
            techNode.classList.toggle('unlocked', GameState.techTree[techId].unlocked);
        });

        updateDiplomaticRelationsDisplay();
    }
};

// 外交系统
function proposeAlliance() {
    const target = prompt('输入要结盟的国家:');
    if (GameState.currentNation.relations[target]?.value >= 70) {
        GameState.currentNation.relations[target].isAllied = true;
        GameState.nations[target].relations[GameState.currentNation.name].isAllied = true;
        logEvent(`与 ${target} 结成同盟!`);
    } else {
        alert("关系值不足或国家不存在!");
    }
    updateDiplomaticRelationsDisplay();
}

function updateDiplomaticRelationsDisplay() {
    const relationsDiv = document.getElementById('diplomaticRelations');
    relationsDiv.innerHTML = '';
    Object.entries(GameState.currentNation.relations).forEach(([nation, data]) => {
        const div = document.createElement('div');
        div.className = 'diplo-relation';
        div.innerHTML = `${nation} <span style="color:${data.isAllied ? '#4CAF50' : '#ff5722'}">关系: ${data.value}${data.isAllied ? ' (同盟)' : ''}</span>`;
        relationsDiv.appendChild(div);
    });
}

// 胜利/失败条件
function checkVictoryConditions() {
    // 失败条件
    if (GameState.currentNation.population <= 0 || GameState.currentNation.territories.length === 0) {
        endGame("失败!你的国家已经灭亡!");
        return;
    }

    // 胜利条件
    const controlled = GameState.europeanCountries.every(country => 
        GameState.currentNation.territories.includes(country)
    );
    
    if (controlled) endGame("胜利!你完全控制了欧洲!");
}

function endGame(message) {
    clearInterval(GameEngine.intervalId);
    alert(message);
    location.reload();
}

// 通用功能
function logEvent(message) {
    const log = document.getElementById('eventLog');
    const entry = document.createElement('div');
    entry.innerHTML = `[${GameState.year}.${GameState.month}] ${message}`;
    log.appendChild(entry);
    log.scrollTop = log.scrollHeight;
}

function switchTab(tabId) {
    document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
    document.getElementById(tabId).classList.add('active');
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const nation = prompt('选择你的国家(德国、苏联、美国、日本、英国):');
    if (GameState.nations[nation]) {
        GameState.currentNation = GameState.nations[nation];
        document.getElementById('ideology').value = GameState.currentNation.ideology;
        GameEngine.init();
        logEvent(`游戏开始!你选择了 ${nation}`);
    } else {
        alert('无效的国家选择!请刷新页面重试。');
    }
});

// 时间控制
function togglePause() {
    GameState.isPaused = !GameState.isPaused;
    document.getElementById('pauseButton').textContent = GameState.isPaused ? '继续' : '暂停';
}

function changeGameSpeed() {
    GameState.gameSpeed = parseInt(document.getElementById('gameSpeed').value);
    clearInterval(GameEngine.intervalId);
    GameEngine.startGameLoop();
}

// 军事功能
function recruitTroops() {
    const nation = GameState.currentNation;
    if (nation.resources.steel >= 200) {
        nation.resources.steel -= 200;
        nation.militaryUnits.infantry += 1;
        logEvent("成功征召1个步兵师");
    } else {
        alert("钢铁不足!");
    }
    GameEngine.updateUI();
}

function buildTank() {
    const nation = GameState.currentNation;
    if (nation.resources.steel >= 500 && nation.resources.oil >= 300) {
        nation.resources.steel -= 500;
        nation.resources.oil -= 300;
        nation.militaryUnits.tanks += 1;
        logEvent("成功生产1个坦克师");
    } else {
        alert("资源不足!");
    }
    GameEngine.updateUI();
}

function declareWar() {
    const target = prompt('输入要宣战的国家:');
    if (!GameState.nations[target]) return alert("无效的国家!");
    
    const attacker = GameState.currentNation;
    const defender = GameState.nations[target];
    
    const attackPower = attacker.militaryUnits.infantry * 10 + attacker.militaryUnits.tanks * 50;
    const defensePower = defender.militaryUnits.infantry * 10 + defender.militaryUnits.tanks * 50;
    
    if (attackPower > defensePower) {
        attacker.territories.push(target);
        defender.territories = defender.territories.filter(t => t !== target);
        logEvent(`成功占领 ${target}!`);
        document.querySelectorAll('.nation-block').forEach(block => {
            if (block.textContent === target) block.classList.add('occupied');
        });
    } else {
        logEvent(`进攻 ${target} 失败!`);
        attacker.militaryUnits.infantry = Math.floor(attacker.militaryUnits.infantry * 0.7);
    }
    GameEngine.updateUI();
}
</script>
</body>
</html>