pythongambling

Python printing list of floats given the range


I'm trying to emulate a really simple version of the gamble game "Crash", where there's a number that increases every second and it's also the multiplier of your credits. So if you put in 50 credits and the multiplier goes to 3.30, you will get 50*3.30=165 credits. The number randomly crashes, and if you did not withdraw your money, you lose them.

from random import randrange, randint

crash_max_range = 50
crash_min_range = 0

multiplier_crash = list(range(crash_min_range, crash_max_range))
multiplier_crash = [float(i) for i in multiplier_crash]
print(*multiplier_crash, sep="\n")

The main thing that i'm struggling with is printing the float list which should look like

0
0.01
0.02
0.03

etc.. (every number on a new line) I don't also know how to increase the chance that it will crash like 70% of the time at a low range because obviously the player can't always win. Could you help me with that?


Solution

  • For a simulation you would normally use a loop that does one step at a time. I suggest using an infinite loop and a break statement on a random condition.

    Inside this loop you will only need to print a single value in every print. You should use the str.format() method for any new code.

    The code might then look like this:

    import random
    
    multiplier = 1.00
    while True:
        print('{:.2f}'.format(multiplier))
        if random.random() < 0.1:
            break
        multiplier += 0.01
    print('CRASH')
    

    The above example is not perfect, because floating point errors accumulate when it is run for a long time. It might be better to use an integer and scale it for output.

    Using itertools you can do it like this.

    import itertools
    import random
    
    for i in itertools.count(100):
        multiplier = float(i) / 100.0
        print('{:.2f}'.format(multiplier))
        if random.random() < 0.1:
           break
    print('CRASH')
    

    This could be further simplified using generator expressions. However, the code might be less clear when you are just beginning pyhton.

    import itertools
    import random
    
    for multiplier in (float(i) / 100.0 for i in itertools.count(100)):
        print('{:.2f}'.format(multiplier))
        if random.random() < 0.1:
           break
    print('CRASH')