开发一款关于“囚徒困境”的博弈论游戏,在单个HTML文件里面展示。
- User
开发一款关于“囚徒困境”的博弈论游戏,在单个HTML文件里面展示。
Assistant
好的,这是一个包含“囚徒困境”迭代博弈论游戏的单个HTML文件。它包含了HTML结构、CSS样式和JavaScript逻辑,全部内联在一个文件中。
你可以直接将以下代码复制到一个
.html文件中,然后用浏览器打开它。<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>囚徒困境博弈论游戏</title> <style> body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; margin: 20px; background-color: #f4f4f4; color: #333; max-width: 800px; margin-left: auto; margin-right: auto; padding: 20px; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } h1, h2 { color: #0056b3; border-bottom: 2px solid #0056b3; padding-bottom: 5px; margin-top: 20px; } #explanation, #settings, #gameArea, #resultsArea { margin-bottom: 20px; padding: 15px; background-color: #fff; border-radius: 8px; border: 1px solid #eee; } table { border-collapse: collapse; width: 100%; margin-top: 10px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: center; } th { background-color: #007bff; color: white; } td:first-child { font-weight: bold; background-color: #f2f2f2; } .payoff-table td { font-weight: normal; } button { padding: 10px 15px; font-size: 16px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; } #cooperateButton { background-color: #28a745; color: white; } #cooperateButton:hover { background-color: #218838; } #defectButton { background-color: #dc3545; color: white; } #defectButton:hover { background-color: #c82333; } #startButton, #resetButton { background-color: #007bff; color: white; margin-top: 10px; } #startButton:hover, #resetButton:hover { background-color: #0056b3; } label { margin-right: 10px; } select, input[type="number"] { padding: 8px; margin-right: 15px; border: 1px solid #ccc; border-radius: 4px; } #gameInfo { margin-top: 15px; font-size: 1.1em; font-weight: bold; } .round-result { border-bottom: 1px solid #eee; padding: 10px 0; margin-bottom: 10px; } .round-result:last-child { border-bottom: none; margin-bottom: 0; } .hidden { display: none; } </style> </head> <body> <h1>囚徒困境博弈论游戏</h1> <div id="explanation"> <h2>游戏说明</h2> <p>你将与一个由电脑控制的对手进行多轮“囚徒困境”博弈。每一轮,你和对手同时选择“合作”或“背叛”。你的选择会影响你们双方的得分。</p> <p>游戏目标是在多轮博弈后获得更高的总得分。</p> <h3>收益矩阵</h3> <p>下表显示了在不同选择组合下的得分:</p> <table class="payoff-table"> <thead> <tr> <th></th> <th>你的选择</th> <th></th> </tr> <tr> <th>对手的选择</th> <th>合作</th> <th>背叛</th> </tr> </thead> <tbody> <tr> <th>合作</th> <td>你得分: 3, 对手得分: 3 <br>(互惠)</td> <td>你得分: 0, 对手得分: 5 <br>(被剥削)</td> </tr> <tr> <th>背叛</th> <td>你得分: 5, 对手得分: 0 <br>(剥削对手)</td> <td>你得分: 1, 对手得分: 1 <br>(互相惩罚)</td> </tr> </tbody> </table> <p><b>注意:</b>得分是基于你和对手<b>同时</b>做出选择的情况。</p> </div> <div id="settings"> <h2>游戏设置</h2> <div> <label for="rounds">总回合数:</label> <input type="number" id="rounds" value="10" min="1"> </div> <div> <label for="aiStrategy">选择电脑对手策略:</label> <select id="aiStrategy"> <option value="tit-for-tat">以牙还牙 (Tit-for-Tat)</option> <option value="always-cooperate">总是合作 (Always Cooperate)</option> <option value="always-defect">总是背叛 (Always Defect)</option> <option value="random">随机选择 (Random)</option> </select> </div> <button id="startButton">开始游戏</button> </div> <div id="gameArea" class="hidden"> <h2>游戏进行中</h2> <div id="gameInfo"></div> <div id="choiceButtons"> <h3>请选择你的行动:</h3> <button id="cooperateButton">合作</button> <button id="defectButton">背叛</button> </div> <div id="roundResults"> <h3>回合结果:</h3> <div id="roundResultsLog"></div> </div> </div> <div id="resultsArea" class="hidden"> <h2>游戏结束</h2> <div id="finalScore"></div> <div id="finalMessage"></div> <button id="resetButton">重新开始</button> </div> <script> // JavaScript Code starts here // Game state variables let totalRounds = 0; let currentRound = 0; let player1Score = 0; // Player's score let player2Score = 0; // AI's score let aiStrategy = ''; let player1Choices = []; // History of player's choices let player2Choices = []; // History of AI's choices // Payoff matrix [player1_score, player2_score] const PAYOFFS = { 'Cooperate-Cooperate': [3, 3], 'Cooperate-Defect': [0, 5], 'Defect-Cooperate': [5, 0], 'Defect-Defect': [1, 1] }; // Get UI elements const settingsDiv = document.getElementById('settings'); const gameAreaDiv = document.getElementById('gameArea'); const resultsAreaDiv = document.getElementById('resultsArea'); const roundsInput = document.getElementById('rounds'); const aiStrategySelect = document.getElementById('aiStrategy'); const startButton = document.getElementById('startButton'); const cooperateButton = document.getElementById('cooperateButton'); const defectButton = document.getElementById('defectButton'); const gameInfoDiv = document.getElementById('gameInfo'); const roundResultsLogDiv = document.getElementById('roundResultsLog'); const finalScoreDiv = document.getElementById('finalScore'); const finalMessageDiv = document.getElementById('finalMessage'); const resetButton = document.getElementById('resetButton'); // Event listeners startButton.addEventListener('click', startGame); cooperateButton.addEventListener('click', () => makeChoice('Cooperate')); defectButton.addEventListener('click', () => makeChoice('Defect')); resetButton.addEventListener('click', resetGame); // Functions // Initializes the game function startGame() { totalRounds = parseInt(roundsInput.value); if (isNaN(totalRounds) || totalRounds < 1) { alert('总回合数必须是大于0的数字!'); return; } currentRound = 1; player1Score = 0; player2Score = 0; aiStrategy = aiStrategySelect.value; player1Choices = []; player2Choices = []; roundResultsLogDiv.innerHTML = ''; // Clear previous results settingsDiv.classList.add('hidden'); gameAreaDiv.classList.remove('hidden'); resultsAreaDiv.classList.add('hidden'); updateGameInfo(); } // Handles player's choice function makeChoice(playerChoice) { const aiChoice = getAiChoice(aiStrategy, currentRound, player1Choices, player2Choices); // Record choices BEFORE processing player1Choices.push(playerChoice); player2Choices.push(aiChoice); const choicesKey = `${playerChoice}-${aiChoice}`; const [p1ScoreThisRound, p2ScoreThisRound] = PAYOFFS[choicesKey]; player1Score += p1ScoreThisRound; player2Score += p2ScoreThisRound; displayRoundResult(currentRound, playerChoice, aiChoice, p1ScoreThisRound, p2ScoreThisRound); currentRound++; if (currentRound > totalRounds) { endGame(); } else { updateGameInfo(); } } // Determines AI's choice based on strategy function getAiChoice(strategy, round, player1History, player2History) { switch (strategy) { case 'always-cooperate': return 'Cooperate'; case 'always-defect': return 'Defect'; case 'random': return Math.random() < 0.5 ? 'Cooperate' : 'Defect'; case 'tit-for-tat': // On first round, cooperate if (round === 1) { return 'Cooperate'; } // Otherwise, do what the player did last round // player1History[round - 2] because arrays are 0-indexed // and round is 1-indexed return player1History[round - 2]; default: return 'Cooperate'; // Default to cooperate } } // Displays the result of a single round function displayRoundResult(round, playerChoice, aiChoice, p1ScoreThisRound, p2ScoreThisRound) { const resultDiv = document.createElement('div'); resultDiv.classList.add('round-result'); resultDiv.innerHTML = ` <h4>回合 ${round}</h4> <p>你的选择: <strong>${playerChoice}</strong></p> <p>对手的选择: <strong>${aiChoice}</strong></p> <p>本回合得分: 你获得 ${p1ScoreThisRound} 分, 对手获得 ${p2ScoreThisRound} 分</p> <p>总得分: 你 ${player1Score} 分, 对手 ${player2Score} 分</p> `; roundResultsLogDiv.appendChild(resultDiv); roundResultsLogDiv.scrollTop = roundResultsLogDiv.scrollHeight; // Auto-scroll to latest result } // Updates the game information display function updateGameInfo() { gameInfoDiv.innerHTML = ` 回合: ${currentRound} / ${totalRounds}<br> 你的总得分: ${player1Score}<br> 对手的总得分: ${player2Score} `; } // Ends the game and displays final results function endGame() { gameAreaDiv.classList.add('hidden'); resultsAreaDiv.classList.remove('hidden'); finalScoreDiv.innerHTML = `最终总得分: 你 ${player1Score} 分, 对手 ${player2Score} 分`; let message = ''; if (player1Score > player2Score) { message = '恭喜!你的总得分高于对手。'; } else if (player1Score < player2Score) { message = '对手的总得分高于你。也许下次试试不同的策略?'; } else { message = '你和对手打成了平手。'; } finalMessageDiv.textContent = message; } // Resets the game to settings screen function resetGame() { settingsDiv.classList.remove('hidden'); gameAreaDiv.classList.add('hidden'); resultsAreaDiv.classList.add('hidden'); // Clear game state (optional, will be reset on startGame) currentRound = 0; player1Score = 0; player2Score = 0; player1Choices = []; player2Choices = []; roundResultsLogDiv.innerHTML = ''; gameInfoDiv.innerHTML = ''; finalScoreDiv.innerHTML = ''; finalMessageDiv.textContent = ''; } // Initial setup on page load (optional, but good practice) document.addEventListener('DOMContentLoaded', () => { // Ensure settings are visible and game/results are hidden initially settingsDiv.classList.remove('hidden'); gameAreaDiv.classList.add('hidden'); resultsAreaDiv.classList.add('hidden'); }); // JavaScript Code ends here </script> </body> </html>代码解释:
- 单文件结构: 整个游戏(HTML, CSS, JavaScript)都包含在一个
<style>标签和<script>标签中,位于<body>标签内。 - HTML 结构:
- 包含游戏的标题、说明(包括收益矩阵)。
settingsdiv 用于设置游戏回合数和 AI 策略。gameAreadiv 在游戏进行时显示回合信息和玩家的选择按钮。resultsAreadiv 在游戏结束时显示最终分数和结果消息。- 使用
hidden类来控制这些 div 的显示/隐藏。
- CSS 样式:
- 包含在
<style>标签中,用于美化页面、布局元素、样式化表格和按钮。 - 使用了基本的颜色、间距和边框,让界面更易读。
hidden类简单地将元素的display设置为none。
- 包含在
- JavaScript 逻辑:
- 包含在
<script>标签中。 - 变量: 存储游戏状态,如当前回合、总得分、AI 策略以及双方的历史选择记录(用于像“以牙还牙”这样的策略)。
- 收益矩阵 (
PAYOFFS): 一个对象,存储不同选择组合下的得分。键是 "你的选择-对手的选择" 格式的字符串。 - UI 元素获取: 使用
document.getElementById获取 HTML 元素的引用,方便后续操作。 - 事件监听器: 将
click事件监听器附加到按钮上,触发相应的 JavaScript 函数 (startGame,makeChoice,resetGame)。 startGame(): 读取设置,初始化游戏状态变量,清除旧结果,隐藏设置区域,显示游戏区域。makeChoice(playerChoice): 这是游戏的核心逻辑。- 接收玩家的选择 ('Cooperate' 或 'Defect')。
- 调用
getAiChoice()函数获取 AI 的选择。 - 记录双方的选择历史。
- 根据双方选择,查阅
PAYOFFS计算本回合得分。 - 更新总得分。
- 调用
displayRoundResult()显示本回合的详细结果。 - 回合数加一。
- 检查是否达到总回合数,如果是则调用
endGame(),否则调用updateGameInfo()更新回合信息。
getAiChoice(): 根据传入的 AI 策略名称和游戏历史,返回 AI 的选择。实现了“总是合作”、“总是背叛”、“随机选择”和“以牙还牙”策略。displayRoundResult(): 创建并添加一个 DOM 元素来显示当前回合的选择和得分。updateGameInfo(): 更新游戏区域顶部的当前回合和总得分信息。endGame(): 隐藏游戏区域,显示结果区域,显示最终总得分和一段简单的总结消息。resetGame(): 隐藏游戏/结果区域,显示设置区域,重置游戏状态变量(尽管开始新游戏时会重新初始化)。DOMContentLoaded: 确保在 DOM 完全加载后再执行 JavaScript,防止脚本找不到元素。
- 包含在
这个游戏提供了一个基本的囚徒困境迭代博弈体验,你可以选择不同的电脑策略来观察它们的行为和结果。
- 单文件结构: 整个游戏(HTML, CSS, JavaScript)都包含在一个
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.