您好,登錄后才能下訂單哦!
利用Python編寫一個剪刀石頭布小游戲?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
創建一個簡單的單輪游戲版本,我們不執行正確的輸入。
如果輸入了無效的內容,則添加while循環可重新提示用戶輸入選擇。
使用while循環讓用戶反復播放,并使用變量來跟蹤得分。
import random input("Welcome to Rock, Paper, Scissors! Press Enter to start.") print() user_wins = 0 computer_wins = 0 choices = ["rock", "paper", "scissors"] while True: random_index = random.randint(0,2) cpu_choice = choices[random_index] user_choice = input("Rock, Paper, or Scissors? ").lower() while user_choice not in choices: user_choice = input("That is not a valid choice. Please try again: ").lower() print() print("Your choice:", user_choice) print("Computer's choice:", cpu_choice) print() if user_choice == 'rock': if cpu_choice == 'rock': print("It's a tie!") elif cpu_choice == 'scissors': print("You win!") user_wins+=1 elif cpu_choice == 'paper': print("You lose!") computer_wins+=1 elif user_choice == 'paper': if cpu_choice == 'paper': print("It's a tie!") elif cpu_choice == 'rock': print("You win!") user_wins+=1 elif cpu_choice == 'scissors': print("You lose!") computer_wins+=1 elif user_choice == 'scissors': if cpu_choice == 'scissors': print("It's a tie!") elif cpu_choice == 'paper': print("You win!") user_wins+=1 elif cpu_choice == 'rock': print("You lose!") computer_wins+=1 print() print("You have "+str(user_wins)+" wins") print("The computer has "+str(computer_wins)+" wins") print() repeat = input("Play again? (Y/N) ").lower() while repeat not in ['y', 'n']: repeat = input("That is not a valid choice. Please try again: ").lower() if repeat == 'n': break print("\n----------------------------\n")
看完上述內容,你們掌握利用Python編寫一個剪刀石頭布小游戲的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。