py 基础之猜拳游戏的实现

本贴最后更新于 983 天前,其中的信息可能已经时过境迁

题目:

用所学的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)
回帖
请输入回帖内容 ...