markov_bayes_v9_mem10

AuthorPiotrekG
Submission date2018-08-31 17:30:00.047010
Rating4803
Matches played287
Win rate52.26

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

Source code:

from __future__ import division
import random
import itertools

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


def create_keys(beat, level):
    keys = list(beat)

    if level > 1:

        for i in range(level - 1):
            key_len = len(keys)
            for i in itertools.product(keys, ''.join(beat)):
                keys.append(''.join(i))
            keys = keys[key_len:]

    return keys


class BayesMarkovChain():

    def __init__(self, matrix):
        self.matrix = matrix

    def update_matrix(self, key_lagged, response, memory):

        for key in self.matrix[key_lagged]:
            self.matrix[key_lagged][key] = memory * self.matrix[key_lagged][key]

        self.matrix[key_lagged][response] += 1

    def predict(self, key_current, memory):

        randoms = [(random.betavariate(matrix[key_current][key], 1 / (1 - memory) - matrix[key_current][key]), key) for key in matrix[key_current]]

        return max(randoms)[1]


if input == '':
    output = random.choice(list(beat.keys()))
    olag1 = ''
    olag2 = ''
    olag3 = ''
    ilag1 = ''
    ilag2 = ''

    level = 3
    memory = 0.9

    keys = create_keys(beat, level)

    matrix = {}
    for key in keys:
        matrix[key] = {'R': 1 / (1 - memory) / 3,
                       'P': 1 / (1 - memory) / 3,
                       'S': 1 / (1 - memory) / 3}

    model = BayesMarkovChain(matrix)

elif len(olag3) > 0:

    key_mat2 = olag3 + ilag2 + olag2
    key_mat1 = olag2 + ilag1 + olag1

    model.update_matrix(key_mat2, ilag1, memory)
    predicted_input = model.predict(key_mat1, memory)
    output = beat[predicted_input]


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

olag3 = olag2
olag2 = olag1
olag1 = output
ilag2 = ilag1
ilag1 = input