"""
sb策略和真人收益对比，其中分别比较sb0,sb0.2,所有人平均，获胜者平均，获胜者最高，统计10-15共6组
"""
import json
import numpy as np
import math
from matplotlib import pyplot as plt
from island.matches import Matches
from island.match import Match

human_avg = np.zeros(6)
human_count = np.zeros(6)
winner_avg = np.zeros(6)
winner_count = np.zeros(6)
winner_max = np.zeros(6)

"""
omega = np.ceil(5/(3-(x*2.6)))
fb0 = 5-omega*(3-(x*2.6+(1-x)*4.5))
fb = fb0 - (15-omega)*(3-2.6)
y = fb/2
"""
r = np.arange(10, 16)
x = 0.1924

sb0 = (8 - 0.4 * (r - 2)) / 2
o = math.ceil(5 / (3 - (x * 2.6)))
sb1 = (5 - o * (3 - (x * 2.6 + (1 - x) * 4.5)) - 0.4 * (r - o)) / 2

for m in Matches.from_profile('SURVIVE').data:
    info = m.query('game', 'created').select('info').first()['info']
    conf = json.loads(info['config'])
    game_end_at = int(info['game_end_at'])
    foods = {}
    for p in m.query('player', 'join').select('pid').raw_data:
        foods[p['pid']] = conf['start_resource']

    for i in range(1, game_end_at + 1):
        for a in m.query('action', 'done').where(lambda x: x['rno'] == i).raw_data:
            foods[a['a']] += conf['payoffs']["%s%s" % (a['act_a'], a['act_b'])][0] * a['tr'] / 1440.0
            foods[a['b']] += conf['payoffs']["%s%s" % (a['act_a'], a['act_b'])][1] * a['tr'] / 1440.0
        for j in foods.keys():
            foods[j] -= conf['rounds']['consumption']
    human_count += len(foods)
    for j in foods.keys():
        if foods[j] > 0:
            winner_avg[game_end_at - 10] += foods[j]
            human_avg[game_end_at - 10] += foods[j]
            winner_count += 1
            if foods[j] > winner_max[game_end_at - 10]:
                winner_max[game_end_at - 10] = foods[j]
                if foods[j] > 3:
                    print(m.name, j, foods[j])

human_avg /= human_count
winner_avg /= winner_count

idx = np.arange(6)
bw = 0.15

fig = plt.figure(figsize=(5,3))
ax = fig.gca()

ax.bar(idx-2*bw, sb0, bw, color='tomato', label='Sacrifice(n=4)')
ax.bar(idx-bw, sb1, bw, color='limegreen', label='Sacrifice Max(n=4)')
ax.bar(idx, human_avg, bw, color='blueviolet', label='Human Average')
ax.bar(idx+bw, winner_avg, bw, color='gold', label='Winner Average')
# ax.bar(idx+2*bw, winner_max, bw, color='deepskyblue', label='Winner Max')

ax.set_ylabel('Average Reward')
ax.set_ylim(0,3.5)
ax.set_xlabel('Match Ends At')
ax.set_xticks(idx + bw / 2)
ax.set_xticklabels(('10', '11', '12', '13', '14', '15'))
ax.legend(ncol=2)
fig.tight_layout()
# plt.show()
plt.savefig("graph/sb_vs_human.eps")

