markov_v7_mem10

AuthorPiotrekG
Submission date2018-08-23 14:45:33.488396
Rating7004
Matches played266
Win rate67.67

Use rpsrunner.py to play unranked matches on your computer.

Source code:

from __future__ import division
import random
import bisect

beat = {'R': 'P', 'P': 'S', 'S': 'R'}


def update_matrix(matrix, olag2, ilag1, lim):

    matrix[olag2][ilag1]['N'] = matrix[olag2][ilag1]['N'] + 1

    sum_n = 0
    for i in matrix[olag2]:
        sum_n += matrix[olag2][i]['N']

    for i in matrix[olag2]:
        matrix[olag2][i]['Pr'] = matrix[olag2][i]['N'] / sum_n

    for i in matrix[olag2]:
        matrix[olag2][i]['N'] = matrix[olag2][i]['N'] * lim / sum_n

    return matrix


def weighted_choice(choices):
    values, weights = zip(*choices)
    total = 0
    cum_weights = []
    for w in weights:
        total += w
        cum_weights.append(total)
    x = random.random() * total
    i = bisect.bisect(cum_weights, x)
    return values[i]


def select_output(matrix, olag1):

    prs = []
    for i in matrix[olag1]:
        prs.append((i, matrix[olag1][i]['Pr']))

    return weighted_choice(prs)

lim = 10

if input == '':
    output = random.choice(list(beat.keys()))
    olag1 = ''
    olag2 = ''
    ilag1 = ''
    # fist level is my output lag(2) and second level is input lag(1)
    matrix = {
        'R': {'R': {'Pr': 1 / 3, 'N': lim/3},
              'P': {'Pr': 1 / 3, 'N': lim/3},
              'S': {'Pr': 1 / 3, 'N': lim/3}},
        'S': {'R': {'Pr': 1 / 3, 'N': lim/3},
              'P': {'Pr': 1 / 3, 'N': lim/3},
              'S': {'Pr': 1 / 3, 'N': lim/3}},
        'P': {'R': {'Pr': 1 / 3, 'N': lim/3},
              'P': {'Pr': 1 / 3, 'N': lim/3},
              'S': {'Pr': 1 / 3, 'N': lim/3}}
    }

elif olag2 != '':

    matrix = update_matrix(matrix, olag2, ilag1, lim)
    predicted_input = select_output(matrix, olag1)
    output = beat[predicted_input]

else:
    output = random.choice(list(beat.keys()))

olag2 = olag1
olag1 = output
ilag1 = input