Nick’s Weblog

Application Development Environments

The Prisoner’s Dilemma and Axelrod’s Tournament – Scheme

;The Prisoner’s Dilemma and Axelrod’s Tournament
;Directed Studies – Assignment 1
;By: Nicholas Webb.

;Limiting the impact of the concrete representations ‘c and ‘d
(define coop ‘c)
(define def ‘d)

;GAME MATRIX

;gmat – Takes the players’ moves and returns their respective scores according to the canonical game matrix.
(define(gmat l)
(cond ((and (eq? (car l) coop) (eq? (cadr l) coop)) ‘(3 3)) ;(c c)
((and (eq? (car l) coop) (eq? (cadr l) def)) ‘(0 5)) ;(c d)
((and (eq? (car l) def) (eq? (cadr l) coop)) ‘(5 0)) ;(d c)
((and (eq? (car l) def) (eq? (cadr l) def)) ‘(1 1)) ;(d d)
)
)

;STRATEGIES

;allDefect – Defects every move.
(define(allDefect l) ((allX def) l))

;allCo-operate – Co-operates every move.
(define(allCo-operate l) ((allX coop) l))

;randomMove – Makes a random decision to defect or co-operate.
(define(randomMove l) (if (= (random 2) 0) coop def))

;majority – Examines the opponent’s history. If the opponent has defected more times than co-operating, then defect, otherwise co-operate.
(define(majority l) (if ( n (length l)) (s1 l) (s2 l))))

;TOURNAMENT

;play – plays two strategies against each other for a given number of rounds for a given game matrix and returns the cumulative score for each player as a list of two elements.
(define(play n m s1 s2) (score m (car (appendHistory n m s1 s2 ‘() ‘())) (cadr (appendHistory n m s1 s2 ‘() ‘()))))

;appendHistory – takes as parameters the players’ move histories. The function builds up the move histories by adding each player’s move (based on the opponent history) to that player’s history and continuing for the specified number of rounds.
(define(appendHistory n m s1 s2 h1 h2)
(if (= n 0) (list h1 h2)
(appendHistory (- n 1) m s1 s2 (cons (s1 h2) h1) (cons (s2 h1) h2))
)
)

;score – takes a game matrix and two move histories and returns the overall score of each player as a two element list.
(define(score m h1 h2)
(foldr (lambda (l1 l2) (map + l1 l2)) ‘(0 0) (map gmat (map list h1 h2))))

May 5, 2009 - Posted by nwebb215 | Own Choice Blog | | No Comments Yet

No comments yet.

Leave a comment