Untitled
import random from typing import Callable FINISH_LINE = 30 PLAYER_NUMBER = 4 def roll_dice(player: int) -> int: return random.randint(1, 3) def roll_dice_cheat(player: int) -> int: if player > 0: return random.randint(0, 3) return random.randint(1, 3) def has_win(position: int): return position >= FINISH_LINE ROLLFUNC = Callable[[int], int] def normal_game(roll_func: ROLLFUNC) -> bool: """Return true if the player won, false otherwise""" player_positions = [0 for _ in range(PLAYER_NUMBER)] player = 0 while True: player_pos = player_positions[player] player_pos = player_pos + roll_func(player) player_positions[player] = player_pos # print(player_positions) if has_win(player_pos): return player == 0 player = (player + 1) % 4 def compute_stats(func: ROLLFUNC, samples: int = 1_000_000): won = 0 for _ in range(int(samples)): won += int(normal_game(func)) return float(won)/samples if __name__ == "__main__": print(compute_stats(roll_dice), compute_stats(roll_dice_cheat))
Leave a Comment