繁体   English   中英

Python中的轮盘模拟

[英]Roulette simulation in Python

我正在用 Python 练习,我决定现在只用颜色创建一个简单的轮盘模拟。 但是,我也想让投注颜色成为可能。 但似乎我做错了什么,因为出于某种原因,我无法在其中一个函数中使用全局变量“平衡”。 此外,我没有想出如何将投注设为全局变量的想法。 我试图将其取出,使其成为具有输入函数的全局变量,但是在这种情况下,它与平衡变量存在相同的问题。

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()

我知道它是超级基础的,但现在我尝试尽可能简单地使用大量模块来练习 python 的基本知识。 如果你能帮我解决这个问题,我将不胜感激。

你的代码很棒。 python 的工作方式,你必须通过使用global关键字明确告诉它你将使用一个全局变量。 如果不这样做,它将在函数内创建一个新的局部变量。 尝试:

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(bet)

# 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_amount):
    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_amount
        print(f"Your balance now {balance}")
        start()
    elif result == 2 and answer == "Black":
        print("You won")
        balance += bet_amount
        print(f"Your balance now {balance}")
        start()
    else:
        print("You lost!")
        balance -= bet_amount
        print(f"Your balance now {balance}")
        start()

start()

这就是你让 Python 知道你正在调用一个全局变量的方式。 为了避免变量遮蔽,我们可以在start函数中使用bet ,然后当我们在simulate函数中调用它时,我们会告诉它我们需要一个bet_amount

您的函数应该隔离在语义上有意义的关注点级别。 这将使代码更易于理解和维护。 该过程可以分解为:

  • 用户选择口袋和下注金额的下注阶段
  • 滚动阶段,球滚动并落入随机袋中
  • 一个游戏循环,反复经历各个阶段并更新输赢。

每个函数都应该是独立的,并且在不影响其外部数据的情况下执行其工作(即没有全局变量)。 这将允许在将它们放在主循环中之前独立测试“阶段”功能。 如果您在测试这些函数时发现任何问题,您就会知道没有来自外部状态的依赖,因此问题在函数本身的有限范围内。

下面是一个例子:

滚动阶段...

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

投注阶段...

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

主游戏循环...

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!")

如果您想让它取决于所选口袋的赔率,则可以在单独的函数中计算获胜回报(例如,特定数字是 35 比 1;红色、偶数……是 1 比 1 的赌注)

测试

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)

样品运行

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!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM