Skip to content

Instantly share code, notes, and snippets.

@Surye
Last active January 1, 2016 16:09
Show Gist options
  • Save Surye/8168512 to your computer and use it in GitHub Desktop.
Save Surye/8168512 to your computer and use it in GitHub Desktop.
#!/bin/env python
import random
from sys import argv
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, rebuttal=False, rebuttal_team=0):
cups_left = [cups,cups]
num_rounds = 0
if rebuttal:
second = rebuttal_team
first = 1 if second == 0 else 0
else:
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 and not rebuttal: # 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[team][0]
made2 = random.random() < self.skills[team][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
on_rebuttal = 1 if cups_left[1] > 0 else 0
winner = self.run_rebuttal(cups_left[on_rebuttal], on_rebuttal)
return winner
def run_rebuttal(self, cups_left, team):
first = max(self.skills[team])
second = min(self.skills[team])
round = 1
while cups_left > 0:
made = random.random() < [first,second][1%round]
if made:
cups_left -= 1
round += 1
else:
break
if cups_left > 0:
return 1 if team != 1 else 0
else:
return self.run_match(True, 3, True, team)
if __name__ == "__main__":
game = PongSim([float(argv[2]), float(argv[3])], [float(argv[4]), float(argv[5])])
num_games = int(argv[1])
outcome = []
for i in range(num_games):
outcome.append(game.run_match())
winners = Counter(outcome)
print("{} Games Simulated: Team 1 wins {} times ({}%), Team 2 wins {} ({}%).".format(num_games,
winners[0], winners[0]/num_games,
winners[1], winners[1]/num_games,))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment