|
| 1 | +# Monty Hall Problem |
| 2 | +import random |
| 3 | + |
| 4 | + |
| 5 | +def message(): |
| 6 | + print('Game Rules & How to play:') |
| 7 | + print('1.\tThere are three doors.') |
| 8 | + print('2.\tPrize is present only behind one of the doors.') |
| 9 | + print('3.\tYou have to choose one of the doors, numbered (1, 2, 3).') |
| 10 | + print('4.\tThen the host will open one of the empty doors (excluding your choice).') |
| 11 | + print('5.\tAfter that you will be asked again for your choice.') |
| 12 | + print('6.\tIf your final choice is same as door hiding prize, you win.') |
| 13 | + print('\n') |
| 14 | + |
| 15 | +def initPrize(): |
| 16 | + return random.randint(1, 3) |
| 17 | + |
| 18 | + |
| 19 | +def hostOpens(prize, choice): |
| 20 | + door = [] |
| 21 | + |
| 22 | + for i in range(1, 4): |
| 23 | + if i not in (prize, choice): |
| 24 | + door.append(i) |
| 25 | + |
| 26 | + k = random.randint(0, len(door) - 1) |
| 27 | + return door[k] |
| 28 | + |
| 29 | + |
| 30 | +def montyHallGame(): |
| 31 | + print('\n\nStarting new game...\n') |
| 32 | + |
| 33 | + prize = initPrize() |
| 34 | + choice = int(input('Enter door to open\t: ')) |
| 35 | + if choice not in range(1, 4): |
| 36 | + raise ValueError |
| 37 | + |
| 38 | + open = hostOpens(prize, choice) |
| 39 | + print('Host opened door\t:', open) |
| 40 | + |
| 41 | + choice = int(input('\nOpen door\t: ')) |
| 42 | + if choice not in range(1, 4): |
| 43 | + raise ValueError |
| 44 | + |
| 45 | + print('Prize at\t:', prize) |
| 46 | + if choice == prize: |
| 47 | + return 1 |
| 48 | + return 0 |
| 49 | + |
| 50 | + |
| 51 | +def main(): |
| 52 | + message() |
| 53 | + |
| 54 | + while True: |
| 55 | + try: |
| 56 | + i = montyHallGame() |
| 57 | + if i: |
| 58 | + print('Congratulations, You won the prize!!!') |
| 59 | + else: |
| 60 | + print('Oops, You lost the prize...') |
| 61 | + |
| 62 | + exit = input('\nPress "1" to exit: ') |
| 63 | + if exit == '1': |
| 64 | + break |
| 65 | + |
| 66 | + except: |
| 67 | + print('\nWrong input, exiting...') |
| 68 | + break |
| 69 | + |
| 70 | + print('\n---Thank You for playing---\n') |
| 71 | + |
| 72 | + |
| 73 | +main() |
0 commit comments