這是一個經典合作博弈的簡化版:兩名玩家各進行 100 輪對決,每輪選擇「合作」或「背叛」:
最終總分最高者獲勝。程式採用介面 ActorBase 規範策略,支援歷史記錄與動態決策。
public interface ActorBase {
bool Gamble(string opponentName); // true=合作, false=背叛
string GetUniqueCode(); // 玩家唯一標識
int Score { get; set; } // 總分
void AddRecord(string opponent, bool record); // 記錄對戰歷史
}
首輪合作,後續模仿對手上一步行為:
public bool Gamble(string name) {
if (!Record.ContainsKey(name)) return true; // 首輪合作
var history = Record[name];
return history.Count > 0 && history[history.Count - 1]; // 模仿最後一步
}
public bool Gamble(string name) => new Random().Next(2) == 1;
統計最近 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;
統計所有歷史,合作多於背叛則合作,相等則背叛:
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 變體、機器學習預測等),共同探討博弈論在代碼中的精彩體現!