[英]Printing / math on Python gambling game?
所以我在输出时再次遇到了这段代码的问题。 基本上,我需要它来打印一些关键功能,但是每当我设法让它打印一件事时,它就会完全弄乱其余的打印。 因此,例如,如果有意义的话,我需要它打印Roll # 1 (1 - 3) was (whatever number)
not Roll (whatever number)
。 但我也需要它最多只能卷到 3 卷。 这是我的第二个问题出现的地方; 每当我尝试对其进行编码以在用户不匹配任何掷骰时从银行中减去赌注时,它会将我的减法计算为第四次掷骰并搞砸数学。 因此,而不是从Roll #1
到#3
Roll #4
现在到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
函数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!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.