Python 2.7 如何使随机选择比其他选择更为罕见?
我想做一个基于文本的游戏,你可以在python中挖掘矿石和宝石,我想让它成为一个随机选择,当你键入“我的”时,你会得到什么,你是如何做的,所以一些随机选择比另一个更少 以下是我目前的代码:`Python 2.7 如何使随机选择比其他选择更为罕见?,python-2.7,random,Python 2.7,Random,我想做一个基于文本的游戏,你可以在python中挖掘矿石和宝石,我想让它成为一个随机选择,当你键入“我的”时,你会得到什么,你是如何做的,所以一些随机选择比另一个更少 以下是我目前的代码:` import random, start = raw_input('Welcome to the mining game! Type "Start" to continue. ') if str.upper(start) == ("START"): default_cash = 14 print
import random,
start = raw_input('Welcome to the mining game! Type "Start" to continue. ')
if str.upper(start) == ("START"):
default_cash = 14
print "You have %g cash." % default_cash
choices = raw_input("What would you like to do? Type 'Mine' to dig for ores, or type 'Shop' to go shopping for equipment. ")
if str.upper(choices) == ("MINE"):
ores = ["emerald", "ruby", "silver", "gold", "diamods", "nothing"]
ores_random = random.choice(ores)
print "you found %s!" % ores_random`
您可以使用numpy的选择功能。请注意概率分布是一个按矿石相同顺序排列的序列。如果您不想使用现有进口以外的任何产品,那么简单的解决方案是用以下替代矿石:
ores = ["emerald"]*3+["ruby"]*7+["silver"]*10+["gold"]*20+["diamods"]*20+["nothing"]*40
,乘数越大,项目越少。然而,这不是一个好的解决方案。更好的解决方案是构建一个函数,其中说明了分布:
dist = [3,10,20,40,60,100]
ores = ["emerald", "ruby", "silver", "gold", "diamods", "nothing"]
,您可以生成一个随机整数并检索正确的项:
for i in range(1,len(ores)):
r = random.randint(0,100)
if dist[i-1]<=r<dist[i]:
break
print "you found %s!" % ores[i]
范围内的i(1,len(ores)):
r=random.randint(0100)
如果距离[i-1]可能是
for i in range(1,len(ores)):
r = random.randint(0,100)
if dist[i-1]<=r<dist[i]:
break
print "you found %s!" % ores[i]