python實現(xiàn)簡單石頭剪刀布游戲
:
相信大家在童年或者生活中都玩過石頭剪刀布這個游戲,這個游戲需要兩個及以上的人。而今天,網(wǎng)上也實現(xiàn)了石頭剪刀布的游戲。通過初步學習python,也學會了如何編寫這個游戲。
目標:
利用python判斷語句實現(xiàn)石頭剪刀布的游戲。
思路:
假設剪刀(0),石頭(1),布(2),那么如何才能獲勝呢?
那么根據(jù)這個表格可以初步寫出代碼:
if user == 0 and computer == 0: print("平局") elif user == 0 and computer == 1: print("玩家勝") elif user == 0 and computer == 2: print("電腦勝") elif user == 1 and computer == 0: print("電腦獲勝") elif user == 1 and computer == 1: print("平局") elif user == 1 and computer == 2: print("玩家勝") elif user == 2 and computer == 0: print("玩家勝") elif user == 2 and computer == 1: print("電腦勝") elif user == 2 and computer == 2: print("平局")
當我們寫完這串代碼,我們不難發(fā)現(xiàn),這樣寫代碼太麻煩了,誰都怕麻煩,所以,我們可以根據(jù)這之中的規(guī)律寫出更短的代碼。
根據(jù)上表,我們可以很輕松的發(fā)現(xiàn)規(guī)律:
1.if user-computer == -2 or user-computer == 1 時,是玩家勝出 2.if user-computer == -1 or user-computer == 2 時,是電腦勝出 3.if user-computer == 0 時,是平局
那么精簡后的部分代碼如下:
if user == computer: print("玩家是%s,電腦是%s,平局"%(usr,com)) elif user - computer == -1 or user - computer == 2: print("玩家是%s,電腦是%s,玩家輸"%(usr,com)) else: print("玩家是%s,電腦是%s,玩家勝"%(usr,com))
因為電腦是隨機的,我們并不知道,所以需要調用random
。完整的代碼如下:
import random computer = random.randint(0,2) user = int(input("剪刀(0),石頭(1),布(2):")) #判斷電腦出的是石頭,剪刀,還是布 if computer == 0: com = "剪刀" elif computer == 1: com = "石頭" else: com = "布" #判斷玩家出的石頭,剪刀,還是布 if user == 0: usr = "剪刀" elif user == 1: usr = "石頭" else: usr = "布" #結果并輸出 if user == computer: print("玩家是%s,電腦是%s,平局"%(usr,com)) elif user - computer == -1 or user - computer == 2: print("玩家是%s,電腦是%s,玩家輸"%(usr,com)) else: print("玩家是%s,電腦是%s,玩家勝"%(usr,com))
效果演示圖如下:
到此這篇關于python實現(xiàn)簡單石頭剪刀布游戲的文章就介紹到這了,更多相關python實現(xiàn)石頭剪刀布游戲內容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持本站!
版權聲明:本站文章來源標注為YINGSOO的內容版權均為本站所有,歡迎引用、轉載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。