import java.util.Random; import pd.IterationResult; import pd.PrisonersDilemmaAgent; import pd.Settings; import pd.PrisonersDilemmaActor.Action; public class Exploit1 extends PrisonersDilemmaAgent.Adapter { double charityThreshold = 0.8; // fields to calculate opponent charity int myDefections = 0; int charityOccurrences = 0; double charity = 0.0; IterationResult previousIteration = null; public void run() { Settings settings = this.actor.getGame().getSettings(); Random rnd = new Random(System.currentTimeMillis() + (long)this.hashCode()); int lastTurn = settings.isFixedGameLength() ? settings.getGameLength() : -1; IterationResult iteration = null; int turnCount = 0; while (actor.getGame().isRunning()) { turnCount++; if ( turnCount == lastTurn || this.charity > charityThreshold || rnd.nextInt() % 4 == 0 ) { iteration = actor.act(Action.DEFECT); } else { iteration = actor.act(Action.COOPERATE); } this.updateOpponentCharity(iteration); } } public void updateOpponentCharity(IterationResult iteration) { if (previousIteration != null) { if (previousIteration.myAction == Action.DEFECT) { myDefections++; if (iteration.otherPlayerAction == Action.COOPERATE) { charityOccurrences++; } charity = (double)charityOccurrences / (double)myDefections; actor.log("Charity measured at " + charity); } } this.previousIteration = iteration; } }