# GamTrials.py
'''
  Gambler's Ruin Problem
  Specify p, i, N (prob, start pos, win pos)
  The game is run NUM_TRIALS times, and the
  fraction of wins is reported.
  A graph is also drawn, showing the time to
  win/lose, an average time for the trials.

  inputs: 0.6
          2 10

  inputs: 0.49
          2 10
'''

import random
import statistics
import matplotlib.pyplot as plt


NUM_TRIALS = 1000

def gamble(p, start, N):
  t = 0
  pos = start
  while (pos > 0) and (pos < N):
    r = random.choices(['win', 'lose'], [p, 1-p])
    t += 1
    if r[0] == 'win':
      pos += 1
    else:
      pos -= 1
  return t, (pos == N)


p = float( input("p? "))
i, N = map(int, input("i, N? ").split())
ts = []
numWins = 0
for _ in range(NUM_TRIALS):
  time, isWin = gamble(p, i, N)
  if isWin:
    numWins += 1
  ts.append(time)
print(f"Win Prob: {(numWins/NUM_TRIALS):.2f}")
avg = statistics.mean(ts)
std = statistics.stdev(ts)
print(f"Average time: {avg:.1f}; stdev: {std:.1f}")
plt.axhline(y=avg, color='r', linestyle='--')

plt.plot(ts)
plt.title(f"Gambler's Ruin (p={p},i={i},N={N})")
plt.xlabel('Trials')
plt.ylabel('Times to win/lose')
plt.show()
