您可以简单地使用数组来解决这个问题。例如,如果您为所有随机选择声明一个数组,例如
choices = ['r', 's', 'p']
如果你在 0 和 len(choices) 之间随机整数,它会选择其中之一。如果您想记住过去的选择,您可以简单地将每个选择添加/删除到数组中。比如玩家玩'r',你可以在选项中加上'p',被选中的概率会增加。
choices.append('p')
现在你的选择数组是这样的
['r', 's', 'p', 'p']
但是每次你需要检查数组中是否至少有'r'、's'和'p'之一。此外,如果您将相同的选项添加到此数组中,它可能会选择最后添加的选项。所以你可能需要调整概率数组。
这是我的解决方案:
import random
probs = ['r', 's', 'p']
opposites = {'r':'p', 'p':'s', 's':'r'}
beats = {'r':'s', 'p':'r', 's':'p'}
def controlProbs():
if 'r' not in probs:
probs.append('r')
if 's' not in probs:
probs.append('s')
if 'p' not in probs:
probs.append('p')
def adjustProbs(choice):
if len(probs) > 20:
probs.remove(choice)
controlProbs()
else:
probs.append(beats[choice])
def pick():
index = random.randint(0, len(probs)-1)
return probs[index]
def controlInput(player):
if len(player) != 1 or player not in 'rsp':
return False
return True
while True:
player = raw_input("Pick your equipment!: ")
if not controlInput:
print "Please choose a valid one! (r, s, p)"
continue
computer = pick()
print "My choice is: " + computer
if opposites[player] == computer:
print "You beat me!"
elif opposites[computer] == player:
print "I beat you!"
else:
print "Tie :)"
#Here is adjusting probobalities
adjustProbs(player)
对于这个解决方案,你会得到这样的输出:
Pick your equipment!: r
My choice is: p
You beat me!
Pick your equipment!: r
My choice is: p
You beat me!
Pick your equipment!: r
My choice is: p
You beat me!
Pick your equipment!: r
My choice is: p
You beat me!
Pick your equipment!: r
My choice is: s
I beat you!
Pick your equipment!: r
My choice is: s
I beat you!
Pick your equipment!: r
My choice is: s
I beat you!
Pick your equipment!:
希望我的回答可以理解!
注意:我的解决方案肯定可以升级。这不是最好的,而是简单的。