Last active
August 29, 2015 14:01
-
-
Save jpfuentes2/8fed6d9940929e4d0962 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
) | |
type Move uint | |
const Cooperate = 1 | |
const Defect = 0 | |
type Prisoner struct { | |
Name string | |
Moves []Move | |
Scores []uint | |
TotalScore uint64 | |
Strategy | |
} | |
type Strategy interface { | |
Move(opponent Prisoner) Move | |
} | |
type scoreTuple [2]Move | |
var ScoreMatrix = map[scoreTuple]uint{ | |
scoreTuple{1, 0}: 0, | |
scoreTuple{0, 0}: 1, | |
scoreTuple{1, 1}: 3, | |
scoreTuple{0, 1}: 5, | |
} | |
type AlwaysDefect struct{} | |
type AlwaysCooperate struct{} | |
type AlwaysRandom struct{} | |
func (s AlwaysDefect) Move(opponent Prisoner) Move { | |
return Defect | |
} | |
func (s AlwaysCooperate) Move(opponent Prisoner) Move { | |
return Cooperate | |
} | |
func (s AlwaysRandom) Move(opponent Prisoner) Move { | |
if rand.Intn(1) == 1 { | |
return Cooperate | |
} else { | |
return Defect | |
} | |
} | |
type Game struct { | |
Prisoners [2]Prisoner | |
} | |
// this terrible shit needs to be cleaned up | |
func (g *Game) Play(times int) { | |
for i := 0; i < times; i++ { | |
a := &g.Prisoners[0] | |
b := &g.Prisoners[1] | |
aMove := a.Move(*b) | |
bMove := b.Move(*a) | |
a.Moves = append(a.Moves, aMove) | |
b.Moves = append(b.Moves, bMove) | |
aScore := computeScore(aMove, bMove) | |
bScore := computeScore(bMove, aMove) | |
a.Scores = append(a.Scores, aScore) | |
b.Scores = append(b.Scores, bScore) | |
a.TotalScore += uint64(aScore) | |
b.TotalScore += uint64(bScore) | |
} | |
} | |
func computeScore(a, b Move) uint { | |
score := ScoreMatrix[scoreTuple{a, b}] | |
return score | |
} | |
func main() { | |
rand.Seed(time.Now().UTC().UnixNano()) | |
a := Prisoner{Name: "a", Strategy: new(AlwaysCooperate)} | |
b := Prisoner{Name: "b", Strategy: new(AlwaysDefect)} | |
g := Game{Prisoners: [2]Prisoner{a, b}} | |
g.Play(2) | |
fmt.Println("Prisoner A (AlwaysCooperate):", g.Prisoners[0].TotalScore) | |
fmt.Println("Prisoner B (AlwaysDefect) :", g.Prisoners[1].TotalScore) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment