博弈论中的简单合作博弈 C#实现
2010-09-30 21:00:00 来源:WEB开发网最后是客户端调用的代码
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using TheGame;
8 public partial class GameTheory : System.Web.UI.Page
9 {
10 protected void Page_Load(object sender, EventArgs e)
11 {
12 List<TheGame.ActorBase> player = new List<TheGame.ActorBase>();//我把接口和实现的代码放入了TheGame命名空间
13 TheGame.ActorBase CareySon = new TheGame.Songyunjian();
14 TheGame.ActorBase RandomPlayer = new TheGame.RandomPlayer();
15 TheGame.ActorBase Tony = new TheGame.Tony();
16 TheGame.ActorBase Jack = new TheGame.Jack();
17 player.Add(CareySon);
18 player.Add(RandomPlayer);
19 player.Add(Tony);
20 player.Add(Jack);
21 /*从这里开始下面都是算法部分*/
22 for (int x = 1; x <= 100; x++)//循环合作100次
23 {
24 for (int i = 0; i < player.Count; i++)//让选手和其他所有选手进行博弈
25 {
26 for (int j = i + 1; j < player.Count; j++)
27 {
28
29 bool abBool = player[i].Gamble(player[j].GetUniqueCode());
30 ActorBase ab = player[i];
31 bool absBool = player[j].Gamble(player[i].GetUniqueCode());
32 ActorBase abs = player[j];
33 if (abBool && absBool)//当AB合作的时候
34 {
35 ab.Score += 3;
36 abs.Score += 3;
37 ab.AddRecord(abs.GetUniqueCode(), true);
38 abs.AddRecord(ab.GetUniqueCode(), true);
39 }
40 else if (abBool & !absBool) //当AB合作而ABS不合作
41 {
42 ab.Score -= 3;
43 abs.Score += 5;
44 ab.AddRecord(abs.GetUniqueCode(), false);
45 abs.AddRecord(ab.GetUniqueCode(), true);
46 }
47 else if (absBool & !abBool)//当abs合作而AB不合作的情况
48 {
49 ab.Score += 5;
50 abs.Score -= 3;
51 ab.AddRecord(abs.GetUniqueCode(), true);
52 abs.AddRecord(ab.GetUniqueCode(), false);
53 }
54 else if (!absBool && !abBool)//当双方都不合作的情况下
55 {
56 ab.Score -= 1;
57 abs.Score -= 1;
58 ab.AddRecord(abs.GetUniqueCode(), false);
59 abs.AddRecord(ab.GetUniqueCode(), false);
60 }
61
62 }
63 }
64 }
65 OutputResult(player);//输出并打印到屏幕上成绩
66
67 }
68 private void OutputResult(List<TheGame.ActorBase> l)
69 {
70 foreach (ActorBase ab in l)
71 {
72 HttpContext.Current.Response.Write("Player: <span style='background-color:#cdcdcd;color:blue;border:solid 1px #3cdcad'>" + ab.GetUniqueCode() + "</span> and the Score is <span style='background-color:#cdcdcd;color:blue;border:solid 1px #3cdcad'>" + ab.Score.ToString() + "</span><br />");
73 }
74 }
75 }
76
自此代码就完了,代码有点粗糙,各位看官切勿仍板砖-.-!!
某一次的运行结果如下,我就不抓图了:
-----------------------------------------------------
Player: CareySon and the Score is 686
Player: RandomPlayer and the Score is 570
Player: Tony and the Score is 670
Player: Jack and the Score is 734
-----------------------------------------------------
园子里有很多博弈学高手,有什么好的策略发上来一起探讨下:-)
更多精彩
赞助商链接