Python赌博游戏打印/数学



因此,我在输出时再次遇到此代码的问题。基本上,我需要它打印一些关键功能,但每当我设法让它打印一件东西时,它就会完全打乱其余的打印工作。例如,如果有意义的话,我需要它来打印Roll # 1 (1 - 3) was (whatever number)而不是Roll (whatever number)。但我也需要它最多只能滚动3个。这就是我的第二期;每当我试图将其编码为在用户没有匹配任何滚动时从银行中减去赌注时,它就会将我的减法计算为第四次滚动,并破坏数学运算。因此,从Roll #1#3,现在是Roll #4我的第三个问题是,我需要程序继续循环,直到用户输入0 (zero)结束脚本或银行金额达到0 (zero)

您应该重新设计您的程序。首先,您在为每个条件检查生成新的结果

if guess == rollDice():
bank = bet * 2
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank

您的代码没有正确缩进。

[...]
elif guess == rollDice():
bank += bet * .5
elif guess == rollDice():
bank = bank
else:
guess != rollDice()
bank = bank - bet
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')

等等…


有一个模拟单掷骰子的功能,比如:

def roll():
return random.randint(1, 6)

并在您的主要功能中处理其余部分,如:

prog_info()
while True: #main loop
rolls = list() #redefines after each loop
score = 2
for i in range(3): #3 dice roll
bank, bet = total_bank(bank)
guess = get_guess()
if not guess: #exit condition
break
rolls.append(roll())
if sum(rolls) == guess:
bank = bet * score
break #break on match
score = score - 0.5 #after each roll we have less money to win
print(f'You have ${bank} in your bank.')
print(f'Thanks for playing!')


几次更改会得到您想要的结果

  • 将滚动计数传递给rollDice函数
  • 在if块的底部添加一个else以检查0存储体

这是更新后的代码:

import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def prog_info():
print("My Dice Game .v02")
print("You have three rolls of the dice to match a number you select.")
print("Good Luck!!")
print("---------------------------------------------------------------")
print(f'You will win 2 times your wager if you guess on the 1st roll.')
print(f'You will win 1 1/2 times your wager if you guess on the 2nd roll.')
print(f'You can win your wager if you guess on the 3rd roll.')
print("---------------------------------------------------------------")
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0': 
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
while True:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet  # no match
if bank == 0: 
print('You have no money left. Thanks for playing!')
exit()

输出

You have $500 in your bank.
Enter your bet (or 0 to quit): 500
Choose a number between 2 and 12: 4
Roll # 1 was 11
Roll # 2 was 6
Roll # 3 was 7
You have no money left. Thanks for playing!

最新更新