Skip to content

Instantly share code, notes, and snippets.

@Surye
Created December 29, 2013 08:07
Show Gist options
  • Save Surye/8168506 to your computer and use it in GitHub Desktop.
Save Surye/8168506 to your computer and use it in GitHub Desktop.
#!/bin/env python
import random
from functools import reduce
from collections import Counter
class PongSim:
skills = [[0,0],[0,0]]
def __init__(self, team1, team2):
self.skills[0] = team1
self.skills[1] = team2
def run_match(self, rollback=True, cups=10):
cups_left = [cups,cups]
num_rounds = 0
first = random.choice([0,1])
second = 1 if first == 0 else 0
while cups_left[0] > 0 and cups_left[1] > 0:
if num_rounds == 0: # Very first turn only the best player shoots
if random.random() < max(self.skills[first]):
cups_left[first] -= 1
else:
teams = [first, second] if num_rounds > 0 else [second] # Only run sim for second team on first round
for team in teams:
made1 = random.random() < self.skills[first][0]
made2 = random.random() < self.skills[first][1]
if made1: cups_left[team] -= 1
if made2: cups_left[team] -= 1
if rollback and made1 and made2 and cups_left[team] > 0:
if random.random() < max(self.skills[team]):
cups_left[team] -= 1
if cups_left[team] < 1: # we have a winner, do rebuttal here
break
num_rounds += 1
winner,loser = [0,1] if cups_left[1] > 0 else [1,0]
cupdiff = cups_left[loser]
return num_rounds, winner, cupdiff
game = PongSim([.65, .65], [.80, .25])
num_games = 1000000
outcome = []
for i in range(num_games):
outcome.append(game.run_match())
avg_rounds = reduce(lambda x, y: x + y, [outcome[0] for outcome in outcome]) / num_games
avg_cupdiff = reduce(lambda x, y: x + y, [outcome[2] for outcome in outcome]) / num_games
winners = Counter([outcome[1] for outcome in outcome])
print("{} Games Simulated: Team 1 wins {} times ({}%), Team 2 wins {} ({}%). Avg number of rounds in the game: {}. Avg cup differential: {}".format(num_games,
winners[0], winners[0]/num_games,
winners[1], winners[1]/num_games,
avg_rounds, avg_cupdiff))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment