1. 程式人生 > >人機對戰(猜拳)

人機對戰(猜拳)

# -*- coding: utf-8 -*-
# 人和機器猜拳遊戲寫成一個類,有如下幾個函式:
# 1)函式1:選擇角色1 曹操 2張飛 3 劉備
# 2)函式2:角色猜拳1剪刀 2石頭 3布 玩家輸入一個1-3的數字
# 3)函式3:電腦出拳 隨機產生1個1-3的數字,提示電腦出拳結果
# 4)函式4:角色和機器出拳對戰,對戰結束後,最後出示本局對戰結果...贏...輸,然後提示使用者是否繼續?按y繼續,按n退出。
# 5)最後結束的時候輸出結果 角色贏幾局 電腦贏幾局,平局幾次 遊戲結束
import random
class Match:
def role(self):
dict={'1':'曹操','2':'張飛','3':'劉備'}
while True:
a=input('請輸入數字選擇角色:1 曹操 2 張飛 3 劉備')
if a in dict.keys():
print('你選擇的角色是:{}'.format(dict[a]))
break
else:
print('你輸入的數字不在範圍內,請重新輸入,1 曹操 2 張飛 3 劉備')
continue
return dict[a]
def role_chu_quan(self):
dict = {'1': '石頭', '2': '剪刀', '3': '布'}
while True:
b=input('輸入數字選擇出拳:1 石頭 2 剪刀 3 布 ')
if b in dict.keys():
print('角色出拳的是:{}'.format(dict[b]))
break
else:
print('你輸入的數字有誤,請重新輸入:1 石頭 2 剪刀 3 布')
continue
return dict[b]
def dian(self):
dict = {'1': '石頭', '2': '剪刀', '3': '布'}
c = str(random.randint(1,3))
if c in dict.keys():
print('電腦出拳的是:{}'.format(dict[c]))
return dict[c]
def ren_dian(self):
role_number=0
dian_number=0
ping_number=0
while True:
role_1=self.role()
role_2=self.role_chu_quan()
dian_1=self.dian()
if role_2!=dian_1:
if role_2==1 and dian_1==2:
role_number+=1
elif role_2==2 and dian_1==3:
role_number+=1
elif role_2==3 and dian_1==1:
role_number+=1
else:
dian_number+=1
else:
ping_number+=1
while True:
choose=input('是否繼續,按y繼續,按n退出')
if choose=='y':
break
elif choose=='n':
print('對戰結束;角色贏了{},電腦贏了{},平局{}'.format(role_number,dian_number,ping_number))
return
else:
print('你輸入的有誤,請重新輸入:按y繼續,按n退出')
continue
p=Match()
p.ren_dian()
# 4)函式4:角色和機器出拳對戰,對戰結束後,最後出示本局對戰結果...贏...輸,然後提示使用者是否繼續?按y繼續,按n退出。
# 5)最後結束的時候輸出結果 角色贏幾局 電腦贏幾局,平局幾次 遊戲結束