class ButtonReaction(): | |
def __init__(self, moves_widget, game_statistics_widget, plot_widget, show_plot): | |
self.moves = moves_widget | |
self.game_statistics = game_statistics_widget | |
self.plot = plot_widget | |
self.history = {'rock': 0, 'paper': 0, 'scissors': 0} # initialize history of moves of our human opponent | |
self.wins = [0, 0, 0] | |
self.show_plot = show_plot | |
def on_button_clicked(self, button_info): | |
actual_human_move = button_info.description.lower() | |
self.history[actual_human_move] += 1 | |
history_list = [val for (key, val) in self.history.items()] | |
history_list_plus_one = [val + 1 for val in history_list] # compute parameters for Dirichlet distribution | |
no_rounds = sum(history_list) | |
probs = tfp.distributions.Dirichlet(history_list_plus_one).sample() | |
hypothetical_human_move = list(tfp.distributions.Multinomial(total_count=1, probs=probs).sample().numpy()) | |
if hypothetical_human_move == [1.0, 0.0, 0.0]: | |
our_move = 'paper' | |
elif hypothetical_human_move == [0.0, 1.0, 0.0]: | |
our_move = 'scissors' | |
else: | |
our_move = 'rock' | |
if actual_human_move == our_move: | |
result = 'draw' | |
self.wins[2] += 1 | |
if (actual_human_move, our_move) in [('rock', 'paper'), ('paper', 'scissors'), ('scissors', 'rock')]: | |
result = 'computer wins' | |
self.wins[1] += 1 | |
else: | |
result = 'you win' | |
self.wins[0] += 1 | |
if self.show_plot: | |
p_exact_posterior = tfp.distributions.Dirichlet(history_list_plus_one).sample(10000) | |
plot_probs = pd.DataFrame({'p_rock': p_exact_posterior[:, 0].numpy(), 'p_paper': p_exact_posterior[:, 1].numpy(), | |
'p_scissors': p_exact_posterior[:, 2].numpy()}) | |
self.plot.clear_output(wait=False) | |
with self.plot: | |
fig, ax = plt.subplots() | |
ax.set_yticklabels(labels='') # the y-axis-labels are the concrete counts of rock/stone/scissors | |
# which are irrelevant here, so we switch y-axis-labels off | |
plot_probs.plot.kde(alpha=0.5, fig=fig, ax=ax) | |
show_inline_matplotlib_plots() | |
moves.value = f"result in round {no_rounds}: your move is {actual_human_move}, computer's move is {our_move}, {result}" | |
game_statistics.value = f'you won {self.wins[0]} times, computer won {self.wins[1]} times and we had {self.wins[2]} draws' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment