如何使用词典?

时间:2017-11-06 05:49:31

标签: python dictionary

我正在尝试制作字典岩石剪刀的游戏,我打算使用很多if和elif,但我的CS Lab技术告诉我,我可以在python中使用字典。我怎么用它来制作一个石头剪刀游戏?

我的计划是使用一个功能,从列表中拉出一个字母,然后尝试比较游戏中的胜利是否胜出"胜利"如果损失说明"损失"如果打印平局" tie"并询问你是否想再玩一次。但就我而言,那就是。

1 个答案:

答案 0 :(得分:2)

假设有两名球员,有三种可能的最终状态(胜利,失败,平局)和九种不同的结果(摇滚,剪刀等)。如果你想把它作为字典来做,你可以创建三个键 - 每个最终游戏状态一个 - 其中每个值是一个列表,其中包含导致该结果的可能游戏。这些游戏可以存储为有序对,其中元组的第一个值代表玩家的选择而第二个值是对手的选择。例如,所有可能的胜利状态的键值对将如下:

"win" : [("rock", "scissors"), ("paper", "rock"), ("scissors", "paper")]

获得所有可能游戏的dict之后,只需迭代每个最终状态键并检查tuple选项是否由{玩家和对手包含在与该键相关联的list值内。如果是,那么你已经找到了游戏的结果。

考虑到这一点,您可以执行以下操作:

from random import choice

answers = {"yes" : ["yes", "y"],
           "no"  : ["no",  "n"]}

choices = ["rock", "paper", "scissors"]

games = {"win"  : [(choices[0], choices[2]), 
                   (choices[1], choices[0]), 
                   (choices[2], choices[1])],

         "lose" : [(choices[0], choices[1]), 
                   (choices[1], choices[2]), 
                   (choices[2], choices[0])],

         "tie"  : [(choices[0], choices[0]), 
                   (choices[1], choices[1]), 
                   (choices[2], choices[2])]}

print("Let's play \"Rock, paper, scissors\"!\n")

replay = True

while replay:

    player = ""

    while player.lower() not in choices:

        player = input("Rock, paper, or scissors?: ")

    opponent = choice(choices)

    print("You chose {}.".format(player.lower()))
    print("Your opponent chose {}.".format(opponent))

    for outcome in games:

        if (player.lower(), opponent) in games[outcome]:

            print("You {} against your opponent!\n".format(outcome))

    replay_decision = ""

    while replay_decision.lower() not in (answers["yes"] + answers["no"]):

        replay_decision = input("Would you like to play again? [y/n]: ")

        if replay_decision.lower() in answers["no"]:

            replay = False

print("\nThanks for playing!")

产生以下样本输出:

Let's play "Rock, paper, scissors"!

Rock, paper, or scissors?: rock
You chose rock.
Your opponent chose rock.
You tie against your opponent!

Would you like to play again? [y/n]: y
Rock, paper, or scissors?: paper
You chose paper.
Your opponent chose rock.
You win against your opponent!

Would you like to play again? [y/n]: y
Rock, paper, or scissors?: scissors
You chose scissors.
Your opponent chose paper.
You win against your opponent!

Would you like to play again? [y/n]: n

Thanks for playing!