import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
我正在尝试制作一台非常基本的老虎机。
我的问题是:如何使生成器功能重复3次并返回3个输出,然后如何让它识别某些组合?
这是否可行,与我目前的格式保持一致?
另外,我如何将数组合并到我的代码中? 感谢
答案 0 :(得分:2)
生成三个值后,生成器返回三个值的列表或元组,使用random.choice()
而不是random.random()
也会更容易。 random.choice()
随机选择一个元素列表值/迭代,所有元素的概率相等。示例 -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
如果你想为不同的元素设置不同的概率,你可以保留当前的方法,只需循环三次,然后像上面那样追加ret
并从中返回ret
。
然后在你的win函数中,保留一个字典,使得键是组合的元组,值是用户获胜的数量,然后你可以简单地使用默认值为0的.get()
来获取用户赢了多少。不要传递generator
作为参数。示例 -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
然后在您的主循环中,调用此win()
函数滚动并查看用户赢得了多少。
答案 1 :(得分:1)
使用范围功能选择3次并将其存储在列表中。
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list