Skip to content

Instantly share code, notes, and snippets.

@samuelsaari
Last active December 16, 2022 23:33
Show Gist options
  • Save samuelsaari/941ee26d74aa974e48f551bc9e96c837 to your computer and use it in GitHub Desktop.
Save samuelsaari/941ee26d74aa974e48f551bc9e96c837 to your computer and use it in GitHub Desktop.
verbose=False
from random import randint
class Risk:
def __init__(self):
self.results_counter=[0]*3
self.percentages=[None]*3
def throw_dice(self):
return randint(1,6)
def attack(self):
offense_dice=sorted([self.throw_dice() for _ in range(3)],reverse=True)
defence_dice=sorted([self.throw_dice() for _ in range(2)],reverse=True)
if verbose:
print(f"{'offense_dice':<30}{offense_dice}")
print(f"{'defence_dice':<30}{defence_dice}")
print(' ')
wins_counter=0
if offense_dice[0]>defence_dice[0]:
wins_counter+=1
if offense_dice[1]>defence_dice[1]:
wins_counter+=1
self.results_counter[wins_counter]+=1
def simulate_attacks(self,num_of_simulations):
self.results_counter=[0]*3 # this will set all results to zero (each new simulation will be independent)
for _ in range(num_of_simulations):
self.attack()
self.percentages=[x/num_of_simulations for x in self.results_counter]
return self.percentages
def __repr__(self):
string=f'2 Wins: {self.percentages[2]} \nTies {self.percentages[1]} \n2 Losses: {self.percentages[0]} '
return string
if __name__ == "__main__":
verbose=False
attack=Risk()
#print(attack.simulate_attacks(10))
print(attack.simulate_attacks(10**4))
print(attack.simulate_attacks(10**5))
print(attack.simulate_attacks(10**6))
print(attack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment