python實(shí)現(xiàn)簡單石頭剪刀布游戲
:
相信大家在童年或者生活中都玩過石頭剪刀布這個(gè)游戲,這個(gè)游戲需要兩個(gè)及以上的人。而今天,網(wǎng)上也實(shí)現(xiàn)了石頭剪刀布的游戲。通過初步學(xué)習(xí)python,也學(xué)會(huì)了如何編寫這個(gè)游戲。
目標(biāo):
利用python判斷語句實(shí)現(xiàn)石頭剪刀布的游戲。
思路:
假設(shè)剪刀(0),石頭(1),布(2),那么如何才能獲勝呢?

那么根據(jù)這個(gè)表格可以初步寫出代碼:
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("平局")
當(dāng)我們寫完這串代碼,我們不難發(fā)現(xiàn),這樣寫代碼太麻煩了,誰都怕麻煩,所以,我們可以根據(jù)這之中的規(guī)律寫出更短的代碼。

根據(jù)上表,我們可以很輕松的發(fā)現(xiàn)規(guī)律:
1.if user-computer == -2 or user-computer == 1 時(shí),是玩家勝出 2.if user-computer == -1 or user-computer == 2 時(shí),是電腦勝出 3.if user-computer == 0 時(shí),是平局
那么精簡后的部分代碼如下:
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))
因?yàn)殡娔X是隨機(jī)的,我們并不知道,所以需要調(diào)用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 = "布"
#結(jié)果并輸出
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))
效果演示圖如下:

到此這篇關(guān)于python實(shí)現(xiàn)簡單石頭剪刀布游戲的文章就介紹到這了,更多相關(guān)python實(shí)現(xiàn)石頭剪刀布游戲內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信