python系统学习第八天

人和激起猜拳游戏写一个类,如下几个函数:
函数1:选择角色 1 曹操 2 张飞 3 刘备
函数2 :角色猜拳 1 见到 2 石头 3 布 玩家输入一个1-3 的数字
函数3 电脑出拳,随机产生1个1-3 的数字,提示电脑出拳结果
函数4 角色和机器出拳对战,对战结束后,print(最后出示本局对战结果…赢…输…
函数5 最后结束的时候输出结果,角色赢几把 电脑赢几把 平几把 游戏结束

#编程思想
#1 首先先定义出类跟函数
#2 用字典把角色存放起来
#3 用户选择随机或者指定角色
#4 用户自己选择时,用if else 判断
#5 随机的时候用random来取值
#6 进行出拳先调用选择角色的方法
#7 让双方出拳都返回一个数字
#8 对返回的数字进行比较来判断输赢
#9 加while 循环判断是否继续

import random
class HumanVsPc:
    def __init__(self):
        self.fist={"1":"剪刀","2":"石头","3":"布"} #因为后面几个函数都会用到这个属性,所以把属性放到init方法里面更方便

    def choose_role(self):
        role_dic={"1":"曹操","2":"张飞","3":"刘备"} #用字典来存放角色,字典循环出来是字符串类型的,所以后面用到的key都要使用str类型
        while True:
            choice=input("要输入自己选择的角色还是随机分配的角色 1:指定 2:随机")
            if choice=="1":
                role_num=input("要输入自己选择的角色还是随机分配的角色1 曹操 2 张飞 3 刘备" )
                print("你选择的角色是{}".format(role_dic[role_num]))
                break

            elif choice=="2":
                role_num = random.randint(1,3)
                print("你选择的角色是{}".format(role_dic[str(role_num)]))#因为role_num通过random循环出来是int类型,所以要强转成字符串类型
                break
            else:
                print("选择的项目不存在请重新输入")
                continue
        return role_dic[str(role_num)]
    def role_fist(self):#角色出拳
        role_name=self.choose_role()  # 调用方法,选角色

        while True:
           fist_num=input("{}请输入1 剪刀 2 石头 3 布".format(role_name))
           if fist_num in self.fist.keys():#获取字典的所有key
            print("{}输入的是{}".format(role_name,self.fist[fist_num]))
            break
           else:
            print("{}您输入的数字不正确,请重新输入".format(role_name))
            continue
        return int(fist_num)
    def pc_fist(self):#pc 出拳
        fist_num = random.randint(1,3)
        print("电脑输入的是{}".format(self.fist[str(fist_num)]))
        return int(fist_num)
    def human_vs_pc(self):#激烈对战
        #双发出拳

      a = 0  # 角色赢
      b = 0  # 电脑赢
      c = 0  # 平局
      while True:
          role=self.role_fist() #角色出拳
          pc=self.pc_fist() #pc出拳
          if (role-pc) in [-2,1]:
              print("恭喜你赢了")
              a += 1
          elif(role-pc)==0:
              print("平局了")
              c+=1
          else:
              print(("电脑赢了"))
              b += 1
          choice=input("是继续猜拳 y 继续 任意键退出")
          if choice=="y":
              continue
          else:
              break
      print("电脑赢了{}角色赢了{}平局{}游戏结束".format(b,a,c))
if __name__ == '__main__':
   # HumanVsPc().choose_role()
  #HumanVsPc().role_fist()
  HumanVsPc().human_vs_pc()

结果

你选择的角色是张飞
张飞请输入1 剪刀 2 石头 3 布2
张飞输入的是石头
电脑输入的是布
电脑赢了
是继续猜拳 y 继续 任意键退出2
电脑赢了1角色赢了0平局0游戏结束

猜你喜欢

转载自blog.csdn.net/guotianxiu1234/article/details/89488065