2015-10-17 44 views
0

我目前相當堅持這個石頭,紙張,剪刀程序,並會非常感謝一些幫助。我通過其他職位關於岩石,紙張,剪刀程序,但我仍然堅持。Rock-Paper-Scissors遊戲

我目前收到的錯誤是當我要求用戶選擇'Rock','Paper'或'Scissors'時,它會不斷詢問它幾次,然後我得到一個錯誤。另外,在我看來,我看到的很大一部分帖子都涉及到我在課堂上沒有用過的概念,所以我對它們並不滿意。

 choices = [ 'Rock', 'Paper', 'Scissors' ] 
# 1. Greetings & Rules 
def showRules(): 
    print("\n*** Rock-Paper-Scissors ***\n") 

    print("\nEach player chooses either Rock, Paper, or Scissors." 
      "\nThe winner is determined by the following rules:" 
      "\n Scissors cuts Paper -> Scissors wins" 
      "\n Paper covers Rock  -> Paper wins" 
      "\n Rock smashes Scissors -> Rock wins\n") 

# 2. Determine User Choice 
def getUserChoice(): 
    usrchoice = input("\nChoose from Rock, Paper or Scissors: ").lower() 
    if (usrchoice not in choices): 
     usrchoice = input("\nChoose again from Rock, Paper or Scissors: ").lower() 
    print('User chose:', usrchoice) 
    return usrchoice 

# 3. Determine Computer choice 
def getComputerChoice(): 
    from random import randint 
    randnum = randint(1, 3) 
    cptrchoice = choices(randnum) 
    print('Computer chose:', cptrchoice) 
    return randnum 

# 4. Determine Winner 
def declareWinner(user, computer): 
    if usrchoice == cptrchoice: 
     print('TIE!!') 
    elif (usrchoice == 'Scissors' and cptrchoice == 'Rock' 
     or usrchoice == 'Rock' and cptrchoice == 'Paper' 
     or usrchoice == 'Paper' and cptrchoice == 'Scissors'): 
     print('You lose!! :(') 
    else: 
     print('You Win!! :)') 


#5. Run program 
def playGame(): 
    showRules()      # Display the title and game rules 
    user = getUserChoice()  # Get user selection (Rock, Paper, or Scissors) 
    computer = getComputerChoice() # Make and display computer's selection 
    declareWinner(user, computer) # decide and display winner 
+1

鑑於「選擇」*不包含小寫字符串,您如何期待'input(「...」) .lower()'永遠工作?另請閱讀https://www.python.org/dev/peps/pep-0008/ – jonrsharpe

+0

查看您的清單。那些小寫字母? – 2015-10-17 20:00:31

回答

1

您有什麼問題的代碼:

首先是要轉換user input爲小寫,但你的列表項都沒有。所以檢查將失敗。

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

第二件事是您所呼叫的選擇(randnum),你必須使用[]從列表中檢索元素將拋出一個錯誤。

cptrchoice = choices[randnum] 

第三是如果輸入無效字符串會發生什麼情況。您只檢查與if但你需要while loop

while (usrchoice not in choices): 
    usrchoice = getUserChoice() #input("\nChoose again from Rock, Paper or Scissors: ").lower() 

四是在declareWinner,你paramsusercomputer但你正在使用usrchoicecptrchoiceif條件

def declareWinner(usrchoice, cptrchoice): 
    if usrchoice == cptrchoice: 

試試這個,給它一個鏡頭