Skip to content

Instantly share code, notes, and snippets.

@misterhay
Created January 29, 2021 08:10
Show Gist options
  • Save misterhay/216316d6d5dae4d309a26dc1b6747215 to your computer and use it in GitHub Desktop.
Save misterhay/216316d6d5dae4d309a26dc1b6747215 to your computer and use it in GitHub Desktop.
Animating a "Rock Paper Scissors" tournament
number_of_rounds = 50
player1 = 'Steven'
player2 = 'Edward'
choices = {
'Steven':['Rock','Paper','Scissors'],
'Bart':['Rock'],
'Edward':['Scissors','Scissors','Scissors','Scissors','Paper','Paper'],
'Freddie':['Paper','Paper','Rock','Paper','Paper','Rock']}
# create a dataframe of rock beats scissors etc.
import pandas as pd
winlose = pd.DataFrame(columns=['Rock','Paper','Scissors'])
winlose['Rock'] = ['Tie','Win','Loss']
winlose['Paper'] = ['Loss','Tie','Win']
winlose['Scissors'] = ['Win','Loss','Tie']
winlose.index = ['Rock','Paper','Scissors']
from random import choices as c
p1wins = 0
p2wins = 0
ties = 0
p1c = ''
p2c = ''
results = pd.DataFrame(columns=['Tie']) # so that 'Tie' is listed below the others in the chart
for x in range(number_of_rounds):
results = results.append({player1+' Choice':p1c, player2+' Choice':p2c, 'Tie':ties, player2:p2wins, player1:p1wins}, ignore_index=True)
p1c = c(choices[player1])[0]
p2c = c(choices[player2])[0]
result = winlose.at[p1c, p2c]
if result == 'Win':
p1wins += 1
if result == 'Loss':
p2wins +=1
if result == 'Tie':
ties += 1
# convert wide dataframe to tidy
results['Round'] = results.index
tidy_results = results.drop(columns=[player1+' Choice', player2+' Choice']).melt('Round', var_name='Player', value_name='Wins')
import plotly.express as px
fig = px.bar(tidy_results, y='Player', x='Wins', orientation='h', animation_frame='Round')
fig.update_layout(xaxis_range=[0,tidy_results['Wins'].max()+1], title='Rock Paper Scissors Tournament to '+str(number_of_rounds))
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment