2014-10-09 41 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)] 

您需要處理相同選擇的情況(就像您已經這樣做了)。