Python - 剪刀,纸和摇滚游戏

时间:2014-10-09 07:26:17

标签: python random input user-input

所以,我正在用python制作这个游戏。事情是,在剪刀,纸和岩石中可以有不同的组合,如岩石和纸,岩石和剪刀等。那么如果不做大量的elif陈述,我怎么能做到这一点。

import random
random_choice = ["Scissors", "Paper", "Rock"][random.randint(0, 2)]

player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in ["Scissors", "Paper", "Rock"]:
      print("Not valid choice")
      raw_input()
      exit()

if player_input == random_choice:
      print("You both choose %s" % random_choice)
elif player_input == "Rock" and random_choice == "Scissors":
      print("You picked Rock and the bot picked Scissors, you win!")
      raw_input()
#And so on making heaps of elif's for all the combinations there can be.

那么我们如何制作这个游戏而不必做那么多的elif语句或输入更少的代码。当然,必须有一个更好的编程序列来处理这些类型的东西?

2 个答案:

答案 0 :(得分:2)

如果您想避开elif树,可以使用一套来存储所有获胜组合:

import random

# random.choice is a convenient method
possible_choices = ["Scissors", "Paper", "Rock"]
random_choice = random.choice(possible_choices)

# set notation, valid since Python 2.7+ and 3.1+ (thanks Nick T)
winning = {("Scissors", "Paper"), ("Paper", "Rock"), ("Rock", "Scissors")}

player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in possible_choices:
      print("Not valid choice.")
      raw_input()

if player_input == random_choice:
      print("You both choose %s" % random_choice)
elif (player_input, random_choice) in winning:
      print("You picked %s and the bot picked %s, you win!" % (player_input, random_choice))
else:
      print("You picked %s and the bot picked %s, you lose!" % (player_input, random_choice))

raw_input()

答案 1 :(得分:1)

如何制作可能结果的地图:

a_beats_b = {('Scissors', 'Paper'): True,
             ('Scissors', 'Rock'):  False,
             ...

(注意,键必须是元组)。然后像这样进行查找:

player_wins = a_beats_b[(player_input, random_choice)]

你需要处理相同选择的情况(就像你已经做的那样)。