【问题标题】:Rock Paper scissors game-python石头剪刀布游戏-python
【发布时间】:2015-12-06 05:51:39
【问题描述】:

我目前正在制作一款类似石头剪刀布的游戏。为此,我正在考虑使用 randint() 函数来生成随机数。但我想让它变得更好,以便程序记住玩家过去的选择历史并与之对抗。我怎么能这样做?我是初学者,但如果指向正确,我已经准备好学习了。

我已经尝试过在脑海中使用条件概率的概念,但到目前为止它并没有按预期工作。

def probable(model,test_model):
    p={}
    for i in 'rps':
        check_sequence=test_model+i
        if model.count(test_model)==0:
            return -1
        p[i]=(model.count(check_sequence)/model.count(test_model))
    if p[max(p)]==0:
        return -1
    else:
        return max(p)

这里的变量“test_model”包含了玩家过去所做的选择。变量“模型”包含用户所做选择的完整列表。

【问题讨论】:

  • 在你学习的过程中,我不会尝试包。这是第一个想法:对于每个剧本,将其他两个备选方案添加到(python)列表中。然后从该列表中抓取一个随机元素。第一步(空列表)随机回复。

标签: python


【解决方案1】:

您可以简单地使用数组来解决这个问题。例如,如果您为所有随机选择声明一个数组,例如

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!: 

希望我的回答可以理解!

注意:我的解决方案肯定可以升级。这不是最好的,而是简单的。

【讨论】:

  • 不错的解决方案;您可以通过只保留岩石、纸张和剪刀的数量以及来自该分布的样本来提高效率。从分布中采样的一些不错的方法:eli.thegreenplace.net/2010/01/22/…
  • @VikasMenon 谢谢!机器学习技术会牵强附会吗?
猜你喜欢
  • 2016-01-16
  • 2022-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多