#题目如下:1:人和机器进行猜拳游戏写成一个类,首先选择角色:1 曹操 2张飞 3 刘备,然后选择的角色进行猜拳:1剪刀 2石头 3布 玩家输入一个1-3的数字 ;
1 import random
class Man_Machine_War():
def __init__(self):
self.USER={1:"曹操",2:"张飞",3:"刘备"}
self.GUESS_TYPE={1:"剪刀",2:"石头",3:"布"} def Choose_User(self):
'''
选择角色
:return:
'''
while (True):
User_Role_Num = input("提示:1曹操 2张飞 3刘备\n请玩家输入数字选择角色:")
try:
User_Role_Num = int(User_Role_Num)
if (User_Role_Num not in [1, 2, 3]):
print("请输入1,2,3选择角色!")
else:
print("用户选择:", self.USER[User_Role_Num])
return self.USER[User_Role_Num]
except(ValueError, TypeError):
print("输入错误!请玩家输入数字")
continue def Computer_Num(self):
'''
返回机器人选择的数字
:return:
'''
ran = random.randint(1,3)
print("电脑出:",self.GUESS_TYPE[ran])
return ran def User_Input_Num(self):
'''
返回用户选择的数字
:return:
'''
while(True):
User_Num = input("提示:1剪刀 2石头 3布\n请玩家输入数字选择出拳:")
try:
User_Num = int(User_Num)
if(User_Num not in [1,2,3]):
print("请输入1,2,3进行出拳!")
else:
print("用户选择:",self.GUESS_TYPE[User_Num])
return User_Num
except(ValueError, TypeError):
print("输入错误!请玩家输入数字")
continue def Judge_Bunko(self,User_Res,Computer_Res):
'''
比赛结果
'''
if Computer_Res==User_Res:
return "Draw"
elif Computer_Res==1:
if User_Res==2:
return "User_Win"
else:
return "User_lose"
elif Computer_Res==2:
if User_Res==3:
return "User_Win"
else:
return "User_lose"
elif Computer_Res==3:
if User_Res==1:
return "User_Win"
else:
return "User_lose"
User_Last_Name=Man_Machine_War().Choose_User()
Use_Result = {User_Last_Name:0,"Computer":0}
User_Win_Num = 0
Com_Win_Num = 0
User_Equal_Com = 0
while(True):
Win_Res=Man_Machine_War().Judge_Bunko(Man_Machine_War().User_Input_Num(),Man_Machine_War().Computer_Num())
if Win_Res=="User_Win":
print(User_Last_Name,"赢了!")
User_Win_Num+=1
elif Win_Res=="User_lose":
print("电脑赢了!")
Com_Win_Num+=1
elif Win_Res=="Draw":
print("平局")
User_Equal_Com+=1
Con = input("是否继续?y/n")
if Con=="y":
continue
elif Con=="n":
break
else:
print("输入错误,默认退出,游戏停止!")
break
print(User_Last_Name,"赢了{}次,电脑赢了{}次,平局{}次".format(User_Win_Num,Com_Win_Num,User_Equal_Com))