#==================================================
# Lecture 23: Randomness and Simulation
#--------------------------------------------------
# Every number on the slides comes from this file.
# Each demo sets its own seed, so a run prints the
# slide's numbers again.

import os
import random

#--------------------------------------------------
# Slides: Dice in Python

# print(random.randint(1, 6))      # 1, 2, 3, 4, 5 or 6: BOTH ends included
# print(random.random())           # a float, 0 <= x < 1
# print(random.choice(['H', 'T'])) # one item of the list

#--------------------------------------------------
# Slide: Bug Hunt 1 (pick who goes first, 8 games)

names = ['Ali', 'Sana', 'Omar']

def pick_buggy():
    return names[random.randint(0, len(names))]    # BUG: can give 3

def pick():
    return names[random.randint(0, len(names) - 1)]
    # or: return random.choice(names)

# for i in range(8):
#     print(pick_buggy())    # works for a while, then IndexError

#--------------------------------------------------
# Slides: Fake Dice (von Neumann's middle-square method, 4 digits)

def middle_square(x):
    """Square x, keep the middle 4 of its 8 digits."""
    s = str(x * x)
    while len(s) < 8:
        s = '0' + s
    return int(s[2:6])

def show_middle_square(x, steps):
    for i in range(steps):
        print(x, end=' ')
        x = middle_square(x)
    print(x)

# show_middle_square(1234, 5)   # 1234 5227 3215 3362 3030 1809
# show_middle_square(5772, 8)   # 5772 3159 9792 8832 42 17 2 0 0
# show_middle_square(4100, 5)   # 4100 8100 6100 2100 4100 8100

#--------------------------------------------------
# Slide: random.seed

# random.seed(7)
# print([random.randint(1, 6) for i in range(8)])   # [3, 2, 4, 6, 1, 1, 5, 1]
# random.seed(7)
# print([random.randint(1, 6) for i in range(8)])   # the same again

#--------------------------------------------------
# Slides: Try It Many Times (two dice make 7)

def chance_of_seven(n):
    hits = 0
    for i in range(n):
        if random.randint(1, 6) + random.randint(1, 6) == 7:
            hits += 1
    return hits / n

def table_seven():
    random.seed(23)
    for n in [10, 100, 1000, 10000, 100000, 1000000]:
        print(n, chance_of_seven(n))
    # exact: 6 / 36 = 0.1667

def dice_sums(n):
    """How many times each total 2..12 came up in n throws."""
    count = [0] * 13
    for i in range(n):
        count[random.randint(1, 6) + random.randint(1, 6)] += 1
    return count[2:]

# Bug Hunt 2: the dice are rolled once, before the loop
def chance_of_seven_buggy(n):
    hits = 0
    a = random.randint(1, 6)            # BUG: rolled once, outside the loop
    b = random.randint(1, 6)
    for i in range(n):
        if a + b == 7:
            hits += 1
    return hits / n

# random.seed(14)
# for i in range(4):
#     print(chance_of_seven_buggy(1000))   # 0.0 0.0 1.0 0.0

def table_sums():
    random.seed(1)
    for n in [100, 1000, 100000]:
        print(n, dice_sums(n))

#--------------------------------------------------
# Slide: Same Recipe, Other Questions (darts)

def estimate_pi(n):
    inside = 0
    for i in range(n):
        x = random.random()
        y = random.random()
        if x*x + y*y <= 1:
            inside += 1
    return 4 * inside / n

def table_pi():
    random.seed(12)
    for n in [100, 1000, 10000, 100000, 1000000]:
        print(n, estimate_pi(n))

# (old Bug Hunt, not on the slides now): whole-number darts land only on the 4 corners
def estimate_pi_buggy(n):
    inside = 0
    for i in range(n):
        x = random.randint(0, 1)        # BUG: 0 or 1, nothing between
        y = random.randint(0, 1)
        if x*x + y*y <= 1:
            inside += 1
    return 4 * inside / n

# random.seed(3)
# for i in range(4):
#     print(estimate_pi_buggy(1000))     # 2.944 2.968 2.948 2.96

#--------------------------------------------------
# Slide: Same Recipe, Other Questions (the frog's random walk)

def walk(steps):
    """Where the frog ends: one step left or right each second."""
    x = 0
    for i in range(steps):
        x += random.choice([-1, 1])
    return x

def average_distance(steps, walks):
    total = 0
    for i in range(walks):
        total += abs(walk(steps))
    return total / walks

def table_walk():
    random.seed(5)
    for steps in [100, 400, 1600, 6400]:
        print(steps, average_distance(steps, 10000))
    # about 0.8 * (square root of steps): steps x4 -> distance x2

#--------------------------------------------------
# Slides: Roll or Stop

def turn_until_one():
    """Roll until a 1 comes up; return every roll (the 1 last)."""
    rolls = []
    while True:
        roll = random.randint(1, 6)
        rolls.append(roll)
        if roll == 1:
            return rolls

# Slides "Play It Now!": the rolls the PDF shows, one per click
# random.seed(1279)
# for i in range(3):
#     print(turn_until_one())   # [6, 4, 5, 3, 3, 3, 1]  [6, 1]  [4, 3, 6, 1]

def turn(hold_at):
    """One turn of Roll or Stop: roll until the turn total reaches hold_at."""
    total = 0
    while total < hold_at:
        roll = random.randint(1, 6)
        if roll == 1:
            return 0
        total += roll
    return total

