首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

博弈論實戰:C# 實現囚徒困境變體合作博弈模擬

     編輯:關於C#

遊戲規則

這是一個經典合作博弈的簡化版:兩名玩家各進行 100 輪對決,每輪選擇「合作」或「背叛」:

  • 雙方合作:各得 3 分
  • 一方合作、一方背叛:背叛者得 5 分,合作者扣 3 分
  • 雙方背叛:各扣 1 分

最終總分最高者獲勝。程式採用介面 ActorBase 規範策略,支援歷史記錄與動態決策。

核心介面設計

public interface ActorBase {
    bool Gamble(string opponentName);  // true=合作, false=背叛
    string GetUniqueCode();            // 玩家唯一標識
    int Score { get; set; }            // 總分
    void AddRecord(string opponent, bool record); // 記錄對戰歷史
}

四種策略實現

1. CareySon(善良模仿策略)

首輪合作,後續模仿對手上一步行為:

public bool Gamble(string name) {
    if (!Record.ContainsKey(name)) return true; // 首輪合作
    var history = Record[name];
    return history.Count > 0 && history[history.Count - 1]; // 模仿最後一步
}

2. RandomPlayer(隨機策略)

public bool Gamble(string name) => new Random().Next(2) == 1;

3. Tony(近三輪多數決)

統計最近 3 輪,合作≥2 則合作:

int z = 0;
if (l[l.Count-1]) z++;
if (l[l.Count-2]) z++;
if (l[l.Count-3]) z++;
return z >= 2;

4. Jack(歷史總體傾向)

統計所有歷史,合作多於背叛則合作,相等則背叛:

foreach (bool b in Record[name]) { if (b) z++; else c++; }
return z > c;

模擬引擎

var players = new List<ActorBase> { new CareySon(), new RandomPlayer(), new Tony(), new Jack() };

for (int round = 1; round <= 100; round++) {
    for (int i = 0; i < players.Count; i++) {
        for (int j = i + 1; j < players.Count; j++) {
            bool a = players[i].Gamble(players[j].GetUniqueCode());
            bool b = players[j].Gamble(players[i].GetUniqueCode());
            // 根據 a,b 組合計分並記錄歷史...
        }
    }
}

典型運行結果

Player: CareySon   Score: 686
Player: RandomPlayer Score: 570
Player: Tony       Score: 670
Player: Jack       Score: 734  ← 勝出

擴展思考

歡迎大家提出更優策略(如 Tit-for-Tat 變體、機器學習預測等),共同探討博弈論在代碼中的精彩體現!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved