我正在使用 Python 进行练习,我决定暂时仅使用颜色创建一个简单的轮盘赌模拟。然而,我也想让押注颜色成为可能。但似乎我做错了什么,因为由于某种原因我无法在其中一个函数中使用全局变量“balance”。另外,我没有想到如何使 bet 成为全局变量。我尝试将其取出,使其成为具有输入函数的全局变量,但是在这种情况下,它与平衡变量具有相同的问题。
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 知道您正在调用全局变量的方式。为了避免变量阴影,我们可以在
bet
函数中使用 start
,然后当我们在 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!
非常感谢https://stackoverflow.com/users/5237560/alain-t
我更新了您的脚本,添加了第 1 个 12、第 2 个 12、第 3 个 12 以及 Line1、Line2、Line3 和每轮多个投注。
from random import choice
from time import sleep
pockets = ["00"]+[str(n) for n in range(37)]
groups = ["Red","Black","Even","Odd","Low","High","1st12","2nd12","3rd12","Line1","Line2","Line3"]
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"
twelveThird = "" if N<1 else "1st12" if N<=12 else "2nd12" if N<=24 else "3rd12"
twelveLine = "" if N<1 else "Line1" if (N - 1) % 3 == 0 else "Line2" if (N - 2) % 3 == 0 else "Line3"
print(number, color)
return number,color,oddEven,lowHigh,twelveThird,twelveLine
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, 1st12, 2nd12, 3rd12, Line1, Line2, Line3)")
else: break
while True:
betValue = input("Amount to bet: ")
try:
betValue = int(betValue)
if betValue <= maxAmount: break
print("Not enough funds")
print("Funds Available: " + str(maxAmount))
except ValueError:
print("invalid number")
return playerChoice, betValue
def playRoulette(balance=100):
placingBets = True
while balance:
#while placingBets:
anyMoreBets = "Y"
betSpread = []
remainingBalance = balance
while anyMoreBets == "Y":
if balance > 0:
betPlaced = placeBet(balance)
remainingBalance -= betPlaced[1]
betSpread.append(betPlaced)
print(betSpread)
if remainingBalance > 0:
anyMoreBets = input("Any More Bets? \n Type Y to add more: ")
else:
50
anyMoreBets = "Balance depleted"
rollResult = roll()
for each in betSpread:
pocket = each[0]
amount = each[1]
if pocket in rollResult:
match pocket:
case "Red" | "Black" | "Even" | "Odd" | "Low" | "High":
payOut = amount
case "1st12" | "2nd12" | "3rd12" | "Line1" | "Line2" | "Line3":
payOut = amount*2
case _:
payOut = amount*35
print("Bet: " + pocket + " | Stake: " + str(amount) + " | Win: " + str(payOut))
balance += payOut
else:
print("Bet: " + pocket + " | Stake: " + str(amount) + " | Lose")
balance -= amount
print(f"Your balance is now {balance}")
print("Game Over!")
playRoulette(100)