2017-02-12 87 views
0

我是新來的python,並試圖寫一個有關上述主題的小項目。岩石,紙和剪刀改進:Python 2.7?

import random 


option = ["rock", "paper", "scissors"]; 
pc_selection = ["rock", "paper", "scissors"]; 
pc_move = random.choice(pc_selection) 

#------------------------------------------------------------------------------- 
def first_condition(): 
    select = raw_input("Please select your choice\n") 
    print "Your choice:", select 
    if select in option: 
     pc_move 
     print "Computer choice:", pc_move 
    else: 
     first_condition() 

    if select == pc_move: 
     print "Result: draw" 
    elif select == "rock" and pc_move == "paper": 
     print "Result: Computer wins" 
    elif select == "paper" and pc_move == "scissors": 
     print "Result: Computer wins" 
    elif select == "scissors" and pc_move == "rock": 
     print "Result: Computer wins" 

    elif select == "rock" and pc_move == "scissors": 
     print "Result: You win" 
    elif select == "paper" and pc_move == "rock": 
     print "Result: You win" 
    elif select == "scissors" and pc_move == "paper": 
     print "Result: You win" 


first_condition() 

我知道我的代碼是不是很有效(最快和最聰明的),所以我的問題是:

哪一部分,我可以修改,使我的項目儘可能短不失其functionaility,即使用其他函數可以減少我的代碼的長度?

謝謝!

+0

http://codereview.stackexchange.com/ – YOU

+1

你是什麼意思?'儘可能高效'?易於修改?理解容易?最小的空間(內存)?最短的時間?等等這些是相互矛盾的要求? ; - /即'規則3:好,快,便宜 - 選兩' –

+0

感謝澄清。我正在尋找的是一個快速而好的代碼,旨在消除儘可能不必要的東西。我現在不覺得正確的是在我的代碼中有太多的elif。 –

回答

0

選項列表中的每個選項都被其前面的選項打敗。如果選擇不同,則可以假定用戶贏得,如果計算機沒有選擇列表中用戶選擇的項目。例如:

import random 

option = ["scissors", "paper", "rock"] # I reversed the original list 
#---------------------------------------------------------------------- 
def first_condition(): 
    pc_move = random.choice(option) # there only needs to be 1 option list 
    select = raw_input("Please select your choice\n") 
    print "Your choice:", select 
    if select in option: 
     print "Computer choice:", pc_move 
    else: 
     return first_condition() 
    if pc_move == select: 
     print("Draw") 
     return 
    # find the index of the user's choice 
    index = option.index(select) 
    # did the pc choose the item before this one?  
    you_win = option[index-1] != pc_move 

    print("You %s" % ("win" if you_win else "lose")) 

while True: 
    print("-"*50) 
    first_condition() 
+0

嗨user2682863。感謝您的解釋,上面的代碼簡潔並具有相同的功能!但是,你能否解釋一下你有「while True」部分的最後部分的原因?擁有它的意圖是什麼? –

+0

我剛剛添加了測試它。我通過幾次迭代來運行它,以確保它按預期工作。 - 如果它解決了您的問題,請隨時接受它作爲答案 – user2682863