Last active
November 11, 2023 13:32
-
-
Save jbdesbas/f8164b97630c36cafe948bbb30fde442 to your computer and use it in GitHub Desktop.
Monty Hall Game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class Door: | |
def __init__(self, name): | |
self.is_winner = False | |
self.is_open = False | |
self.name = name | |
self.is_chosen = False | |
def __repr__(self): | |
if self.is_chosen : | |
symbol = '*' | |
elif self.is_open and not self.is_winner: | |
symbol = ' ' | |
elif self.is_open and self.is_winner: | |
symbol = '!' | |
else : | |
symbol = 'X' | |
return '[' + symbol + ']' | |
class Game(): | |
def __init__(self): | |
self.doors = [Door('A'), Door('B'), Door('C')] | |
self.doors[random.randint(0,2)].is_winner = True | |
def player_choice_door(self, choice): # Player choose a door (by door name) | |
for d in self.doors: | |
if d.name==choice: | |
d.is_chosen=True | |
else : | |
d.is_chosen=False # Reset choice | |
def reset_choice(self): | |
for d in self.doors: | |
d.is_chosen=False | |
def change_door(self): # Change door for non-open door | |
potential_doors = [d for d in self.doors if d.is_chosen == False and d.is_open == False] | |
self.reset_choice() | |
d = random.choice(potential_doors) | |
d.is_chosen = True | |
def animator_reveal_door(self): # Animator reveals a non-chosen and non-winner door | |
potential_doors = [ d for d in self.doors if d.is_chosen == False and d.is_winner == False] | |
d = random.choice(potential_doors) | |
d.is_open = True | |
def is_player_winner(self): # Player choose a winner door | |
if next((x for x in self.doors if x.is_winner and x.is_chosen), False) : | |
return True | |
return False | |
def play_game(strategy): | |
""" | |
Strategy 2 : change door after revelation of non-winner door | |
Stragegy 1 : keep door | |
""" | |
g = Game() | |
g.player_choice_door(random.choice(['A','B','C'])) | |
g.animator_reveal_door() | |
if strategy == 2 : | |
g.change_door() | |
return g.is_player_winner() | |
def percent_win(matrice): | |
i = 0 | |
for v in matrice : | |
if v : | |
i+=1 | |
return i/len(matrice) | |
def play_games(strategy, i=1000): | |
matrice_victoire = [ play_game(strategy) for x in range(0,i) ] | |
return percent_win(matrice_victoire) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment