#! /usr/bin/env python3

"""Simulates a simple version of the Gambler's Ruin predicament: even if you
start with a good pile of money, if you bet for long enough 

"""

import sys
import random

def main():
    assert len(sys.argv) == 1 or len(sys.argv) == 4
    initial_money = 100.0       # starting purse
    # coin flip odds - 0.5 is perfectly fair; 0.3 is bad for us; 0.6
    # is good for us
    flip_odds = 0.5
    bet_base = 2.0
    if len(sys.argv) == 4:
        initial_money = float(sys.argv[1])
        flip_odds = float(sys.argv[2])
        bet_base  = float(sys.argv[3])
    max_n_bets = 10000000
    duration = do_betting_sequence(bet_base, initial_money, flip_odds,
                                   max_n_bets, False)
    print(f'flip_odds_and_duration: {flip_odds}   {duration}')
    print()

def do_betting_sequence(bet_base, initial_money, flip_odds, max_n_bets,
                        silent=False):
    """Carry out a sequence of bets, at most max_n_bets of them, for
    coin/roulette with odds given by flip_odds (0.5 is fair; less than 0.5
    means the house has an advantage; more than 0.5 means that we have an
    advantage).  The basic bet is bet_base, and we start with initial_money.

    """
    current_money = initial_money
    bet_amount = bet_base
    assert(bet_amount <= initial_money)
    bet_result = 0
    if not silent:
        print(f'# iteration bet_result current_money')
    for i in range(max_n_bets):
        do_martingale = False
        if do_martingale:
            # try martingale betting: double after a loss
            if bet_result < 0:
                bet_amount *= 2
            else:
                bet_amount = bet_base
        bet_result = make_bet(current_money, bet_amount, flip_odds)
        current_money += bet_result
        if not silent:
            print(f'{i}   {bet_result}   {current_money}')
        if current_money <= 0:
            if not silent:
                print('#RUIN!! no money left for betting')
            return i
    return max_n_bets

def make_bet(current_money, bet_amount, flip_odds):
    """Put the given amount into a coin bet with the given flip odds;
    return how much money we earned (if positive) or lost (if negative)."""
    rand_no = random.random()
    # print(f'# {rand_no}   {flip_odds}')
    if rand_no < flip_odds:
        bet_result = bet_amount
    else:
        bet_result = -bet_amount
    return bet_result

if __name__ == '__main__':
    main()