def turn_traced(hold_at):
    """turn(), but also returns the rolls, for the Shell slide."""
    total = 0
    rolls = []
    while total < hold_at:
        roll = random.randint(1, 6)
        rolls.append(roll)
        if roll == 1:
            return 0, rolls
        total += roll
    return total, rolls

# random.seed(58)
# for i in range(3):
#     print(turn_traced(10))   # (15, [5, 2, 2, 6]) (0, [6, 2, 1]) (10, [2, 4, 4])

# Bug Hunt 3
def turn_buggy(hold_at):
    total = 0
    while total < hold_at:
        roll = random.randint(1, 6)
        if roll == 1:
            break                        # BUG: keeps the points
        total += roll
    return total

def average_turn(f, hold_at, turns):
    """average_points on the slides, with the turn function passed in."""
    total = 0
    for i in range(turns):
        total += f(hold_at)
    return total / turns

def table_turns():
    random.seed(8)
    for h in [5, 10, 15, 20, 25, 30, 35, 40, 100]:
        print(h, average_turn(turn, h, 100000),
                 average_turn(turn_buggy, h, 100000))

def exact_points(hold_at):
    """The average points per turn with endless turns, worked out exactly.
    best[t] = what a turn is worth when it already has t points."""
    best = {}
    for t in range(hold_at + 6, -1, -1):
        if t >= hold_at:
            best[t] = t
        else:
            best[t] = sum(best[t + d] for d in range(2, 7)) / 6   # a 1 adds 0
    return best[0]

def table_exact():
    """The orange curve on the Points per Turn chart, h = 1 to 60."""
    print(' '.join(f'({0.2 * h:.1f},{exact_points(h):.2f})' for h in range(1, 61)))
    # peak: h = 20 and h = 21, both 8.14

def game(hold_a, hold_b):
    """A race to 100. A plays first. Returns 'A' or 'B'."""
    a, b = 0, 0
    while True:
        a += turn(min(hold_a, 100 - a))
        if a >= 100:
            return 'A'
        b += turn(min(hold_b, 100 - b))
        if b >= 100:
            return 'B'

def race(hold_a, hold_b, games):
    """How often A wins; A and B take turns to go first."""
    wins = 0
    for g in range(games):
        if g % 2 == 0:
            if game(hold_a, hold_b) == 'A':
                wins += 1
        else:
            if game(hold_b, hold_a) == 'B':
                wins += 1
    return wins / games

def table_race():
    random.seed(24)
    for other in [10, 15, 25, 30, 40]:
        print(20, 'vs', other, race(20, other, 100000))

#--------------------------------------------------
# Slides: Remember Hangman? (Assignment 2's game, Lecture 20's letter counts)
# Needs Assignment 2's words.txt: put it beside this file.

ABC = 'abcdefghijklmnopqrstuvwxyz'

def load_words():
    here = os.path.dirname(os.path.abspath(__file__))
    for name in ['words.txt', '../../../assignments/a2/starter/words.txt']:
        path = os.path.join(here, name)
        if os.path.exists(path):
            return open(path).read().split()
    print('words.txt is missing: copy it here from Assignment 2')
    return []

def has_player_won(secret_word, letters_guessed):
    """Assignment 2: True if every letter of the word has been guessed."""
    for letter in secret_word:
        if letter not in letters_guessed:
            return False
    return True

def count_letters(text):
    """Lecture 20: a dictionary, letter -> how many times it appears."""
    counts = {}
    for ch in text:
        if ch in ABC:
            if ch in counts:
                counts[ch] += 1
            else:
                counts[ch] = 1
    return counts

def by_count(counts):
    """Lecture 20: the letters, most common first."""
    return sorted(counts, key=lambda ch: counts[ch], reverse=True)

def play(secret, order):
    """One game of Hangman by a player who guesses the letters in this
    order and never looks at the dashes. True for a win."""
    guesses = 10
    guessed = []
    for letter in order:
        guessed.append(letter)
        if letter not in secret:
            if letter in 'aeiou':
                guesses -= 2             # Assignment 2: a wrong vowel costs 2
            else:
                guesses -= 1
        if has_player_won(secret, guessed):
            return True
        if guesses <= 0:
            return False

wordlist = load_words()

def choose_word(wordlist):
    """Assignment 2: a word from the list, at random."""
    return random.choice(wordlist)

def chance_to_win(order, n):
    wins = 0
    for i in range(n):
        word = choose_word(wordlist)
        if play(word, order):
            wins += 1
    return wins / n

def chance_to_win_shuffled(n):
    """The same, for a player who guesses in a new random order each game."""
    wins = 0
    order = list(ABC)
    for i in range(n):
        random.shuffle(order)
        if play(choose_word(wordlist), order):
            wins += 1
    return wins / n

def table_hangman():
    if wordlist == []:
        return
    common = by_count(count_letters(' '.join(wordlist)))
    print(len(wordlist), 'words;', ''.join(common))   # 55900 words; esiarntold...
    random.seed(2)
    print('random order     ', chance_to_win_shuffled(100000))   # 0.01484
    print('most common first', chance_to_win(common, 100000))    # 0.22223

#--------------------------------------------------
# Exit Ticket
# print(random.choice(['ROLL', 'STOP']))

if __name__ == '__main__':
    table_seven()
    table_sums()
    table_pi()
    table_walk()
    table_turns()
    table_exact()
    table_race()
    table_hangman()
