2014-10-09 62 views
2

所以,我在python中制作这个游戏。事情是,在剪刀,纸和摇滚中,可以有不同的组合。例如,岩石和纸,岩石和剪刀等等。那么,如何做到这一点,而不用做一堆elif语句。Python - 剪刀,纸和摇滚游戏

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语句或输入更少的代码。当然,处理这些类型的事情必须有一个更好的编程序列?

+0

'如果“剪刀”或“纸”或“摇滚”不player_input'赢得”不要做你期望的事情。 – Tim 2014-10-09 07:28:36

+0

你首先警惕流氓用户输入将立即返回'剪刀',你可能想'player_input'不在['Scissors'中]。我也会把它封装在一个循环中,所以当*用户一直给你垃圾输入时,你一直在问你想要什么(现在,如果'if'是正确的),你只问两次。 – 2014-10-09 07:28:59

+0

我一直在SO上一遍又一遍地看到这个问题。我已经回答了过去,但只是发现删除的问题,但现在不知道它是否是直接从编程任务 – Spade 2014-10-09 07:39:58

回答

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() 
+0

谢谢,但你能解释一下这套设备的用途吗? – user3818650 2014-10-09 07:39:39

+2

小调:Python 2.7+和3.1+支持设置字面值,所以我可能更喜欢'{('Scissors','Paper'),...}'set over([(...),.. 。])' – 2014-10-09 07:40:05

+1

@ user3818650 [一组(Python文档)](https://docs.python.org/3/tutorial/datastructures.html#sets)是可哈希对象的无序集合。把它想象成一个字典,但没有值(':'后面的位)。它们可能是用于'in'运算符的最合适的数据类型,因为它们具有不变的查找时间。 – 2014-10-09 07:41:38

1

如何做地图的可能的结果:

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

(请注意,密钥必须是元组)。然后用这样的方式查找:

player_wins = a_beats_b[(player_input, random_choice)] 

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

相关问题