py基础之猜拳游戏的实现

题目:

用所学的 py 基础实现猜拳游戏的 5 局 3 胜(面向对象之前的所有基础知识)

要求:

5 局 3 胜,平局时再加一局
人与电脑对局

思路:

  1. 用 0 表示剪刀,1 表示石头,2 表示布
  2. 先单局比较胜负,注意判断用户输入的是否符合要求
  3. 单局比较胜负时,记录每位用户的胜场数
  4. 比较 5 局之后最终的胜负结果,平局时加一局
  5. 格式化输出,能直观看到用户及电脑的输入
    import random
    
    
    # 单局胜负,并计算胜场数
    def Guessone(i, m, n):
        while n <= 5:
            try:
                userplayer = int(input("请输入(0)剪刀 (1)石头 (2)布\n"))
            except:
                print("输入错误,请按照提示输入!")
            else:
                if 0 <= userplayer < 3:
                    # random.randint(0,2)在0-2之间随机取数
                    computerplayer = random.randint(0, 2)
                    name1, name2 = Numname(userplayer, computerplayer)
                    print("你出的是{}\n对方出的是{}".format(name1, name2))
                    # 判断单局谁赢
                    if userplayer == computerplayer:
                        print("~~~~这轮平手~~~~~~")
                    elif userplayer > computerplayer or userplayer == 0 and computerplayer == 2:
                        print("~~~~~~这轮你赢~~~~~~~~")
                        i = i + 1
                    else:
                        print("~~~~~~这轮对方赢~~~~~~")
                        m = m + 1
                    n = n + 1
                else:
                    print("输入错误,请按照提示输入!")
                    continue
        return i, m, n
    
    
    def Numname(userplayer, computerplayer):
        if userplayer == 0 or computerplayer == 0:
            guess1 = "剪刀"
            guess2 = "剪刀"
        elif userplayer == 1 or computerplayer == 1:
            guess1 = "石头"
            guess2 = "石头"
        else:
            guess1 = "布"
            guess2 = "布"
        return guess1, guess2
    
    
    # 比较胜负
    def end(o, p, q):
        if o > p or o == 3:
            print("~~~~~~~哇偶,是你赢了呀!~~~~~~")
        elif p > o or p == 3:
            print("最终结果\n~~~~~~~真遗憾,最终对方赢了!~~~~~~")
        else:
            print("~~~~再加一局~~~~")
            q = q - 1
            a, b, c = Guessone(o, p, q)
            end(a, b, c)
    
    
    x, y, z = Guessone(1, 1, 1)
    end(x, y, z)

你可能感兴趣的:(py基础练习,游戏,python)