#!/usr/bin/python

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
#                                                                         #
# ipridi (Iterated Prisoner's Dilemma) v0.1, by Little Neo, June 2005     #
#                                                                         #
# the goal of this game is to program players to win tournaments          #
# in an environnement of cooperation and defects                          #
#                                                                         #
# A player is programmed like that :                                      #
#                                                      |||||              #
# def player_name(turn,me):                             o -    don't      #
#      (do some stuff)                                   |    be shy !    #
#      (return 1 to cooperate or 0 to defect)           \_/ __/           #
#                                                                         #
# "turn" is the current turn i                                            #
# you may use the tuple t to access the previous exchanges :              #
# t[me][i] : what you played at turn #i (i<turn)                          #
# t[1-me][i] : what the other played at turn #i (i<turn)                  #
#                                                                         #
# Have fun, etc                                                           #
#                                                                         #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 



version='0.1'

# here we go
if __name__=="__main__":
	import sys, code, imp
	# the code to load the emulator has been shamelessly stolen from scapy
	# http://www.cartel-securite.fr/pbiondi/scapy.html
	ipridi_mod = sys.argv[0][sys.argv[0].rfind("/")+1:]
	if not ipridi_mod:
		ipridi_mod = "ipridi"
	else:
		if ipridi_mod.endswith(".py"):
			ipridi_mod = ipridi_mod[:-3]
	ipridi=imp.load_module("ipridi",*imp.find_module(ipridi_mod))
	__builtins__.__dict__.update(ipridi.__dict__)
	code.interact(banner="- Welcome to ipridi ! -\n   h() for help")
	print "Bye !"
	sys.exit(0)

import sys,re,random
turnspergame=20
payoff=[[1,1],[5,0]],[[0,5],[3,3]]
t=[[],[]]

def fight(fst, snd, verbose=False):
	"""fight(s p1, s p2, b verbose)
gives the result of the match p1 vs p2"""
	if not fst in lsp() or not snd in lsp():
		print "Uh-oh... one of the two players doesn't exist !"
		return
	# to do : add a "control" routine detecting
	# trivial attempts to cheat
	global t
	t=[[],[]]
	s=[0,0]
	for i in range(turnspergame):
		# "protection"
		t,s=tuple(t),tuple(s)
		#game
		a,b=globals()[fst](i,0),globals()[snd](i,1)
		# un-protection
		t,s=list(t),list(s)
		t[0].append(a); t[1].append(b)
		if verbose:
			print "%-5s : "%(i), t[0][i], t[1][i]
		# score update
		s[0]+=payoff[t[0][i]][t[1][i]][0]
		s[1]+=payoff[t[0][i]][t[1][i]][1]	
	return s[0],s[1]

def tournament(l):
	"""tournament(l participants)
tournament between the given participants"""
	score=[]
	for i in range(l.__len__()):
		score+=[0]
	for i in range(l.__len__()): 
		for j in range(l.__len__()):   
			si,sj=fight(l[i],l[j])
			score[i]+=si
			score[j]+=sj
	def cmpscores(x,y):
		return x>y and -1 or 1
	# kinda "Schwartzian transform" :)
	final=zip(score,l)
	final.sort(cmpscores)
	cx=1
	for i in range(l.__len__()):
		print  "%-3s"%(1 and a or ""),"%-15s : "%(final[i][0]), final[i][1]
		cx+=1
	return 
	
def lsp():
	"""lsp()
gives the list of all available players"""
	# actually, lsp() looks for functions in the
	# source and assumes they are robots, nothing more
	f=open(sys.argv[0])
	fcts=[re.sub("\(.*","",re.sub("def ","",line))\
	for line in f.read().split("\n") if re.search("^def ",line)!=None]
	pl=fcts[fcts.index('sucker'):]
	f.close()
	return pl

def tpg(n):
	"""tpg(i n)
set the number of turns per game to n"""
	global turnspergame
	turnspergame=n
	return

def about():
	"""about()
gives info about the ipridi program"""
	print "ipridi v",version,"\nby Little Neo"
	print "http://submoon.freeshell.org/en/ipridi"	

def h():
	"""h()
gives ipridi commands"""
	print "Welcome to the zupa built-in help system !"
	for c in [h,tpg,lsp,fight,tournament,about]:
		cd=c.__doc__.split("\n",1)
		print "%-30s : "%(cd[0]), cd[1]

################ the players ##################

# if you look at lsp(), you see that sucker should be the 1st player...
def sucker(turn, me):
	""" sucker always cooperates"""
	return 1

def meanie(turn, me):
	""" meanie always defects"""
	return 0

def rnd(turn,me):
	""" rnd cooperates or defects randomly"""
	return random.choice([0,1])

def tft(turn, me):
	""" tft is Anatol Rapoport's Tit for Tat
 Note he can't beat his opponent"""
	return turn==0 and 1 or t[1-me][turn-1]

def tftz(turn, me):
	""" like tft, but defects at the 1st turn"""
	return turn>0 and t[1-me][turn-1] or 0

def ntft(turn, me):
	""" ntft plays the opposite of what the partner played"""
	return turn==0 and 1 or 1-t[1-me][turn-1]

def tf2t(turn,me):
	""" tf2t cooperates except if the other defected during both precedent turns"""
	return turn<2 and 1 or (t[1-me][turn-1]+t[1-me][turn-2]>0 and 1 or 0)

def avenger(turn,me):
	""" avenger cooperates until the other defects (Friedman)"""
	if (turn==0):
		return 0
	for i in range(turn-1):
		if t[1-me][i]==0:
			return 0
	return 1
	
def cheater(turn,me):
	# illustrates how ipridi could be abused :D
	""" cheats !"""
	global t
	t=list(t)
	if turn>0:
		t[me][turn-1]=1
	t=tuple(t)
	return 0

################### END OF FILE ######################



Little Neo + code2html, 2005

ipridi

Accueil