Author | yeye |
Submission date | 2019-05-03 05:53:47.181380 |
Rating | 4956 |
Matches played | 243 |
Win rate | 48.97 |
Use rpsrunner.py to play unranked matches on your computer.
import random
states=['RR', 'RP', 'RS', 'PR', 'PP', 'PS', 'SR', 'SP', 'SS']
class RPSai:
def __init__(self):
self.d={}
self.history=[]
self.matrix={}
for i in states:
self.matrix[i]={'R': {'prob' : 1 / 3,'times' : 0},'P': {'prob' : 1 / 3,'times' : 0},'S': {'prob' : 1 / 3,'times' : 0}}
def opponentMove(self,oppo_move):
if oppo_move=="R" or oppo_move=="P" or oppo_move=="S":
#update markov chain
if len(self.history)>=2:
state=self.history[-2]+self.history[-1]
self.matrix[state][oppo_move]['times'] = self.matrix[state][oppo_move]['times'] + 1
total = 0
for i in self.matrix[state]:
total += self.matrix[state][i]['times']
for i in self.matrix[state]:
self.matrix[state][i]['prob'] = self.matrix[state][i]['times'] / total
#update self.history
self.history.append(oppo_move)
#update dictionary
if oppo_move in self.d:
self.d[oppo_move]+=1
else:
self.d[oppo_move]=1
def beatMove(self,expected_oppo_move):
if expected_oppo_move=="R":
return "P"
if expected_oppo_move=="P":
return "S"
if expected_oppo_move=="S":
return "R"
def predictMovePro(self):
if len(self.history)<2:
return random.choice(["R","P","S"])
if len(self.history)>=2:
state=self.history[-2]+self.history[-1]
lst_prob=[]
lst_time=[]
for i in self.matrix[state]:
lst_prob.append(self.matrix[state][i]["prob"])
lst_time.append(self.matrix[state][i]["times"])
if max(lst_prob)==min(lst_prob):
if max(lst_time)==min(lst_time):
return random.choice(["R","P","S"])
else:
return self.matrix[state][lst_times.index(max(lst_time))]
else:
for i in self.matrix[state]:
if self.matrix[state][i]["prob"]==max(lst_prob):
return i
def playMovePro(self):
return self.beatMove(self.predictMovePro())
me=RPSai()
if input=="":
output=random.choice(["R","P","S"])
else:
me.opponentMove(input)
output=me.playMovePro()