Home > other >  Roulette simulation in Python
Roulette simulation in Python

Time:10-16

I am practicing in Python and I decided to create a simple roulette simulation with colors only for now. However, I also wanted to make it possible to bet on color. But it seems like I did something wrong, since for some reason I can't use the global variable 'balance' in one of the function. Also, I didn't come up with the idea of how to make bet a global variable. I tried to take it out so that it become the global variable with input function, however in this case it has the same issue as with balance variable.

import random

balance = 100

# user decides how much they will bet
def start():
    print("Place your bet:")
    bet = int(input(">"))
    if bet > balance:
        insufficient_funds()
    else:
        simulate()

# if user placed too much
def insufficient_funds():
    print("Oops, your don't have enough funds to place a bet")
    start()

# color choose and roulette simulation
def simulate():
    print("Choose Red or for Black:")
    answer = input("> ")
    result = random.randint(1, 2)
    if result == 1 and answer == "Red":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start()
    elif result == 2 and answer == "Black":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start()
    else:
        print("You lost!")
        balance -= bet
        print(f"Your balance now {balance}")
        start()

start()

I know it is super basic, but for now I try to make it as simple as possible to practice with python's fundamental things w/o using a lot of modules. I'd extremely appreciate if you could help me out with it.

CodePudding user response:

Your code is awesome. I'm pretty new to python as well. One thing I noticed is that you aren't passing in the bet and balance variables as parameters into the functions.

By passing balance as a parameter in the simulate() function, it will allow the value of balance to be changed; it's called passing by reference.

Try this:

import random

balance = 100

# user decides how much they will bet
def start(balance):
    print("Place your bet:")
    bet = int(input(">"))
    if bet > balance:
        insufficient_funds()
    else:
        simulate(balance, bet)

# if user placed too much
def insufficient_funds():
    print("Oops, your don't have enough funds to place a bet")
    start(balance)

# color choose and roulette simulation
def simulate(balance, bet):
    print("Choose Red or for Black:")
    answer = input("> ")
    result = random.randint(1, 2)
    if result == 1 and answer == "Red":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start(balance)
    elif result == 2 and answer == "Black":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start(balance)
    else:
        print("You lost!")
        balance -= bet
        print(f"Your balance now {balance}")
        start(balance)

start(balance)

As mentioned in the comment, you could also type global balance at the beginning of your start() and simulate() functions.

import random

balance = 100

# user decides how much they will bet
def start():
    global balance
    print("Place your bet:")
    bet = int(input(">"))
    if bet > balance:
        insufficient_funds()
    else:
        simulate()

# if user placed too much
def insufficient_funds():
    print("Oops, your don't have enough funds to place a bet")
    start()

# color choose and roulette simulation
def simulate(bet):
    global balance
    print("Choose Red or for Black:")
    answer = input("> ")
    result = random.randint(1, 2)
    if result == 1 and answer == "Red":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start()
    elif result == 2 and answer == "Black":
        print("You won")
        balance  = bet
        print(f"Your balance now {balance}")
        start()
    else:
        print("You lost!")
        balance -= bet
        print(f"Your balance now {balance}")
        start()

start()

This is how you let Python know you're calling a global variable. Either way, however, you'd need to pass at least the bet variable in the simulate() function.

CodePudding user response:

Your functions should isolate levels of concerns that are semantically meaningful. This would make the code easier to understand and maintain. The process can be decomposed into:

  • A betting phase where the user selects a pocket and bet amount
  • A rolling phase where the ball is rolled and falls in a random pocket
  • A game loop to repeatedly go through the phases and update wins & losses.

Each function should be standalone and perform its work without affecting data outside of it (i.e. no global variable). This will allow testing the "phase" functions independently before putting them together in the main loop. If you find any issue while testing these functions, you will know that there is no dependencies from external states so the problem is in the limited scope of the function itself.

Here's an example:

Rolling Phase...

from random import choice
from time import sleep

# CONSTANTS
pockets = ["00"] [str(n) for n in range(37)]
groups  = ["Red","Black","Even","Odd","Low","High"]
reds    = [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32,34,36]

def roll():
    print("Rolling! ... ", end="")
    sleep(2)
    number  = choice(pockets)
    N       = int(number)
    color   = "" if N<1 else "Red" if N in reds else "Black"
    oddEven = "" if N<1 else "Odd" if N%2       else "Even"
    lowHigh = "" if N<1 else "Low" if N<=18     else "High"
    print(number, color)
    return number,color,oddEven,lowHigh

Betting Phase...

def placeBet(maxAmount):
    while True:
        playerChoice = input("Pocket number or group: ")
        if playerChoice not in pockets   groups:
            print("must chose a number (00,0,1..36)")
            print("or group (Red, Black, Odd, Even, Low, High)")
        else: break
    while True:
        betValue = input("Amount to bet: ")
        try:
            betValue = int(betValue)
            if betValue <= maxAmount: break
            print("Not enough funds")
        except ValueError:
            print("invalid number")
    return playerChoice, betValue

Main game loop...

def playRoulette(balance=100):
    while balance:
        pocket, amount = placeBet(balance)
        if pocket in roll():
            print("You win!")
            balance  = amount  # or balance  = payBack(pocket,amount)
        else:
            print("You lose!")
            balance -= amount
        print(f"Your balance is now {balance}")
    print("Game Over!")

Winning payback could be computed in a separate function if you want to make it dependent on the odds of the selected pocket (e.g. a specific number is 35 to 1; Red, Even, ... are 1 to 1 bets)

Testing

roll()
Rolling! ... 6 Black
('6', 'Black', 'Even', 'Low') 

roll()
Rolling! ... 33 Black
('33', 'Black', 'Odd', 'High')

placeBet(50)
Pocket number or group: green
must chose a number (00,0,1..36)
or group (Red, Black, Odd, Even, Low, High)
Pocket number or group: 99
must chose a number (00,0,1..36)
or group (Red, Black, Odd, Even, Low, High)
Pocket number or group: Red
Amount to bet: xxx
invalid number
Amount to bet: 65
Not enough funds
Amount to bet: 24
('Red', 24)

Sample run

playRoulette()

Pocket number or group: Red
Amount to bet: 10
Rolling! ... 2 Black
You lose!
Your balance is now 90
Pocket number or group: Black
Amount to bet: 25
Rolling! ... 12 Black
You win!
Your balance is now 115
Pocket number or group: 00
Amount to bet: 120
Not enough funds
Amount to bet: 115
Rolling! ... 9 Red
You lose!
Your balance is now 0
Game Over!
  • Related