From 7f9a32a84c8e2170b36d4593b7018da5a3a3a2db Mon Sep 17 00:00:00 2001 From: Tobias Kuhn Date: Fri, 18 Oct 2013 11:16:30 +0200 Subject: [PATCH] Add files for prisoner's dilemma --- prisoner/iteratedpd.m | 52 +++++++++++++++++++++++++++++++++++++ prisoner/play.m | 54 ++++++++++++++++++++++++++++++++++++++ prisoner/tournament.m | 60 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 166 insertions(+) create mode 100755 prisoner/iteratedpd.m create mode 100755 prisoner/play.m create mode 100755 prisoner/tournament.m diff --git a/prisoner/iteratedpd.m b/prisoner/iteratedpd.m new file mode 100755 index 0000000..372063c --- /dev/null +++ b/prisoner/iteratedpd.m @@ -0,0 +1,52 @@ +%% Iterates the Prisoner Dilemma between two players +% +% Returns four arguments: the two lists of strategies (0=defect, 1=coop) +% and the two scores. + +function [X,Y,Xscore,Yscore]=iteratedpd(r,p1strat,p2strat,payoff) + +% Init +mdefect=payoff(1,1); +mcoop=payoff(2,2); +suckerlose=payoff(1,2); +suckerwin=payoff(2,1); + +X=[]; +Y=[]; +Xscore=0; +Yscore=0; + +for i=1:r + + % Determine the next move based on the past history + newX=play(X,Y,p1strat); + newY=play(Y,X,p2strat); + + % Add the last move + X=[X,newX]; + Y=[Y,newY]; + + % Update the score + if (newX==0) %P1 defect + if(newY==0) + Xscore=Xscore+mdefect; + Yscore=Yscore+mdefect; + else + Xscore=Xscore+suckerwin; + Yscore=Yscore+suckerlose; + end + else %P1 cooperate + if(newY==0) + Xscore=Xscore+suckerlose; + Yscore=Yscore+suckerwin; + else + Xscore=Xscore+mcoop; + Yscore=Yscore+mcoop; + end + end +end +end + + + + \ No newline at end of file diff --git a/prisoner/play.m b/prisoner/play.m new file mode 100755 index 0000000..c07f9a1 --- /dev/null +++ b/prisoner/play.m @@ -0,0 +1,54 @@ +%% Play a round of Prisoner Dilemma +% Evaluate previous history and execute a strategy. +% +% Returns 1 to cooperate or 0 to defect. +% +% Strategies implemented: +% +% * 1 = always defect +% * 2 = always cooperate +% * 3 = Tit-for-tat +% * 4 = GRIM (defect forever if opponent ever defects) +% * Any other input implements RANDOM- 50% chance of either. + +function x=play(player,opp,strategy) + +if (strategy == 1) %always defect + x=0; + +elseif (strategy == 2) %always cooperate + x=1; + +elseif(strategy==3) %titfortat + if(isempty(opp)) + x=1; % Be nice first + else + x=opp(length(opp)); % Repeat last opponent's move + end + +elseif(strategy==4) %GRIM + if(isempty(opp)) % Be nice first + x=1; + else + if(sum(opp) 5+0 + +bothDefect = 1; +bothCooperate = 3; +temptationToDefect = 5; +suckerPayoff = 0; + +payoffMatrix = [bothDefect,suckerPayoff; + temptationToDefect,bothCooperate] + +%% START THE TOURNAMENT +% +Z=zeros(n,n); % tournament table + +for i=1:n + for j=1:n + [hP1,hP2,scoreP1,scoreP2]=iteratedpd(R,Q(i),Q(j),payoffMatrix); + Z(i,j)=scoreP1; + end +end + + +%% PRINT RESULTS +% +display(Z); +scores = zeros(n,1); +for i=1:n + scores(i)=sum(Z(i,1:n)); +end +display(scores); + +imagesc(Z); + +% Who wins? +% Why? +